diff --git a/akka-actor-testkit-typed/src/test/java/akka/actor/testkit/typed/javadsl/ActorTestKitTest.java b/akka-actor-testkit-typed/src/test/java/akka/actor/testkit/typed/javadsl/ActorTestKitTest.java index 3b7495c170..14aa41ef6e 100644 --- a/akka-actor-testkit-typed/src/test/java/akka/actor/testkit/typed/javadsl/ActorTestKitTest.java +++ b/akka-actor-testkit-typed/src/test/java/akka/actor/testkit/typed/javadsl/ActorTestKitTest.java @@ -19,8 +19,7 @@ import static org.junit.Assert.assertEquals; public class ActorTestKitTest extends JUnitSuite { - @ClassRule - public static TestKitJunitResource testKit = new TestKitJunitResource(); + @ClassRule public static TestKitJunitResource testKit = new TestKitJunitResource(); @Test public void systemNameShouldComeFromTestClassViaJunitResource() { @@ -51,10 +50,12 @@ public class ActorTestKitTest extends JUnitSuite { @Test public void testKitShouldSpawnActor() throws Exception { final CompletableFuture started = new CompletableFuture<>(); - testKit.spawn(Behaviors.setup((context) -> { - started.complete(done()); - return Behaviors.same(); - })); + testKit.spawn( + Behaviors.setup( + (context) -> { + started.complete(done()); + return Behaviors.same(); + })); started.get(3, TimeUnit.SECONDS); } } diff --git a/akka-actor-testkit-typed/src/test/java/akka/actor/testkit/typed/javadsl/BehaviorTestKitTest.java b/akka-actor-testkit-typed/src/test/java/akka/actor/testkit/typed/javadsl/BehaviorTestKitTest.java index 25bb78a8f3..10a2128994 100644 --- a/akka-actor-testkit-typed/src/test/java/akka/actor/testkit/typed/javadsl/BehaviorTestKitTest.java +++ b/akka-actor-testkit-typed/src/test/java/akka/actor/testkit/typed/javadsl/BehaviorTestKitTest.java @@ -30,8 +30,7 @@ import static org.junit.Assert.assertTrue; public class BehaviorTestKitTest extends JUnitSuite { - public interface Command { - } + public interface Command {} public static class SpawnWatchAndUnWatch implements Command { private final String name; @@ -123,72 +122,102 @@ public class BehaviorTestKitTest extends JUnitSuite { } } - public interface Action { - } + public interface Action {} private static Behavior childInitial = Behaviors.ignore(); private static Props props = Props.empty().withDispatcherFromConfig("cat"); - private static Behavior behavior = Behaviors.receive(Command.class) - .onMessage(SpawnChildren.class, (context, message) -> { - IntStream.range(0, message.numberOfChildren).forEach(i -> { - context.spawn(childInitial, "child" + i); - }); - return Behaviors.same(); - }) - .onMessage(SpawnChildrenAnonymous.class, (context, message) -> { - IntStream.range(0, message.numberOfChildren).forEach(i -> { - context.spawnAnonymous(childInitial); - }); - return Behaviors.same(); - }) - .onMessage(SpawnChildrenWithProps.class, (context, message) -> { - IntStream.range(0, message.numberOfChildren).forEach(i -> { - context.spawn(childInitial, "child" + i, message.props); - }); - return Behaviors.same(); - }) - .onMessage(SpawnChildrenAnonymousWithProps.class, (context, message) -> { - IntStream.range(0, message.numberOfChildren).forEach(i -> { - context.spawnAnonymous(childInitial, message.props); - }); - return Behaviors.same(); - }) - .onMessage(CreateMessageAdapter.class, (context, message) -> { - context.messageAdapter(message.clazz, message.f); - return Behaviors.same(); - }) - .onMessage(SpawnWatchAndUnWatch.class, (context, message) -> { - ActorRef c = context.spawn(childInitial, message.name); - context.watch(c); - context.unwatch(c); - return Behaviors.same(); - }) - .onMessage(SpawnAndWatchWith.class, (context, message) -> { - ActorRef c = context.spawn(childInitial, message.name); - context.watchWith(c, message); - return Behaviors.same(); - }) - .onMessage(SpawnSession.class, (context, message) -> { - ActorRef session = context.spawnAnonymous(Behaviors.receiveMessage( m -> { - message.sessionHandler.tell(m); - return Behaviors.same(); - })); - message.replyTo.tell(session); - return Behaviors.same(); - }) - .onMessage(KillSession.class, (context, message) -> { - context.stop(message.session); - message.replyTo.tell(Done.getInstance()); - return Behaviors.same(); - }) - .onMessage(Log.class, (context, message) -> { - context.getLog().info(message.what); - return Behaviors.same(); - }) - .build(); - + private static Behavior behavior = + Behaviors.receive(Command.class) + .onMessage( + SpawnChildren.class, + (context, message) -> { + IntStream.range(0, message.numberOfChildren) + .forEach( + i -> { + context.spawn(childInitial, "child" + i); + }); + return Behaviors.same(); + }) + .onMessage( + SpawnChildrenAnonymous.class, + (context, message) -> { + IntStream.range(0, message.numberOfChildren) + .forEach( + i -> { + context.spawnAnonymous(childInitial); + }); + return Behaviors.same(); + }) + .onMessage( + SpawnChildrenWithProps.class, + (context, message) -> { + IntStream.range(0, message.numberOfChildren) + .forEach( + i -> { + context.spawn(childInitial, "child" + i, message.props); + }); + return Behaviors.same(); + }) + .onMessage( + SpawnChildrenAnonymousWithProps.class, + (context, message) -> { + IntStream.range(0, message.numberOfChildren) + .forEach( + i -> { + context.spawnAnonymous(childInitial, message.props); + }); + return Behaviors.same(); + }) + .onMessage( + CreateMessageAdapter.class, + (context, message) -> { + context.messageAdapter(message.clazz, message.f); + return Behaviors.same(); + }) + .onMessage( + SpawnWatchAndUnWatch.class, + (context, message) -> { + ActorRef c = context.spawn(childInitial, message.name); + context.watch(c); + context.unwatch(c); + return Behaviors.same(); + }) + .onMessage( + SpawnAndWatchWith.class, + (context, message) -> { + ActorRef c = context.spawn(childInitial, message.name); + context.watchWith(c, message); + return Behaviors.same(); + }) + .onMessage( + SpawnSession.class, + (context, message) -> { + ActorRef session = + context.spawnAnonymous( + Behaviors.receiveMessage( + m -> { + message.sessionHandler.tell(m); + return Behaviors.same(); + })); + message.replyTo.tell(session); + return Behaviors.same(); + }) + .onMessage( + KillSession.class, + (context, message) -> { + context.stop(message.session); + message.replyTo.tell(Done.getInstance()); + return Behaviors.same(); + }) + .onMessage( + Log.class, + (context, message) -> { + context.getLog().info(message.what); + return Behaviors.same(); + }) + .build(); @Test public void allowAssertionsOnEffectType() { @@ -240,8 +269,7 @@ public class BehaviorTestKitTest extends JUnitSuite { @Test @Ignore("Not supported for Java API") - public void allowAssertionsUsingPartialFunctions() { - } + public void allowAssertionsUsingPartialFunctions() {} @Test public void spawnChildrenWithNoProps() { @@ -249,9 +277,10 @@ public class BehaviorTestKitTest extends JUnitSuite { test.run(new SpawnChildren(2)); List allEffects = test.getAllEffects(); assertEquals( - Arrays.asList(Effects.spawned(childInitial, "child0"), Effects.spawned(childInitial, "child1", Props.empty())), - allEffects - ); + Arrays.asList( + Effects.spawned(childInitial, "child0"), + Effects.spawned(childInitial, "child1", Props.empty())), + allEffects); } @Test @@ -267,9 +296,10 @@ public class BehaviorTestKitTest extends JUnitSuite { test.run(new SpawnChildrenAnonymous(2)); List allEffects = test.getAllEffects(); assertEquals( - Arrays.asList(Effects.spawnedAnonymous(childInitial), Effects.spawnedAnonymous(childInitial, Props.empty())), - allEffects - ); + Arrays.asList( + Effects.spawnedAnonymous(childInitial), + Effects.spawnedAnonymous(childInitial, Props.empty())), + allEffects); } @Test @@ -330,5 +360,4 @@ public class BehaviorTestKitTest extends JUnitSuite { assertEquals(Collections.singletonList(Done.getInstance()), d.getAllReceived()); test.expectEffectClass(Effect.Stopped.class); } - } diff --git a/akka-actor-testkit-typed/src/test/java/akka/actor/testkit/typed/javadsl/TestProbeTest.java b/akka-actor-testkit-typed/src/test/java/akka/actor/testkit/typed/javadsl/TestProbeTest.java index 22ea79d1cb..ed433521fc 100644 --- a/akka-actor-testkit-typed/src/test/java/akka/actor/testkit/typed/javadsl/TestProbeTest.java +++ b/akka-actor-testkit-typed/src/test/java/akka/actor/testkit/typed/javadsl/TestProbeTest.java @@ -18,8 +18,7 @@ import static org.junit.Assert.*; public class TestProbeTest extends JUnitSuite { - @ClassRule - public static TestKitJunitResource testKit = new TestKitJunitResource(); + @ClassRule public static TestKitJunitResource testKit = new TestKitJunitResource(); @Test public void testReceiveOne() { @@ -27,10 +26,11 @@ public class TestProbeTest extends JUnitSuite { List eventsT = akka.japi.Util.javaArrayList(TestProbeSpec.eventsT(10)); - eventsT.forEach(e->{ - probe.getRef().tell(e); - assertEquals(probe.receiveOne(), e); - }); + eventsT.forEach( + e -> { + probe.getRef().tell(e); + assertEquals(probe.receiveOne(), e); + }); probe.expectNoMessage(); } @@ -41,10 +41,11 @@ public class TestProbeTest extends JUnitSuite { List eventsT = akka.japi.Util.javaArrayList(TestProbeSpec.eventsT(2)); - eventsT.forEach(e->{ - probe.getRef().tell(e); - assertEquals(probe.receiveOne(Duration.ofMillis(100)), e); - }); + eventsT.forEach( + e -> { + probe.getRef().tell(e); + assertEquals(probe.receiveOne(Duration.ofMillis(100)), e); + }); probe.expectNoMessage(); } @@ -58,19 +59,25 @@ public class TestProbeTest extends JUnitSuite { @Test public void testAwaitAssert() { TestProbe probe = TestProbe.create(testKit.system()); - probe.awaitAssert(() -> { - // ... something ... - return null; - }); - probe.awaitAssert(Duration.ofSeconds(3), () -> { - // ... something ... - return null; - }); + probe.awaitAssert( + () -> { + // ... something ... + return null; + }); + probe.awaitAssert( + Duration.ofSeconds(3), + () -> { + // ... something ... + return null; + }); String awaitAssertResult = - probe.awaitAssert(Duration.ofSeconds(3), Duration.ofMillis(100), () -> { - // ... something ... - return "some result"; - }); + probe.awaitAssert( + Duration.ofSeconds(3), + Duration.ofMillis(100), + () -> { + // ... something ... + return "some result"; + }); assertEquals("some result", awaitAssertResult); } @@ -90,22 +97,28 @@ public class TestProbeTest extends JUnitSuite { probe.getRef().tell("one"); probe.getRef().tell("one"); probe.getRef().tell("two"); - List results = probe.fishForMessage(Duration.ofSeconds(3), "hint", message -> { - if (message.equals("one")) return FishingOutcomes.continueAndIgnore(); - else if (message.equals("two")) return FishingOutcomes.complete(); - else return FishingOutcomes.fail("error"); - }); + List results = + probe.fishForMessage( + Duration.ofSeconds(3), + "hint", + message -> { + if (message.equals("one")) return FishingOutcomes.continueAndIgnore(); + else if (message.equals("two")) return FishingOutcomes.complete(); + else return FishingOutcomes.fail("error"); + }); assertEquals(Arrays.asList("two"), results); } @Test public void testWithin() { TestProbe probe = TestProbe.create(testKit.system()); - String withinResult = probe.within(Duration.ofSeconds(3), () -> { - // ... something ... - return "result"; - }); + String withinResult = + probe.within( + Duration.ofSeconds(3), + () -> { + // ... something ... + return "result"; + }); assertEquals("result", withinResult); } - } diff --git a/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/AsyncTestingExampleTest.java b/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/AsyncTestingExampleTest.java index c78a8016af..689bf51053 100644 --- a/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/AsyncTestingExampleTest.java +++ b/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/AsyncTestingExampleTest.java @@ -25,12 +25,12 @@ import java.util.Objects; import static org.junit.Assert.assertEquals; -//#test-header +// #test-header public class AsyncTestingExampleTest extends JUnitSuite { - final static ActorTestKit testKit = ActorTestKit.create(); -//#test-header + static final ActorTestKit testKit = ActorTestKit.create(); + // #test-header - //#under-test + // #under-test public static class Ping { private String message; private ActorRef replyTo; @@ -40,6 +40,7 @@ public class AsyncTestingExampleTest extends JUnitSuite { this.replyTo = replyTo; } } + public static class Pong { private String message; @@ -61,18 +62,20 @@ public class AsyncTestingExampleTest extends JUnitSuite { } } - Behavior echoActor = Behaviors.receive((context, ping) -> { - ping.replyTo.tell(new Pong(ping.message)); - return Behaviors.same(); - }); - //#under-test + Behavior echoActor = + Behaviors.receive( + (context, ping) -> { + ping.replyTo.tell(new Pong(ping.message)); + return Behaviors.same(); + }); + // #under-test - - //#under-test-2 + // #under-test-2 static class Message { int i; ActorRef> replyTo; + Message(int i, ActorRef> replyTo) { this.i = i; this.replyTo = replyTo; @@ -95,37 +98,36 @@ public class AsyncTestingExampleTest extends JUnitSuite { private CompletionStage> publish(int i) { return AskPattern.ask( - publisher, - (ActorRef> ref) -> new Message(i, ref), - Duration.ofSeconds(3), - scheduler - ); + publisher, + (ActorRef> ref) -> new Message(i, ref), + Duration.ofSeconds(3), + scheduler); } } - //#under-test-2 + // #under-test-2 - //#test-shutdown + // #test-shutdown @AfterClass public static void cleanup() { testKit.shutdownTestKit(); } - //#test-shutdown + // #test-shutdown @Test public void testVerifyingAResponse() { - //#test-spawn + // #test-spawn ActorRef pinger = testKit.spawn(echoActor, "ping"); TestProbe probe = testKit.createTestProbe(); pinger.tell(new Ping("hello", probe.ref())); probe.expectMessage(new Pong("hello")); - //#test-spawn + // #test-spawn } @Test public void testVerifyingAResponseAnonymous() { - //#test-spawn-anonymous + // #test-spawn-anonymous ActorRef pinger = testKit.spawn(echoActor); - //#test-spawn-anonymous + // #test-spawn-anonymous TestProbe probe = testKit.createTestProbe(); pinger.tell(new Ping("hello", probe.ref())); probe.expectMessage(new Pong("hello")); @@ -134,7 +136,7 @@ public class AsyncTestingExampleTest extends JUnitSuite { @Test public void testStoppingActors() { TestProbe probe = testKit.createTestProbe(); - //#test-stop-actors + // #test-stop-actors ActorRef pinger1 = testKit.spawn(echoActor, "pinger"); pinger1.tell(new Ping("hello", probe.ref())); probe.expectMessage(new Pong("hello")); @@ -145,19 +147,22 @@ public class AsyncTestingExampleTest extends JUnitSuite { pinger2.tell(new Ping("hello", probe.ref())); probe.expectMessage(new Pong("hello")); testKit.stop(pinger2, Duration.ofSeconds(10)); - //#test-stop-actors + // #test-stop-actors } @Test public void testObserveMockedBehavior() { - //#test-observe-mocked-behavior + // #test-observe-mocked-behavior // simulate the happy path - Behavior mockedBehavior = Behaviors.receiveMessage(message -> { - message.replyTo.tell(new Success<>(message.i)); - return Behaviors.same(); - }); + Behavior mockedBehavior = + Behaviors.receiveMessage( + message -> { + message.replyTo.tell(new Success<>(message.i)); + return Behaviors.same(); + }); TestProbe probe = testKit.createTestProbe(); - ActorRef mockedPublisher = testKit.spawn(Behaviors.monitor(probe.ref(), mockedBehavior)); + ActorRef mockedPublisher = + testKit.spawn(Behaviors.monitor(probe.ref(), mockedBehavior)); // test our component Producer producer = new Producer(testKit.scheduler(), mockedPublisher); @@ -165,11 +170,13 @@ public class AsyncTestingExampleTest extends JUnitSuite { producer.produce(messages); // verify expected behavior - IntStream.range(0, messages).forEach(i -> { - Message msg = probe.expectMessageClass(Message.class); - assertEquals(i, msg.i); - }); - //#test-observe-mocked-behavior + IntStream.range(0, messages) + .forEach( + i -> { + Message msg = probe.expectMessageClass(Message.class); + assertEquals(i, msg.i); + }); + // #test-observe-mocked-behavior } @Test diff --git a/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/JunitIntegrationExampleTest.java b/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/JunitIntegrationExampleTest.java index 947142ebbe..35bf14f602 100644 --- a/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/JunitIntegrationExampleTest.java +++ b/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/JunitIntegrationExampleTest.java @@ -12,14 +12,12 @@ import org.junit.Test; public class JunitIntegrationExampleTest { - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(); @Test public void testSomething() { TestProbe probe = testKit.createTestProbe(); // ... assertions etc. } - } // #junit-integration diff --git a/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/ManualTimerExampleTest.java b/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/ManualTimerExampleTest.java index 5442c4fd53..9313065591 100644 --- a/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/ManualTimerExampleTest.java +++ b/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/ManualTimerExampleTest.java @@ -4,7 +4,7 @@ package jdocs.akka.actor.testkit.typed.javadsl; -//#manual-scheduling-simple +// #manual-scheduling-simple import akka.actor.typed.Behavior; import akka.actor.testkit.typed.javadsl.ManualTime; @@ -27,18 +27,22 @@ public class ManualTimerExampleTest extends JUnitSuite { private final ManualTime manualTime = ManualTime.get(testKit.system()); static final class Tick {} + static final class Tock {} @Test public void testScheduleNonRepeatedTicks() { TestProbe probe = testKit.createTestProbe(); - Behavior behavior = Behaviors.withTimers(timer -> { - timer.startSingleTimer("T", new Tick(), Duration.ofMillis(10)); - return Behaviors.receive( (context, tick) -> { - probe.ref().tell(new Tock()); - return Behaviors.same(); - }); - }); + Behavior behavior = + Behaviors.withTimers( + timer -> { + timer.startSingleTimer("T", new Tick(), Duration.ofMillis(10)); + return Behaviors.receive( + (context, tick) -> { + probe.ref().tell(new Tock()); + return Behaviors.same(); + }); + }); testKit.spawn(behavior); @@ -49,7 +53,5 @@ public class ManualTimerExampleTest extends JUnitSuite { manualTime.expectNoMessageFor(Duration.ofSeconds(10), probe); } - - } -//#manual-scheduling-simple +// #manual-scheduling-simple diff --git a/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/SyncTestingExampleTest.java b/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/SyncTestingExampleTest.java index 812096851b..24321f3621 100644 --- a/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/SyncTestingExampleTest.java +++ b/akka-actor-testkit-typed/src/test/java/jdocs/akka/actor/testkit/typed/javadsl/SyncTestingExampleTest.java @@ -4,7 +4,7 @@ package jdocs.akka.actor.testkit.typed.javadsl; -//#imports +// #imports import akka.actor.testkit.typed.CapturedLogEvent; import akka.actor.testkit.typed.javadsl.BehaviorTestKit; import akka.actor.testkit.typed.javadsl.Effects; @@ -15,34 +15,41 @@ import akka.event.Logging; import java.util.HashMap; import java.util.List; import java.util.Optional; -//#imports +// #imports import org.junit.Test; import static org.junit.Assert.assertEquals; import org.scalatest.junit.JUnitSuite; - public class SyncTestingExampleTest extends JUnitSuite { - //#child - public static Behavior childActor = Behaviors.receive((context, message) -> Behaviors.same()); - //#child + // #child + public static Behavior childActor = + Behaviors.receive((context, message) -> Behaviors.same()); + // #child + + // #under-test + interface Command {} - //#under-test - interface Command { } public static class CreateAChild implements Command { private final String childName; + public CreateAChild(String childName) { this.childName = childName; } } - public static class CreateAnAnonymousChild implements Command { } + + public static class CreateAnAnonymousChild implements Command {} + public static class SayHelloToChild implements Command { private final String childName; + public SayHelloToChild(String childName) { this.childName = childName; } } - public static class SayHelloToAnonymousChild implements Command { } + + public static class SayHelloToAnonymousChild implements Command {} + public static class SayHello implements Command { private final ActorRef who; @@ -50,6 +57,7 @@ public class SyncTestingExampleTest extends JUnitSuite { this.who = who; } } + public static class LogAndSayHello implements Command { private final ActorRef who; @@ -58,99 +66,116 @@ public class SyncTestingExampleTest extends JUnitSuite { } } - public static Behavior myBehavior = Behaviors.receive(Command.class) - .onMessage(CreateAChild.class, (context, message) -> { - context.spawn(childActor, message.childName); - return Behaviors.same(); - }) - .onMessage(CreateAnAnonymousChild.class, (context, message) -> { - context.spawnAnonymous(childActor); - return Behaviors.same(); - }) - .onMessage(SayHelloToChild.class, (context, message) -> { - ActorRef child = context.spawn(childActor, message.childName); - child.tell("hello"); - return Behaviors.same(); - }) - .onMessage(SayHelloToAnonymousChild.class, (context, message) -> { - ActorRef child = context.spawnAnonymous(childActor); - child.tell("hello stranger"); - return Behaviors.same(); - }) - .onMessage(SayHello.class, (context, message) -> { - message.who.tell("hello"); - return Behaviors.same(); - }) - .onMessage(LogAndSayHello.class, (context, message) -> { - context.getLog().info("Saying hello to {}", message.who.path().name()); - message.who.tell("hello"); - return Behaviors.same(); - }) - .build(); - //#under-test - + public static Behavior myBehavior = + Behaviors.receive(Command.class) + .onMessage( + CreateAChild.class, + (context, message) -> { + context.spawn(childActor, message.childName); + return Behaviors.same(); + }) + .onMessage( + CreateAnAnonymousChild.class, + (context, message) -> { + context.spawnAnonymous(childActor); + return Behaviors.same(); + }) + .onMessage( + SayHelloToChild.class, + (context, message) -> { + ActorRef child = context.spawn(childActor, message.childName); + child.tell("hello"); + return Behaviors.same(); + }) + .onMessage( + SayHelloToAnonymousChild.class, + (context, message) -> { + ActorRef child = context.spawnAnonymous(childActor); + child.tell("hello stranger"); + return Behaviors.same(); + }) + .onMessage( + SayHello.class, + (context, message) -> { + message.who.tell("hello"); + return Behaviors.same(); + }) + .onMessage( + LogAndSayHello.class, + (context, message) -> { + context.getLog().info("Saying hello to {}", message.who.path().name()); + message.who.tell("hello"); + return Behaviors.same(); + }) + .build(); + // #under-test @Test public void testSpawning() { - //#test-child + // #test-child BehaviorTestKit test = BehaviorTestKit.create(myBehavior); test.run(new CreateAChild("child")); test.expectEffect(Effects.spawned(childActor, "child", Props.empty())); - //#test-child + // #test-child } @Test public void testSpawningAnonymous() { - //#test-anonymous-child + // #test-anonymous-child BehaviorTestKit test = BehaviorTestKit.create(myBehavior); test.run(new CreateAnAnonymousChild()); test.expectEffect(Effects.spawnedAnonymous(childActor, Props.empty())); - //#test-anonymous-child + // #test-anonymous-child } @Test public void testRecodingMessageSend() { - //#test-message + // #test-message BehaviorTestKit test = BehaviorTestKit.create(myBehavior); TestInbox inbox = TestInbox.create(); test.run(new SayHello(inbox.getRef())); inbox.expectMessage("hello"); - //#test-message + // #test-message } @Test public void testMessageToChild() { - //#test-child-message - BehaviorTestKit testKit = BehaviorTestKit.create(myBehavior); - testKit.run(new SayHelloToChild("child")); - TestInbox childInbox = testKit.childInbox("child"); - childInbox.expectMessage("hello"); - //#test-child-message + // #test-child-message + BehaviorTestKit testKit = BehaviorTestKit.create(myBehavior); + testKit.run(new SayHelloToChild("child")); + TestInbox childInbox = testKit.childInbox("child"); + childInbox.expectMessage("hello"); + // #test-child-message } @Test public void testMessageToAnonymousChild() { - //#test-child-message-anonymous - BehaviorTestKit testKit = BehaviorTestKit.create(myBehavior); - testKit.run(new SayHelloToAnonymousChild()); - // Anonymous actors are created as: $a $b etc - TestInbox childInbox = testKit.childInbox("$a"); - childInbox.expectMessage("hello stranger"); - //#test-child-message-anonymous + // #test-child-message-anonymous + BehaviorTestKit testKit = BehaviorTestKit.create(myBehavior); + testKit.run(new SayHelloToAnonymousChild()); + // Anonymous actors are created as: $a $b etc + TestInbox childInbox = testKit.childInbox("$a"); + childInbox.expectMessage("hello stranger"); + // #test-child-message-anonymous } @Test public void testCheckLogging() { - //#test-check-logging + // #test-check-logging BehaviorTestKit test = BehaviorTestKit.create(myBehavior); TestInbox inbox = TestInbox.create("Inboxer"); test.run(new LogAndSayHello(inbox.getRef())); List allLogEntries = test.getAllLogEntries(); assertEquals(1, allLogEntries.size()); - CapturedLogEvent expectedLogEvent = new CapturedLogEvent(Logging.InfoLevel(),"Saying hello to Inboxer", - Optional.empty(), Optional.empty(), new HashMap<>()); + CapturedLogEvent expectedLogEvent = + new CapturedLogEvent( + Logging.InfoLevel(), + "Saying hello to Inboxer", + Optional.empty(), + Optional.empty(), + new HashMap<>()); assertEquals(expectedLogEvent, allLogEntries.get(0)); - //#test-check-logging + // #test-check-logging } } diff --git a/akka-actor-tests/src/test/java/akka/actor/AbstractFSMActorTest.java b/akka-actor-tests/src/test/java/akka/actor/AbstractFSMActorTest.java index 838ccd0156..c0ece1d76e 100644 --- a/akka-actor-tests/src/test/java/akka/actor/AbstractFSMActorTest.java +++ b/akka-actor-tests/src/test/java/akka/actor/AbstractFSMActorTest.java @@ -24,9 +24,7 @@ public class AbstractFSMActorTest extends JUnitSuite { this.probe = probe; onTransition(this::logTransition); startWith("start", "data"); - when("start", matchEventEquals("next", (newState, data) -> - goTo(newState) - )); + when("start", matchEventEquals("next", (newState, data) -> goTo(newState))); when("next", AbstractFSM.NullFunction()); initialize(); } @@ -36,10 +34,9 @@ public class AbstractFSMActorTest extends JUnitSuite { } } - @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("AbstractFSMActorTest", - AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("AbstractFSMActorTest", AkkaSpec.testConf()); private final ActorSystem system = actorSystemResource.getSystem(); @@ -55,6 +52,4 @@ public class AbstractFSMActorTest extends JUnitSuite { probe.expectMsg("Transitioning from start to next."); } - - } diff --git a/akka-actor-tests/src/test/java/akka/actor/ActorCreationTest.java b/akka-actor-tests/src/test/java/akka/actor/ActorCreationTest.java index 2bdac28e00..847dd0b645 100644 --- a/akka-actor-tests/src/test/java/akka/actor/ActorCreationTest.java +++ b/akka-actor-tests/src/test/java/akka/actor/ActorCreationTest.java @@ -42,8 +42,7 @@ public class ActorCreationTest extends JUnitSuite { } } - static interface I extends Creator { - } + static interface I extends Creator {} static class F implements I { @Override @@ -52,7 +51,6 @@ public class ActorCreationTest extends JUnitSuite { } } - static class G implements Creator { public Object create() { return null; @@ -60,8 +58,7 @@ public class ActorCreationTest extends JUnitSuite { } abstract class H extends AbstractActor { - public H(String a) { - } + public H(String a) {} } static class P implements Creator { @@ -99,7 +96,6 @@ public class ActorCreationTest extends JUnitSuite { public Receive createReceive() { return receiveBuilder().build(); } - } public static class TestActor2 extends UntypedAbstractActor { @@ -107,40 +103,42 @@ public class ActorCreationTest extends JUnitSuite { public static Props propsUsingCreator(final int magicNumber) { // You need to specify the actual type of the returned actor // since runtime type information erased - return Props.create(TestActor2.class, new Creator() { - private static final long serialVersionUID = 1L; + return Props.create( + TestActor2.class, + new Creator() { + private static final long serialVersionUID = 1L; - @Override - public TestActor2 create() throws Exception { - return new TestActor2(magicNumber); - } - }); + @Override + public TestActor2 create() throws Exception { + return new TestActor2(magicNumber); + } + }); } public static Props propsUsingCreatorWithoutClass(final int magicNumber) { - return Props.create(new Creator() { - private static final long serialVersionUID = 1L; + return Props.create( + new Creator() { + private static final long serialVersionUID = 1L; - @Override - public TestActor2 create() throws Exception { - return new TestActor2(magicNumber); - } - }); + @Override + public TestActor2 create() throws Exception { + return new TestActor2(magicNumber); + } + }); } - private static final Creator staticCreator = new Creator() { - private static final long serialVersionUID = 1L; + private static final Creator staticCreator = + new Creator() { + private static final long serialVersionUID = 1L; - @Override - public TestActor2 create() throws Exception { - return new TestActor2(12); - } - }; + @Override + public TestActor2 create() throws Exception { + return new TestActor2(12); + } + }; public static Props propsUsingStaticCreator(final int magicNumber) { - - return Props.create(staticCreator); } @@ -151,8 +149,7 @@ public class ActorCreationTest extends JUnitSuite { } @Override - public void onReceive(Object msg) { - } + public void onReceive(Object msg) {} } public static class Issue20537Reproducer extends UntypedAbstractActor { @@ -171,26 +168,27 @@ public class ActorCreationTest extends JUnitSuite { } } - public Issue20537Reproducer(boolean create) { - } + public Issue20537Reproducer(boolean create) {} @Override - public void onReceive(Object message) throws Exception { - } + public void onReceive(Object message) throws Exception {} } @Test public void testWrongAnonymousInPlaceCreator() { try { - Props.create(new Creator() { - @Override - public Actor create() throws Exception { - return null; - } - }); + Props.create( + new Creator() { + @Override + public Actor create() throws Exception { + return null; + } + }); assert false; } catch (IllegalArgumentException e) { - assertEquals("cannot use non-static local Creator to create actors; make it static (e.g. local to a static method) or top-level", e.getMessage()); + assertEquals( + "cannot use non-static local Creator to create actors; make it static (e.g. local to a static method) or top-level", + e.getMessage()); } } @@ -201,7 +199,9 @@ public class ActorCreationTest extends JUnitSuite { Props.create(new G()); assert false; } catch (IllegalArgumentException e) { - assertEquals("erased Creator types (e.g. lambdas) are unsupported, use Props.create(actorClass, creator) instead", e.getMessage()); + assertEquals( + "erased Creator types (e.g. lambdas) are unsupported, use Props.create(actorClass, creator) instead", + e.getMessage()); } Props.create(AbstractActor.class, new G()); } @@ -218,7 +218,9 @@ public class ActorCreationTest extends JUnitSuite { Props.create(new C() {}); // has implicit reference to outer class org.junit.Assert.fail("Should have detected this is not a real static class, and thrown"); } catch (IllegalArgumentException e) { - assertEquals("cannot use non-static local Creator to create actors; make it static (e.g. local to a static method) or top-level", e.getMessage()); + assertEquals( + "cannot use non-static local Creator to create actors; make it static (e.g. local to a static method) or top-level", + e.getMessage()); } } @@ -253,7 +255,9 @@ public class ActorCreationTest extends JUnitSuite { Props.create(H.class, "a"); assert false; } catch (IllegalArgumentException e) { - assertEquals(String.format("Actor class [%s] must not be abstract", H.class.getName()), e.getMessage()); + assertEquals( + String.format("Actor class [%s] must not be abstract", H.class.getName()), + e.getMessage()); } } @@ -268,7 +272,8 @@ public class ActorCreationTest extends JUnitSuite { @Test public void testAnonymousClassCreatedInStaticMethodCreator() { - final Creator anonymousCreatorFromStaticMethod = createAnonymousCreatorInStaticMethod(); + final Creator anonymousCreatorFromStaticMethod = + createAnonymousCreatorInStaticMethod(); Props.create(anonymousCreatorFromStaticMethod); } @@ -282,12 +287,14 @@ public class ActorCreationTest extends JUnitSuite { public void testAnonymousClassCreatorWithArguments() { try { final Creator anonymousCreatorFromStaticMethod = new P("hello") { - // captures enclosing class - }; + // captures enclosing class + }; Props.create(anonymousCreatorFromStaticMethod); org.junit.Assert.fail("Should have detected this is not a real static class, and thrown"); } catch (IllegalArgumentException e) { - assertEquals("cannot use non-static local Creator to create actors; make it static (e.g. local to a static method) or top-level", e.getMessage()); + assertEquals( + "cannot use non-static local Creator to create actors; make it static (e.g. local to a static method) or top-level", + e.getMessage()); } } @@ -305,7 +312,8 @@ public class ActorCreationTest extends JUnitSuite { TestActor.propsUsingLamdaWithoutClass(17); org.junit.Assert.fail("Should have detected lambda erasure, and thrown"); } catch (IllegalArgumentException e) { - assertEquals("erased Creator types (e.g. lambdas) are unsupported, use Props.create(actorClass, creator) instead", + assertEquals( + "erased Creator types (e.g. lambdas) are unsupported, use Props.create(actorClass, creator) instead", e.getMessage()); } } @@ -324,16 +332,17 @@ public class ActorCreationTest extends JUnitSuite { @Test public void testIssue20537Reproducer() { - final Issue20537Reproducer.ReproducerCreator creator = new Issue20537Reproducer.ReproducerCreator(false); + final Issue20537Reproducer.ReproducerCreator creator = + new Issue20537Reproducer.ReproducerCreator(false); final Props p = Props.create(creator); assertEquals(Issue20537Reproducer.class, p.actorClass()); - ArrayList pList = IntStream.range(0, 4).mapToObj(i -> Props.create(creator)) - .collect(toCollection(ArrayList::new)); + ArrayList pList = + IntStream.range(0, 4) + .mapToObj(i -> Props.create(creator)) + .collect(toCollection(ArrayList::new)); for (Props each : pList) { assertEquals(Issue20537Reproducer.class, each.actorClass()); } } - - } diff --git a/akka-actor-tests/src/test/java/akka/actor/ActorSelectionTest.java b/akka-actor-tests/src/test/java/akka/actor/ActorSelectionTest.java index 6051dbc0bf..8484ef3a06 100644 --- a/akka-actor-tests/src/test/java/akka/actor/ActorSelectionTest.java +++ b/akka-actor-tests/src/test/java/akka/actor/ActorSelectionTest.java @@ -19,8 +19,8 @@ import static org.junit.Assert.assertEquals; public class ActorSelectionTest extends JUnitSuite { @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("ActorSelectionTest", - AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("ActorSelectionTest", AkkaSpec.testConf()); private final ActorSystem system = actorSystemResource.getSystem(); diff --git a/akka-actor-tests/src/test/java/akka/actor/ActorSystemTest.java b/akka-actor-tests/src/test/java/akka/actor/ActorSystemTest.java index 4783a268f6..e10645f504 100644 --- a/akka-actor-tests/src/test/java/akka/actor/ActorSystemTest.java +++ b/akka-actor-tests/src/test/java/akka/actor/ActorSystemTest.java @@ -19,7 +19,7 @@ public class ActorSystemTest extends JUnitSuite { @Rule public final AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("ActorSystemTest"); + new AkkaJUnitActorSystemResource("ActorSystemTest"); private ActorSystem system = null; diff --git a/akka-actor-tests/src/test/java/akka/actor/InboxJavaAPITest.java b/akka-actor-tests/src/test/java/akka/actor/InboxJavaAPITest.java index f9b0106d65..023caadf97 100644 --- a/akka-actor-tests/src/test/java/akka/actor/InboxJavaAPITest.java +++ b/akka-actor-tests/src/test/java/akka/actor/InboxJavaAPITest.java @@ -15,8 +15,8 @@ import org.scalatest.junit.JUnitSuite; public class InboxJavaAPITest extends JUnitSuite { @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("InboxJavaAPITest", - AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("InboxJavaAPITest", AkkaSpec.testConf()); private final ActorSystem system = actorSystemResource.getSystem(); @@ -25,5 +25,4 @@ public class InboxJavaAPITest extends JUnitSuite { Inbox inbox = Inbox.create(system); inbox.receive(Duration.ofMillis(10)); } - } diff --git a/akka-actor-tests/src/test/java/akka/actor/JavaAPI.java b/akka-actor-tests/src/test/java/akka/actor/JavaAPI.java index 58c53e3693..d605959b3e 100644 --- a/akka-actor-tests/src/test/java/akka/actor/JavaAPI.java +++ b/akka-actor-tests/src/test/java/akka/actor/JavaAPI.java @@ -30,8 +30,8 @@ import static org.junit.Assert.*; public class JavaAPI extends JUnitSuite { @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("JavaAPI", - AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("JavaAPI", AkkaSpec.testConf()); private final ActorSystem system = actorSystemResource.getSystem(); @@ -62,11 +62,13 @@ public class JavaAPI extends JUnitSuite { @SuppressWarnings("unchecked") public static Props mkErasedProps() { - return Props.create(JavaAPITestActor.class, new Creator() { - public Object create() { - return new JavaAPITestActor(); - } - }); + return Props.create( + JavaAPITestActor.class, + new Creator() { + public Object create() { + return new JavaAPITestActor(); + } + }); } public static Props mkPropsWithLambda() { @@ -87,7 +89,9 @@ public class JavaAPI extends JUnitSuite { @Test public void mustBeAbleToCreateActorWIthConstructorParams() { - ActorRef ref = system.actorOf(Props.create(ActorWithConstructorParams.class, "a", "b", new Integer(17), 18)); + ActorRef ref = + system.actorOf( + Props.create(ActorWithConstructorParams.class, "a", "b", new Integer(17), 18)); final TestProbe probe = new TestProbe(system); probe.send(ref, "get"); probe.expectMsg("a-b-17-18"); @@ -95,7 +99,9 @@ public class JavaAPI extends JUnitSuite { @Test public void mustBeAbleToCreateActorWIthBoxedAndUnBoxedConstructorParams() { - ActorRef ref = system.actorOf(Props.create(ActorWithConstructorParams.class, "a", "b", 17, new Integer(18))); + ActorRef ref = + system.actorOf( + Props.create(ActorWithConstructorParams.class, "a", "b", 17, new Integer(18))); final TestProbe probe = new TestProbe(system); probe.send(ref, "get"); probe.expectMsg("a-b-17-18"); @@ -103,7 +109,8 @@ public class JavaAPI extends JUnitSuite { @Test public void mustBeAbleToCreateActorWIthNullConstructorParams() { - ActorRef ref = system.actorOf(Props.create(ActorWithConstructorParams.class, "a", null, null, 18)); + ActorRef ref = + system.actorOf(Props.create(ActorWithConstructorParams.class, "a", null, null, 18)); final TestProbe probe = new TestProbe(system); probe.send(ref, "get"); probe.expectMsg("a-null-null-18"); @@ -112,7 +119,8 @@ public class JavaAPI extends JUnitSuite { @Test public void mustBeAbleToCreateActorWIthNullConstructorParams2() { // without this Object array wrapper it will not compile: "reference to create is ambiguous" - ActorRef ref = system.actorOf(Props.create(ActorWithConstructorParams.class, new Object[] { null })); + ActorRef ref = + system.actorOf(Props.create(ActorWithConstructorParams.class, new Object[] {null})); final TestProbe probe = new TestProbe(system); probe.send(ref, "get"); probe.expectMsg("null-undefined-0-0"); @@ -186,9 +194,15 @@ public class JavaAPI extends JUnitSuite { } public void onReceive(Object msg) { - String reply = String.valueOf(a) + "-" + String.valueOf(b) + "-" + String.valueOf(c) + "-" + String.valueOf(d); + String reply = + String.valueOf(a) + + "-" + + String.valueOf(b) + + "-" + + String.valueOf(c) + + "-" + + String.valueOf(d); getSender().tell(reply, getSelf()); } } - } diff --git a/akka-actor-tests/src/test/java/akka/actor/JavaExtension.java b/akka-actor-tests/src/test/java/akka/actor/JavaExtension.java index 33e0ab1643..05f723e388 100644 --- a/akka-actor-tests/src/test/java/akka/actor/JavaExtension.java +++ b/akka-actor-tests/src/test/java/akka/actor/JavaExtension.java @@ -14,8 +14,9 @@ import static org.junit.Assert.*; public class JavaExtension extends JUnitSuite { - static class TestExtensionId extends AbstractExtensionId implements ExtensionIdProvider { - public final static TestExtensionId TestExtensionProvider = new TestExtensionId(); + static class TestExtensionId extends AbstractExtensionId + implements ExtensionIdProvider { + public static final TestExtensionId TestExtensionProvider = new TestExtensionId(); public ExtensionId lookup() { return TestExtensionId.TestExtensionProvider; @@ -34,9 +35,10 @@ public class JavaExtension extends JUnitSuite { } } - static class OtherExtensionId extends AbstractExtensionId implements ExtensionIdProvider { + static class OtherExtensionId extends AbstractExtensionId + implements ExtensionIdProvider { - public final static OtherExtensionId OtherExtensionProvider = new OtherExtensionId(); + public static final OtherExtensionId OtherExtensionProvider = new OtherExtensionId(); @Override public ExtensionId lookup() { @@ -47,7 +49,6 @@ public class JavaExtension extends JUnitSuite { public OtherExtension createExtension(ExtendedActorSystem system) { return new OtherExtension(system); } - } static class OtherExtension implements Extension { @@ -62,9 +63,11 @@ public class JavaExtension extends JUnitSuite { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("JavaExtension", - ConfigFactory.parseString("akka.extensions = [ \"akka.actor.JavaExtension$TestExtensionId\" ]") - .withFallback(AkkaSpec.testConf())); + new AkkaJUnitActorSystemResource( + "JavaExtension", + ConfigFactory.parseString( + "akka.extensions = [ \"akka.actor.JavaExtension$TestExtensionId\" ]") + .withFallback(AkkaSpec.testConf())); private final ActorSystem system = actorSystemResource.getSystem(); @@ -79,5 +82,4 @@ public class JavaExtension extends JUnitSuite { public void mustBeAdHoc() { assertSame(OtherExtension.key.apply(system).system, system); } - } diff --git a/akka-actor-tests/src/test/java/akka/actor/NonPublicClass.java b/akka-actor-tests/src/test/java/akka/actor/NonPublicClass.java index 902ffe4aab..9717467bc5 100644 --- a/akka-actor-tests/src/test/java/akka/actor/NonPublicClass.java +++ b/akka-actor-tests/src/test/java/akka/actor/NonPublicClass.java @@ -5,13 +5,14 @@ package akka.actor; public class NonPublicClass { - public static Props createProps() { - return Props.create(MyNonPublicActorClass.class); - } + public static Props createProps() { + return Props.create(MyNonPublicActorClass.class); + } } class MyNonPublicActorClass extends UntypedAbstractActor { - @Override public void onReceive(Object msg) { - getSender().tell(msg, getSelf()); - } + @Override + public void onReceive(Object msg) { + getSender().tell(msg, getSelf()); + } } diff --git a/akka-actor-tests/src/test/java/akka/actor/NonStaticCreator.java b/akka-actor-tests/src/test/java/akka/actor/NonStaticCreator.java index d8c25dff54..3e98a1daff 100644 --- a/akka-actor-tests/src/test/java/akka/actor/NonStaticCreator.java +++ b/akka-actor-tests/src/test/java/akka/actor/NonStaticCreator.java @@ -7,8 +7,8 @@ package akka.actor; import akka.japi.Creator; public class NonStaticCreator implements Creator { - @Override + @Override public UntypedAbstractActor create() throws Exception { - return null; - } + return null; + } } diff --git a/akka-actor-tests/src/test/java/akka/actor/StashJavaAPI.java b/akka-actor-tests/src/test/java/akka/actor/StashJavaAPI.java index 83d22585ec..0abdb1382d 100644 --- a/akka-actor-tests/src/test/java/akka/actor/StashJavaAPI.java +++ b/akka-actor-tests/src/test/java/akka/actor/StashJavaAPI.java @@ -15,17 +15,17 @@ public class StashJavaAPI extends JUnitSuite { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("StashJavaAPI", ActorWithBoundedStashSpec.testConf()); + new AkkaJUnitActorSystemResource("StashJavaAPI", ActorWithBoundedStashSpec.testConf()); private final ActorSystem system = actorSystemResource.getSystem(); private void testAStashApi(Props props) { - ActorRef ref = system.actorOf(props); - final TestProbe probe = new TestProbe(system); - probe.send(ref, "Hello"); - probe.send(ref, "Hello2"); - probe.send(ref, "Hello12"); - probe.expectMsg(5); + ActorRef ref = system.actorOf(props); + final TestProbe probe = new TestProbe(system); + probe.send(ref, "Hello"); + probe.send(ref, "Hello2"); + probe.send(ref, "Hello12"); + probe.expectMsg(5); } @Test @@ -40,9 +40,8 @@ public class StashJavaAPI extends JUnitSuite { @Test public void mustBeAbleToUseUnrestrictedStash() { - testAStashApi(Props.create(StashJavaAPITestActors.WithUnrestrictedStash.class) + testAStashApi( + Props.create(StashJavaAPITestActors.WithUnrestrictedStash.class) .withMailbox("akka.actor.mailbox.unbounded-deque-based")); } - - } diff --git a/akka-actor-tests/src/test/java/akka/actor/StashJavaAPITestActors.java b/akka-actor-tests/src/test/java/akka/actor/StashJavaAPITestActors.java index c6a12be998..fade3b47c6 100644 --- a/akka-actor-tests/src/test/java/akka/actor/StashJavaAPITestActors.java +++ b/akka-actor-tests/src/test/java/akka/actor/StashJavaAPITestActors.java @@ -8,65 +8,71 @@ import static org.junit.Assert.*; public class StashJavaAPITestActors { - /* + /* * Helper method to make the tests of AbstractActorWithStash, AbstractActorWithUnboundedStash and * AbstractActorWithUnrestrictedStash more DRY since mixin is not possible. */ - private static int testReceive(Object msg, int count, ActorRef sender, ActorRef self, UnrestrictedStash stash) { - if (msg instanceof String) { - if (count < 0) { - sender.tell(new Integer(((String) msg).length()), self); - } else if (count == 2) { - stash.unstashAll(); - return -1; - } else { - stash.stash(); - return count + 1; - } - } else if (msg instanceof Integer) { - int value = ((Integer) msg).intValue(); - assertEquals(value, 5); - } - return count; - } - - public static class WithStash extends AbstractActorWithStash { - int count = 0; - - @Override - public Receive createReceive() { - return receiveBuilder() - .match(Object.class, msg -> { - count = testReceive(msg, count, getSender(), getSelf(), this); - }) - .build(); + private static int testReceive( + Object msg, int count, ActorRef sender, ActorRef self, UnrestrictedStash stash) { + if (msg instanceof String) { + if (count < 0) { + sender.tell(new Integer(((String) msg).length()), self); + } else if (count == 2) { + stash.unstashAll(); + return -1; + } else { + stash.stash(); + return count + 1; } + } else if (msg instanceof Integer) { + int value = ((Integer) msg).intValue(); + assertEquals(value, 5); } + return count; + } - public static class WithUnboundedStash extends AbstractActorWithUnboundedStash { - int count = 0; + public static class WithStash extends AbstractActorWithStash { + int count = 0; - @Override - public Receive createReceive() { - return receiveBuilder() - .match(Object.class, msg -> { - count = testReceive(msg, count, getSender(), getSelf(), this); - }) + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + Object.class, + msg -> { + count = testReceive(msg, count, getSender(), getSelf(), this); + }) .build(); - } } + } - public static class WithUnrestrictedStash extends AbstractActorWithUnrestrictedStash { - int count = 0; + public static class WithUnboundedStash extends AbstractActorWithUnboundedStash { + int count = 0; - @Override - public Receive createReceive() { - return receiveBuilder() - .match(Object.class, msg -> { - count = testReceive(msg, count, getSender(), getSelf(), this); - }) + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + Object.class, + msg -> { + count = testReceive(msg, count, getSender(), getSelf(), this); + }) .build(); - } } + } + + public static class WithUnrestrictedStash extends AbstractActorWithUnrestrictedStash { + int count = 0; + + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + Object.class, + msg -> { + count = testReceive(msg, count, getSender(), getSelf(), this); + }) + .build(); + } + } } - diff --git a/akka-actor-tests/src/test/java/akka/actor/TestAnnotation.java b/akka-actor-tests/src/test/java/akka/actor/TestAnnotation.java index 587226d94a..ac726c6b07 100644 --- a/akka-actor-tests/src/test/java/akka/actor/TestAnnotation.java +++ b/akka-actor-tests/src/test/java/akka/actor/TestAnnotation.java @@ -10,5 +10,5 @@ import java.lang.annotation.*; @Target(ElementType.METHOD) @Inherited public @interface TestAnnotation { - String someString() default "pigdog"; + String someString() default "pigdog"; } diff --git a/akka-actor-tests/src/test/java/akka/actor/setup/ActorSystemSetupTest.java b/akka-actor-tests/src/test/java/akka/actor/setup/ActorSystemSetupTest.java index 1c2675ab1b..bf21a41629 100644 --- a/akka-actor-tests/src/test/java/akka/actor/setup/ActorSystemSetupTest.java +++ b/akka-actor-tests/src/test/java/akka/actor/setup/ActorSystemSetupTest.java @@ -17,6 +17,7 @@ public class ActorSystemSetupTest extends JUnitSuite { static class JavaSetup extends Setup { public final String name; + public JavaSetup(String name) { this.name = name; } @@ -25,13 +26,10 @@ public class ActorSystemSetupTest extends JUnitSuite { @Test public void apiMustBeUsableFromJava() { final JavaSetup javaSetting = new JavaSetup("Jasmine Rice"); - final Optional result = ActorSystemSetup.create() - .withSetup(javaSetting) - .get(JavaSetup.class); + final Optional result = + ActorSystemSetup.create().withSetup(javaSetting).get(JavaSetup.class); assertTrue(result.isPresent()); assertEquals(result.get(), javaSetting); - } - } diff --git a/akka-actor-tests/src/test/java/akka/event/ActorWithMDC.java b/akka-actor-tests/src/test/java/akka/event/ActorWithMDC.java index 52a895ec78..7007d5325a 100644 --- a/akka-actor-tests/src/test/java/akka/event/ActorWithMDC.java +++ b/akka-actor-tests/src/test/java/akka/event/ActorWithMDC.java @@ -13,7 +13,7 @@ import java.util.Map; public class ActorWithMDC extends AbstractActor { - private final DiagnosticLoggingAdapter logger = Logging.getLogger(this); + private final DiagnosticLoggingAdapter logger = Logging.getLogger(this); @Override public Receive createReceive() { @@ -33,36 +33,34 @@ public class ActorWithMDC extends AbstractActor { logger.setMDC(mdc); switch (log.level()) { - case 1: - logger.error(log.message); - break; - case 2: - logger.warning(log.message); - break; - case 3: - logger.info(log.message); - break; - default: - logger.debug(log.message); - break; + case 1: + logger.error(log.message); + break; + case 2: + logger.warning(log.message); + break; + case 3: + logger.info(log.message); + break; + default: + logger.debug(log.message); + break; } logger.clearMDC(); } - public static class Log { - private final Object level; - public final String message; + public static class Log { + private final Object level; + public final String message; - public Log(Object level, String message) { - this.level = level; - this.message = message; - } - - public int level() { - return (Integer) this.level; - } + public Log(Object level, String message) { + this.level = level; + this.message = message; } - + public int level() { + return (Integer) this.level; + } + } } diff --git a/akka-actor-tests/src/test/java/akka/event/LoggingAdapterTest.java b/akka-actor-tests/src/test/java/akka/event/LoggingAdapterTest.java index 42f0801163..0b67a41307 100644 --- a/akka-actor-tests/src/test/java/akka/event/LoggingAdapterTest.java +++ b/akka-actor-tests/src/test/java/akka/event/LoggingAdapterTest.java @@ -27,134 +27,143 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; - public class LoggingAdapterTest extends JUnitSuite { - private static final Config config = ConfigFactory.parseString( - "akka.loglevel = DEBUG\n" + - "akka.actor.serialize-messages = off" - ); + private static final Config config = + ConfigFactory.parseString("akka.loglevel = DEBUG\n" + "akka.actor.serialize-messages = off"); - @Rule - public AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("LoggingAdapterTest", config); + @Rule + public AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("LoggingAdapterTest", config); - private ActorSystem system = null; + private ActorSystem system = null; - @Before - public void beforeEach() { - system = actorSystemResource.getSystem(); - } + @Before + public void beforeEach() { + system = actorSystemResource.getSystem(); + } - @Test - public void mustFormatMessage() { - final LoggingAdapter log = Logging.getLogger(system, this); - new LogJavaTestKit(system) {{ - system.getEventStream().subscribe(getRef(), LogEvent.class); - log.error("One arg message: {}", "the arg"); - expectLog(ErrorLevel(), "One arg message: the arg"); + @Test + public void mustFormatMessage() { + final LoggingAdapter log = Logging.getLogger(system, this); + new LogJavaTestKit(system) { + { + system.getEventStream().subscribe(getRef(), LogEvent.class); + log.error("One arg message: {}", "the arg"); + expectLog(ErrorLevel(), "One arg message: the arg"); - Throwable cause = new IllegalStateException("This state is illegal") { - @Override - public synchronized Throwable fillInStackTrace() { - return this; // no stack trace - } + Throwable cause = + new IllegalStateException("This state is illegal") { + @Override + public synchronized Throwable fillInStackTrace() { + return this; // no stack trace + } }; - log.error(cause, "Two args message: {}, {}", "an arg", "another arg"); - expectLog(ErrorLevel(), "Two args message: an arg, another arg", cause); + log.error(cause, "Two args message: {}, {}", "an arg", "another arg"); + expectLog(ErrorLevel(), "Two args message: an arg, another arg", cause); - int[] primitiveArgs = {10, 20, 30}; - log.warning("Args as array of primitives: {}, {}, {}", primitiveArgs); - expectLog(WarningLevel(), "Args as array of primitives: 10, 20, 30"); + int[] primitiveArgs = {10, 20, 30}; + log.warning("Args as array of primitives: {}, {}, {}", primitiveArgs); + expectLog(WarningLevel(), "Args as array of primitives: 10, 20, 30"); - Date now = new Date(); - UUID uuid = UUID.randomUUID(); - Object[] objArgs = {"A String", now, uuid}; - log.info("Args as array of objects: {}, {}, {}", objArgs); - expectLog(InfoLevel(), "Args as array of objects: A String, " + now.toString() + ", " + uuid.toString()); + Date now = new Date(); + UUID uuid = UUID.randomUUID(); + Object[] objArgs = {"A String", now, uuid}; + log.info("Args as array of objects: {}, {}, {}", objArgs); + expectLog( + InfoLevel(), + "Args as array of objects: A String, " + now.toString() + ", " + uuid.toString()); - log.debug("Four args message: {}, {}, {}, {}", 1, 2, 3, 4); - expectLog(DebugLevel(), "Four args message: 1, 2, 3, 4"); + log.debug("Four args message: {}, {}, {}, {}", 1, 2, 3, 4); + expectLog(DebugLevel(), "Four args message: 1, 2, 3, 4"); + } + }; + } - }}; + @Test + public void mustCallMdcForEveryLog() throws Exception { + new LogJavaTestKit(system) { + { + system.getEventStream().subscribe(getRef(), LogEvent.class); + ActorRef ref = system.actorOf(Props.create(ActorWithMDC.class)); + + ref.tell(new Log(ErrorLevel(), "An Error"), system.deadLetters()); + expectLog(ErrorLevel(), "An Error", "{messageLength=8}"); + ref.tell(new Log(WarningLevel(), "A Warning"), system.deadLetters()); + expectLog(WarningLevel(), "A Warning", "{messageLength=9}"); + ref.tell(new Log(InfoLevel(), "Some Info"), system.deadLetters()); + expectLog(InfoLevel(), "Some Info", "{messageLength=9}"); + ref.tell(new Log(DebugLevel(), "No MDC for 4th call"), system.deadLetters()); + expectLog(DebugLevel(), "No MDC for 4th call"); + ref.tell( + new Log(Logging.DebugLevel(), "And now yes, a debug with MDC"), system.deadLetters()); + expectLog(DebugLevel(), "And now yes, a debug with MDC", "{messageLength=29}"); + } + }; + } + + @Test + public void mustSupportMdcNull() throws Exception { + new LogJavaTestKit(system) { + { + system.getEventStream().subscribe(getRef(), LogEvent.class); + ActorRef ref = system.actorOf(Props.create(ActorWithMDC.class)); + + ref.tell(new Log(InfoLevel(), "Null MDC"), system.deadLetters()); + expectLog(InfoLevel(), "Null MDC", "{}"); + } + }; + } + + /* + * #3671: Let the application specify custom MDC values + * Java backward compatibility check + */ + @Test + public void mustBeAbleToCreateLogEventsWithOldConstructor() throws Exception { + assertNotNull(new Error(new Exception(), "logSource", this.getClass(), "The message")); + assertNotNull(new Error("logSource", this.getClass(), "The message")); + assertNotNull(new Warning("logSource", this.getClass(), "The message")); + assertNotNull(new Info("logSource", this.getClass(), "The message")); + assertNotNull(new Debug("logSource", this.getClass(), "The message")); + } + + private static class LogJavaTestKit extends TestKit { + + private static final String emptyMDC = "{}"; + + public LogJavaTestKit(ActorSystem system) { + super(system); } - @Test - public void mustCallMdcForEveryLog() throws Exception { - new LogJavaTestKit(system) {{ - system.getEventStream().subscribe(getRef(), LogEvent.class); - ActorRef ref = system.actorOf(Props.create(ActorWithMDC.class)); - - ref.tell(new Log(ErrorLevel(), "An Error"), system.deadLetters()); - expectLog(ErrorLevel(), "An Error", "{messageLength=8}"); - ref.tell(new Log(WarningLevel(), "A Warning"), system.deadLetters()); - expectLog(WarningLevel(), "A Warning", "{messageLength=9}"); - ref.tell(new Log(InfoLevel(), "Some Info"), system.deadLetters()); - expectLog(InfoLevel(), "Some Info", "{messageLength=9}"); - ref.tell(new Log(DebugLevel(), "No MDC for 4th call"), system.deadLetters()); - expectLog(DebugLevel(), "No MDC for 4th call"); - ref.tell(new Log(Logging.DebugLevel(), "And now yes, a debug with MDC"), system.deadLetters()); - expectLog(DebugLevel(), "And now yes, a debug with MDC", "{messageLength=29}"); - }}; + void expectLog(Object level, String message) { + expectLog(level, message, null, emptyMDC); } - @Test - public void mustSupportMdcNull() throws Exception { - new LogJavaTestKit(system) {{ - system.getEventStream().subscribe(getRef(), LogEvent.class); - ActorRef ref = system.actorOf(Props.create(ActorWithMDC.class)); - - ref.tell(new Log(InfoLevel(), "Null MDC"), system.deadLetters()); - expectLog(InfoLevel(), "Null MDC", "{}"); - }}; + void expectLog(Object level, String message, Throwable cause) { + expectLog(level, message, cause, emptyMDC); } - /* - * #3671: Let the application specify custom MDC values - * Java backward compatibility check - */ - @Test - public void mustBeAbleToCreateLogEventsWithOldConstructor() throws Exception { - assertNotNull(new Error(new Exception(), "logSource", this.getClass(), "The message")); - assertNotNull(new Error("logSource", this.getClass(), "The message")); - assertNotNull(new Warning("logSource", this.getClass(), "The message")); - assertNotNull(new Info("logSource", this.getClass(), "The message")); - assertNotNull(new Debug("logSource", this.getClass(), "The message")); + void expectLog(Object level, String message, String mdc) { + expectLog(level, message, null, mdc); } - private static class LogJavaTestKit extends TestKit { - - private static final String emptyMDC = "{}"; - - public LogJavaTestKit(ActorSystem system) { - super(system); - } - - void expectLog(Object level, String message) { - expectLog(level, message, null, emptyMDC); - } - - void expectLog(Object level, String message, Throwable cause) { - expectLog(level, message, cause, emptyMDC); - } - - void expectLog(Object level, String message, String mdc) { - expectLog(level, message, null, mdc); - } - - void expectLog(final Object level, final String message, final Throwable cause, final String mdc) { - expectMsgPF(Duration.ofSeconds(3), "LogEvent", event -> { - LogEvent log = (LogEvent) event; - assertEquals(message, log.message()); - assertEquals(level, log.level()); - assertEquals(mdc, log.getMDC().toString()); - if(cause != null) { - Error error = (Error) log; - assertSame(cause, error.cause()); - } - return null; - }); - } + void expectLog( + final Object level, final String message, final Throwable cause, final String mdc) { + expectMsgPF( + Duration.ofSeconds(3), + "LogEvent", + event -> { + LogEvent log = (LogEvent) event; + assertEquals(message, log.message()); + assertEquals(level, log.level()); + assertEquals(mdc, log.getMDC().toString()); + if (cause != null) { + Error error = (Error) log; + assertSame(cause, error.cause()); + } + return null; + }); } + } } - diff --git a/akka-actor-tests/src/test/java/akka/japi/JavaAPITestBase.java b/akka-actor-tests/src/test/java/akka/japi/JavaAPITestBase.java index 0cb099d1ba..23e78db2c9 100644 --- a/akka-actor-tests/src/test/java/akka/japi/JavaAPITestBase.java +++ b/akka-actor-tests/src/test/java/akka/japi/JavaAPITestBase.java @@ -41,8 +41,7 @@ public class JavaAPITestBase extends JUnitSuite { @Test public void shouldEnterForLoop() { - for (@SuppressWarnings("unused") - String s : Option.some("abc")) { + for (@SuppressWarnings("unused") String s : Option.some("abc")) { return; } org.junit.Assert.fail("for-loop not entered"); @@ -50,8 +49,7 @@ public class JavaAPITestBase extends JUnitSuite { @Test public void shouldNotEnterForLoop() { - for (@SuppressWarnings("unused") - Object o : Option.none()) { + for (@SuppressWarnings("unused") Object o : Option.none()) { org.junit.Assert.fail("for-loop entered"); } } @@ -63,16 +61,20 @@ public class JavaAPITestBase extends JUnitSuite { @Test public void mustBeAbleToGetNoLogging() { - LoggingAdapter a = NoLogging.getInstance(); - assertNotNull(a); + LoggingAdapter a = NoLogging.getInstance(); + assertNotNull(a); } - + @Test public void mustBeAbleToUseCurrentSystem() { - assertNull(JavaSerializer.currentSystem().withValue(null, new Callable() { - public ExtendedActorSystem call() { - return JavaSerializer.currentSystem().value(); - } - })); + assertNull( + JavaSerializer.currentSystem() + .withValue( + null, + new Callable() { + public ExtendedActorSystem call() { + return JavaSerializer.currentSystem().value(); + } + })); } } diff --git a/akka-actor-tests/src/test/java/akka/japi/MatchBuilderTest.java b/akka-actor-tests/src/test/java/akka/japi/MatchBuilderTest.java index 670e588de2..cc688ab1cc 100644 --- a/akka-actor-tests/src/test/java/akka/japi/MatchBuilderTest.java +++ b/akka-actor-tests/src/test/java/akka/japi/MatchBuilderTest.java @@ -16,31 +16,40 @@ import static org.junit.Assert.*; public class MatchBuilderTest extends JUnitSuite { - @Rule - public ExpectedException exception = ExpectedException.none(); + @Rule public ExpectedException exception = ExpectedException.none(); @Test public void shouldPassBasicMatchTest() { - Match pf = Match.create(Match.match(Integer.class, new FI.Apply() { - @Override - public Double apply(Integer integer) { - return integer * 10.0; - } - }).match(Number.class, new FI.Apply() { - @Override - public Double apply(Number number) { - return number.doubleValue() * (-10.0); - } - })); + Match pf = + Match.create( + Match.match( + Integer.class, + new FI.Apply() { + @Override + public Double apply(Integer integer) { + return integer * 10.0; + } + }) + .match( + Number.class, + new FI.Apply() { + @Override + public Double apply(Number number) { + return number.doubleValue() * (-10.0); + } + })); - assertTrue("An integer should be multiplied by 10", new Double(47110).equals(pf.match(new Integer(4711)))); - assertTrue("A double should be multiplied by -10", new Double(-47110).equals(pf.match(new Double(4711)))); + assertTrue( + "An integer should be multiplied by 10", + new Double(47110).equals(pf.match(new Integer(4711)))); + assertTrue( + "A double should be multiplied by -10", + new Double(-47110).equals(pf.match(new Double(4711)))); exception.expect(MatchError.class); assertFalse("A string should throw a MatchError", new Double(4711).equals(pf.match("4711"))); } - static class GenericClass { T val; @@ -51,32 +60,44 @@ public class MatchBuilderTest extends JUnitSuite { @Test public void shouldHandleMatchOnGenericClass() { - Match pf = Match.create(Match.matchUnchecked(GenericClass.class, new FI.Apply, String>() { - @Override - public String apply(GenericClass stringGenericClass) { - return stringGenericClass.val; - } - })); + Match pf = + Match.create( + Match.matchUnchecked( + GenericClass.class, + new FI.Apply, String>() { + @Override + public String apply(GenericClass stringGenericClass) { + return stringGenericClass.val; + } + })); - assertTrue("String value should be extract from GenericMessage", "A".equals(pf.match(new GenericClass("A")))); + assertTrue( + "String value should be extract from GenericMessage", + "A".equals(pf.match(new GenericClass("A")))); } - @Test public void shouldHandleMatchWithPredicateOnGenericClass() { - Match pf = Match.create(Match.matchUnchecked(GenericClass.class, new FI.TypedPredicate>() { - @Override - public boolean defined(GenericClass genericClass) { - return !genericClass.val.isEmpty(); - } - }, new FI.Apply, String>() { - @Override - public String apply(GenericClass stringGenericClass) { - return stringGenericClass.val; - } - })); + Match pf = + Match.create( + Match.matchUnchecked( + GenericClass.class, + new FI.TypedPredicate>() { + @Override + public boolean defined(GenericClass genericClass) { + return !genericClass.val.isEmpty(); + } + }, + new FI.Apply, String>() { + @Override + public String apply(GenericClass stringGenericClass) { + return stringGenericClass.val; + } + })); exception.expect(MatchError.class); - assertTrue("empty GenericMessage should throw match error", "".equals(pf.match(new GenericClass("")))); + assertTrue( + "empty GenericMessage should throw match error", + "".equals(pf.match(new GenericClass("")))); } } diff --git a/akka-actor-tests/src/test/java/akka/japi/ThrowablesTest.java b/akka-actor-tests/src/test/java/akka/japi/ThrowablesTest.java index ad22c38646..2a587f6079 100644 --- a/akka-actor-tests/src/test/java/akka/japi/ThrowablesTest.java +++ b/akka-actor-tests/src/test/java/akka/japi/ThrowablesTest.java @@ -9,19 +9,19 @@ import org.junit.Test; import scala.util.control.ControlThrowable; public class ThrowablesTest { - @Test - public void testIsNonFatal(){ - Assert.assertTrue(Throwables.isNonFatal(new IllegalArgumentException("isNonFatal"))); - } + @Test + public void testIsNonFatal() { + Assert.assertTrue(Throwables.isNonFatal(new IllegalArgumentException("isNonFatal"))); + } - private static class ControlThrowableImpl extends Throwable implements ControlThrowable{} + private static class ControlThrowableImpl extends Throwable implements ControlThrowable {} - @Test - public void testIsFatal(){ - Assert.assertTrue(Throwables.isFatal(new StackOverflowError("fatal"))); - Assert.assertTrue(Throwables.isFatal(new ThreadDeath())); - Assert.assertTrue(Throwables.isFatal(new InterruptedException("fatal"))); - Assert.assertTrue(Throwables.isFatal(new LinkageError("fatal"))); - Assert.assertTrue(Throwables.isFatal(new ControlThrowableImpl())); - } + @Test + public void testIsFatal() { + Assert.assertTrue(Throwables.isFatal(new StackOverflowError("fatal"))); + Assert.assertTrue(Throwables.isFatal(new ThreadDeath())); + Assert.assertTrue(Throwables.isFatal(new InterruptedException("fatal"))); + Assert.assertTrue(Throwables.isFatal(new LinkageError("fatal"))); + Assert.assertTrue(Throwables.isFatal(new ControlThrowableImpl())); + } } diff --git a/akka-actor-tests/src/test/java/akka/japi/pf/PFBuilderTest.java b/akka-actor-tests/src/test/java/akka/japi/pf/PFBuilderTest.java index 05a03c1288..121aa2557c 100644 --- a/akka-actor-tests/src/test/java/akka/japi/pf/PFBuilderTest.java +++ b/akka-actor-tests/src/test/java/akka/japi/pf/PFBuilderTest.java @@ -15,10 +15,11 @@ public class PFBuilderTest extends JUnitSuite { @Test public void pfbuilder_matchAny_should_infer_declared_input_type_for_lambda() { - PartialFunction pf = new PFBuilder() - .matchEquals("hello", s -> 1) - .matchAny(s -> Integer.valueOf(s)) - .build(); + PartialFunction pf = + new PFBuilder() + .matchEquals("hello", s -> 1) + .matchAny(s -> Integer.valueOf(s)) + .build(); assertTrue(pf.isDefinedAt("hello")); assertTrue(pf.isDefinedAt("42")); diff --git a/akka-actor-tests/src/test/java/akka/japi/pf/ReceiveBuilderTest.java b/akka-actor-tests/src/test/java/akka/japi/pf/ReceiveBuilderTest.java index be46aef42c..571f37dfef 100644 --- a/akka-actor-tests/src/test/java/akka/japi/pf/ReceiveBuilderTest.java +++ b/akka-actor-tests/src/test/java/akka/japi/pf/ReceiveBuilderTest.java @@ -18,12 +18,14 @@ import static org.junit.Assert.*; public class ReceiveBuilderTest extends JUnitSuite { public static interface Msg {} + public static class Msg1 implements Msg { @Override public String toString() { return "Msg1"; } } + public static class Msg2 implements Msg { public final String value; @@ -41,18 +43,13 @@ public class ReceiveBuilderTest extends JUnitSuite { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; Msg2 other = (Msg2) obj; if (value == null) { - if (other.value != null) - return false; - } else if (!value.equals(other.value)) - return false; + if (other.value != null) return false; + } else if (!value.equals(other.value)) return false; return true; } @@ -60,7 +57,6 @@ public class ReceiveBuilderTest extends JUnitSuite { public String toString() { return "Msg2 [value=" + value + "]"; } - } // using instance variable, because lambdas can only modify final fields @@ -76,11 +72,10 @@ public class ReceiveBuilderTest extends JUnitSuite { result = r; } - @Before public void beforeEach() { result = ""; - } + } @Test public void shouldNotMatchWhenEmpty() { @@ -91,9 +86,7 @@ public class ReceiveBuilderTest extends JUnitSuite { @Test public void shouldMatchByClass() { - Receive rcv = ReceiveBuilder.create() - .match(Msg1.class, m -> result("match Msg1")) - .build(); + Receive rcv = ReceiveBuilder.create().match(Msg1.class, m -> result("match Msg1")).build(); assertTrue(rcv.onMessage().isDefinedAt(new Msg1())); rcv.onMessage().apply(new Msg1()); assertEquals("match Msg1", result()); @@ -105,9 +98,7 @@ public class ReceiveBuilderTest extends JUnitSuite { @Test public void shouldMatchBySubclass() { - Receive rcv = ReceiveBuilder.create() - .match(Msg.class, m -> result("match Msg")) - .build(); + Receive rcv = ReceiveBuilder.create().match(Msg.class, m -> result("match Msg")).build(); assertTrue(rcv.onMessage().isDefinedAt(new Msg1())); rcv.onMessage().apply(new Msg1()); assertEquals("match Msg", result()); @@ -134,11 +125,12 @@ public class ReceiveBuilderTest extends JUnitSuite { @Test public void shouldMatchDelegatingToSpecificMethod() { - Receive rcv = ReceiveBuilder.create() - .match(Msg1.class, this::handleMsg) - .match(Msg2.class, this::handleMsg) - .match(Msg.class, this::handleMsg) - .build(); + Receive rcv = + ReceiveBuilder.create() + .match(Msg1.class, this::handleMsg) + .match(Msg2.class, this::handleMsg) + .match(Msg.class, this::handleMsg) + .build(); assertTrue(rcv.onMessage().isDefinedAt(new Msg1())); rcv.onMessage().apply(new Msg1()); assertEquals("match Msg1", result()); @@ -158,10 +150,11 @@ public class ReceiveBuilderTest extends JUnitSuite { @Test public void shouldMatchDelegatingToGeneralMethod() { - Receive rcv = ReceiveBuilder.create() - .match(Msg1.class, this::anotherHandleMsg) - .match(Msg2.class, this::anotherHandleMsg) - .build(); + Receive rcv = + ReceiveBuilder.create() + .match(Msg1.class, this::anotherHandleMsg) + .match(Msg2.class, this::anotherHandleMsg) + .build(); assertTrue(rcv.onMessage().isDefinedAt(new Msg1())); rcv.onMessage().apply(new Msg1()); assertEquals("match Msg1", result()); @@ -173,10 +166,11 @@ public class ReceiveBuilderTest extends JUnitSuite { @Test public void shouldMatchByPredicate() { - Receive rcv = ReceiveBuilder.create() - .match(Msg1.class, m -> true, m -> result("match Msg1")) - .match(Msg2.class, m -> m.value.equals("foo"), m -> result("match Msg2")) - .build(); + Receive rcv = + ReceiveBuilder.create() + .match(Msg1.class, m -> true, m -> result("match Msg1")) + .match(Msg2.class, m -> m.value.equals("foo"), m -> result("match Msg2")) + .build(); assertTrue(rcv.onMessage().isDefinedAt(new Msg1())); rcv.onMessage().apply(new Msg1()); assertEquals("match Msg1", result()); @@ -191,29 +185,31 @@ public class ReceiveBuilderTest extends JUnitSuite { assertFalse(rcv.onMessage().isDefinedAt(42)); } - private boolean externalPredicateAlwaysTrue(){ - return true; + private boolean externalPredicateAlwaysTrue() { + return true; } @Test - public void shouldMatchByExternalPredicate(){ - Receive rcv = ReceiveBuilder.create() - .match(Msg1.class, this::externalPredicateAlwaysTrue, m -> result("match Msg1")) - .build(); - assertTrue(rcv.onMessage().isDefinedAt(new Msg1())); - rcv.onMessage().apply(new Msg1()); - assertEquals("match Msg1", result()); - assertFalse(rcv.onMessage().isDefinedAt(new Msg2("foo"))); + public void shouldMatchByExternalPredicate() { + Receive rcv = + ReceiveBuilder.create() + .match(Msg1.class, this::externalPredicateAlwaysTrue, m -> result("match Msg1")) + .build(); + assertTrue(rcv.onMessage().isDefinedAt(new Msg1())); + rcv.onMessage().apply(new Msg1()); + assertEquals("match Msg1", result()); + assertFalse(rcv.onMessage().isDefinedAt(new Msg2("foo"))); } @Test public void shouldMatchEquals() { Msg2 msg2 = new Msg2("foo"); - Receive rcv = ReceiveBuilder.create() - .matchEquals(msg2, m -> result("match msg2")) - .matchEquals("foo", m -> result("match foo")) - .matchEquals(17, m -> result("match 17")) - .build(); + Receive rcv = + ReceiveBuilder.create() + .matchEquals(msg2, m -> result("match msg2")) + .matchEquals("foo", m -> result("match foo")) + .matchEquals(17, m -> result("match 17")) + .build(); assertTrue(rcv.onMessage().isDefinedAt(new Msg2("foo"))); rcv.onMessage().apply(new Msg2("foo")); assertEquals("match msg2", result()); @@ -233,10 +229,11 @@ public class ReceiveBuilderTest extends JUnitSuite { @Test public void shouldMatchAny() { - Receive rcv = ReceiveBuilder.create() - .match(Msg1.class, m -> result("match Msg1")) - .matchAny(m -> result("match any")) - .build(); + Receive rcv = + ReceiveBuilder.create() + .match(Msg1.class, m -> result("match Msg1")) + .matchAny(m -> result("match any")) + .build(); assertTrue(rcv.onMessage().isDefinedAt(new Msg1())); rcv.onMessage().apply(new Msg1()); assertEquals("match Msg1", result()); @@ -251,11 +248,14 @@ public class ReceiveBuilderTest extends JUnitSuite { @Test public void shouldMatchUnchecked() { - Receive rcv = ReceiveBuilder.create() - .matchUnchecked(List.class, (List list) -> { - result("match List"); - }) - .build(); + Receive rcv = + ReceiveBuilder.create() + .matchUnchecked( + List.class, + (List list) -> { + result("match List"); + }) + .build(); List list = Arrays.asList("foo"); assertTrue(rcv.onMessage().isDefinedAt(list)); rcv.onMessage().apply(list); @@ -265,11 +265,14 @@ public class ReceiveBuilderTest extends JUnitSuite { @Test(expected = ClassCastException.class) public void shouldThrowWhenUncheckedWithWrongTypes() { // note that this doesn't compile with ordinary match - Receive rcv = ReceiveBuilder.create() - .matchUnchecked(String.class, (Integer i) -> { - result(String.valueOf(i + 2)); - }) - .build(); + Receive rcv = + ReceiveBuilder.create() + .matchUnchecked( + String.class, + (Integer i) -> { + result(String.valueOf(i + 2)); + }) + .build(); assertTrue(rcv.onMessage().isDefinedAt("foo")); rcv.onMessage().apply("foo"); } diff --git a/akka-actor-tests/src/test/java/akka/pattern/CircuitBreakerTest.java b/akka-actor-tests/src/test/java/akka/pattern/CircuitBreakerTest.java index 48d1c732e1..6d0b6bee90 100644 --- a/akka-actor-tests/src/test/java/akka/pattern/CircuitBreakerTest.java +++ b/akka-actor-tests/src/test/java/akka/pattern/CircuitBreakerTest.java @@ -25,8 +25,8 @@ import static org.junit.Assert.assertEquals; public class CircuitBreakerTest extends JUnitSuite { @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("JavaAPI", AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("JavaAPI", AkkaSpec.testConf()); private final ActorSystem system = actorSystemResource.getSystem(); @@ -34,27 +34,37 @@ public class CircuitBreakerTest extends JUnitSuite { public void useCircuitBreakerWithCompletableFuture() throws Exception { final Duration fiveSeconds = Duration.ofSeconds(5); final Duration fiveHundredMillis = Duration.ofMillis(500); - final CircuitBreaker breaker = new CircuitBreaker(system.dispatcher(), system.scheduler(), 1, fiveSeconds, fiveHundredMillis); + final CircuitBreaker breaker = + new CircuitBreaker( + system.dispatcher(), system.scheduler(), 1, fiveSeconds, fiveHundredMillis); final CompletableFuture f = new CompletableFuture<>(); f.complete("hello"); final CompletionStage res = breaker.callWithCircuitBreakerCS(() -> f); - assertEquals("hello", Await.result(FutureConverters.toScala(res), JavaDurationConverters.asFiniteDuration(fiveSeconds))); + assertEquals( + "hello", + Await.result( + FutureConverters.toScala(res), JavaDurationConverters.asFiniteDuration(fiveSeconds))); } @Test public void useCircuitBreakerWithCompletableFutureAndCustomDefineFailure() throws Exception { final Duration fiveSeconds = Duration.ofSeconds(5); final Duration fiveHundredMillis = Duration.ofMillis(500); - final CircuitBreaker breaker = new CircuitBreaker(system.dispatcher(), system.scheduler(), 1, fiveSeconds, fiveHundredMillis); + final CircuitBreaker breaker = + new CircuitBreaker( + system.dispatcher(), system.scheduler(), 1, fiveSeconds, fiveHundredMillis); final BiFunction, Optional, java.lang.Boolean> fn = - (result, err) -> (result.isPresent() && result.get().equals("hello")); + (result, err) -> (result.isPresent() && result.get().equals("hello")); final CompletableFuture f = new CompletableFuture<>(); f.complete("hello"); final CompletionStage res = breaker.callWithCircuitBreakerCS(() -> f, fn); - assertEquals("hello", Await.result(FutureConverters.toScala(res), JavaDurationConverters.asFiniteDuration(fiveSeconds))); + assertEquals( + "hello", + Await.result( + FutureConverters.toScala(res), JavaDurationConverters.asFiniteDuration(fiveSeconds))); assertEquals(1, breaker.currentFailureCount()); } } diff --git a/akka-actor-tests/src/test/java/akka/pattern/PatternsTest.java b/akka-actor-tests/src/test/java/akka/pattern/PatternsTest.java index 4441038ddb..e7aa572fc8 100644 --- a/akka-actor-tests/src/test/java/akka/pattern/PatternsTest.java +++ b/akka-actor-tests/src/test/java/akka/pattern/PatternsTest.java @@ -27,449 +27,426 @@ import static akka.pattern.Patterns.pipe; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.Assert.assertEquals; -/** - * Copyright (C) 2009-2018 Lightbend Inc. - */ +/** Copyright (C) 2009-2018 Lightbend Inc. */ public class PatternsTest extends JUnitSuite { - public static final class ExplicitAskTestActor extends AbstractActor { + public static final class ExplicitAskTestActor extends AbstractActor { - public static final class Message implements NoSerializationVerificationNeeded { + public static final class Message implements NoSerializationVerificationNeeded { - public Message(final String text, ActorRef replyTo) { - this.text = text; - this.replyTo = replyTo; - } + public Message(final String text, ActorRef replyTo) { + this.text = text; + this.replyTo = replyTo; + } - public final String text; - public final ActorRef replyTo; - } - - public Receive createReceive() { - return receiveBuilder() - .match(Message.class, message -> message.replyTo.tell(message.text, getSelf())) - .build(); - } + public final String text; + public final ActorRef replyTo; } - public static final class StopActor extends AbstractActor { - - @Override - public Receive createReceive() { - return receiveBuilder() - .match(String.class, message -> sender().tell("Pong", getSelf())) - .build(); - } + public Receive createReceive() { + return receiveBuilder() + .match(Message.class, message -> message.replyTo.tell(message.text, getSelf())) + .build(); } + } - @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("JavaAPI", - AkkaSpec.testConf()); + public static final class StopActor extends AbstractActor { - private final ActorSystem system = actorSystemResource.getSystem(); - - private final ExecutionContext ec = system.dispatcher(); - - - @Test - public void useAsk() throws Exception { - ActorRef testActor = system.actorOf(Props.create(JavaAPITestActor.class), "test"); - scala.concurrent.duration.Duration timeout = scala.concurrent.duration.Duration.create(3, "seconds"); - assertEquals("Ask should return expected answer", - JavaAPITestActor.ANSWER, Await.result(ask(testActor, "hey!", 3000), timeout)); + @Override + public Receive createReceive() { + return receiveBuilder() + .match(String.class, message -> sender().tell("Pong", getSelf())) + .build(); } + } - @Test - public void useAskWithActorSelection() throws Exception { - scala.concurrent.duration.Duration timeout = scala.concurrent.duration.Duration.create(3, "seconds"); - ActorRef testActor = system.actorOf(Props.create(JavaAPITestActor.class), "test2"); - ActorSelection selection = system.actorSelection("/user/test2"); - ActorIdentity id = (ActorIdentity) Await.result(ask(selection, new Identify("yo!"), 3000), timeout); - assertEquals("Ask (Identify) should return the proper ActorIdentity", testActor, id.getActorRef().get()); - } + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("JavaAPI", AkkaSpec.testConf()); - @Test - public void testCSAsk() throws Exception { - ActorRef target = system.actorOf(Props.create(JavaAPITestActor.class)); - CompletionStage result = Patterns.ask(target, "hello", Duration.ofSeconds(3)).thenApply(o -> (String)o); + private final ActorSystem system = actorSystemResource.getSystem(); - String actual = result.toCompletableFuture().get(3, SECONDS); - assertEquals(JavaAPITestActor.ANSWER, actual); - } + private final ExecutionContext ec = system.dispatcher(); - @Test - public void testCSAskWithActorSelection() throws Exception { - ActorRef target = system.actorOf(Props.create(JavaAPITestActor.class), "test3"); + @Test + public void useAsk() throws Exception { + ActorRef testActor = system.actorOf(Props.create(JavaAPITestActor.class), "test"); + scala.concurrent.duration.Duration timeout = + scala.concurrent.duration.Duration.create(3, "seconds"); + assertEquals( + "Ask should return expected answer", + JavaAPITestActor.ANSWER, + Await.result(ask(testActor, "hey!", 3000), timeout)); + } - ActorSelection selection = system.actorSelection("/user/test3"); - ActorIdentity id = Patterns.ask(selection, new Identify("hello"), Duration.ofSeconds(3)) - .toCompletableFuture() - .thenApply(o -> (ActorIdentity)o) - .get(3, SECONDS); + @Test + public void useAskWithActorSelection() throws Exception { + scala.concurrent.duration.Duration timeout = + scala.concurrent.duration.Duration.create(3, "seconds"); + ActorRef testActor = system.actorOf(Props.create(JavaAPITestActor.class), "test2"); + ActorSelection selection = system.actorSelection("/user/test2"); + ActorIdentity id = + (ActorIdentity) Await.result(ask(selection, new Identify("yo!"), 3000), timeout); + assertEquals( + "Ask (Identify) should return the proper ActorIdentity", testActor, id.getActorRef().get()); + } - assertEquals(target, id.getActorRef().get()); - } + @Test + public void testCSAsk() throws Exception { + ActorRef target = system.actorOf(Props.create(JavaAPITestActor.class)); + CompletionStage result = + Patterns.ask(target, "hello", Duration.ofSeconds(3)).thenApply(o -> (String) o); - @Test - public void testCSAskWithReplyToTimeout() throws Exception { - final String expected = "hello"; + String actual = result.toCompletableFuture().get(3, SECONDS); + assertEquals(JavaAPITestActor.ANSWER, actual); + } - final ActorRef echo = system.actorOf(Props.create(ExplicitAskTestActor.class)); - final CompletionStage response = Patterns - .askWithReplyTo( - echo, - replyTo -> new ExplicitAskTestActor.Message(expected, replyTo), - Duration.ofSeconds(3)) - .thenApply(o -> (String)o); + @Test + public void testCSAskWithActorSelection() throws Exception { + ActorRef target = system.actorOf(Props.create(JavaAPITestActor.class), "test3"); - final String actual = response.toCompletableFuture().get(3, SECONDS); - assertEquals(expected, actual); - } + ActorSelection selection = system.actorSelection("/user/test3"); + ActorIdentity id = + Patterns.ask(selection, new Identify("hello"), Duration.ofSeconds(3)) + .toCompletableFuture() + .thenApply(o -> (ActorIdentity) o) + .get(3, SECONDS); + assertEquals(target, id.getActorRef().get()); + } - @Test - public void testCSAskWithReplyToTimeoutMillis() throws Exception { - final String expected = "hello"; + @Test + public void testCSAskWithReplyToTimeout() throws Exception { + final String expected = "hello"; - final ActorRef echo = system.actorOf(Props.create(ExplicitAskTestActor.class)); - final CompletionStage response = Patterns - .askWithReplyTo( - echo, - replyTo -> new ExplicitAskTestActor.Message(expected, replyTo), - Duration.ofSeconds(3) - ) - .thenApply(o -> (String)o); + final ActorRef echo = system.actorOf(Props.create(ExplicitAskTestActor.class)); + final CompletionStage response = + Patterns.askWithReplyTo( + echo, + replyTo -> new ExplicitAskTestActor.Message(expected, replyTo), + Duration.ofSeconds(3)) + .thenApply(o -> (String) o); - final String actual = response.toCompletableFuture().get(3, SECONDS); - assertEquals(expected, actual); - } + final String actual = response.toCompletableFuture().get(3, SECONDS); + assertEquals(expected, actual); + } - @Test - public void testCSAskSelectionWithReplyToTimeoutMillis() throws Exception { - final String expected = "hello"; + @Test + public void testCSAskWithReplyToTimeoutMillis() throws Exception { + final String expected = "hello"; - final ActorRef echo = system.actorOf(Props.create(ExplicitAskTestActor.class)); - final ActorSelection selection = system.actorSelection(echo.path()); - final CompletionStage response = Patterns - .askWithReplyTo( - selection, - replyTo -> new ExplicitAskTestActor.Message(expected, replyTo), - Duration.ofSeconds(3) - ) - .thenApply(o -> (String)o); + final ActorRef echo = system.actorOf(Props.create(ExplicitAskTestActor.class)); + final CompletionStage response = + Patterns.askWithReplyTo( + echo, + replyTo -> new ExplicitAskTestActor.Message(expected, replyTo), + Duration.ofSeconds(3)) + .thenApply(o -> (String) o); - final String actual = response.toCompletableFuture().get(3, SECONDS); - assertEquals(expected, actual); - } + final String actual = response.toCompletableFuture().get(3, SECONDS); + assertEquals(expected, actual); + } - @Test - public void testAskWithReplyToTimeoutMillis() throws Exception { - final String expected = "hello"; + @Test + public void testCSAskSelectionWithReplyToTimeoutMillis() throws Exception { + final String expected = "hello"; - final ActorRef echo = system.actorOf(Props.create(ExplicitAskTestActor.class)); - final Future response = Patterns - .askWithReplyTo( - echo, - replyTo -> new ExplicitAskTestActor.Message(expected, replyTo), - 3000); + final ActorRef echo = system.actorOf(Props.create(ExplicitAskTestActor.class)); + final ActorSelection selection = system.actorSelection(echo.path()); + final CompletionStage response = + Patterns.askWithReplyTo( + selection, + replyTo -> new ExplicitAskTestActor.Message(expected, replyTo), + Duration.ofSeconds(3)) + .thenApply(o -> (String) o); + final String actual = response.toCompletableFuture().get(3, SECONDS); + assertEquals(expected, actual); + } - final Object actual = Await.result(response, FiniteDuration.apply(3, SECONDS)); - assertEquals(expected, actual); - } + @Test + public void testAskWithReplyToTimeoutMillis() throws Exception { + final String expected = "hello"; - @Test - public void testAskSelectionWithReplyToTimeoutMillis() throws Exception { - final String expected = "hello"; + final ActorRef echo = system.actorOf(Props.create(ExplicitAskTestActor.class)); + final Future response = + Patterns.askWithReplyTo( + echo, replyTo -> new ExplicitAskTestActor.Message(expected, replyTo), 3000); - final ActorRef echo = system.actorOf(Props.create(ExplicitAskTestActor.class)); - final ActorSelection selection = system.actorSelection(echo.path()); - final Future response = Patterns - .askWithReplyTo( - selection, - replyTo -> new ExplicitAskTestActor.Message(expected, replyTo), - 3000); + final Object actual = Await.result(response, FiniteDuration.apply(3, SECONDS)); + assertEquals(expected, actual); + } + @Test + public void testAskSelectionWithReplyToTimeoutMillis() throws Exception { + final String expected = "hello"; - final Object actual = Await.result(response, FiniteDuration.apply(3, SECONDS)); - assertEquals(expected, actual); - } + final ActorRef echo = system.actorOf(Props.create(ExplicitAskTestActor.class)); + final ActorSelection selection = system.actorSelection(echo.path()); + final Future response = + Patterns.askWithReplyTo( + selection, replyTo -> new ExplicitAskTestActor.Message(expected, replyTo), 3000); + final Object actual = Await.result(response, FiniteDuration.apply(3, SECONDS)); + assertEquals(expected, actual); + } - @Test - public void testAskWithReplyToTimeout() throws Exception { - final String expected = "hello"; + @Test + public void testAskWithReplyToTimeout() throws Exception { + final String expected = "hello"; - final ActorRef echo = system.actorOf(Props.create(ExplicitAskTestActor.class)); - final Future response = Patterns - .askWithReplyTo( - echo, - replyTo -> new ExplicitAskTestActor.Message(expected, replyTo), - Timeout.apply(3, SECONDS)); + final ActorRef echo = system.actorOf(Props.create(ExplicitAskTestActor.class)); + final Future response = + Patterns.askWithReplyTo( + echo, + replyTo -> new ExplicitAskTestActor.Message(expected, replyTo), + Timeout.apply(3, SECONDS)); + final Object actual = Await.result(response, FiniteDuration.apply(3, SECONDS)); + assertEquals(expected, actual); + } - final Object actual = Await.result(response, FiniteDuration.apply(3, SECONDS)); - assertEquals(expected, actual); - } + @Test + public void usePipe() throws Exception { + TestProbe probe = new TestProbe(system); + pipe(Futures.successful("ho!"), system.dispatcher()).to(probe.ref()); + probe.expectMsg("ho!"); + } - @Test - public void usePipe() throws Exception { - TestProbe probe = new TestProbe(system); - pipe(Futures.successful("ho!"), system.dispatcher()).to(probe.ref()); - probe.expectMsg("ho!"); - } + @Test + public void usePipeWithActorSelection() throws Exception { + TestProbe probe = new TestProbe(system); + ActorSelection selection = system.actorSelection(probe.ref().path()); + pipe(Futures.successful("hi!"), system.dispatcher()).to(selection); + probe.expectMsg("hi!"); + } - @Test - public void usePipeWithActorSelection() throws Exception { - TestProbe probe = new TestProbe(system); - ActorSelection selection = system.actorSelection(probe.ref().path()); - pipe(Futures.successful("hi!"), system.dispatcher()).to(selection); - probe.expectMsg("hi!"); - } + @Test + public void testCSPipeToActorRef() throws Exception { + TestProbe probe = new TestProbe(system); + CompletableFuture f = new CompletableFuture<>(); + f.complete("ho!"); + Patterns.pipe(f, ec).to(probe.ref()); + probe.expectMsg("ho!"); + } - @Test - public void testCSPipeToActorRef() throws Exception { - TestProbe probe = new TestProbe(system); - CompletableFuture f = new CompletableFuture<>(); - f.complete("ho!"); - Patterns.pipe(f, ec).to(probe.ref()); - probe.expectMsg("ho!"); - } + @Test + public void testCSPipeToActorSelection() throws Exception { + TestProbe probe = new TestProbe(system); + ActorSelection selection = system.actorSelection(probe.ref().path()); + CompletableFuture f = new CompletableFuture<>(); + f.complete("hi!"); + Patterns.pipe(f, ec).to(selection); + probe.expectMsg("hi!"); + } - @Test - public void testCSPipeToActorSelection() throws Exception { - TestProbe probe = new TestProbe(system); - ActorSelection selection = system.actorSelection(probe.ref().path()); - CompletableFuture f = new CompletableFuture<>(); - f.complete("hi!"); - Patterns.pipe(f, ec).to(selection); - probe.expectMsg("hi!"); - } + @Test + public void testRetry() throws Exception { + final String expected = "hello"; - @Test - public void testRetry() throws Exception { - final String expected = "hello"; + Future retriedFuture = + Patterns.retry( + () -> Futures.successful(expected), + 3, + scala.concurrent.duration.Duration.apply(200, "millis"), + system.scheduler(), + ec); - Future retriedFuture = - Patterns.retry( - () -> Futures.successful(expected), - 3, - scala.concurrent.duration.Duration.apply(200, "millis"), - system.scheduler(), ec); + String actual = Await.result(retriedFuture, FiniteDuration.apply(3, SECONDS)); + assertEquals(expected, actual); + } - String actual = Await.result(retriedFuture, FiniteDuration.apply(3, SECONDS)); - assertEquals(expected, actual); - } + @Test + public void testCSRetry() throws Exception { + final String expected = "hello"; - @Test - public void testCSRetry() throws Exception { - final String expected = "hello"; + Callable> attempt = () -> CompletableFuture.completedFuture(expected); - Callable> attempt = () -> CompletableFuture.completedFuture(expected); + CompletionStage retriedStage = + Patterns.retry(attempt, 3, Duration.ofMillis(200), system.scheduler(), ec); - CompletionStage retriedStage = - Patterns.retry( - attempt, - 3, - Duration.ofMillis(200), - system.scheduler(), ec); + final String actual = retriedStage.toCompletableFuture().get(3, SECONDS); + assertEquals(expected, actual); + } - final String actual = retriedStage.toCompletableFuture().get(3, SECONDS); - assertEquals(expected, actual); - } + @Test(expected = IllegalStateException.class) + public void testAfterFailedCallable() throws Exception { + Callable> failedCallable = + () -> Futures.failed(new IllegalStateException("Illegal!")); - @Test(expected = IllegalStateException.class) - public void testAfterFailedCallable() throws Exception { - Callable> failedCallable = () -> Futures.failed(new IllegalStateException("Illegal!")); + Future delayedFuture = + Patterns.after( + scala.concurrent.duration.Duration.create(200, "millis"), + system.scheduler(), + ec, + failedCallable); - Future delayedFuture = Patterns - .after( - scala.concurrent.duration.Duration.create(200, "millis"), - system.scheduler(), - ec, - failedCallable); + Future resultFuture = Futures.firstCompletedOf(Arrays.asList(delayedFuture), ec); + Await.result(resultFuture, scala.concurrent.duration.FiniteDuration.apply(3, SECONDS)); + } - Future resultFuture = Futures.firstCompletedOf(Arrays.asList(delayedFuture), ec); - Await.result(resultFuture, scala.concurrent.duration.FiniteDuration.apply(3, SECONDS)); - } + @Test(expected = IllegalStateException.class) + public void testAfterFailedFuture() throws Exception { + Future failedFuture = Futures.failed(new IllegalStateException("Illegal!")); - @Test(expected = IllegalStateException.class) - public void testAfterFailedFuture() throws Exception { - Future failedFuture = Futures.failed(new IllegalStateException("Illegal!")); + Future delayedFuture = + Patterns.after( + scala.concurrent.duration.Duration.create(200, "millis"), + system.scheduler(), + ec, + failedFuture); - Future delayedFuture = Patterns - .after( - scala.concurrent.duration.Duration.create(200, "millis"), - system.scheduler(), - ec, - failedFuture); + Future resultFuture = Futures.firstCompletedOf(Arrays.asList(delayedFuture), ec); + Await.result(resultFuture, FiniteDuration.apply(3, SECONDS)); + } - Future resultFuture = Futures.firstCompletedOf(Arrays.asList(delayedFuture), ec); - Await.result(resultFuture, FiniteDuration.apply(3, SECONDS)); - } + @Test + public void testAfterSuccessfulCallable() throws Exception { + final String expected = "Hello"; - @Test - public void testAfterSuccessfulCallable() throws Exception { - final String expected = "Hello"; + Future delayedFuture = + Patterns.after( + scala.concurrent.duration.Duration.create(200, "millis"), + system.scheduler(), + ec, + () -> Futures.successful(expected)); - Future delayedFuture = Patterns - .after( - scala.concurrent.duration.Duration.create(200, "millis"), - system.scheduler(), - ec, - () -> Futures.successful(expected)); + Future resultFuture = Futures.firstCompletedOf(Arrays.asList(delayedFuture), ec); + final String actual = Await.result(resultFuture, FiniteDuration.apply(3, SECONDS)); - Future resultFuture = Futures.firstCompletedOf(Arrays.asList(delayedFuture), ec); - final String actual = Await.result(resultFuture, FiniteDuration.apply(3, SECONDS)); + assertEquals(expected, actual); + } - assertEquals(expected, actual); - } + @Test + public void testAfterSuccessfulFuture() throws Exception { + final String expected = "Hello"; - @Test - public void testAfterSuccessfulFuture() throws Exception { - final String expected = "Hello"; + Future delayedFuture = + Patterns.after( + scala.concurrent.duration.Duration.create(200, "millis"), + system.scheduler(), + ec, + Futures.successful(expected)); - Future delayedFuture = Patterns - .after( - scala.concurrent.duration.Duration.create(200, "millis"), - system.scheduler(), - ec, - Futures.successful(expected)); + Future resultFuture = Futures.firstCompletedOf(Arrays.asList(delayedFuture), ec); - Future resultFuture = Futures.firstCompletedOf(Arrays.asList(delayedFuture), ec); + final String actual = Await.result(resultFuture, FiniteDuration.apply(3, SECONDS)); + assertEquals(expected, actual); + } - final String actual = Await.result(resultFuture, FiniteDuration.apply(3, SECONDS)); - assertEquals(expected, actual); - } + @Test + public void testAfterFiniteDuration() throws Exception { + final String expected = "Hello"; - @Test - public void testAfterFiniteDuration() throws Exception { - final String expected = "Hello"; + Future delayedFuture = + Patterns.after( + scala.concurrent.duration.Duration.create(200, "millis"), + system.scheduler(), + ec, + Futures.successful("world")); - Future delayedFuture = Patterns - .after( - scala.concurrent.duration.Duration.create(200, "millis"), - system.scheduler(), - ec, - Futures.successful("world")); + Future immediateFuture = Futures.future(() -> expected, ec); - Future immediateFuture = Futures.future(() -> expected, ec); + Future resultFuture = + Futures.firstCompletedOf(Arrays.asList(delayedFuture, immediateFuture), ec); - Future resultFuture = Futures.firstCompletedOf(Arrays.asList(delayedFuture, immediateFuture), ec); + final String actual = Await.result(resultFuture, FiniteDuration.apply(3, SECONDS)); + assertEquals(expected, actual); + } - final String actual = Await.result(resultFuture, FiniteDuration.apply(3, SECONDS)); - assertEquals(expected, actual); - } - - @Test(expected = ExecutionException.class) - public void testCSAfterFailedCallable() throws Exception { - Callable> failedCallable = () -> { - CompletableFuture f = new CompletableFuture<>(); - f.completeExceptionally(new IllegalStateException("Illegal!")); - return f; + @Test(expected = ExecutionException.class) + public void testCSAfterFailedCallable() throws Exception { + Callable> failedCallable = + () -> { + CompletableFuture f = new CompletableFuture<>(); + f.completeExceptionally(new IllegalStateException("Illegal!")); + return f; }; - CompletionStage delayedStage = Patterns - .after( - Duration.ofMillis(200), - system.scheduler(), - ec, - failedCallable); + CompletionStage delayedStage = + Patterns.after(Duration.ofMillis(200), system.scheduler(), ec, failedCallable); - delayedStage.toCompletableFuture().get(3, SECONDS); - } + delayedStage.toCompletableFuture().get(3, SECONDS); + } - @Test(expected = ExecutionException.class) - public void testCSAfterFailedFuture() throws Exception { - Callable> failedFuture = () -> { - CompletableFuture f = new CompletableFuture<>(); - f.completeExceptionally(new IllegalStateException("Illegal!")); - return f; + @Test(expected = ExecutionException.class) + public void testCSAfterFailedFuture() throws Exception { + Callable> failedFuture = + () -> { + CompletableFuture f = new CompletableFuture<>(); + f.completeExceptionally(new IllegalStateException("Illegal!")); + return f; }; - CompletionStage delayedStage = Patterns - .after( - Duration.ofMillis(200), - system.scheduler(), - ec, - failedFuture); + CompletionStage delayedStage = + Patterns.after(Duration.ofMillis(200), system.scheduler(), ec, failedFuture); - String result = delayedStage.toCompletableFuture().get(3, SECONDS); - } + String result = delayedStage.toCompletableFuture().get(3, SECONDS); + } - @Test - public void testCSAfterSuccessfulCallable() throws Exception { - final String expected = "Hello"; + @Test + public void testCSAfterSuccessfulCallable() throws Exception { + final String expected = "Hello"; - final Callable> cf = () -> { - CompletableFuture f = CompletableFuture.completedFuture(expected); - return f; + final Callable> cf = + () -> { + CompletableFuture f = CompletableFuture.completedFuture(expected); + return f; }; - CompletionStage delayedStage = Patterns - .after( - Duration.ofMillis(200), - system.scheduler(), - ec, - cf); + CompletionStage delayedStage = + Patterns.after(Duration.ofMillis(200), system.scheduler(), ec, cf); - final String actual = delayedStage.toCompletableFuture().get(3, SECONDS); - assertEquals(expected, actual); - } + final String actual = delayedStage.toCompletableFuture().get(3, SECONDS); + assertEquals(expected, actual); + } - @Test - public void testCSAfterSuccessfulFuture() throws Exception { - final String expected = "Hello"; + @Test + public void testCSAfterSuccessfulFuture() throws Exception { + final String expected = "Hello"; - final CompletionStage f = CompletableFuture.completedFuture(expected); + final CompletionStage f = CompletableFuture.completedFuture(expected); - CompletionStage delayedStage = Patterns - .after( - Duration.ofMillis(200), - system.scheduler(), - ec, - f); + CompletionStage delayedStage = + Patterns.after(Duration.ofMillis(200), system.scheduler(), ec, f); - final String actual = delayedStage.toCompletableFuture().get(3, SECONDS); - assertEquals(expected, actual); - } + final String actual = delayedStage.toCompletableFuture().get(3, SECONDS); + assertEquals(expected, actual); + } - @Test - public void testCSAfterDuration() throws Exception { - final String expected = "Hello"; + @Test + public void testCSAfterDuration() throws Exception { + final String expected = "Hello"; - final CompletionStage f = CompletableFuture.completedFuture("world!"); + final CompletionStage f = CompletableFuture.completedFuture("world!"); - CompletionStage delayedStage = Patterns - .after( - Duration.ofMillis(200), - system.scheduler(), - ec, - f); + CompletionStage delayedStage = + Patterns.after(Duration.ofMillis(200), system.scheduler(), ec, f); - CompletableFuture immediateStage = CompletableFuture.completedFuture(expected); - CompletableFuture resultStage = CompletableFuture.anyOf(delayedStage.toCompletableFuture(), immediateStage); + CompletableFuture immediateStage = CompletableFuture.completedFuture(expected); + CompletableFuture resultStage = + CompletableFuture.anyOf(delayedStage.toCompletableFuture(), immediateStage); - final String actual = (String) resultStage.get(3, SECONDS); - assertEquals(expected, actual); - } + final String actual = (String) resultStage.get(3, SECONDS); + assertEquals(expected, actual); + } - @Test - public void testGracefulStop() throws Exception { - ActorRef target = system.actorOf(Props.create(StopActor.class)); - Future result = Patterns.gracefulStop(target, FiniteDuration.apply(200, TimeUnit.MILLISECONDS)); + @Test + public void testGracefulStop() throws Exception { + ActorRef target = system.actorOf(Props.create(StopActor.class)); + Future result = + Patterns.gracefulStop(target, FiniteDuration.apply(200, TimeUnit.MILLISECONDS)); - Boolean actual = Await.result(result, FiniteDuration.apply(3, SECONDS)); - assertEquals(true, actual); - } + Boolean actual = Await.result(result, FiniteDuration.apply(3, SECONDS)); + assertEquals(true, actual); + } - @Test - public void testCSGracefulStop() throws Exception { - ActorRef target = system.actorOf(Props.create(StopActor.class)); - CompletionStage result = Patterns.gracefulStop(target, Duration.ofMillis(200)); - - Boolean actual = result.toCompletableFuture().get(3, SECONDS); - assertEquals(true, actual); - } + @Test + public void testCSGracefulStop() throws Exception { + ActorRef target = system.actorOf(Props.create(StopActor.class)); + CompletionStage result = Patterns.gracefulStop(target, Duration.ofMillis(200)); + Boolean actual = result.toCompletableFuture().get(3, SECONDS); + assertEquals(true, actual); + } } diff --git a/akka-actor-tests/src/test/java/akka/util/ByteStringTest.java b/akka-actor-tests/src/test/java/akka/util/ByteStringTest.java index 838ddf01f7..eec0675324 100644 --- a/akka-actor-tests/src/test/java/akka/util/ByteStringTest.java +++ b/akka-actor-tests/src/test/java/akka/util/ByteStringTest.java @@ -25,5 +25,4 @@ public class ByteStringTest extends JUnitSuite { sb.append(ByteString.fromString("World")); assertEquals(ByteString.fromString("Hello World"), sb.result()); } - } diff --git a/akka-actor-tests/src/test/java/akka/util/JavaDuration.java b/akka-actor-tests/src/test/java/akka/util/JavaDuration.java index cd80c32b5c..934e62d393 100644 --- a/akka-actor-tests/src/test/java/akka/util/JavaDuration.java +++ b/akka-actor-tests/src/test/java/akka/util/JavaDuration.java @@ -19,5 +19,4 @@ public class JavaDuration extends JUnitSuite { assert Duration.Zero().lteq(Duration.Inf()); assert Duration.Inf().gt(Duration.Zero().neg()); } - } diff --git a/akka-actor-tests/src/test/java/akka/util/LineNumberSpecCodeForJava.java b/akka-actor-tests/src/test/java/akka/util/LineNumberSpecCodeForJava.java index 2c98e16c4e..ba38c473b6 100644 --- a/akka-actor-tests/src/test/java/akka/util/LineNumberSpecCodeForJava.java +++ b/akka-actor-tests/src/test/java/akka/util/LineNumberSpecCodeForJava.java @@ -37,5 +37,4 @@ public class LineNumberSpecCodeForJava { } }; } - } diff --git a/akka-actor-typed-tests/src/test/java/akka/actor/typed/ActorSystemTest.java b/akka-actor-typed-tests/src/test/java/akka/actor/typed/ActorSystemTest.java index fafac127d6..0c07613ba6 100644 --- a/akka-actor-typed-tests/src/test/java/akka/actor/typed/ActorSystemTest.java +++ b/akka-actor-typed-tests/src/test/java/akka/actor/typed/ActorSystemTest.java @@ -2,9 +2,7 @@ * Copyright (C) 2018-2019 Lightbend Inc. */ -/** - * Copyright (C) 2009-2018 Lightbend Inc. - */ +/** Copyright (C) 2009-2018 Lightbend Inc. */ package akka.actor.typed; import org.junit.Test; @@ -27,7 +25,8 @@ public class ActorSystemTest extends JUnitSuite { @Test public void testGetWhenTerminatedWithoutTermination() { - final ActorSystem system = ActorSystem.create(Behavior.empty(), "GetWhenTerminatedWithoutTermination"); + final ActorSystem system = + ActorSystem.create(Behavior.empty(), "GetWhenTerminatedWithoutTermination"); assertFalse(system.getWhenTerminated().toCompletableFuture().isDone()); } } diff --git a/akka-actor-typed-tests/src/test/java/akka/actor/typed/ExtensionsTest.java b/akka-actor-typed-tests/src/test/java/akka/actor/typed/ExtensionsTest.java index 60ceaa064c..40124f17cb 100644 --- a/akka-actor-typed-tests/src/test/java/akka/actor/typed/ExtensionsTest.java +++ b/akka-actor-typed-tests/src/test/java/akka/actor/typed/ExtensionsTest.java @@ -18,15 +18,13 @@ import static org.junit.Assert.assertTrue; public class ExtensionsTest extends JUnitSuite { - public static class MyExtImpl implements Extension { - } + public static class MyExtImpl implements Extension {} public static class MyExtension extends ExtensionId { - private final static MyExtension instance = new MyExtension(); + private static final MyExtension instance = new MyExtension(); - private MyExtension() { - } + private MyExtension() {} public static MyExtension getInstance() { return instance; @@ -41,8 +39,7 @@ public class ExtensionsTest extends JUnitSuite { } } - public static class MyExtImplViaSetup extends MyExtImpl { - } + public static class MyExtImplViaSetup extends MyExtImpl {} public static class MyExtensionSetup extends ExtensionSetup { public MyExtensionSetup(Function, MyExtImpl> createExtension) { @@ -50,15 +47,14 @@ public class ExtensionsTest extends JUnitSuite { } } - @Test public void loadJavaExtensionsFromConfig() { - Config cfg = ConfigFactory.parseString( - "akka.actor.typed.extensions += \"akka.actor.typed.ExtensionsTest$MyExtension\"").resolve(); - final ActorSystem system = ActorSystem.create( - Behavior.empty(), - "loadJavaExtensionsFromConfig", - cfg); + Config cfg = + ConfigFactory.parseString( + "akka.actor.typed.extensions += \"akka.actor.typed.ExtensionsTest$MyExtension\"") + .resolve(); + final ActorSystem system = + ActorSystem.create(Behavior.empty(), "loadJavaExtensionsFromConfig", cfg); try { // note that this is not the intended end user way to access it @@ -88,10 +84,11 @@ public class ExtensionsTest extends JUnitSuite { @Test public void overrideExtensionsViaActorSystemSetup() { - final ActorSystem system = ActorSystem.create( - Behavior.empty(), - "overrideExtensionsViaActorSystemSetup", - ActorSystemSetup.create(new MyExtensionSetup(sys -> new MyExtImplViaSetup()))); + final ActorSystem system = + ActorSystem.create( + Behavior.empty(), + "overrideExtensionsViaActorSystemSetup", + ActorSystemSetup.create(new MyExtensionSetup(sys -> new MyExtImplViaSetup()))); try { MyExtImpl instance1 = MyExtension.get(system); @@ -104,5 +101,4 @@ public class ExtensionsTest extends JUnitSuite { system.terminate(); } } - } diff --git a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorCompile.java b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorCompile.java index a6993298fa..4485ff04c9 100644 --- a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorCompile.java +++ b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorCompile.java @@ -11,7 +11,6 @@ import java.time.Duration; import static akka.actor.typed.javadsl.Behaviors.*; - @SuppressWarnings("unused") public class ActorCompile { @@ -33,67 +32,82 @@ public class ActorCompile { } } - Behavior actor1 = Behaviors.receive((context, message) -> stopped(), (context, signal) -> same()); + Behavior actor1 = + Behaviors.receive((context, message) -> stopped(), (context, signal) -> same()); Behavior actor2 = Behaviors.receive((context, message) -> unhandled()); Behavior actor4 = empty(); Behavior actor5 = ignore(); - Behavior actor6 = intercept(new BehaviorInterceptor() { - @Override - public Behavior aroundReceive(TypedActorContext context, MyMsg message, ReceiveTarget target) { - return target.apply(context, message); - } + Behavior actor6 = + intercept( + new BehaviorInterceptor() { + @Override + public Behavior aroundReceive( + TypedActorContext context, MyMsg message, ReceiveTarget target) { + return target.apply(context, message); + } - @Override - public Behavior aroundSignal(TypedActorContext context, Signal signal, SignalTarget target) { - return target.apply(context, signal); - } - }, actor5); + @Override + public Behavior aroundSignal( + TypedActorContext context, Signal signal, SignalTarget target) { + return target.apply(context, signal); + } + }, + actor5); Behavior actor7 = actor6.narrow(); - Behavior actor8 = setup(context -> { - final ActorRef self = context.getSelf(); - return monitor(self, ignore()); - }); + Behavior actor8 = + setup( + context -> { + final ActorRef self = context.getSelf(); + return monitor(self, ignore()); + }); Behavior actor9 = widened(actor7, pf -> pf.match(MyMsgA.class, x -> x)); - Behavior actor10 = Behaviors.receive((context, message) -> stopped(actor4), (context, signal) -> same()); + Behavior actor10 = + Behaviors.receive((context, message) -> stopped(actor4), (context, signal) -> same()); ActorSystem system = ActorSystem.create(actor1, "Sys"); { - Behaviors.receive((context, message) -> { - if (message instanceof MyMsgA) { - return Behaviors.receive((ctx2, msg2) -> { - if (msg2 instanceof MyMsgB) { - ((MyMsgA) message).replyTo.tell(((MyMsgB) msg2).greeting); + Behaviors.receive( + (context, message) -> { + if (message instanceof MyMsgA) { + return Behaviors.receive( + (ctx2, msg2) -> { + if (msg2 instanceof MyMsgB) { + ((MyMsgA) message).replyTo.tell(((MyMsgB) msg2).greeting); - ActorRef adapter = ctx2.messageAdapter(String.class, s -> new MyMsgB(s.toUpperCase())); - } - return same(); + ActorRef adapter = + ctx2.messageAdapter(String.class, s -> new MyMsgB(s.toUpperCase())); + } + return same(); + }); + } else return unhandled(); }); - } else return unhandled(); - }); } { - Behavior b = Behaviors.withTimers(timers -> { - timers.startPeriodicTimer("key", new MyMsgB("tick"), Duration.ofSeconds(1)); - return Behaviors.ignore(); - }); + Behavior b = + Behaviors.withTimers( + timers -> { + timers.startPeriodicTimer("key", new MyMsgB("tick"), Duration.ofSeconds(1)); + return Behaviors.ignore(); + }); } - static class MyBehavior extends ExtensibleBehavior { @Override - public Behavior receiveSignal(TypedActorContext context, Signal message) throws Exception { + public Behavior receiveSignal(TypedActorContext context, Signal message) + throws Exception { return this; } @Override - public Behavior receive(TypedActorContext context, MyMsg message) throws Exception { - ActorRef adapter = context.asJava().messageAdapter(String.class, s -> new MyMsgB(s.toUpperCase())); + public Behavior receive(TypedActorContext context, MyMsg message) + throws Exception { + ActorRef adapter = + context.asJava().messageAdapter(String.class, s -> new MyMsgB(s.toUpperCase())); return this; } - } // SupervisorStrategy @@ -101,27 +115,19 @@ public class ActorCompile { SupervisorStrategy strategy1 = SupervisorStrategy.restart(); SupervisorStrategy strategy2 = SupervisorStrategy.restart().withLoggingEnabled(false); SupervisorStrategy strategy3 = SupervisorStrategy.resume(); - SupervisorStrategy strategy4 = - SupervisorStrategy.restartWithLimit(3, Duration.ofSeconds(1)); + SupervisorStrategy strategy4 = SupervisorStrategy.restartWithLimit(3, Duration.ofSeconds(1)); SupervisorStrategy strategy5 = - SupervisorStrategy.restartWithBackoff( - Duration.ofMillis(200), - Duration.ofSeconds(10), - 0.1); + SupervisorStrategy.restartWithBackoff(Duration.ofMillis(200), Duration.ofSeconds(10), 0.1); BackoffSupervisorStrategy strategy6 = - SupervisorStrategy.restartWithBackoff( - Duration.ofMillis(200), - Duration.ofSeconds(10), - 0.1); + SupervisorStrategy.restartWithBackoff(Duration.ofMillis(200), Duration.ofSeconds(10), 0.1); SupervisorStrategy strategy7 = strategy6.withResetBackoffAfter(Duration.ofSeconds(2)); Behavior behv = - Behaviors.supervise( - Behaviors.supervise(Behaviors.ignore()).onFailure(IllegalStateException.class, strategy6) - ).onFailure(RuntimeException.class, strategy1); + Behaviors.supervise( + Behaviors.supervise(Behaviors.ignore()) + .onFailure(IllegalStateException.class, strategy6)) + .onFailure(RuntimeException.class, strategy1); } - - } diff --git a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorContextAskTest.java b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorContextAskTest.java index c530578575..e50f92f3f3 100644 --- a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorContextAskTest.java +++ b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorContextAskTest.java @@ -24,42 +24,48 @@ public class ActorContextAskTest extends JUnitSuite { static class Ping { final ActorRef respondTo; + public Ping(ActorRef respondTo) { this.respondTo = respondTo; } } - static class Pong { } + + static class Pong {} @Test public void provideASafeAsk() { - final Behavior pingPongBehavior = Behaviors.receive((ActorContext context, Ping message) -> { - message.respondTo.tell(new Pong()); - return Behaviors.same(); - }); + final Behavior pingPongBehavior = + Behaviors.receive( + (ActorContext context, Ping message) -> { + message.respondTo.tell(new Pong()); + return Behaviors.same(); + }); final ActorRef pingPong = testKit.spawn(pingPongBehavior); final TestProbe probe = testKit.createTestProbe(); - final Behavior snitch = Behaviors.setup((ActorContext context) -> { - context.ask(Pong.class, - pingPong, - Duration.ofSeconds(3), - (ActorRef ref) -> new Ping(ref), - (pong, exception) -> { - if (pong != null) return pong; - else return exception; - }); + final Behavior snitch = + Behaviors.setup( + (ActorContext context) -> { + context.ask( + Pong.class, + pingPong, + Duration.ofSeconds(3), + (ActorRef ref) -> new Ping(ref), + (pong, exception) -> { + if (pong != null) return pong; + else return exception; + }); - return Behaviors.receiveMessage((Object message) -> { - probe.ref().tell(message); - return Behaviors.same(); - }); - }); + return Behaviors.receiveMessage( + (Object message) -> { + probe.ref().tell(message); + return Behaviors.same(); + }); + }); testKit.spawn(snitch); probe.expectMessageClass(Pong.class); } - - } diff --git a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorContextPipeToSelfTest.java b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorContextPipeToSelfTest.java index 84497e7ffe..6242d84bfc 100644 --- a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorContextPipeToSelfTest.java +++ b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorContextPipeToSelfTest.java @@ -23,10 +23,10 @@ public final class ActorContextPipeToSelfTest extends JUnitSuite { @ClassRule public static final TestKitJunitResource testKit = - new TestKitJunitResource(ConfigFactory.parseString( - "pipe-to-self-spec-dispatcher.executor = thread-pool-executor\n" + - "pipe-to-self-spec-dispatcher.type = PinnedDispatcher\n" - )); + new TestKitJunitResource( + ConfigFactory.parseString( + "pipe-to-self-spec-dispatcher.executor = thread-pool-executor\n" + + "pipe-to-self-spec-dispatcher.type = PinnedDispatcher\n")); static final class Msg { final String response; @@ -40,11 +40,13 @@ public final class ActorContextPipeToSelfTest extends JUnitSuite { } } - @Test public void handlesSuccess() { + @Test + public void handlesSuccess() { assertEquals("ok: hi", responseFrom(CompletableFuture.completedFuture("hi"))); } - @Test public void handlesFailure() { + @Test + public void handlesFailure() { assertEquals("ko: boom", responseFrom(failedFuture(new RuntimeException("boom")))); } @@ -56,19 +58,28 @@ public final class ActorContextPipeToSelfTest extends JUnitSuite { private String responseFrom(final CompletionStage future) { final TestProbe probe = testKit.createTestProbe(); - final Behavior behavior = Behaviors.setup(context -> { - context.pipeToSelf(future, (string, exception) -> { - final String response; - if (string != null) response = String.format("ok: %s", string); - else if (exception != null) response = String.format("ko: %s", exception.getMessage()); - else response = "???"; - return new Msg(response, context.getSelf().path().name(), Thread.currentThread().getName()); - }); - return Behaviors.receiveMessage(msg -> { - probe.getRef().tell(msg); - return Behaviors.stopped(); - }); - }); + final Behavior behavior = + Behaviors.setup( + context -> { + context.pipeToSelf( + future, + (string, exception) -> { + final String response; + if (string != null) response = String.format("ok: %s", string); + else if (exception != null) + response = String.format("ko: %s", exception.getMessage()); + else response = "???"; + return new Msg( + response, + context.getSelf().path().name(), + Thread.currentThread().getName()); + }); + return Behaviors.receiveMessage( + msg -> { + probe.getRef().tell(msg); + return Behaviors.stopped(); + }); + }); final String name = "pipe-to-self-spec"; final Props props = Props.empty().withDispatcherFromConfig("pipe-to-self-spec-dispatcher"); @@ -77,7 +88,8 @@ public final class ActorContextPipeToSelfTest extends JUnitSuite { final Msg msg = probe.expectMessageClass(Msg.class); assertEquals("pipe-to-self-spec", msg.selfName); - assertThat(msg.threadName, startsWith("ActorContextPipeToSelfTest-pipe-to-self-spec-dispatcher")); + assertThat( + msg.threadName, startsWith("ActorContextPipeToSelfTest-pipe-to-self-spec-dispatcher")); return msg.response; } } diff --git a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorLoggingTest.java b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorLoggingTest.java index 2ec7f7c281..74aba449a9 100644 --- a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorLoggingTest.java +++ b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ActorLoggingTest.java @@ -22,11 +22,10 @@ import java.util.concurrent.TimeUnit; public class ActorLoggingTest extends JUnitSuite { @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource( - ConfigFactory.parseString( - "akka.loglevel = INFO\n" + - "akka.loggers = [\"akka.testkit.TestEventListener\"]" - )); + public static final TestKitJunitResource testKit = + new TestKitJunitResource( + ConfigFactory.parseString( + "akka.loglevel = INFO\n" + "akka.loggers = [\"akka.testkit.TestEventListener\"]")); interface Protocol { String getTransactionId(); @@ -34,9 +33,11 @@ public class ActorLoggingTest extends JUnitSuite { static class Message implements Protocol { public final String transactionId; + public Message(String transactionId) { this.transactionId = transactionId; } + public String getTransactionId() { return transactionId; } @@ -44,28 +45,31 @@ public class ActorLoggingTest extends JUnitSuite { @Test public void loggingProvidesMDC() { - Behavior behavior = Behaviors.withMdc( - null, - (message) -> { - Map mdc = new HashMap<>(); - mdc.put("txId", message.getTransactionId()); - return mdc; - }, - Behaviors.receive(Protocol.class) - .onMessage(Message.class, (context, message) -> { - context.getLog().info(message.toString()); - return Behaviors.same(); - }).build() - ); + Behavior behavior = + Behaviors.withMdc( + null, + (message) -> { + Map mdc = new HashMap<>(); + mdc.put("txId", message.getTransactionId()); + return mdc; + }, + Behaviors.receive(Protocol.class) + .onMessage( + Message.class, + (context, message) -> { + context.getLog().info(message.toString()); + return Behaviors.same(); + }) + .build()); - CustomEventFilter eventFilter = new CustomEventFilter(new PFBuilder() - .match(Logging.LogEvent.class, (event) -> - event.getMDC().containsKey("txId")) - .build(), - 1); + CustomEventFilter eventFilter = + new CustomEventFilter( + new PFBuilder() + .match(Logging.LogEvent.class, (event) -> event.getMDC().containsKey("txId")) + .build(), + 1); testKit.spawn(behavior); eventFilter.awaitDone(FiniteDuration.create(3, TimeUnit.SECONDS)); - } } diff --git a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/AdapterTest.java b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/AdapterTest.java index ea965b3162..878ca68c54 100644 --- a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/AdapterTest.java +++ b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/AdapterTest.java @@ -33,11 +33,13 @@ public class AdapterTest extends JUnitSuite { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("ping", s -> getSender().tell("pong", getSelf())) - .match(ThrowIt.class, t -> { - throw t; - }) - .build(); + .matchEquals("ping", s -> getSender().tell("pong", getSelf())) + .match( + ThrowIt.class, + t -> { + throw t; + }) + .build(); } } @@ -83,11 +85,11 @@ public class AdapterTest extends JUnitSuite { Adapter.watch(context, child); Adapter.stop(context, child); return same(); - } else if (message.equals("stop-self")){ + } else if (message.equals("stop-self")) { try { context.stop(context.getSelf()); - } catch (Exception e){ - probe.tell(e,akka.actor.ActorRef.noSender()); + } catch (Exception e) { + probe.tell(e, akka.actor.ActorRef.noSender()); } return same(); } else { @@ -106,6 +108,7 @@ public class AdapterTest extends JUnitSuite { } static interface Typed2Msg {}; + static final class Ping implements Typed2Msg { public final ActorRef replyTo; @@ -113,10 +116,15 @@ public class AdapterTest extends JUnitSuite { this.replyTo = replyTo; } } + static final class StopIt implements Typed2Msg {} - static abstract class ThrowIt extends RuntimeException implements Typed2Msg {} + + abstract static class ThrowIt extends RuntimeException implements Typed2Msg {} + static class ThrowIt1 extends ThrowIt {} + static class ThrowIt2 extends ThrowIt {} + static class ThrowIt3 extends ThrowIt {} static akka.actor.Props untyped2(ActorRef ref, akka.actor.ActorRef probe) { @@ -137,31 +145,39 @@ public class AdapterTest extends JUnitSuite { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("send", s -> { - ActorRef replyTo = Adapter.toTyped(getSelf()); - ref.tell(new Ping(replyTo)); - }) - .matchEquals("pong", s -> probe.tell("ok", getSelf())) - .matchEquals("spawn", s -> { - ActorRef child = Adapter.spawnAnonymous(getContext(), typed2()); - child.tell(new Ping(Adapter.toTyped(getSelf()))); - }) - .matchEquals("actorOf-props", s -> { - // this is how Cluster Sharding can be used - akka.actor.ActorRef child = getContext().actorOf(typed2Props()); - child.tell(new Ping(Adapter.toTyped(getSelf())), akka.actor.ActorRef.noSender()); - }) - .matchEquals("watch", s -> Adapter.watch(getContext(), ref)) - .match(akka.actor.Terminated.class, t -> probe.tell("terminated", getSelf())) - .matchEquals("supervise-stop", s -> testSupervice(new ThrowIt1())) - .matchEquals("supervise-resume", s -> testSupervice(new ThrowIt2())) - .matchEquals("supervise-restart", s -> testSupervice(new ThrowIt3())) - .matchEquals("stop-child", s -> { - ActorRef child = Adapter.spawnAnonymous(getContext(), typed2()); - Adapter.watch(getContext(), child); - Adapter.stop(getContext(), child); - }) - .build(); + .matchEquals( + "send", + s -> { + ActorRef replyTo = Adapter.toTyped(getSelf()); + ref.tell(new Ping(replyTo)); + }) + .matchEquals("pong", s -> probe.tell("ok", getSelf())) + .matchEquals( + "spawn", + s -> { + ActorRef child = Adapter.spawnAnonymous(getContext(), typed2()); + child.tell(new Ping(Adapter.toTyped(getSelf()))); + }) + .matchEquals( + "actorOf-props", + s -> { + // this is how Cluster Sharding can be used + akka.actor.ActorRef child = getContext().actorOf(typed2Props()); + child.tell(new Ping(Adapter.toTyped(getSelf())), akka.actor.ActorRef.noSender()); + }) + .matchEquals("watch", s -> Adapter.watch(getContext(), ref)) + .match(akka.actor.Terminated.class, t -> probe.tell("terminated", getSelf())) + .matchEquals("supervise-stop", s -> testSupervice(new ThrowIt1())) + .matchEquals("supervise-resume", s -> testSupervice(new ThrowIt2())) + .matchEquals("supervise-restart", s -> testSupervice(new ThrowIt3())) + .matchEquals( + "stop-child", + s -> { + ActorRef child = Adapter.spawnAnonymous(getContext(), typed2()); + Adapter.watch(getContext(), child); + Adapter.stop(getContext(), child); + }) + .build(); } private void testSupervice(ThrowIt t) { @@ -172,21 +188,28 @@ public class AdapterTest extends JUnitSuite { } private SupervisorStrategy strategy() { - return new akka.actor.OneForOneStrategy(false, akka.japi.pf.DeciderBuilder - .match(ThrowIt1.class, e -> { - probe.tell("thrown-stop", getSelf()); - return SupervisorStrategy.stop(); - }) - .match(ThrowIt2.class, e -> { - probe.tell("thrown-resume", getSelf()); - return SupervisorStrategy.resume(); - }) - .match(ThrowIt3.class, e -> { - probe.tell("thrown-restart", getSelf()); - // TODO Restart will not really restart the behavior - return SupervisorStrategy.restart(); - }) - .build()); + return new akka.actor.OneForOneStrategy( + false, + akka.japi.pf.DeciderBuilder.match( + ThrowIt1.class, + e -> { + probe.tell("thrown-stop", getSelf()); + return SupervisorStrategy.stop(); + }) + .match( + ThrowIt2.class, + e -> { + probe.tell("thrown-resume", getSelf()); + return SupervisorStrategy.resume(); + }) + .match( + ThrowIt3.class, + e -> { + probe.tell("thrown-restart", getSelf()); + // TODO Restart will not really restart the behavior + return SupervisorStrategy.restart(); + }) + .build()); } @Override @@ -196,19 +219,20 @@ public class AdapterTest extends JUnitSuite { } static Behavior typed2() { - return Behaviors.receive((context, message) -> { - if (message instanceof Ping) { - ActorRef replyTo = ((Ping) message).replyTo; - replyTo.tell("pong"); - return same(); - } else if (message instanceof StopIt) { - return stopped(); - } else if (message instanceof ThrowIt) { - throw (ThrowIt) message; - } else { - return unhandled(); - } - }); + return Behaviors.receive( + (context, message) -> { + if (message instanceof Ping) { + ActorRef replyTo = ((Ping) message).replyTo; + replyTo.tell("pong"); + return same(); + } else if (message instanceof StopIt) { + return stopped(); + } else if (message instanceof ThrowIt) { + throw (ThrowIt) message; + } else { + return unhandled(); + } + }); } static akka.actor.Props typed2Props() { @@ -216,18 +240,17 @@ public class AdapterTest extends JUnitSuite { } @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("ActorSelectionTest", - AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("ActorSelectionTest", AkkaSpec.testConf()); private final ActorSystem system = actorSystemResource.getSystem(); - - @Test public void shouldSendMessageFromTypedToUntyped() { TestKit probe = new TestKit(system); akka.actor.ActorRef untypedRef = system.actorOf(untyped1()); - ActorRef typedRef = Adapter.spawnAnonymous(system, Typed1.create(untypedRef, probe.getRef())); + ActorRef typedRef = + Adapter.spawnAnonymous(system, Typed1.create(untypedRef, probe.getRef())); typedRef.tell("send"); probe.expectMsg("ok"); } @@ -263,7 +286,8 @@ public class AdapterTest extends JUnitSuite { public void shouldActorOfUntypedChildFromTypedParent() { TestKit probe = new TestKit(system); akka.actor.ActorRef ignore = system.actorOf(akka.actor.Props.empty()); - ActorRef typedRef = Adapter.spawnAnonymous(system, Typed1.create(ignore, probe.getRef())); + ActorRef typedRef = + Adapter.spawnAnonymous(system, Typed1.create(ignore, probe.getRef())); typedRef.tell("actorOf"); probe.expectMsg("ok"); } @@ -283,9 +307,10 @@ public class AdapterTest extends JUnitSuite { public void shouldWatchUntypedFromTyped() { TestKit probe = new TestKit(system); akka.actor.ActorRef untypedRef = system.actorOf(untyped1()); - ActorRef typedRef = Adapter.spawnAnonymous(system, Typed1.create(untypedRef, probe.getRef())); + ActorRef typedRef = + Adapter.spawnAnonymous(system, Typed1.create(untypedRef, probe.getRef())); typedRef.tell("watch"); - untypedRef.tell(akka.actor.PoisonPill.getInstance() , akka.actor.ActorRef.noSender()); + untypedRef.tell(akka.actor.PoisonPill.getInstance(), akka.actor.ActorRef.noSender()); probe.expectMsg("terminated"); } @@ -312,7 +337,8 @@ public class AdapterTest extends JUnitSuite { public void shouldSuperviseUntypedChildFromTypedParent() { TestKit probe = new TestKit(system); akka.actor.ActorRef ignore = system.actorOf(akka.actor.Props.empty()); - ActorRef typedRef = Adapter.spawnAnonymous(system, Typed1.create(ignore, probe.getRef())); + ActorRef typedRef = + Adapter.spawnAnonymous(system, Typed1.create(ignore, probe.getRef())); int originalLogLevel = system.getEventStream().logLevel(); try { @@ -341,7 +367,8 @@ public class AdapterTest extends JUnitSuite { public void shouldStopUntypedChildFromTypedParent() { TestKit probe = new TestKit(system); akka.actor.ActorRef ignore = system.actorOf(akka.actor.Props.empty()); - ActorRef typedRef = Adapter.spawnAnonymous(system, Typed1.create(ignore, probe.getRef())); + ActorRef typedRef = + Adapter.spawnAnonymous(system, Typed1.create(ignore, probe.getRef())); typedRef.tell("stop-child"); probe.expectMsg("terminated"); } @@ -350,7 +377,8 @@ public class AdapterTest extends JUnitSuite { public void stopSelfWillCauseError() { TestKit probe = new TestKit(system); akka.actor.ActorRef ignore = system.actorOf(akka.actor.Props.empty()); - ActorRef typedRef = Adapter.spawnAnonymous(system, Typed1.create(ignore, probe.getRef())); + ActorRef typedRef = + Adapter.spawnAnonymous(system, Typed1.create(ignore, probe.getRef())); typedRef.tell("stop-self"); probe.expectMsgClass(IllegalArgumentException.class); } diff --git a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/BehaviorBuilderTest.java b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/BehaviorBuilderTest.java index f4cf1e1584..5549d14e38 100644 --- a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/BehaviorBuilderTest.java +++ b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/BehaviorBuilderTest.java @@ -16,70 +16,82 @@ import java.util.ArrayList; import static akka.actor.typed.javadsl.Behaviors.same; import static akka.actor.typed.javadsl.Behaviors.stopped; -/** - * Test creating [[Behavior]]s using [[BehaviorBuilder]] - */ +/** Test creating [[Behavior]]s using [[BehaviorBuilder]] */ public class BehaviorBuilderTest extends JUnitSuite { - interface Message { - } + interface Message {} - static final class One implements Message { - public String foo() { - return "Bar"; - } + static final class One implements Message { + public String foo() { + return "Bar"; } - static final class MyList extends ArrayList implements Message { - }; + } - @Test - public void shouldCompile() { - Behavior b = Behaviors.receive(Message.class) - .onMessage(One.class, (context, o) -> { - o.foo(); - return same(); - }) - .onMessage(One.class, o -> o.foo().startsWith("a"), (context, o) -> same()) - .onMessageUnchecked(MyList.class, (ActorContext context, MyList l) -> { - String first = l.get(0); - return Behaviors.same(); - }) - .onSignal(Terminated.class, (context, t) -> { - System.out.println("Terminating along with " + t.getRef()); - return stopped(); - }) + static final class MyList extends ArrayList implements Message {}; + + @Test + public void shouldCompile() { + Behavior b = + Behaviors.receive(Message.class) + .onMessage( + One.class, + (context, o) -> { + o.foo(); + return same(); + }) + .onMessage(One.class, o -> o.foo().startsWith("a"), (context, o) -> same()) + .onMessageUnchecked( + MyList.class, + (ActorContext context, MyList l) -> { + String first = l.get(0); + return Behaviors.same(); + }) + .onSignal( + Terminated.class, + (context, t) -> { + System.out.println("Terminating along with " + t.getRef()); + return stopped(); + }) + .build(); + } + + interface CounterMessage {}; + + static final class Increase implements CounterMessage {}; + + static final class Get implements CounterMessage { + final ActorRef sender; + + public Get(ActorRef sender) { + this.sender = sender; + } + }; + + static final class Got { + final int n; + + public Got(int n) { + this.n = n; + } + } + + public Behavior immutableCounter(int currentValue) { + return Behaviors.receive(CounterMessage.class) + .onMessage( + Increase.class, + (context, o) -> { + return immutableCounter(currentValue + 1); + }) + .onMessage( + Get.class, + (context, o) -> { + o.sender.tell(new Got(currentValue)); + return same(); + }) .build(); - } - - interface CounterMessage {}; - static final class Increase implements CounterMessage {}; - static final class Get implements CounterMessage { - final ActorRef sender; - public Get(ActorRef sender) { - this.sender = sender; - } - }; - static final class Got { - final int n; - public Got(int n) { - this.n = n; - } - } - - public Behavior immutableCounter(int currentValue) { - return Behaviors.receive(CounterMessage.class) - .onMessage(Increase.class, (context, o) -> { - return immutableCounter(currentValue + 1); - }) - .onMessage(Get.class, (context, o) -> { - o.sender.tell(new Got(currentValue)); - return same(); - }) - .build(); - } - - @Test - public void testImmutableCounter() { - Behavior immutable = immutableCounter(0); - } + } + @Test + public void testImmutableCounter() { + Behavior immutable = immutableCounter(0); + } } diff --git a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/InterceptTest.java b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/InterceptTest.java index 963c7459c4..5adb78b4af 100644 --- a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/InterceptTest.java +++ b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/InterceptTest.java @@ -20,24 +20,32 @@ public class InterceptTest extends JUnitSuite { @Test public void interceptMessage() { final TestProbe interceptProbe = testKit.createTestProbe(); - BehaviorInterceptor interceptor = new BehaviorInterceptor() { - @Override - public Behavior aroundReceive(TypedActorContext ctx, String msg, ReceiveTarget target) { - interceptProbe.getRef().tell(msg); - return target.apply(ctx, msg); - } + BehaviorInterceptor interceptor = + new BehaviorInterceptor() { + @Override + public Behavior aroundReceive( + TypedActorContext ctx, String msg, ReceiveTarget target) { + interceptProbe.getRef().tell(msg); + return target.apply(ctx, msg); + } - @Override - public Behavior aroundSignal(TypedActorContext ctx, Signal signal, SignalTarget target) { - return target.apply(ctx, signal); - } - }; + @Override + public Behavior aroundSignal( + TypedActorContext ctx, Signal signal, SignalTarget target) { + return target.apply(ctx, signal); + } + }; final TestProbe probe = testKit.createTestProbe(); - ActorRef ref = testKit.spawn(Behaviors.intercept(interceptor, Behaviors.receiveMessage((String msg) -> { - probe.getRef().tell(msg); - return Behaviors.same(); - }))); + ActorRef ref = + testKit.spawn( + Behaviors.intercept( + interceptor, + Behaviors.receiveMessage( + (String msg) -> { + probe.getRef().tell(msg); + return Behaviors.same(); + }))); ref.tell("Hello"); interceptProbe.expectMessage("Hello"); @@ -45,36 +53,46 @@ public class InterceptTest extends JUnitSuite { } interface Message {} + static class A implements Message {} + static class B implements Message {} @Test public void interceptMessagesSelectively() { final TestProbe interceptProbe = testKit.createTestProbe(); - BehaviorInterceptor interceptor = new BehaviorInterceptor() { + BehaviorInterceptor interceptor = + new BehaviorInterceptor() { - @Override - public Class interceptMessageType() { - return B.class; - } + @Override + public Class interceptMessageType() { + return B.class; + } - @Override - public Behavior aroundReceive(TypedActorContext ctx, Message msg, ReceiveTarget target) { - interceptProbe.getRef().tell(msg); - return target.apply(ctx, msg); - } + @Override + public Behavior aroundReceive( + TypedActorContext ctx, Message msg, ReceiveTarget target) { + interceptProbe.getRef().tell(msg); + return target.apply(ctx, msg); + } - @Override - public Behavior aroundSignal(TypedActorContext ctx, Signal signal, SignalTarget target) { - return target.apply(ctx, signal); - } - }; + @Override + public Behavior aroundSignal( + TypedActorContext ctx, Signal signal, SignalTarget target) { + return target.apply(ctx, signal); + } + }; final TestProbe probe = testKit.createTestProbe(); - ActorRef ref = testKit.spawn(Behaviors.intercept(interceptor, Behaviors.receiveMessage((Message msg) -> { - probe.getRef().tell(msg); - return Behaviors.same(); - }))); + ActorRef ref = + testKit.spawn( + Behaviors.intercept( + interceptor, + Behaviors.receiveMessage( + (Message msg) -> { + probe.getRef().tell(msg); + return Behaviors.same(); + }))); ref.tell(new A()); ref.tell(new B()); @@ -82,5 +100,4 @@ public class InterceptTest extends JUnitSuite { interceptProbe.expectMessageClass(B.class); probe.expectMessageClass(B.class); } - } diff --git a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ReceiveBuilderTest.java b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ReceiveBuilderTest.java index df26d0b38a..aeeac4588b 100644 --- a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ReceiveBuilderTest.java +++ b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/ReceiveBuilderTest.java @@ -11,37 +11,41 @@ import akka.actor.typed.Behavior; import static org.junit.Assert.assertEquals; -/** - * Test creating [[MutableActor]]s using [[ReceiveBuilder]] - */ +/** Test creating [[MutableActor]]s using [[ReceiveBuilder]] */ public class ReceiveBuilderTest extends JUnitSuite { @Test public void testMutableCounter() { - Behavior mutable = Behaviors.setup(context -> new AbstractBehavior() { - int currentValue = 0; + Behavior mutable = + Behaviors.setup( + context -> + new AbstractBehavior() { + int currentValue = 0; - private Behavior receiveIncrease(BehaviorBuilderTest.Increase message) { - currentValue++; - return this; - } + private Behavior receiveIncrease( + BehaviorBuilderTest.Increase message) { + currentValue++; + return this; + } - private Behavior receiveGet(BehaviorBuilderTest.Get get) { - get.sender.tell(new BehaviorBuilderTest.Got(currentValue)); - return this; - } + private Behavior receiveGet( + BehaviorBuilderTest.Get get) { + get.sender.tell(new BehaviorBuilderTest.Got(currentValue)); + return this; + } - @Override - public Receive createReceive() { - return receiveBuilder() - .onMessage(BehaviorBuilderTest.Increase.class, this::receiveIncrease) - .onMessage(BehaviorBuilderTest.Get.class, this::receiveGet) - .build(); - } - }); + @Override + public Receive createReceive() { + return receiveBuilder() + .onMessage(BehaviorBuilderTest.Increase.class, this::receiveIncrease) + .onMessage(BehaviorBuilderTest.Get.class, this::receiveGet) + .build(); + } + }); } - private static class MyAbstractBehavior extends AbstractBehavior { + private static class MyAbstractBehavior + extends AbstractBehavior { private int value; public MyAbstractBehavior(int initialValue) { diff --git a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/WatchTest.java b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/WatchTest.java index 758c779722..cb4f46fcb6 100644 --- a/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/WatchTest.java +++ b/akka-actor-typed-tests/src/test/java/akka/actor/typed/javadsl/WatchTest.java @@ -22,10 +22,9 @@ import static akka.actor.typed.javadsl.Behaviors.*; public class WatchTest extends JUnitSuite { - @ClassRule - public static TestKitJunitResource testKit = new TestKitJunitResource(); + @ClassRule public static TestKitJunitResource testKit = new TestKitJunitResource(); - interface Message { } + interface Message {} static final class RunTest implements Message { private final ActorRef replyTo; @@ -35,74 +34,81 @@ public class WatchTest extends JUnitSuite { } } - static final class Stop { - } + static final class Stop {} - static final class CustomTerminationMessage implements Message { - } + static final class CustomTerminationMessage implements Message {} final Duration timeout = Duration.ofSeconds(5); - final Behavior exitingActor = receive((context, message) -> { - System.out.println("Stopping!"); - return stopped(); - }); + final Behavior exitingActor = + receive( + (context, message) -> { + System.out.println("Stopping!"); + return stopped(); + }); private Behavior waitingForTermination(ActorRef replyWhenTerminated) { return receive( - (context, message) -> unhandled(), - (context, sig) -> { - if (sig instanceof Terminated) { - replyWhenTerminated.tell(done()); - } - return same(); - } - ); + (context, message) -> unhandled(), + (context, sig) -> { + if (sig instanceof Terminated) { + replyWhenTerminated.tell(done()); + } + return same(); + }); } private Behavior waitingForMessage(ActorRef replyWhenReceived) { return receive( - (context, message) -> { - if (message instanceof CustomTerminationMessage) { - replyWhenReceived.tell(done()); - return same(); - } else { - return unhandled(); - } - } - ); + (context, message) -> { + if (message instanceof CustomTerminationMessage) { + replyWhenReceived.tell(done()); + return same(); + } else { + return unhandled(); + } + }); } @Test public void shouldWatchTerminatingActor() throws Exception { - Behavior exiting = Behaviors.receive(RunTest.class) - .onMessage(RunTest.class, (context, message) -> { - ActorRef watched = context.spawn(exitingActor, "exitingActor"); - context.watch(watched); - watched.tell(new Stop()); - return waitingForTermination(message.replyTo); - }).build(); + Behavior exiting = + Behaviors.receive(RunTest.class) + .onMessage( + RunTest.class, + (context, message) -> { + ActorRef watched = context.spawn(exitingActor, "exitingActor"); + context.watch(watched); + watched.tell(new Stop()); + return waitingForTermination(message.replyTo); + }) + .build(); ActorRef exitingRef = testKit.spawn(exiting); - CompletionStage result = AskPattern.ask(exitingRef, RunTest::new, timeout, testKit.scheduler()); + CompletionStage result = + AskPattern.ask(exitingRef, RunTest::new, timeout, testKit.scheduler()); result.toCompletableFuture().get(3, TimeUnit.SECONDS); } @Test public void shouldWatchWithCustomMessage() throws Exception { - Behavior exiting = Behaviors.receive(Message.class) - .onMessage(RunTest.class, (context, message) -> { - ActorRef watched = context.spawn(exitingActor, "exitingActor"); - context.watchWith(watched, new CustomTerminationMessage()); - watched.tell(new Stop()); - return waitingForMessage(message.replyTo); - }).build(); + Behavior exiting = + Behaviors.receive(Message.class) + .onMessage( + RunTest.class, + (context, message) -> { + ActorRef watched = context.spawn(exitingActor, "exitingActor"); + context.watchWith(watched, new CustomTerminationMessage()); + watched.tell(new Stop()); + return waitingForMessage(message.replyTo); + }) + .build(); ActorRef exitingRef = testKit.spawn(exiting); // Not sure why this does not compile without an explicit cast? // system.tell(new RunTest()); - CompletionStage result = AskPattern.ask(exitingRef, RunTest::new, timeout, testKit.scheduler()); + CompletionStage result = + AskPattern.ask(exitingRef, RunTest::new, timeout, testKit.scheduler()); result.toCompletableFuture().get(3, TimeUnit.SECONDS); - } } diff --git a/akka-actor-typed-tests/src/test/java/akka/actor/typed/receptionist/ReceptionistApiTest.java b/akka-actor-typed-tests/src/test/java/akka/actor/typed/receptionist/ReceptionistApiTest.java index 9925c92601..adb812f5f3 100644 --- a/akka-actor-typed-tests/src/test/java/akka/actor/typed/receptionist/ReceptionistApiTest.java +++ b/akka-actor-typed-tests/src/test/java/akka/actor/typed/receptionist/ReceptionistApiTest.java @@ -26,72 +26,89 @@ public class ReceptionistApiTest { system.receptionist().tell(Receptionist.register(key, service)); // registration from outside with ack, should be rare - CompletionStage registeredCS = AskPattern.ask( - system.receptionist(), - sendRegTo -> Receptionist.register(key, service, sendRegTo), - timeout, - system.scheduler() - ); - registeredCS.whenComplete((r, failure) -> { - if (r != null) { - r.getServiceInstance(key); - } else { - throw new RuntimeException("Not registered"); - } - }); + CompletionStage registeredCS = + AskPattern.ask( + system.receptionist(), + sendRegTo -> Receptionist.register(key, service, sendRegTo), + timeout, + system.scheduler()); + registeredCS.whenComplete( + (r, failure) -> { + if (r != null) { + r.getServiceInstance(key); + } else { + throw new RuntimeException("Not registered"); + } + }); // one-off ask outside of actor, should be uncommon but not rare - CompletionStage result = AskPattern.ask( - system.receptionist(), - sendListingTo -> Receptionist.find(key, sendListingTo), - timeout, - system.scheduler() - ); - result.whenComplete((listing, throwable) -> { - if (listing != null && listing.isForKey(key)) { - Set> serviceInstances = listing.getServiceInstances(key); - } else { - throw new RuntimeException("not what I wanted"); - } - }); - - Behaviors.setup(context -> { - // oneoff ask inside of actor - // this is somewhat verbose, however this should be a rare use case - context.ask( - Receptionist.Listing.class, - context.getSystem().receptionist(), - timeout, - resRef -> Receptionist.find(key, resRef), + CompletionStage result = + AskPattern.ask( + system.receptionist(), + sendListingTo -> Receptionist.find(key, sendListingTo), + timeout, + system.scheduler()); + result.whenComplete( (listing, throwable) -> { - if (listing != null) return listing.getServiceInstances(key); - else return "listing failed"; - } - ); + if (listing != null && listing.isForKey(key)) { + Set> serviceInstances = listing.getServiceInstances(key); + } else { + throw new RuntimeException("not what I wanted"); + } + }); - // this is a more "normal" use case which is clean - context.getSystem().receptionist().tell(Receptionist.subscribe(key, context.getSelf().narrow())); + Behaviors.setup( + context -> { + // oneoff ask inside of actor + // this is somewhat verbose, however this should be a rare use case + context.ask( + Receptionist.Listing.class, + context.getSystem().receptionist(), + timeout, + resRef -> Receptionist.find(key, resRef), + (listing, throwable) -> { + if (listing != null) return listing.getServiceInstances(key); + else return "listing failed"; + }); - // another more "normal" is subscribe using an adapter - ActorRef listingAdapter = context.messageAdapter( - Receptionist.Listing.class, - (listing) -> listing.serviceInstances(key) - ); - context.getSystem().receptionist().tell(Receptionist.subscribe(key, listingAdapter)); + // this is a more "normal" use case which is clean + context + .getSystem() + .receptionist() + .tell(Receptionist.subscribe(key, context.getSelf().narrow())); - // ofc this doesn't make sense to do in the same actor, this is just - // to cover as much of the API as possible - context.getSystem().receptionist().tell(Receptionist.register(key, context.getSelf().narrow(), context.getSelf().narrow())); + // another more "normal" is subscribe using an adapter + ActorRef listingAdapter = + context.messageAdapter( + Receptionist.Listing.class, (listing) -> listing.serviceInstances(key)); + context.getSystem().receptionist().tell(Receptionist.subscribe(key, listingAdapter)); - return Behaviors.receive(Object.class) - // matching is done best using the predicate version - .onMessage(Receptionist.Listing.class, listing -> listing.isForKey(key), (msgCtx, listing) -> { - Set> services = listing.getServiceInstances(key); - return Behaviors.same(); - }).onMessage(Receptionist.Registered.class, registered -> registered.isForKey(key), (msgCtx, registered) -> { - ActorRef registree = registered.getServiceInstance(key); - return Behaviors.same(); - }).build(); - }); + // ofc this doesn't make sense to do in the same actor, this is just + // to cover as much of the API as possible + context + .getSystem() + .receptionist() + .tell( + Receptionist.register( + key, context.getSelf().narrow(), context.getSelf().narrow())); + + return Behaviors.receive(Object.class) + // matching is done best using the predicate version + .onMessage( + Receptionist.Listing.class, + listing -> listing.isForKey(key), + (msgCtx, listing) -> { + Set> services = listing.getServiceInstances(key); + return Behaviors.same(); + }) + .onMessage( + Receptionist.Registered.class, + registered -> registered.isForKey(key), + (msgCtx, registered) -> { + ActorRef registree = registered.getServiceInstance(key); + return Behaviors.same(); + }) + .build(); + }); } } diff --git a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/DispatchersDocTest.java b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/DispatchersDocTest.java index 1ce8e902af..1d76d37e0e 100644 --- a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/DispatchersDocTest.java +++ b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/DispatchersDocTest.java @@ -11,17 +11,23 @@ import akka.actor.typed.DispatcherSelector; public class DispatchersDocTest { - private static Behavior yourBehavior = Behaviors.empty(); + private static Behavior yourBehavior = Behaviors.empty(); - private static Behavior example = Behaviors.receive((context, message) -> { + private static Behavior example = + Behaviors.receive( + (context, message) -> { - //#spawn-dispatcher - context.spawn(yourBehavior, "DefaultDispatcher"); - context.spawn(yourBehavior, "ExplicitDefaultDispatcher", DispatcherSelector.defaultDispatcher()); - context.spawn(yourBehavior, "BlockingDispatcher", DispatcherSelector.blocking()); - context.spawn(yourBehavior, "DispatcherFromConfig", DispatcherSelector.fromConfig("your-dispatcher")); - //#spawn-dispatcher + // #spawn-dispatcher + context.spawn(yourBehavior, "DefaultDispatcher"); + context.spawn( + yourBehavior, "ExplicitDefaultDispatcher", DispatcherSelector.defaultDispatcher()); + context.spawn(yourBehavior, "BlockingDispatcher", DispatcherSelector.blocking()); + context.spawn( + yourBehavior, + "DispatcherFromConfig", + DispatcherSelector.fromConfig("your-dispatcher")); + // #spawn-dispatcher - return Behaviors.same(); - }); + return Behaviors.same(); + }); } diff --git a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/FSMDocTest.java b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/FSMDocTest.java index 3011e4357f..fe6557945c 100644 --- a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/FSMDocTest.java +++ b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/FSMDocTest.java @@ -16,174 +16,181 @@ import java.util.List; public class FSMDocTest { - //#simple-events - interface Event { } - //#simple-events + // #simple-events + interface Event {} + // #simple-events - static - //#simple-events - public final class SetTarget implements Event { - private final ActorRef ref; + public + // #simple-events + static final class SetTarget implements Event { + private final ActorRef ref; - public SetTarget(ActorRef ref) { - this.ref = ref; - } - - public ActorRef getRef() { - return ref; - } - } - //#simple-events - - static - //#simple-events - final class Timeout implements Event {} - final static Timeout TIMEOUT = new Timeout(); - //#simple-events - - //#simple-events - public enum Flush implements Event { - FLUSH - } - //#simple-events - - static - //#simple-events - public final class Queue implements Event { - private final Object obj; - - public Queue(Object obj) { - this.obj = obj; - } - - public Object getObj() { - return obj; - } + public SetTarget(ActorRef ref) { + this.ref = ref; } - //#simple-events - static public final class Batch { - private final List list; + public ActorRef getRef() { + return ref; + } + } + // #simple-events - public Batch(List list) { - this.list = list; - } + static + // #simple-events + final class Timeout implements Event {} - public List getList() { - return list; - } - //#boilerplate + static final Timeout TIMEOUT = new Timeout(); + // #simple-events - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + // #simple-events + public enum Flush implements Event { + FLUSH + } + // #simple-events - Batch batch = (Batch) o; + public + // #simple-events + static final class Queue implements Event { + private final Object obj; - return list.equals(batch.list); - } + public Queue(Object obj) { + this.obj = obj; + } - @Override - public int hashCode() { - return list.hashCode(); - } + public Object getObj() { + return obj; + } + } - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Batch{list="); - list.stream().forEachOrdered(e -> { + // #simple-events + public static final class Batch { + private final List list; + + public Batch(List list) { + this.list = list; + } + + public List getList() { + return list; + } + // #boilerplate + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Batch batch = (Batch) o; + + return list.equals(batch.list); + } + + @Override + public int hashCode() { + return list.hashCode(); + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Batch{list="); + list.stream() + .forEachOrdered( + e -> { builder.append(e); builder.append(","); - }); - int len = builder.length(); - builder.replace(len, len, "}"); - return builder.toString(); - } - //#boilerplate + }); + int len = builder.length(); + builder.replace(len, len, "}"); + return builder.toString(); + } + // #boilerplate + } + + // #storing-state + interface Data {} + // #storing-state + + static + // #storing-state + final class Todo implements Data { + private final ActorRef target; + private final List queue; + + public Todo(ActorRef target, List queue) { + this.target = target; + this.queue = queue; } - //#storing-state - interface Data { - } - //#storing-state - - static - //#storing-state - final class Todo implements Data { - private final ActorRef target; - private final List queue; - - public Todo(ActorRef target, List queue) { - this.target = target; - this.queue = queue; - } - - public ActorRef getTarget() { - return target; - } - - public List getQueue() { - return queue; - } - //#boilerplate - - @Override - public String toString() { - return "Todo{" + - "target=" + target + - ", queue=" + queue + - '}'; - } - - public Todo addElement(Object element) { - List nQueue = new LinkedList<>(queue); - nQueue.add(element); - return new Todo(this.target, nQueue); - } - - public Todo copy(List queue) { - return new Todo(this.target, queue); - } - - public Todo copy(ActorRef target) { - return new Todo(target, this.queue); - } - //#boilerplate - } - //#storing-state - - //#simple-state - // FSM states represented as behaviors - private static Behavior uninitialized() { - return Behaviors.receive(Event.class) - .onMessage(SetTarget.class, (context, message) -> idle(new Todo(message.getRef(), Collections.emptyList()))) - .build(); + public ActorRef getTarget() { + return target; } - private static Behavior idle(Todo data) { - return Behaviors.receive(Event.class) - .onMessage(Queue.class, (context, message) -> active(data.addElement(message))) - .build(); + public List getQueue() { + return queue; + } + // #boilerplate + + @Override + public String toString() { + return "Todo{" + "target=" + target + ", queue=" + queue + '}'; } - private static Behavior active(Todo data) { - return Behaviors.withTimers(timers -> { - // State timeouts done with withTimers - timers.startSingleTimer("Timeout", TIMEOUT, Duration.ofSeconds(1)); - return Behaviors.receive(Event.class) - .onMessage(Queue.class, (context, message) -> active(data.addElement(message))) - .onMessage(Flush.class, (context, message) -> { - data.getTarget().tell(new Batch(data.queue)); - return idle(data.copy(new ArrayList<>())); - }) - .onMessage(Timeout.class, (context, message) -> { - data.getTarget().tell(new Batch(data.queue)); - return idle(data.copy(new ArrayList<>())); - }).build(); + public Todo addElement(Object element) { + List nQueue = new LinkedList<>(queue); + nQueue.add(element); + return new Todo(this.target, nQueue); + } + + public Todo copy(List queue) { + return new Todo(this.target, queue); + } + + public Todo copy(ActorRef target) { + return new Todo(target, this.queue); + } + // #boilerplate + } + // #storing-state + + // #simple-state + // FSM states represented as behaviors + private static Behavior uninitialized() { + return Behaviors.receive(Event.class) + .onMessage( + SetTarget.class, + (context, message) -> idle(new Todo(message.getRef(), Collections.emptyList()))) + .build(); + } + + private static Behavior idle(Todo data) { + return Behaviors.receive(Event.class) + .onMessage(Queue.class, (context, message) -> active(data.addElement(message))) + .build(); + } + + private static Behavior active(Todo data) { + return Behaviors.withTimers( + timers -> { + // State timeouts done with withTimers + timers.startSingleTimer("Timeout", TIMEOUT, Duration.ofSeconds(1)); + return Behaviors.receive(Event.class) + .onMessage(Queue.class, (context, message) -> active(data.addElement(message))) + .onMessage( + Flush.class, + (context, message) -> { + data.getTarget().tell(new Batch(data.queue)); + return idle(data.copy(new ArrayList<>())); + }) + .onMessage( + Timeout.class, + (context, message) -> { + data.getTarget().tell(new Batch(data.queue)); + return idle(data.copy(new ArrayList<>())); + }) + .build(); }); - } - //#simple-state + } + // #simple-state } diff --git a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/FaultToleranceDocTest.java b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/FaultToleranceDocTest.java index c394decbf6..de41bf5b61 100644 --- a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/FaultToleranceDocTest.java +++ b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/FaultToleranceDocTest.java @@ -17,8 +17,10 @@ import org.scalatest.junit.JUnitSuite; public class FaultToleranceDocTest extends JUnitSuite { // #bubbling-example interface Message {} + class Fail implements Message { public final String text; + Fail(String text) { this.text = text; } @@ -29,65 +31,83 @@ public class FaultToleranceDocTest extends JUnitSuite { @Test public void bubblingSample() { // #bubbling-example - final Behavior failingChildBehavior = Behaviors.receive(Message.class) - .onMessage(Fail.class, (context, message) -> { - throw new RuntimeException(message.text); - }) - .build(); + final Behavior failingChildBehavior = + Behaviors.receive(Message.class) + .onMessage( + Fail.class, + (context, message) -> { + throw new RuntimeException(message.text); + }) + .build(); - Behavior middleManagementBehavior = Behaviors.setup((context) -> { - context.getLog().info("Middle management starting up"); - final ActorRef child = context.spawn(failingChildBehavior, "child"); - // we want to know when the child terminates, but since we do not handle - // the Terminated signal, we will in turn fail on child termination - context.watch(child); + Behavior middleManagementBehavior = + Behaviors.setup( + (context) -> { + context.getLog().info("Middle management starting up"); + final ActorRef child = context.spawn(failingChildBehavior, "child"); + // we want to know when the child terminates, but since we do not handle + // the Terminated signal, we will in turn fail on child termination + context.watch(child); - // 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 - return Behaviors.receive(Message.class) - .onMessage(Message.class, (innerCtx, message) -> { - // just pass messages on to the child - child.tell(message); - return Behaviors.same(); - }).build(); - }); + // 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 + return Behaviors.receive(Message.class) + .onMessage( + Message.class, + (innerCtx, message) -> { + // just pass messages on to the child + child.tell(message); + return Behaviors.same(); + }) + .build(); + }); - Behavior bossBehavior = Behaviors.setup((context) -> { - context.getLog().info("Boss starting up"); - final ActorRef middleManagement = context.spawn(middleManagementBehavior, "middle-management"); - context.watch(middleManagement); + Behavior bossBehavior = + Behaviors.setup( + (context) -> { + context.getLog().info("Boss starting up"); + final ActorRef middleManagement = + context.spawn(middleManagementBehavior, "middle-management"); + context.watch(middleManagement); - // here we don't handle Terminated at all which means that - // when middle management fails with a DeathWatchException - // this actor will also fail - return Behaviors.receive(Message.class) - .onMessage(Message.class, (innerCtx, message) -> { - // just pass messages on to the child - middleManagement.tell(message); - return Behaviors.same(); - }).build(); - }); + // here we don't handle Terminated at all which means that + // when middle management fails with a DeathWatchException + // this actor will also fail + return Behaviors.receive(Message.class) + .onMessage( + Message.class, + (innerCtx, message) -> { + // just pass messages on to the child + middleManagement.tell(message); + return Behaviors.same(); + }) + .build(); + }); { - // #bubbling-example - final ActorSystem system = - ActorSystem.create(bossBehavior, "boss"); - // #bubbling-example + // #bubbling-example + final ActorSystem system = ActorSystem.create(bossBehavior, "boss"); + // #bubbling-example } final ActorSystem system = - ActorSystem.create(bossBehavior, "boss", ConfigFactory.parseString( - "akka.loggers = [ akka.testkit.TestEventListener ]\n" + - "akka.loglevel=warning")); + ActorSystem.create( + bossBehavior, + "boss", + ConfigFactory.parseString( + "akka.loggers = [ akka.testkit.TestEventListener ]\n" + "akka.loglevel=warning")); // #bubbling-example // actual exception and thent the deathpacts - new EventFilter(Exception.class, ActorSystemAdapter.toUntyped(system)).occurrences(4).intercept(() -> { - // #bubbling-example - system.tell(new Fail("boom")); - // #bubbling-example - return null; - }); + new EventFilter(Exception.class, ActorSystemAdapter.toUntyped(system)) + .occurrences(4) + .intercept( + () -> { + // #bubbling-example + system.tell(new Fail("boom")); + // #bubbling-example + return null; + }); // #bubbling-example // this will now bubble up all the way to the boss and as that is the user guardian it means // the entire actor system will stop @@ -95,5 +115,4 @@ public class FaultToleranceDocTest extends JUnitSuite { // #bubbling-example } - } diff --git a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/GracefulStopDocTest.java b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/GracefulStopDocTest.java index 1c1f85b5a4..e02f64ee72 100644 --- a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/GracefulStopDocTest.java +++ b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/GracefulStopDocTest.java @@ -4,7 +4,7 @@ package jdocs.akka.typed; -//#imports +// #imports import java.util.concurrent.TimeUnit; @@ -13,20 +13,18 @@ import akka.actor.typed.Behavior; import akka.actor.typed.PostStop; import akka.actor.typed.javadsl.Behaviors; -//#imports +// #imports public class GracefulStopDocTest { - //#master-actor + // #master-actor public abstract static class JobControl { // no instances of this class, it's only a name space for messages // and static methods - private JobControl() { - } + private JobControl() {} - static interface JobControlLanguage { - } + static interface JobControlLanguage {} public static final class SpawnJob implements JobControlLanguage { public final String name; @@ -38,40 +36,50 @@ public class GracefulStopDocTest { public static final class GracefulShutdown implements JobControlLanguage { - public GracefulShutdown() { - } + public GracefulShutdown() {} } - public static final Behavior mcpa = Behaviors.receive(JobControlLanguage.class) - .onMessage(SpawnJob.class, (context, message) -> { - context.getSystem().log().info("Spawning job {}!", message.name); - context.spawn(Job.job(message.name), message.name); - return Behaviors.same(); - }) - .onSignal(PostStop.class, (context, signal) -> { - context.getSystem().log().info("Master Control Programme stopped"); - return Behaviors.same(); - }) - .onMessage(GracefulShutdown.class, (context, message) -> { - context.getSystem().log().info("Initiating graceful shutdown..."); + public static final Behavior mcpa = + Behaviors.receive(JobControlLanguage.class) + .onMessage( + SpawnJob.class, + (context, message) -> { + context.getSystem().log().info("Spawning job {}!", message.name); + context.spawn(Job.job(message.name), message.name); + return Behaviors.same(); + }) + .onSignal( + PostStop.class, + (context, signal) -> { + context.getSystem().log().info("Master Control Programme stopped"); + return Behaviors.same(); + }) + .onMessage( + GracefulShutdown.class, + (context, message) -> { + context.getSystem().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 - return Behaviors.stopped(Behaviors.receiveSignal((_ctx, PostStop) -> { - context.getSystem().log().info("Cleanup!"); - return Behaviors.same(); - })); - }) - .onSignal(PostStop.class, (context, signal) -> { - context.getSystem().log().info("Master Control Programme stopped"); - return Behaviors.same(); - }) - .build(); + // perform graceful stop, executing cleanup before final system termination + // behavior executing cleanup is passed as a parameter to Actor.stopped + return Behaviors.stopped( + Behaviors.receiveSignal( + (_ctx, PostStop) -> { + context.getSystem().log().info("Cleanup!"); + return Behaviors.same(); + })); + }) + .onSignal( + PostStop.class, + (context, signal) -> { + context.getSystem().log().info("Master Control Programme stopped"); + return Behaviors.same(); + }) + .build(); } - //#master-actor + // #master-actor public static void main(String[] args) throws Exception { - //#graceful-shutdown + // #graceful-shutdown final ActorSystem system = ActorSystem.create(JobControl.mcpa, "B6700"); @@ -85,19 +93,19 @@ public class GracefulStopDocTest { system.tell(new JobControl.GracefulShutdown()); system.getWhenTerminated().toCompletableFuture().get(3, TimeUnit.SECONDS); - //#graceful-shutdown + // #graceful-shutdown } - //#worker-actor + // #worker-actor public static class Job { public static Behavior job(String name) { - return Behaviors.receiveSignal((context, PostStop) -> { - context.getSystem().log().info("Worker {} stopped", name); - return Behaviors.same(); - }); - + return Behaviors.receiveSignal( + (context, PostStop) -> { + context.getSystem().log().info("Worker {} stopped", name); + return Behaviors.same(); + }); } } - //#worker-actor + // #worker-actor } diff --git a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/InteractionPatternsTest.java b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/InteractionPatternsTest.java index 348e12d61a..b2d3536de5 100644 --- a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/InteractionPatternsTest.java +++ b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/InteractionPatternsTest.java @@ -26,22 +26,28 @@ public class InteractionPatternsTest extends JUnitSuite { // #fire-and-forget-definition class PrintMe { public final String message; + public PrintMe(String message) { this.message = message; } } - static final Behavior printerBehavior = Behaviors.receive(PrintMe.class) - .onMessage(PrintMe.class, (context, printMe) -> { - context.getLog().info(printMe.message); - return Behaviors.same(); - }).build(); + static final Behavior printerBehavior = + Behaviors.receive(PrintMe.class) + .onMessage( + PrintMe.class, + (context, printMe) -> { + context.getLog().info(printMe.message); + return Behaviors.same(); + }) + .build(); // #fire-and-forget-definition // #request-response-protocol class Request { public final String query; public final ActorRef respondTo; + public Request(String query, ActorRef respondTo) { this.query = query; this.respondTo = respondTo; @@ -50,6 +56,7 @@ public class InteractionPatternsTest extends JUnitSuite { class Response { public final String result; + public Response(String result) { this.result = result; } @@ -61,11 +68,14 @@ public class InteractionPatternsTest extends JUnitSuite { // #request-response-respond // actor behavior Behaviors.receive(Request.class) - .onMessage(Request.class, (context, request) -> { - // ... process request ... - request.respondTo.tell(new Response("Here's your response!")); - return Behaviors.same(); - }).build(); + .onMessage( + Request.class, + (context, request) -> { + // ... process request ... + request.respondTo.tell(new Response("Here's your response!")); + return Behaviors.same(); + }) + .build(); // #request-response-respond ActorRef otherActor = null; @@ -76,11 +86,11 @@ public class InteractionPatternsTest extends JUnitSuite { // #request-response-send } - // #adapted-response public static class Backend { interface Request {} + public static class StartTranslationJob implements Request { public final int taskId; public final URI site; @@ -94,6 +104,7 @@ public class InteractionPatternsTest extends JUnitSuite { } interface Response {} + public static class JobStarted implements Response { public final int taskId; @@ -121,12 +132,12 @@ public class InteractionPatternsTest extends JUnitSuite { this.result = result; } } - } public static class Frontend { interface Command {} + public static class Translate implements Command { public final URI site; public final ActorRef replyTo; @@ -181,54 +192,66 @@ public class InteractionPatternsTest extends JUnitSuite { this.context = context; this.backend = backend; this.backendResponseAdapter = - context.messageAdapter(Backend.Response.class, rsp -> { - if (rsp instanceof Backend.JobStarted) - return new WrappedJobStarted((Backend.JobStarted) rsp); - else if (rsp instanceof Backend.JobProgress) - return new WrappedJobProgress((Backend.JobProgress) rsp); - else if (rsp instanceof Backend.JobCompleted) - return new WrappedJobCompleted((Backend.JobCompleted) rsp); - else return new OtherResponse(rsp); - }); + context.messageAdapter( + Backend.Response.class, + rsp -> { + if (rsp instanceof Backend.JobStarted) + return new WrappedJobStarted((Backend.JobStarted) rsp); + else if (rsp instanceof Backend.JobProgress) + return new WrappedJobProgress((Backend.JobProgress) rsp); + else if (rsp instanceof Backend.JobCompleted) + return new WrappedJobCompleted((Backend.JobCompleted) rsp); + else return new OtherResponse(rsp); + }); } @Override public Receive createReceive() { return receiveBuilder() - .onMessage(Translate.class, cmd -> { - taskIdCounter += 1; - inProgress.put(taskIdCounter, cmd.replyTo); - backend.tell(new Backend.StartTranslationJob( - taskIdCounter, cmd.site, backendResponseAdapter)); - return this; - }) - .onMessage(WrappedJobStarted.class, wrapped -> { - context.getLog().info("Started {}", wrapped.response.taskId); - return this; - }) - .onMessage(WrappedJobProgress.class, wrapped -> { - context.getLog().info("Progress {}: {}", wrapped.response.taskId, - wrapped.response.progress); - return this; - }) - .onMessage(WrappedJobCompleted.class, wrapped -> { - context.getLog().info("Completed {}: {}", wrapped.response.taskId, - wrapped.response.result); - return this; - }) - .onMessage(OtherResponse.class, other -> Behaviors.unhandled()) - .build(); + .onMessage( + Translate.class, + cmd -> { + taskIdCounter += 1; + inProgress.put(taskIdCounter, cmd.replyTo); + backend.tell( + new Backend.StartTranslationJob( + taskIdCounter, cmd.site, backendResponseAdapter)); + return this; + }) + .onMessage( + WrappedJobStarted.class, + wrapped -> { + context.getLog().info("Started {}", wrapped.response.taskId); + return this; + }) + .onMessage( + WrappedJobProgress.class, + wrapped -> { + context + .getLog() + .info("Progress {}: {}", wrapped.response.taskId, wrapped.response.progress); + return this; + }) + .onMessage( + WrappedJobCompleted.class, + wrapped -> { + context + .getLog() + .info("Completed {}: {}", wrapped.response.taskId, wrapped.response.result); + return this; + }) + .onMessage(OtherResponse.class, other -> Behaviors.unhandled()) + .build(); } } } // #adapted-response - @Test public void fireAndForgetSample() throws Exception { // #fire-and-forget-doit final ActorSystem system = - ActorSystem.create(printerBehavior, "printer-sample-system"); + ActorSystem.create(printerBehavior, "printer-sample-system"); // note that system is also the ActorRef to the guardian actor final ActorRef ref = system; @@ -242,9 +265,8 @@ public class InteractionPatternsTest extends JUnitSuite { system.getWhenTerminated().toCompletableFuture().get(5, TimeUnit.SECONDS); } - //#timer - interface Msg { - } + // #timer + interface Msg {} public static final class Batch { private final List messages; @@ -281,186 +303,213 @@ public class InteractionPatternsTest extends JUnitSuite { private static final Object TIMER_KEY = new Object(); - private static class TimeoutMsg implements Msg { - } + private static class TimeoutMsg implements Msg {} public static Behavior behavior(ActorRef target, Duration after, int maxSize) { return Behaviors.withTimers(timers -> idle(timers, target, after, maxSize)); } - private static Behavior idle(TimerScheduler timers, ActorRef target, - Duration after, int maxSize) { + private static Behavior idle( + TimerScheduler timers, ActorRef target, Duration after, int maxSize) { return Behaviors.receive(Msg.class) - .onMessage(Msg.class, (context, message) -> { - timers.startSingleTimer(TIMER_KEY, new TimeoutMsg(), after); - List buffer = new ArrayList<>(); - buffer.add(message); - return active(buffer, timers, target, after, maxSize); - }) - .build(); + .onMessage( + Msg.class, + (context, message) -> { + timers.startSingleTimer(TIMER_KEY, new TimeoutMsg(), after); + List buffer = new ArrayList<>(); + buffer.add(message); + return active(buffer, timers, target, after, maxSize); + }) + .build(); } - private static Behavior active(List buffer, TimerScheduler timers, - ActorRef target, Duration after, int maxSize) { + private static Behavior active( + List buffer, + TimerScheduler timers, + ActorRef target, + Duration after, + int maxSize) { return Behaviors.receive(Msg.class) - .onMessage(TimeoutMsg.class, (context, message) -> { - target.tell(new Batch(buffer)); - return idle(timers, target, after, maxSize); - }) - .onMessage(Msg.class, (context, message) -> { - buffer.add(message); - if (buffer.size() == maxSize) { - timers.cancel(TIMER_KEY); - target.tell(new Batch(buffer)); - return idle(timers, target, after, maxSize); - } else { - return active(buffer, timers, target, after, maxSize); - } - }) - .build(); + .onMessage( + TimeoutMsg.class, + (context, message) -> { + target.tell(new Batch(buffer)); + return idle(timers, target, after, maxSize); + }) + .onMessage( + Msg.class, + (context, message) -> { + buffer.add(message); + if (buffer.size() == maxSize) { + timers.cancel(TIMER_KEY); + target.tell(new Batch(buffer)); + return idle(timers, target, after, maxSize); + } else { + return active(buffer, timers, target, after, maxSize); + } + }) + .build(); } - //#timer + // #timer @Test public void timers() throws Exception { final ActorSystem system = ActorSystem.create(Behaviors.empty(), "timers-sample"); TestProbe probe = TestProbe.create("batcher", system); - ActorRef bufferer = Await.result(system.systemActorOf( - behavior(probe.ref(), Duration.ofSeconds(1), 10), - "batcher", Props.empty(), akka.util.Timeout.create(Duration.ofSeconds(1))), - FiniteDuration.create(3, TimeUnit.SECONDS)); + ActorRef bufferer = + Await.result( + system.systemActorOf( + behavior(probe.ref(), Duration.ofSeconds(1), 10), + "batcher", + Props.empty(), + akka.util.Timeout.create(Duration.ofSeconds(1))), + FiniteDuration.create(3, TimeUnit.SECONDS)); ExcitingMessage msgOne = new ExcitingMessage("one"); ExcitingMessage msgTwo = new ExcitingMessage("two"); bufferer.tell(msgOne); bufferer.tell(msgTwo); probe.expectNoMessage(Duration.ofMillis(1)); - probe.expectMessage(Duration.ofSeconds(2), - new Batch(Arrays.asList(msgOne, msgTwo))); + probe.expectMessage(Duration.ofSeconds(2), new Batch(Arrays.asList(msgOne, msgTwo))); system.terminate(); system.getWhenTerminated().toCompletableFuture().get(5, TimeUnit.SECONDS); } - - // #actor-ask interface HalCommand {} + static final class OpenThePodBayDoorsPlease implements HalCommand { public final ActorRef respondTo; + OpenThePodBayDoorsPlease(ActorRef respondTo) { this.respondTo = respondTo; } } + static final class HalResponse { public final String message; + HalResponse(String message) { this.message = message; } } static final Behavior halBehavior = - Behaviors.receive(HalCommand.class) - .onMessage(OpenThePodBayDoorsPlease.class, (context, message) -> { - message.respondTo.tell(new HalResponse("I'm sorry, Dave. I'm afraid I can't do that.")); - return Behaviors.same(); - }).build(); + Behaviors.receive(HalCommand.class) + .onMessage( + OpenThePodBayDoorsPlease.class, + (context, message) -> { + message.respondTo.tell( + new HalResponse("I'm sorry, Dave. I'm afraid I can't do that.")); + return Behaviors.same(); + }) + .build(); interface DaveProtocol {} // this is a part of the protocol that is internal to the actor itself private static final class AdaptedResponse implements DaveProtocol { public final String message; + public AdaptedResponse(String message) { this.message = message; } } public static Behavior daveBehavior(final ActorRef hal) { - return Behaviors.setup((ActorContext context) -> { + return Behaviors.setup( + (ActorContext context) -> { - // asking someone requires a timeout, if the timeout hits without response - // the ask is failed with a TimeoutException - final Duration timeout = Duration.ofSeconds(3); + // asking someone requires a timeout, if the timeout hits without response + // the ask is failed with a TimeoutException + final Duration timeout = Duration.ofSeconds(3); - context.ask( - HalResponse.class, - hal, - timeout, - // construct the outgoing message - (ActorRef ref) -> new OpenThePodBayDoorsPlease(ref), - // adapt the response (or failure to respond) - (response, throwable) -> { - if (response != null) { - return new AdaptedResponse(response.message); - } else { - return new AdaptedResponse("Request failed"); - } - }); + context.ask( + HalResponse.class, + hal, + timeout, + // construct the outgoing message + (ActorRef ref) -> new OpenThePodBayDoorsPlease(ref), + // adapt the response (or failure to respond) + (response, throwable) -> { + if (response != null) { + return new AdaptedResponse(response.message); + } else { + return new AdaptedResponse("Request failed"); + } + }); - // we can also tie in request context into an interaction, it is safe to look at - // actor internal state from the transformation function, but remember that it may have - // changed at the time the response arrives and the transformation is done, best is to - // use immutable state we have closed over like here. - final int requestId = 1; - context.ask( - HalResponse.class, - hal, - timeout, - // construct the outgoing message - (ActorRef ref) -> new OpenThePodBayDoorsPlease(ref), - // adapt the response (or failure to respond) - (response, throwable) -> { - if (response != null) { - return new AdaptedResponse(requestId + ": " + response.message); - } else { - return new AdaptedResponse(requestId + ": Request failed"); - } + // we can also tie in request context into an interaction, it is safe to look at + // actor internal state from the transformation function, but remember that it may have + // changed at the time the response arrives and the transformation is done, best is to + // use immutable state we have closed over like here. + final int requestId = 1; + context.ask( + HalResponse.class, + hal, + timeout, + // construct the outgoing message + (ActorRef ref) -> new OpenThePodBayDoorsPlease(ref), + // adapt the response (or failure to respond) + (response, throwable) -> { + if (response != null) { + return new AdaptedResponse(requestId + ": " + response.message); + } else { + return new AdaptedResponse(requestId + ": Request failed"); + } + }); + + return Behaviors.receive(DaveProtocol.class) + // the adapted message ends up being processed like any other + // message sent to the actor + .onMessage( + AdaptedResponse.class, + (innerCtx, response) -> { + innerCtx.getLog().info("Got response from HAL: {}", response.message); + return Behaviors.same(); + }) + .build(); }); - - return Behaviors.receive(DaveProtocol.class) - // the adapted message ends up being processed like any other - // message sent to the actor - .onMessage(AdaptedResponse.class, (innerCtx, response) -> { - innerCtx.getLog().info("Got response from HAL: {}", response.message); - return Behaviors.same(); - }).build(); - }); } // #actor-ask - // #standalone-ask interface CookieCommand {} + static class GiveMeCookies implements CookieCommand { public final ActorRef cookies; + GiveMeCookies(ActorRef cookies) { this.cookies = cookies; } }; + static class Cookies {} - public void askAndPrint(ActorSystem system, ActorRef cookieActorRef) { - CompletionStage result = AskPattern.ask( - cookieActorRef, - GiveMeCookies::new, - // asking someone requires a timeout and a scheduler, if the timeout hits without response - // the ask is failed with a TimeoutException - Duration.ofSeconds(3), - system.scheduler()); + CompletionStage result = + AskPattern.ask( + cookieActorRef, + GiveMeCookies::new, + // asking someone requires a timeout and a scheduler, if the timeout hits without + // response + // the ask is failed with a TimeoutException + Duration.ofSeconds(3), + system.scheduler()); - result.whenComplete((cookies, failure) -> { - if (cookies != null) System.out.println("Yay, cookies!"); - else System.out.println("Boo! didn't get cookies in time."); - }); + result.whenComplete( + (cookies, failure) -> { + if (cookies != null) System.out.println("Yay, cookies!"); + else System.out.println("Boo! didn't get cookies in time."); + }); } // #standalone-ask - // #per-session-child // dummy data types just for this sample interface Keys {} + interface Wallet {} // #per-session-child @@ -471,14 +520,17 @@ public class InteractionPatternsTest extends JUnitSuite { class GetKeys { public final String whoseKeys; public final ActorRef respondTo; + public GetKeys(String whoseKeys, ActorRef respondTo) { this.whoseKeys = whoseKeys; this.respondTo = respondTo; } } + class GetWallet { public final String whoseWallet; public final ActorRef respondTo; + public GetWallet(String whoseWallet, ActorRef respondTo) { this.whoseWallet = whoseWallet; this.respondTo = respondTo; @@ -486,9 +538,11 @@ public class InteractionPatternsTest extends JUnitSuite { } interface HomeCommand {} + class LeaveHome implements HomeCommand { public final String who; public final ActorRef respondTo; + public LeaveHome(String who, ActorRef respondTo) { this.who = who; this.respondTo = respondTo; @@ -499,6 +553,7 @@ public class InteractionPatternsTest extends JUnitSuite { public final String who; public final Keys keys; public final Wallet wallet; + public ReadyToLeaveHome(String who, Keys keys, Wallet wallet) { this.who = who; this.keys = keys; @@ -508,16 +563,22 @@ public class InteractionPatternsTest extends JUnitSuite { // actor behavior public Behavior homeBehavior() { - return Behaviors.setup((context) -> { - final ActorRef keyCabinet = context.spawn(keyCabinetBehavior, "key-cabinet"); - final ActorRef drawer = context.spawn(drawerBehavior, "drawer"); + return Behaviors.setup( + (context) -> { + final ActorRef keyCabinet = context.spawn(keyCabinetBehavior, "key-cabinet"); + final ActorRef drawer = context.spawn(drawerBehavior, "drawer"); - return Behaviors.receive(HomeCommand.class) - .onMessage(LeaveHome.class, (innerCtx, message) -> { - context.spawn(new PrepareToLeaveHome(message.who, message.respondTo, keyCabinet, drawer), "leaving" + message.who); - return Behavior.same(); - }).build(); - }); + return Behaviors.receive(HomeCommand.class) + .onMessage( + LeaveHome.class, + (innerCtx, message) -> { + context.spawn( + new PrepareToLeaveHome(message.who, message.respondTo, keyCabinet, drawer), + "leaving" + message.who); + return Behavior.same(); + }) + .build(); + }); } // per session actor behavior @@ -528,7 +589,12 @@ public class InteractionPatternsTest extends JUnitSuite { private final ActorRef drawer; private Optional wallet = Optional.empty(); private Optional keys = Optional.empty(); - public PrepareToLeaveHome(String whoIsLeaving, ActorRef respondTo, ActorRef keyCabinet, ActorRef drawer) { + + public PrepareToLeaveHome( + String whoIsLeaving, + ActorRef respondTo, + ActorRef keyCabinet, + ActorRef drawer) { this.whoIsLeaving = whoIsLeaving; this.respondTo = respondTo; this.keyCabinet = keyCabinet; @@ -538,16 +604,21 @@ public class InteractionPatternsTest extends JUnitSuite { @Override public Receive createReceive() { return receiveBuilder() - .onMessage(Wallet.class, (wallet) -> { - this.wallet = Optional.of(wallet); - return completeOrContinue(); - }).onMessage(Keys.class, (keys) -> { - this.keys = Optional.of(keys); - return completeOrContinue(); - }).build(); + .onMessage( + Wallet.class, + (wallet) -> { + this.wallet = Optional.of(wallet); + return completeOrContinue(); + }) + .onMessage( + Keys.class, + (keys) -> { + this.keys = Optional.of(keys); + return completeOrContinue(); + }) + .build(); } - private Behavior completeOrContinue() { if (wallet.isPresent() && keys.isPresent()) { respondTo.tell(new ReadyToLeaveHome(whoIsLeaving, keys.get(), wallet.get())); @@ -559,9 +630,4 @@ public class InteractionPatternsTest extends JUnitSuite { } // #per-session-child - - } - - - diff --git a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/IntroTest.java b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/IntroTest.java index ba1ec6c108..8aac6edb1f 100644 --- a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/IntroTest.java +++ b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/IntroTest.java @@ -4,7 +4,7 @@ package jdocs.akka.typed; -//#imports +// #imports import akka.actor.typed.ActorRef; import akka.actor.typed.ActorSystem; @@ -14,7 +14,7 @@ import akka.actor.typed.Props; import akka.actor.typed.DispatcherSelector; import akka.actor.typed.javadsl.Behaviors; -//#imports +// #imports import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -23,14 +23,13 @@ import java.util.List; public class IntroTest { - //#hello-world-actor + // #hello-world-actor public abstract static class HelloWorld { - //no instances of this class, it's only a name space for messages + // no instances of this class, it's only a name space for messages // and static methods - private HelloWorld() { - } + private HelloWorld() {} - public static final class Greet{ + public static final class Greet { public final String whom; public final ActorRef replyTo; @@ -50,38 +49,39 @@ public class IntroTest { } } - public static final Behavior greeter = Behaviors.receive((context, message) -> { - context.getLog().info("Hello {}!", message.whom); - message.replyTo.tell(new Greeted(message.whom, context.getSelf())); - return Behaviors.same(); - }); + public static final Behavior greeter = + Behaviors.receive( + (context, message) -> { + context.getLog().info("Hello {}!", message.whom); + message.replyTo.tell(new Greeted(message.whom, context.getSelf())); + return Behaviors.same(); + }); } - //#hello-world-actor + // #hello-world-actor - //#hello-world-bot + // #hello-world-bot public abstract static class HelloWorldBot { - private HelloWorldBot() { - } + private HelloWorldBot() {} public static final Behavior bot(int greetingCounter, int max) { - return Behaviors.receive((context, message) -> { - int n = greetingCounter + 1; - context.getLog().info("Greeting {} for {}", n, message.whom); - if (n == max) { - return Behaviors.stopped(); - } else { - message.from.tell(new HelloWorld.Greet(message.whom, context.getSelf())); - return bot(n, max); - } - }); + return Behaviors.receive( + (context, message) -> { + int n = greetingCounter + 1; + context.getLog().info("Greeting {} for {}", n, message.whom); + if (n == max) { + return Behaviors.stopped(); + } else { + message.from.tell(new HelloWorld.Greet(message.whom, context.getSelf())); + return bot(n, max); + } + }); } } - //#hello-world-bot + // #hello-world-bot - //#hello-world-main + // #hello-world-main public abstract static class HelloWorldMain { - private HelloWorldMain() { - } + private HelloWorldMain() {} public static class Start { public final String name; @@ -92,23 +92,24 @@ public class IntroTest { } public static final Behavior main = - Behaviors.setup(context -> { - final ActorRef greeter = - context.spawn(HelloWorld.greeter, "greeter"); + Behaviors.setup( + context -> { + final ActorRef greeter = + context.spawn(HelloWorld.greeter, "greeter"); - return Behaviors.receiveMessage(message -> { - ActorRef replyTo = - context.spawn(HelloWorldBot.bot(0, 3), message.name); - greeter.tell(new HelloWorld.Greet(message.name, replyTo)); - return Behaviors.same(); - }); - }); + return Behaviors.receiveMessage( + message -> { + ActorRef replyTo = + context.spawn(HelloWorldBot.bot(0, 3), message.name); + greeter.tell(new HelloWorld.Greet(message.name, replyTo)); + return Behaviors.same(); + }); + }); } - //#hello-world-main + // #hello-world-main public abstract static class CustomDispatchersExample { - private CustomDispatchersExample() { - } + private CustomDispatchersExample() {} public static class Start { public final String name; @@ -118,79 +119,90 @@ public class IntroTest { } } - //#hello-world-main-with-dispatchers + // #hello-world-main-with-dispatchers public static final Behavior main = - Behaviors.setup(context -> { - final String dispatcherPath = "akka.actor.default-blocking-io-dispatcher"; + Behaviors.setup( + context -> { + final String dispatcherPath = "akka.actor.default-blocking-io-dispatcher"; - Props props = DispatcherSelector.fromConfig(dispatcherPath); - final ActorRef greeter = - context.spawn(HelloWorld.greeter, "greeter", props); + Props props = DispatcherSelector.fromConfig(dispatcherPath); + final ActorRef greeter = + context.spawn(HelloWorld.greeter, "greeter", props); - return Behaviors.receiveMessage(message -> { - ActorRef replyTo = - context.spawn(HelloWorldBot.bot(0, 3), message.name); - greeter.tell(new HelloWorld.Greet(message.name, replyTo)); - return Behaviors.same(); - }); - }); - //#hello-world-main-with-dispatchers + return Behaviors.receiveMessage( + message -> { + ActorRef replyTo = + context.spawn(HelloWorldBot.bot(0, 3), message.name); + greeter.tell(new HelloWorld.Greet(message.name, replyTo)); + return Behaviors.same(); + }); + }); + // #hello-world-main-with-dispatchers } public static void main(String[] args) throws Exception { - //#hello-world + // #hello-world final ActorSystem system = - ActorSystem.create(HelloWorldMain.main, "hello"); + ActorSystem.create(HelloWorldMain.main, "hello"); system.tell(new HelloWorldMain.Start("World")); system.tell(new HelloWorldMain.Start("Akka")); - //#hello-world + // #hello-world Thread.sleep(3000); system.terminate(); } - //#chatroom-actor + // #chatroom-actor public static class ChatRoom { - //#chatroom-protocol + // #chatroom-protocol static interface RoomCommand {} + public static final class GetSession implements RoomCommand { public final String screenName; public final ActorRef replyTo; + public GetSession(String screenName, ActorRef replyTo) { this.screenName = screenName; this.replyTo = replyTo; } } - //#chatroom-protocol - //#chatroom-behavior + // #chatroom-protocol + // #chatroom-behavior private static final class PublishSessionMessage implements RoomCommand { public final String screenName; public final String message; + public PublishSessionMessage(String screenName, String message) { this.screenName = screenName; this.message = message; } } - //#chatroom-behavior - //#chatroom-protocol + // #chatroom-behavior + // #chatroom-protocol static interface SessionEvent {} + public static final class SessionGranted implements SessionEvent { public final ActorRef handle; + public SessionGranted(ActorRef handle) { this.handle = handle; } } + public static final class SessionDenied implements SessionEvent { public final String reason; + public SessionDenied(String reason) { this.reason = reason; } } + public static final class MessagePosted implements SessionEvent { public final String screenName; public final String message; + public MessagePosted(String screenName, String message) { this.screenName = screenName; this.message = message; @@ -198,20 +210,24 @@ public class IntroTest { } static interface SessionCommand {} + public static final class PostMessage implements SessionCommand { public final String message; + public PostMessage(String message) { this.message = message; } } + private static final class NotifyClient implements SessionCommand { final MessagePosted message; + NotifyClient(MessagePosted message) { this.message = message; } } - //#chatroom-protocol - //#chatroom-behavior + // #chatroom-protocol + // #chatroom-behavior public static Behavior behavior() { return chatRoom(new ArrayList>()); @@ -219,96 +235,106 @@ public class IntroTest { private static Behavior chatRoom(List> sessions) { return Behaviors.receive(RoomCommand.class) - .onMessage(GetSession.class, (context, getSession) -> { - ActorRef client = getSession.replyTo; - ActorRef ses = context.spawn( - session(context.getSelf(), getSession.screenName, client), - URLEncoder.encode(getSession.screenName, StandardCharsets.UTF_8.name())); - // narrow to only expose PostMessage - client.tell(new SessionGranted(ses.narrow())); - List> newSessions = new ArrayList<>(sessions); - newSessions.add(ses); - return chatRoom(newSessions); - }) - .onMessage(PublishSessionMessage.class, (context, pub) -> { - NotifyClient notification = - new NotifyClient((new MessagePosted(pub.screenName, pub.message))); - sessions.forEach(s -> s.tell(notification)); - return Behaviors.same(); - }) - .build(); + .onMessage( + GetSession.class, + (context, getSession) -> { + ActorRef client = getSession.replyTo; + ActorRef ses = + context.spawn( + session(context.getSelf(), getSession.screenName, client), + URLEncoder.encode(getSession.screenName, StandardCharsets.UTF_8.name())); + // narrow to only expose PostMessage + client.tell(new SessionGranted(ses.narrow())); + List> newSessions = new ArrayList<>(sessions); + newSessions.add(ses); + return chatRoom(newSessions); + }) + .onMessage( + PublishSessionMessage.class, + (context, pub) -> { + NotifyClient notification = + new NotifyClient((new MessagePosted(pub.screenName, pub.message))); + sessions.forEach(s -> s.tell(notification)); + return Behaviors.same(); + }) + .build(); } public static Behavior session( - ActorRef room, - String screenName, - ActorRef client) { + ActorRef room, String screenName, ActorRef client) { return Behaviors.receive(ChatRoom.SessionCommand.class) - .onMessage(PostMessage.class, (context, post) -> { - // from client, publish to others via the room - room.tell(new PublishSessionMessage(screenName, post.message)); - return Behaviors.same(); - }) - .onMessage(NotifyClient.class, (context, notification) -> { - // published from the room - client.tell(notification.message); - return Behaviors.same(); - }) + .onMessage( + PostMessage.class, + (context, post) -> { + // from client, publish to others via the room + room.tell(new PublishSessionMessage(screenName, post.message)); + return Behaviors.same(); + }) + .onMessage( + NotifyClient.class, + (context, notification) -> { + // published from the room + client.tell(notification.message); + return Behaviors.same(); + }) .build(); } - //#chatroom-behavior + // #chatroom-behavior } - //#chatroom-actor + // #chatroom-actor - //#chatroom-gabbler - public static abstract class Gabbler { - private Gabbler() { - } + // #chatroom-gabbler + public abstract static class Gabbler { + private Gabbler() {} public static Behavior behavior() { return Behaviors.receive(ChatRoom.SessionEvent.class) - .onMessage(ChatRoom.SessionDenied.class, (context, message) -> { - System.out.println("cannot start chat room session: " + message.reason); - return Behaviors.stopped(); - }) - .onMessage(ChatRoom.SessionGranted.class, (context, message) -> { - message.handle.tell(new ChatRoom.PostMessage("Hello World!")); - return Behaviors.same(); - }) - .onMessage(ChatRoom.MessagePosted.class, (context, message) -> { - System.out.println("message has been posted by '" + - message.screenName +"': " + message.message); - return Behaviors.stopped(); - }) - .build(); + .onMessage( + ChatRoom.SessionDenied.class, + (context, message) -> { + System.out.println("cannot start chat room session: " + message.reason); + return Behaviors.stopped(); + }) + .onMessage( + ChatRoom.SessionGranted.class, + (context, message) -> { + message.handle.tell(new ChatRoom.PostMessage("Hello World!")); + return Behaviors.same(); + }) + .onMessage( + ChatRoom.MessagePosted.class, + (context, message) -> { + System.out.println( + "message has been posted by '" + message.screenName + "': " + message.message); + return Behaviors.stopped(); + }) + .build(); } - } - //#chatroom-gabbler + // #chatroom-gabbler public static void runChatRoom() throws Exception { - //#chatroom-main - Behavior main = Behaviors.setup(context -> { - ActorRef chatRoom = - context.spawn(ChatRoom.behavior(), "chatRoom"); - ActorRef gabbler = - context.spawn(Gabbler.behavior(), "gabbler"); - context.watch(gabbler); - chatRoom.tell(new ChatRoom.GetSession("ol’ Gabbler", gabbler)); + // #chatroom-main + Behavior main = + Behaviors.setup( + context -> { + ActorRef chatRoom = + context.spawn(ChatRoom.behavior(), "chatRoom"); + ActorRef gabbler = + context.spawn(Gabbler.behavior(), "gabbler"); + context.watch(gabbler); + chatRoom.tell(new ChatRoom.GetSession("ol’ Gabbler", gabbler)); - return Behaviors.receiveSignal( - (c, sig) -> { - if (sig instanceof Terminated) return Behaviors.stopped(); - else return Behaviors.unhandled(); - } - ); - }); + return Behaviors.receiveSignal( + (c, sig) -> { + if (sig instanceof Terminated) return Behaviors.stopped(); + else return Behaviors.unhandled(); + }); + }); - final ActorSystem system = - ActorSystem.create(main, "ChatRoomDemo"); - //#chatroom-main + final ActorSystem system = ActorSystem.create(main, "ChatRoomDemo"); + // #chatroom-main } - } diff --git a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/OOIntroTest.java b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/OOIntroTest.java index 8b5354ba7c..ca8650ccb4 100644 --- a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/OOIntroTest.java +++ b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/OOIntroTest.java @@ -4,7 +4,7 @@ package jdocs.akka.typed; -//#imports +// #imports import akka.NotUsed; import akka.actor.typed.ActorRef; import akka.actor.typed.ActorSystem; @@ -14,7 +14,7 @@ import akka.actor.typed.javadsl.AbstractBehavior; import akka.actor.typed.javadsl.ActorContext; import akka.actor.typed.javadsl.Behaviors; import akka.actor.typed.javadsl.Receive; -//#imports +// #imports import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -22,47 +22,56 @@ import java.util.List; public class OOIntroTest { - //#chatroom-actor + // #chatroom-actor public static class ChatRoom { - //#chatroom-protocol + // #chatroom-protocol static interface RoomCommand {} + public static final class GetSession implements RoomCommand { public final String screenName; public final ActorRef replyTo; + public GetSession(String screenName, ActorRef replyTo) { this.screenName = screenName; this.replyTo = replyTo; } } - //#chatroom-protocol - //#chatroom-behavior + // #chatroom-protocol + // #chatroom-behavior private static final class PublishSessionMessage implements RoomCommand { public final String screenName; public final String message; + public PublishSessionMessage(String screenName, String message) { this.screenName = screenName; this.message = message; } } - //#chatroom-behavior - //#chatroom-protocol + // #chatroom-behavior + // #chatroom-protocol static interface SessionEvent {} + public static final class SessionGranted implements SessionEvent { public final ActorRef handle; + public SessionGranted(ActorRef handle) { this.handle = handle; } } + public static final class SessionDenied implements SessionEvent { public final String reason; + public SessionDenied(String reason) { this.reason = reason; } } + public static final class MessagePosted implements SessionEvent { public final String screenName; public final String message; + public MessagePosted(String screenName, String message) { this.screenName = screenName; this.message = message; @@ -70,20 +79,24 @@ public class OOIntroTest { } static interface SessionCommand {} + public static final class PostMessage implements SessionCommand { public final String message; + public PostMessage(String message) { this.message = message; } } + private static final class NotifyClient implements SessionCommand { final MessagePosted message; + NotifyClient(MessagePosted message) { this.message = message; } } - //#chatroom-protocol - //#chatroom-behavior + // #chatroom-protocol + // #chatroom-behavior public static Behavior behavior() { return Behaviors.setup(ChatRoomBehavior::new); @@ -100,95 +113,105 @@ public class OOIntroTest { @Override public Receive createReceive() { return receiveBuilder() - .onMessage(GetSession.class, getSession -> { - ActorRef client = getSession.replyTo; - ActorRef ses = context.spawn( - session(context.getSelf(), getSession.screenName, client), - URLEncoder.encode(getSession.screenName, StandardCharsets.UTF_8.name())); - // narrow to only expose PostMessage - client.tell(new SessionGranted(ses.narrow())); - sessions.add(ses); - return this; - }) - .onMessage(PublishSessionMessage.class, pub -> { - NotifyClient notification = - new NotifyClient((new MessagePosted(pub.screenName, pub.message))); - sessions.forEach(s -> s.tell(notification)); - return this; - }) - .build(); + .onMessage( + GetSession.class, + getSession -> { + ActorRef client = getSession.replyTo; + ActorRef ses = + context.spawn( + session(context.getSelf(), getSession.screenName, client), + URLEncoder.encode(getSession.screenName, StandardCharsets.UTF_8.name())); + // narrow to only expose PostMessage + client.tell(new SessionGranted(ses.narrow())); + sessions.add(ses); + return this; + }) + .onMessage( + PublishSessionMessage.class, + pub -> { + NotifyClient notification = + new NotifyClient((new MessagePosted(pub.screenName, pub.message))); + sessions.forEach(s -> s.tell(notification)); + return this; + }) + .build(); } } public static Behavior session( - ActorRef room, - String screenName, - ActorRef client) { + ActorRef room, String screenName, ActorRef client) { return Behaviors.receive(ChatRoom.SessionCommand.class) - .onMessage(PostMessage.class, (context, post) -> { - // from client, publish to others via the room - room.tell(new PublishSessionMessage(screenName, post.message)); - return Behaviors.same(); - }) - .onMessage(NotifyClient.class, (context, notification) -> { - // published from the room - client.tell(notification.message); - return Behaviors.same(); - }) + .onMessage( + PostMessage.class, + (context, post) -> { + // from client, publish to others via the room + room.tell(new PublishSessionMessage(screenName, post.message)); + return Behaviors.same(); + }) + .onMessage( + NotifyClient.class, + (context, notification) -> { + // published from the room + client.tell(notification.message); + return Behaviors.same(); + }) .build(); } - //#chatroom-behavior + // #chatroom-behavior } - //#chatroom-actor + // #chatroom-actor - - //#chatroom-gabbler - public static abstract class Gabbler { - private Gabbler() { - } + // #chatroom-gabbler + public abstract static class Gabbler { + private Gabbler() {} public static Behavior behavior() { return Behaviors.receive(ChatRoom.SessionEvent.class) - .onMessage(ChatRoom.SessionDenied.class, (context, message) -> { - System.out.println("cannot start chat room session: " + message.reason); - return Behaviors.stopped(); - }) - .onMessage(ChatRoom.SessionGranted.class, (context, message) -> { - message.handle.tell(new ChatRoom.PostMessage("Hello World!")); - return Behaviors.same(); - }) - .onMessage(ChatRoom.MessagePosted.class, (context, message) -> { - System.out.println("message has been posted by '" + - message.screenName +"': " + message.message); - return Behaviors.stopped(); - }) + .onMessage( + ChatRoom.SessionDenied.class, + (context, message) -> { + System.out.println("cannot start chat room session: " + message.reason); + return Behaviors.stopped(); + }) + .onMessage( + ChatRoom.SessionGranted.class, + (context, message) -> { + message.handle.tell(new ChatRoom.PostMessage("Hello World!")); + return Behaviors.same(); + }) + .onMessage( + ChatRoom.MessagePosted.class, + (context, message) -> { + System.out.println( + "message has been posted by '" + message.screenName + "': " + message.message); + return Behaviors.stopped(); + }) .build(); } - } - //#chatroom-gabbler + // #chatroom-gabbler public static void runChatRoom() throws Exception { - //#chatroom-main - Behavior main = Behaviors.setup(context -> { - ActorRef chatRoom = - context.spawn(ChatRoom.behavior(), "chatRoom"); - ActorRef gabbler = - context.spawn(Gabbler.behavior(), "gabbler"); - context.watch(gabbler); - chatRoom.tell(new ChatRoom.GetSession("ol’ Gabbler", gabbler)); + // #chatroom-main + Behavior main = + Behaviors.setup( + context -> { + ActorRef chatRoom = + context.spawn(ChatRoom.behavior(), "chatRoom"); + ActorRef gabbler = + context.spawn(Gabbler.behavior(), "gabbler"); + context.watch(gabbler); + chatRoom.tell(new ChatRoom.GetSession("ol’ Gabbler", gabbler)); - return Behaviors.receiveSignal( - (c, sig) -> { - if (sig instanceof Terminated) return Behaviors.stopped(); - else return Behaviors.unhandled(); - } - ); - }); + return Behaviors.receiveSignal( + (c, sig) -> { + if (sig instanceof Terminated) return Behaviors.stopped(); + else return Behaviors.unhandled(); + }); + }); - final ActorSystem system = - ActorSystem.create(main, "ChatRoomDemo"); - //#chatroom-main + final ActorSystem system = ActorSystem.create(main, "ChatRoomDemo"); + // #chatroom-main } } diff --git a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/SpawnProtocolDocTest.java b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/SpawnProtocolDocTest.java index 95d7244d1b..99a848d04c 100644 --- a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/SpawnProtocolDocTest.java +++ b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/SpawnProtocolDocTest.java @@ -9,79 +9,81 @@ import jdocs.akka.typed.IntroTest.HelloWorld; import java.time.Duration; import java.util.concurrent.CompletionStage; -//#imports1 +// #imports1 import akka.actor.typed.Behavior; import akka.actor.typed.SpawnProtocol; import akka.actor.typed.javadsl.Behaviors; -//#imports1 +// #imports1 -//#imports2 +// #imports2 import akka.actor.typed.ActorRef; import akka.actor.typed.ActorSystem; import akka.actor.typed.Props; import akka.actor.typed.javadsl.AskPattern; import akka.util.Timeout; -//#imports2 +// #imports2 public class SpawnProtocolDocTest { - //#main + // #main public abstract static class HelloWorldMain { - private HelloWorldMain() { - } + private HelloWorldMain() {} public static final Behavior main = - Behaviors.setup( context -> { - // Start initial tasks - // context.spawn(...) + Behaviors.setup( + context -> { + // Start initial tasks + // context.spawn(...) - return SpawnProtocol.behavior(); - }); + return SpawnProtocol.behavior(); + }); } - //#main + // #main public static void main(String[] args) throws Exception { - //#system-spawn - final ActorSystem system = - ActorSystem.create(HelloWorldMain.main, "hello"); + // #system-spawn + final ActorSystem system = ActorSystem.create(HelloWorldMain.main, "hello"); final Duration timeout = Duration.ofSeconds(3); - CompletionStage> greeter = AskPattern.ask( - system, - replyTo -> new SpawnProtocol.Spawn<>(HelloWorld.greeter, "greeter", - Props.empty(), replyTo), - timeout, - system.scheduler()); + CompletionStage> greeter = + AskPattern.ask( + system, + replyTo -> + new SpawnProtocol.Spawn<>(HelloWorld.greeter, "greeter", Props.empty(), replyTo), + timeout, + system.scheduler()); Behavior greetedBehavior = - Behaviors.receive((context, message) -> { - context.getLog().info("Greeting for {} from {}", message.whom, message.from); - return Behaviors.stopped(); - }); + Behaviors.receive( + (context, message) -> { + context.getLog().info("Greeting for {} from {}", message.whom, message.from); + return Behaviors.stopped(); + }); - CompletionStage> greetedReplyTo = AskPattern.ask( - system, - replyTo -> new SpawnProtocol.Spawn<>(greetedBehavior, "", - Props.empty(), replyTo), - timeout, - system.scheduler()); + CompletionStage> greetedReplyTo = + AskPattern.ask( + system, + replyTo -> new SpawnProtocol.Spawn<>(greetedBehavior, "", Props.empty(), replyTo), + timeout, + system.scheduler()); - greeter.whenComplete((greeterRef, exc) -> { - if (exc == null) { - greetedReplyTo.whenComplete((greetedReplyToRef, exc2) -> { - if (exc2 == null) { - greeterRef.tell(new HelloWorld.Greet("Akka", greetedReplyToRef)); + greeter.whenComplete( + (greeterRef, exc) -> { + if (exc == null) { + greetedReplyTo.whenComplete( + (greetedReplyToRef, exc2) -> { + if (exc2 == null) { + greeterRef.tell(new HelloWorld.Greet("Akka", greetedReplyToRef)); + } + }); } }); - } - }); - //#system-spawn + // #system-spawn Thread.sleep(3000); system.terminate(); } - } diff --git a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/StashDocTest.java b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/StashDocTest.java index 77d15107cc..8b250ce56b 100644 --- a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/StashDocTest.java +++ b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/StashDocTest.java @@ -4,9 +4,9 @@ package jdocs.akka.typed; -//#import +// #import import akka.actor.typed.javadsl.StashBuffer; -//#import +// #import import akka.Done; import akka.actor.typed.ActorRef; @@ -23,20 +23,20 @@ import java.util.concurrent.CompletionStage; public class StashDocTest extends JUnitSuite { - //#db + // #db interface DB { CompletionStage save(String id, String value); + CompletionStage load(String id); } - //#db + // #db - //#stashing + // #stashing public static class DataAccess { - static interface Command { - } + static interface Command {} public static class Save implements Command { public final String payload; @@ -67,8 +67,7 @@ public class StashDocTest extends JUnitSuite { static class SaveSuccess implements Command { public static final SaveSuccess instance = new SaveSuccess(); - private SaveSuccess() { - } + private SaveSuccess() {} } static class DBError implements Command { @@ -79,7 +78,6 @@ public class StashDocTest extends JUnitSuite { } } - private final StashBuffer buffer = StashBuffer.create(100); private final String id; private final DB db; @@ -90,70 +88,86 @@ public class StashDocTest extends JUnitSuite { } Behavior behavior() { - return Behaviors.setup(context -> { - context.pipeToSelf(db.load(id), (value, cause) -> { - if (cause == null) - return new InitialState(value); - else - return new DBError(asRuntimeException(cause)); - }); + return Behaviors.setup( + context -> { + context.pipeToSelf( + db.load(id), + (value, cause) -> { + if (cause == null) return new InitialState(value); + else return new DBError(asRuntimeException(cause)); + }); - return init(); - }); + return init(); + }); } private Behavior init() { return Behaviors.receive(Command.class) - .onMessage(InitialState.class, (context, message) -> { - // now we are ready to handle stashed messages if any - return buffer.unstashAll(context, active(message.value)); - }) - .onMessage(DBError.class, (context, message) -> { - throw message.cause; - }) - .onMessage(Command.class, (context, message) -> { - // stash all other messages for later processing - buffer.stash(message); - return Behaviors.same(); - }) + .onMessage( + InitialState.class, + (context, message) -> { + // now we are ready to handle stashed messages if any + return buffer.unstashAll(context, active(message.value)); + }) + .onMessage( + DBError.class, + (context, message) -> { + throw message.cause; + }) + .onMessage( + Command.class, + (context, message) -> { + // stash all other messages for later processing + buffer.stash(message); + return Behaviors.same(); + }) .build(); } private Behavior active(String state) { return Behaviors.receive(Command.class) - .onMessage(Get.class, (context, message) -> { - message.replyTo.tell(state); - return Behaviors.same(); - }) - .onMessage(Save.class, (context, message) -> { - context.pipeToSelf(db.save(id, message.payload), (value, cause) -> { - if (cause == null) - return SaveSuccess.instance; - else - return new DBError(asRuntimeException(cause)); - }); - return saving(message.payload, message.replyTo); - }) + .onMessage( + Get.class, + (context, message) -> { + message.replyTo.tell(state); + return Behaviors.same(); + }) + .onMessage( + Save.class, + (context, message) -> { + context.pipeToSelf( + db.save(id, message.payload), + (value, cause) -> { + if (cause == null) return SaveSuccess.instance; + else return new DBError(asRuntimeException(cause)); + }); + return saving(message.payload, message.replyTo); + }) .build(); } private Behavior saving(String state, ActorRef replyTo) { return Behaviors.receive(Command.class) - .onMessageEquals(SaveSuccess.instance, context -> { - replyTo.tell(Done.getInstance()); - return buffer.unstashAll(context, active(state)); - }) - .onMessage(DBError.class, (context, message) -> { - throw message.cause; - }) - .onMessage(Command.class, (context, message) -> { - buffer.stash(message); - return Behaviors.same(); - }) + .onMessageEquals( + SaveSuccess.instance, + context -> { + replyTo.tell(Done.getInstance()); + return buffer.unstashAll(context, active(state)); + }) + .onMessage( + DBError.class, + (context, message) -> { + throw message.cause; + }) + .onMessage( + Command.class, + (context, message) -> { + buffer.stash(message); + return Behaviors.same(); + }) .build(); } - private static RuntimeException asRuntimeException(Throwable t) { // can't throw Throwable in lambdas if (t instanceof RuntimeException) { @@ -162,27 +176,27 @@ public class StashDocTest extends JUnitSuite { return new RuntimeException(t); } } - } - //#stashing - - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(); + // #stashing + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(); @Test public void stashingExample() throws Exception { - final DB db = new DB() { - public CompletionStage save(String id, String value) { - return CompletableFuture.completedFuture(Done.getInstance()); - } - public CompletionStage load(String id) { - return CompletableFuture.completedFuture("TheValue"); - } - }; + final DB db = + new DB() { + public CompletionStage save(String id, String value) { + return CompletableFuture.completedFuture(Done.getInstance()); + } - final ActorRef dataAccess = testKit.spawn(new DataAccess("17", db).behavior()); + public CompletionStage load(String id) { + return CompletableFuture.completedFuture("TheValue"); + } + }; + + final ActorRef dataAccess = + testKit.spawn(new DataAccess("17", db).behavior()); TestProbe getInbox = testKit.createTestProbe(String.class); dataAccess.tell(new DataAccess.Get(getInbox.getRef())); getInbox.expectMessage("TheValue"); @@ -196,8 +210,4 @@ public class StashDocTest extends JUnitSuite { dataAccess.tell(new DataAccess.Get(getInbox.getRef())); getInbox.expectMessage("UpdatedValue"); } - } - - - diff --git a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/coexistence/TypedWatchingUntypedTest.java b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/coexistence/TypedWatchingUntypedTest.java index 0051746205..7031cfb83b 100644 --- a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/coexistence/TypedWatchingUntypedTest.java +++ b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/coexistence/TypedWatchingUntypedTest.java @@ -8,10 +8,10 @@ import akka.actor.AbstractActor; import akka.actor.ActorSystem; import akka.actor.typed.ActorRef; import akka.actor.typed.Behavior; -//#adapter-import +// #adapter-import // in Java use the static methods on Adapter to convert from untyped to typed import akka.actor.typed.javadsl.Adapter; -//#adapter-import +// #adapter-import import akka.testkit.javadsl.TestKit; import akka.testkit.TestProbe; import org.junit.Test; @@ -23,8 +23,8 @@ import static akka.actor.typed.javadsl.Behaviors.stopped; public class TypedWatchingUntypedTest extends JUnitSuite { - //#typed - public static abstract class Typed { + // #typed + public abstract static class Typed { public static class Ping { public final akka.actor.typed.ActorRef replyTo; @@ -33,31 +33,35 @@ public class TypedWatchingUntypedTest extends JUnitSuite { } } - interface Command { } - public static class Pong implements Command { } + interface Command {} + + public static class Pong implements Command {} public static Behavior behavior() { - return akka.actor.typed.javadsl.Behaviors.setup(context -> { - akka.actor.ActorRef second = Adapter.actorOf(context, Untyped.props(), "second"); + return akka.actor.typed.javadsl.Behaviors.setup( + context -> { + akka.actor.ActorRef second = Adapter.actorOf(context, Untyped.props(), "second"); - Adapter.watch(context, second); + Adapter.watch(context, second); - second.tell(new Typed.Ping(context.getSelf().narrow()), - Adapter.toUntyped(context.getSelf())); + second.tell( + new Typed.Ping(context.getSelf().narrow()), Adapter.toUntyped(context.getSelf())); - return akka.actor.typed.javadsl.Behaviors.receive(Typed.Command.class) - .onMessage(Typed.Pong.class, (_ctx, message) -> { - Adapter.stop(context, second); - return same(); - }) - .onSignal(akka.actor.typed.Terminated.class, (_ctx, sig) -> stopped()) - .build(); - }); + return akka.actor.typed.javadsl.Behaviors.receive(Typed.Command.class) + .onMessage( + Typed.Pong.class, + (_ctx, message) -> { + Adapter.stop(context, second); + return same(); + }) + .onSignal(akka.actor.typed.Terminated.class, (_ctx, sig) -> stopped()) + .build(); + }); } } - //#typed + // #typed - //#untyped + // #untyped public static class Untyped extends AbstractActor { public static akka.actor.Props props() { return akka.actor.Props.create(Untyped.class); @@ -66,20 +70,22 @@ public class TypedWatchingUntypedTest extends JUnitSuite { @Override public Receive createReceive() { return receiveBuilder() - .match(Typed.Ping.class, message -> { - message.replyTo.tell(new Typed.Pong()); - }) - .build(); + .match( + Typed.Ping.class, + message -> { + message.replyTo.tell(new Typed.Pong()); + }) + .build(); } } - //#untyped + // #untyped @Test public void testItWorks() { - //#create + // #create ActorSystem as = ActorSystem.create(); ActorRef typed = Adapter.spawn(as, Typed.behavior(), "Typed"); - //#create + // #create TestProbe probe = new TestProbe(as); probe.watch(Adapter.toUntyped(typed)); probe.expectTerminated(Adapter.toUntyped(typed), Duration.create(1, "second")); diff --git a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/coexistence/UntypedWatchingTypedTest.java b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/coexistence/UntypedWatchingTypedTest.java index c93ef03809..e32f905fb2 100644 --- a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/coexistence/UntypedWatchingTypedTest.java +++ b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/coexistence/UntypedWatchingTypedTest.java @@ -9,10 +9,10 @@ import akka.actor.typed.ActorRef; import akka.actor.typed.ActorSystem; import akka.actor.typed.Behavior; import akka.actor.typed.javadsl.Behaviors; -//#adapter-import +// #adapter-import // In java use the static methods on Adapter to convert from typed to untyped import akka.actor.typed.javadsl.Adapter; -//#adapter-import +// #adapter-import import akka.testkit.TestProbe; import akka.testkit.javadsl.TestKit; import org.junit.Test; @@ -23,14 +23,14 @@ import static akka.actor.typed.javadsl.Behaviors.same; public class UntypedWatchingTypedTest extends JUnitSuite { - //#untyped-watch + // #untyped-watch public static class Untyped extends AbstractActor { public static akka.actor.Props props() { return akka.actor.Props.create(Untyped.class); } private final akka.actor.typed.ActorRef second = - Adapter.spawn(getContext(), Typed.behavior(), "second"); + Adapter.spawn(getContext(), Typed.behavior(), "second"); @Override public void preStart() { @@ -41,20 +41,24 @@ public class UntypedWatchingTypedTest extends JUnitSuite { @Override public Receive createReceive() { return receiveBuilder() - .match(Typed.Pong.class, message -> { - Adapter.stop(getContext(), second); - }) - .match(akka.actor.Terminated.class, t -> { - getContext().stop(getSelf()); - }) - .build(); + .match( + Typed.Pong.class, + message -> { + Adapter.stop(getContext(), second); + }) + .match( + akka.actor.Terminated.class, + t -> { + getContext().stop(getSelf()); + }) + .build(); } } - //#untyped-watch + // #untyped-watch - //#typed - public static abstract class Typed { - interface Command { } + // #typed + public abstract static class Typed { + interface Command {} public static class Ping implements Command { public final akka.actor.typed.ActorRef replyTo; @@ -64,25 +68,27 @@ public class UntypedWatchingTypedTest extends JUnitSuite { } } - public static class Pong { } + public static class Pong {} public static Behavior behavior() { return Behaviors.receive(Typed.Command.class) - .onMessage(Typed.Ping.class, (context, message) -> { - message.replyTo.tell(new Pong()); - return same(); - }) - .build(); + .onMessage( + Typed.Ping.class, + (context, message) -> { + message.replyTo.tell(new Pong()); + return same(); + }) + .build(); } } - //#typed + // #typed @Test public void testItWorks() { - //#create-untyped + // #create-untyped akka.actor.ActorSystem as = akka.actor.ActorSystem.create(); akka.actor.ActorRef untyped = as.actorOf(Untyped.props()); - //#create-untyped + // #create-untyped TestProbe probe = new TestProbe(as); probe.watch(untyped); probe.expectTerminated(untyped, Duration.create(1, "second")); @@ -91,10 +97,10 @@ public class UntypedWatchingTypedTest extends JUnitSuite { @Test public void testConversionFromUnTypedSystemToTyped() { - //#convert-untyped + // #convert-untyped akka.actor.ActorSystem untypedActorSystem = akka.actor.ActorSystem.create(); ActorSystem typedActorSystem = Adapter.toTyped(untypedActorSystem); - //#convert-untyped + // #convert-untyped TestKit.shutdownActorSystem(untypedActorSystem); } } diff --git a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/supervision/SupervisionCompileOnlyTest.java b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/supervision/SupervisionCompileOnlyTest.java index 168f6ab282..1a0ec4fa4b 100644 --- a/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/supervision/SupervisionCompileOnlyTest.java +++ b/akka-actor-typed-tests/src/test/java/jdocs/akka/typed/supervision/SupervisionCompileOnlyTest.java @@ -13,10 +13,10 @@ import scala.concurrent.duration.FiniteDuration; import java.util.concurrent.TimeUnit; public class SupervisionCompileOnlyTest { - //#wrap - interface CounterMessage { } + // #wrap + interface CounterMessage {} - public static final class Increase implements CounterMessage { } + public static final class Increase implements CounterMessage {} public static final class Get implements CounterMessage { final ActorRef sender; @@ -36,46 +36,50 @@ public class SupervisionCompileOnlyTest { public static Behavior counter(int currentValue) { return Behaviors.receive(CounterMessage.class) - .onMessage(Increase.class, (context, o) -> { - return counter(currentValue + 1); - }) - .onMessage(Get.class, (context, o) -> { - o.sender.tell(new Got(currentValue)); - return Behaviors.same(); - }) - .build(); + .onMessage( + Increase.class, + (context, o) -> { + return counter(currentValue + 1); + }) + .onMessage( + Get.class, + (context, o) -> { + o.sender.tell(new Got(currentValue)); + return Behaviors.same(); + }) + .build(); } - //#wrap + // #wrap public static Behavior behavior = Behaviors.empty(); public void supervision() { - //#restart + // #restart Behaviors.supervise(behavior) - .onFailure(IllegalStateException.class, SupervisorStrategy.restart()); - //#restart + .onFailure(IllegalStateException.class, SupervisorStrategy.restart()); + // #restart - //#resume + // #resume Behaviors.supervise(behavior) - .onFailure(IllegalStateException.class, SupervisorStrategy.resume()); - //#resume + .onFailure(IllegalStateException.class, SupervisorStrategy.resume()); + // #resume - //#restart-limit + // #restart-limit Behaviors.supervise(behavior) - .onFailure(IllegalStateException.class, SupervisorStrategy.restartWithLimit( - 10, FiniteDuration.apply(10, TimeUnit.SECONDS) - )); - //#restart-limit + .onFailure( + IllegalStateException.class, + SupervisorStrategy.restartWithLimit(10, FiniteDuration.apply(10, TimeUnit.SECONDS))); + // #restart-limit - //#multiple - Behaviors.supervise(Behaviors.supervise(behavior) - .onFailure(IllegalStateException.class, SupervisorStrategy.restart())) - .onFailure(IllegalArgumentException.class, SupervisorStrategy.stop()); - //#multiple + // #multiple + Behaviors.supervise( + Behaviors.supervise(behavior) + .onFailure(IllegalStateException.class, SupervisorStrategy.restart())) + .onFailure(IllegalArgumentException.class, SupervisorStrategy.stop()); + // #multiple - - //#top-level + // #top-level Behaviors.supervise(counter(1)); - //#top-level + // #top-level } } diff --git a/akka-actor/src/main/java/akka/actor/AbstractActorRef.java b/akka-actor/src/main/java/akka/actor/AbstractActorRef.java index 3ca7dc2404..b760c6aaf5 100644 --- a/akka-actor/src/main/java/akka/actor/AbstractActorRef.java +++ b/akka-actor/src/main/java/akka/actor/AbstractActorRef.java @@ -7,15 +7,19 @@ package akka.actor; import akka.util.Unsafe; final class AbstractActorRef { - final static long cellOffset; - final static long lookupOffset; + static final long cellOffset; + static final long lookupOffset; - static { - try { - cellOffset = Unsafe.instance.objectFieldOffset(RepointableActorRef.class.getDeclaredField("_cellDoNotCallMeDirectly")); - lookupOffset = Unsafe.instance.objectFieldOffset(RepointableActorRef.class.getDeclaredField("_lookupDoNotCallMeDirectly")); - } catch(Throwable t){ - throw new ExceptionInInitializerError(t); - } + static { + try { + cellOffset = + Unsafe.instance.objectFieldOffset( + RepointableActorRef.class.getDeclaredField("_cellDoNotCallMeDirectly")); + lookupOffset = + Unsafe.instance.objectFieldOffset( + RepointableActorRef.class.getDeclaredField("_lookupDoNotCallMeDirectly")); + } catch (Throwable t) { + throw new ExceptionInInitializerError(t); } + } } diff --git a/akka-actor/src/main/java/akka/actor/AbstractScheduler.java b/akka-actor/src/main/java/akka/actor/AbstractScheduler.java index 4ae2e819da..0816098184 100644 --- a/akka-actor/src/main/java/akka/actor/AbstractScheduler.java +++ b/akka-actor/src/main/java/akka/actor/AbstractScheduler.java @@ -8,76 +8,72 @@ import akka.util.JavaDurationConverters; import scala.concurrent.ExecutionContext; import scala.concurrent.duration.FiniteDuration; -//#scheduler +// #scheduler /** - * An Akka scheduler service. This one needs one special behavior: if - * Closeable, it MUST execute all outstanding tasks upon .close() in order - * to properly shutdown all dispatchers. + * An Akka scheduler service. This one needs one special behavior: if Closeable, it MUST execute all + * outstanding tasks upon .close() in order to properly shutdown all dispatchers. * - * Furthermore, this timer service MUST throw IllegalStateException if it - * cannot schedule a task. Once scheduled, the task MUST be executed. If - * executed upon close(), the task may execute before its timeout. + *

Furthermore, this timer service MUST throw IllegalStateException if it cannot schedule a task. + * Once scheduled, the task MUST be executed. If executed upon close(), the task may execute before + * its timeout. * - * Scheduler implementation are loaded reflectively at ActorSystem start-up - * with the following constructor arguments: - * 1) the system’s com.typesafe.config.Config (from system.settings.config) - * 2) a akka.event.LoggingAdapter - * 3) a java.util.concurrent.ThreadFactory + *

Scheduler implementation are loaded reflectively at ActorSystem start-up with the following + * constructor arguments: 1) the system’s com.typesafe.config.Config (from system.settings.config) + * 2) a akka.event.LoggingAdapter 3) a java.util.concurrent.ThreadFactory */ public abstract class AbstractScheduler extends AbstractSchedulerBase { /** - * Schedules a function to be run repeatedly with an initial delay and - * a frequency. E.g. if you would like the function to be run after 2 - * seconds and thereafter every 100ms you would set delay = Duration(2, - * TimeUnit.SECONDS) and interval = Duration(100, TimeUnit.MILLISECONDS) + * Schedules a function to be run repeatedly with an initial delay and a frequency. E.g. if you + * would like the function to be run after 2 seconds and thereafter every 100ms you would set + * delay = Duration(2, TimeUnit.SECONDS) and interval = Duration(100, TimeUnit.MILLISECONDS) */ @Override - public abstract Cancellable schedule(FiniteDuration initialDelay, - FiniteDuration interval, - Runnable runnable, - ExecutionContext executor); + public abstract Cancellable schedule( + FiniteDuration initialDelay, + FiniteDuration interval, + Runnable runnable, + ExecutionContext executor); /** - * Schedules a function to be run repeatedly with an initial delay and - * a frequency. E.g. if you would like the function to be run after 2 - * seconds and thereafter every 100ms you would set delay = Duration(2, - * TimeUnit.SECONDS) and interval = Duration.ofMillis(100) + * Schedules a function to be run repeatedly with an initial delay and a frequency. E.g. if you + * would like the function to be run after 2 seconds and thereafter every 100ms you would set + * delay = Duration(2, TimeUnit.SECONDS) and interval = Duration.ofMillis(100) */ - public Cancellable schedule(final java.time.Duration initialDelay, - final java.time.Duration interval, - final Runnable runnable, - final ExecutionContext executor) { - return schedule( - JavaDurationConverters.asFiniteDuration(initialDelay), - JavaDurationConverters.asFiniteDuration(interval), - runnable, - executor); + public Cancellable schedule( + final java.time.Duration initialDelay, + final java.time.Duration interval, + final Runnable runnable, + final ExecutionContext executor) { + return schedule( + JavaDurationConverters.asFiniteDuration(initialDelay), + JavaDurationConverters.asFiniteDuration(interval), + runnable, + executor); } /** - * Schedules a Runnable to be run once with a delay, i.e. a time period that - * has to pass before the runnable is executed. + * Schedules a Runnable to be run once with a delay, i.e. a time period that has to pass before + * the runnable is executed. */ @Override - public abstract Cancellable scheduleOnce(FiniteDuration delay, Runnable runnable, - ExecutionContext executor); + public abstract Cancellable scheduleOnce( + FiniteDuration delay, Runnable runnable, ExecutionContext executor); /** - * Schedules a Runnable to be run once with a delay, i.e. a time period that - * has to pass before the runnable is executed. + * Schedules a Runnable to be run once with a delay, i.e. a time period that has to pass before + * the runnable is executed. */ - public Cancellable scheduleOnce(final java.time.Duration delay, - final Runnable runnable, - final ExecutionContext executor) { - return scheduleOnce(JavaDurationConverters.asFiniteDuration(delay), runnable, executor); + public Cancellable scheduleOnce( + final java.time.Duration delay, final Runnable runnable, final ExecutionContext executor) { + return scheduleOnce(JavaDurationConverters.asFiniteDuration(delay), runnable, executor); } /** - * The maximum supported task frequency of this scheduler, i.e. the inverse - * of the minimum time interval between executions of a recurring task, in Hz. + * The maximum supported task frequency of this scheduler, i.e. the inverse of the minimum time + * interval between executions of a recurring task, in Hz. */ @Override public abstract double maxFrequency(); } -//#scheduler +// #scheduler diff --git a/akka-actor/src/main/java/akka/actor/dungeon/AbstractActorCell.java b/akka-actor/src/main/java/akka/actor/dungeon/AbstractActorCell.java index e2a35815fe..39194d75a5 100644 --- a/akka-actor/src/main/java/akka/actor/dungeon/AbstractActorCell.java +++ b/akka-actor/src/main/java/akka/actor/dungeon/AbstractActorCell.java @@ -8,19 +8,31 @@ import akka.actor.ActorCell; import akka.util.Unsafe; final class AbstractActorCell { - final static long mailboxOffset; - final static long childrenOffset; - final static long nextNameOffset; - final static long functionRefsOffset; + static final long mailboxOffset; + static final long childrenOffset; + static final long nextNameOffset; + static final long functionRefsOffset; - static { - try { - mailboxOffset = Unsafe.instance.objectFieldOffset(ActorCell.class.getDeclaredField("akka$actor$dungeon$Dispatch$$_mailboxDoNotCallMeDirectly")); - childrenOffset = Unsafe.instance.objectFieldOffset(ActorCell.class.getDeclaredField("akka$actor$dungeon$Children$$_childrenRefsDoNotCallMeDirectly")); - nextNameOffset = Unsafe.instance.objectFieldOffset(ActorCell.class.getDeclaredField("akka$actor$dungeon$Children$$_nextNameDoNotCallMeDirectly")); - functionRefsOffset = Unsafe.instance.objectFieldOffset(ActorCell.class.getDeclaredField("akka$actor$dungeon$Children$$_functionRefsDoNotCallMeDirectly")); - } catch(Throwable t){ - throw new ExceptionInInitializerError(t); - } + static { + try { + mailboxOffset = + Unsafe.instance.objectFieldOffset( + ActorCell.class.getDeclaredField( + "akka$actor$dungeon$Dispatch$$_mailboxDoNotCallMeDirectly")); + childrenOffset = + Unsafe.instance.objectFieldOffset( + ActorCell.class.getDeclaredField( + "akka$actor$dungeon$Children$$_childrenRefsDoNotCallMeDirectly")); + nextNameOffset = + Unsafe.instance.objectFieldOffset( + ActorCell.class.getDeclaredField( + "akka$actor$dungeon$Children$$_nextNameDoNotCallMeDirectly")); + functionRefsOffset = + Unsafe.instance.objectFieldOffset( + ActorCell.class.getDeclaredField( + "akka$actor$dungeon$Children$$_functionRefsDoNotCallMeDirectly")); + } catch (Throwable t) { + throw new ExceptionInInitializerError(t); } + } } diff --git a/akka-actor/src/main/java/akka/annotation/ApiMayChange.java b/akka-actor/src/main/java/akka/annotation/ApiMayChange.java index fa0b36d8ce..dfaad04252 100644 --- a/akka-actor/src/main/java/akka/annotation/ApiMayChange.java +++ b/akka-actor/src/main/java/akka/annotation/ApiMayChange.java @@ -8,22 +8,29 @@ import java.lang.annotation.*; /** * Marks APIs that are meant to evolve towards becoming stable APIs, but are not stable APIs yet. - * - * Evolving interfaces MAY change from one patch release to another (i.e. 2.4.10 to 2.4.11) without up-front notice. - * A best-effort approach is taken to not cause more breakage than really necessary, and usual deprecation techniques - * are utilised while evolving these APIs, however there is NO strong guarantee regarding the source or binary - * compatibility of APIs marked using this annotation. - * - * It MAY also change when promoting the API to stable, for example such changes may include removal of deprecated - * methods that were introduced during the evolution and final refactoring that were deferred because they would - * have introduced to much breaking changes during the evolution phase. - * - * Promoting the API to stable MAY happen in a patch release. - * - * It is encouraged to document in ScalaDoc how exactly this API is expected to evolve. + * + *

Evolving interfaces MAY change from one patch release to another (i.e. 2.4.10 to 2.4.11) + * without up-front notice. A best-effort approach is taken to not cause more breakage than really + * necessary, and usual deprecation techniques are utilised while evolving these APIs, however there + * is NO strong guarantee regarding the source or binary compatibility of APIs marked using this + * annotation. + * + *

It MAY also change when promoting the API to stable, for example such changes may include + * removal of deprecated methods that were introduced during the evolution and final refactoring + * that were deferred because they would have introduced to much breaking changes during the + * evolution phase. + * + *

Promoting the API to stable MAY happen in a patch release. + * + *

It is encouraged to document in ScalaDoc how exactly this API is expected to evolve. */ @Documented @Retention(RetentionPolicy.CLASS) // to be accessible by MiMa -@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.TYPE, ElementType.PACKAGE}) -public @interface ApiMayChange { -} +@Target({ + ElementType.METHOD, + ElementType.CONSTRUCTOR, + ElementType.FIELD, + ElementType.TYPE, + ElementType.PACKAGE +}) +public @interface ApiMayChange {} diff --git a/akka-actor/src/main/java/akka/annotation/DoNotInherit.java b/akka-actor/src/main/java/akka/annotation/DoNotInherit.java index 9042698472..74e1a8c596 100644 --- a/akka-actor/src/main/java/akka/annotation/DoNotInherit.java +++ b/akka-actor/src/main/java/akka/annotation/DoNotInherit.java @@ -7,20 +7,21 @@ package akka.annotation; import java.lang.annotation.*; /** - * Marks APIs that are designed under an closed-world assumption for and are NOT meant to be extended by user-code. - * It is fine to extend these classes within Akka itself however. - *

- * This is most useful for binary compatibility purposes when a set of classes and interfaces assume a "closed world" - * between them, and gain the ability to add methods to the interfaces without breaking binary compatibility for - * users of this code. Specifically this assumption may be understood intuitively: as all classes that implement this - * interface are in this compilation unit / artifact, it is impossible to obtain a "old" class with a "new" interface, - * as they are part of the same dependency. - *

- * Notable examples of such API include the FlowOps trait in Akka Streams or Akka HTTP model interfaces, - * which extensively uses inheritance internally, but are not meant for extension by user code. + * Marks APIs that are designed under an closed-world assumption for and are NOT meant to be + * extended by user-code. It is fine to extend these classes within Akka itself however. + * + *

This is most useful for binary compatibility purposes when a set of classes and interfaces + * assume a "closed world" between them, and gain the ability to add methods to the interfaces + * without breaking binary compatibility for users of this code. Specifically this assumption may be + * understood intuitively: as all classes that implement this interface are in this compilation unit + * / artifact, it is impossible to obtain a "old" class with a "new" interface, as they are part of + * the same dependency. + * + *

Notable examples of such API include the FlowOps trait in Akka Streams or Akka HTTP model + * interfaces, which extensively uses inheritance internally, but are not meant for extension by + * user code. */ @Documented @Retention(RetentionPolicy.CLASS) // to be accessible by MiMa @Target({ElementType.TYPE}) -public @interface DoNotInherit { -} +public @interface DoNotInherit {} diff --git a/akka-actor/src/main/java/akka/annotation/InternalApi.java b/akka-actor/src/main/java/akka/annotation/InternalApi.java index 1c48119dac..6c7d518d02 100644 --- a/akka-actor/src/main/java/akka/annotation/InternalApi.java +++ b/akka-actor/src/main/java/akka/annotation/InternalApi.java @@ -7,18 +7,25 @@ package akka.annotation; import java.lang.annotation.*; /** - * Marks APIs that are considered internal to Akka and may change at any point in time without any warning. - *

- * For example, this annotation should be used when the Scala {@code private[akka]} access restriction is used, - * as Java has no way of representing this package restricted access and such methods and classes are represented - * as {@code public} in byte-code. - *

- * If a method/class annotated with this method has a javadoc/scaladoc comment, the first line MUST include - * {@code INTERNAL API} in order to be easily identifiable from generated documentation. Additional information - * may be put on the same line as the INTERNAL API comment in order to clarify further. + * Marks APIs that are considered internal to Akka and may change at any point in time without any + * warning. + * + *

For example, this annotation should be used when the Scala {@code private[akka]} access + * restriction is used, as Java has no way of representing this package restricted access and such + * methods and classes are represented as {@code public} in byte-code. + * + *

If a method/class annotated with this method has a javadoc/scaladoc comment, the first line + * MUST include {@code INTERNAL API} in order to be easily identifiable from generated + * documentation. Additional information may be put on the same line as the INTERNAL API comment in + * order to clarify further. */ @Documented @Retention(RetentionPolicy.CLASS) // to be accessible by MiMa -@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.TYPE, ElementType.PACKAGE}) -public @interface InternalApi { -} +@Target({ + ElementType.METHOD, + ElementType.CONSTRUCTOR, + ElementType.FIELD, + ElementType.TYPE, + ElementType.PACKAGE +}) +public @interface InternalApi {} diff --git a/akka-actor/src/main/java/akka/japi/JAPI.java b/akka-actor/src/main/java/akka/japi/JAPI.java index efe9d7361d..ca98a58c87 100644 --- a/akka-actor/src/main/java/akka/japi/JAPI.java +++ b/akka-actor/src/main/java/akka/japi/JAPI.java @@ -12,5 +12,4 @@ public class JAPI { public static Seq seq(T... ts) { return Util.immutableSeq(ts); } - } diff --git a/akka-actor/src/main/java/akka/japi/pf/AbstractMatch.java b/akka-actor/src/main/java/akka/japi/pf/AbstractMatch.java index 57b8f51fa4..2cd7a42154 100644 --- a/akka-actor/src/main/java/akka/japi/pf/AbstractMatch.java +++ b/akka-actor/src/main/java/akka/japi/pf/AbstractMatch.java @@ -7,8 +7,7 @@ package akka.japi.pf; import scala.PartialFunction; /** - * Version of {@link scala.PartialFunction} that can be built during - * runtime from Java. + * Version of {@link scala.PartialFunction} that can be built during runtime from Java. * * @param the input type, that this PartialFunction will be applied to * @param the return type, that the results of the application will have @@ -19,16 +18,14 @@ class AbstractMatch { AbstractMatch(PartialFunction statements) { PartialFunction empty = CaseStatement.empty(); - if (statements == null) - this.statements = empty; - else - this.statements = statements.orElse(empty); + if (statements == null) this.statements = empty; + else this.statements = statements.orElse(empty); } /** * Turn this {@link Match} into a {@link scala.PartialFunction}. * - * @return a partial function representation ot his {@link Match} + * @return a partial function representation ot his {@link Match} */ public PartialFunction asPF() { return statements; diff --git a/akka-actor/src/main/java/akka/japi/pf/AbstractPFBuilder.java b/akka-actor/src/main/java/akka/japi/pf/AbstractPFBuilder.java index 96ca0be42e..7be2710f8f 100644 --- a/akka-actor/src/main/java/akka/japi/pf/AbstractPFBuilder.java +++ b/akka-actor/src/main/java/akka/japi/pf/AbstractPFBuilder.java @@ -11,33 +11,28 @@ import scala.PartialFunction; * * @param the input type, that this PartialFunction will be applied to * @param the return type, that the results of the application will have - * */ abstract class AbstractPFBuilder { protected PartialFunction statements = null; protected void addStatement(PartialFunction statement) { - if (statements == null) - statements = statement; - else - statements = statements.orElse(statement); + if (statements == null) statements = statement; + else statements = statements.orElse(statement); } /** - * Build a {@link scala.PartialFunction} from this builder. - * After this call the builder will be reset. + * Build a {@link scala.PartialFunction} from this builder. After this call the builder will be + * reset. * - * @return a PartialFunction for this builder. + * @return a PartialFunction for this builder. */ public PartialFunction build() { PartialFunction empty = CaseStatement.empty(); PartialFunction statements = this.statements; this.statements = null; - if (statements == null) - return empty; - else - return statements.orElse(empty); + if (statements == null) return empty; + else return statements.orElse(empty); } } diff --git a/akka-actor/src/main/java/akka/japi/pf/DeciderBuilder.java b/akka-actor/src/main/java/akka/japi/pf/DeciderBuilder.java index efbf92cad7..9e4ac99be9 100644 --- a/akka-actor/src/main/java/akka/japi/pf/DeciderBuilder.java +++ b/akka-actor/src/main/java/akka/japi/pf/DeciderBuilder.java @@ -7,12 +7,12 @@ package akka.japi.pf; import static akka.actor.SupervisorStrategy.Directive; /** - * Used for building a partial function for {@link akka.actor.Actor#supervisorStrategy() Actor.supervisorStrategy()}. - * * - * Inside an actor you can use it like this with Java 8 to define your supervisorStrategy. - *

- * Example: - *

+ * Used for building a partial function for {@link akka.actor.Actor#supervisorStrategy() + * Actor.supervisorStrategy()}. * Inside an actor you can use it like this with Java 8 to define + * your supervisorStrategy. + * + *

Example: + * *

  * @Override
  * private static SupervisorStrategy strategy =
@@ -27,42 +27,41 @@ import static akka.actor.SupervisorStrategy.Directive;
  *   return strategy;
  * }
  * 
- * */ public class DeciderBuilder { - private DeciderBuilder() { - } + private DeciderBuilder() {} /** * Return a new {@link PFBuilder} with a case statement added. * - * @param type a type to match the argument against - * @param apply an action to apply to the argument if the type matches - * @return a builder with the case statement added + * @param type a type to match the argument against + * @param apply an action to apply to the argument if the type matches + * @return a builder with the case statement added */ - public static

PFBuilder match(final Class

type, FI.Apply apply) { + public static

PFBuilder match( + final Class

type, FI.Apply apply) { return Match.match(type, apply); } /** * Return a new {@link PFBuilder} with a case statement added. * - * @param type a type to match the argument against - * @param predicate a predicate that will be evaluated on the argument if the type matches - * @param apply an action to apply to the argument if the type matches and the predicate returns true - * @return a builder with the case statement added + * @param type a type to match the argument against + * @param predicate a predicate that will be evaluated on the argument if the type matches + * @param apply an action to apply to the argument if the type matches and the predicate returns + * true + * @return a builder with the case statement added */ - public static

PFBuilder match(final Class

type, - FI.TypedPredicate

predicate, - FI.Apply apply) { + public static

PFBuilder match( + final Class

type, FI.TypedPredicate

predicate, FI.Apply apply) { return Match.match(type, predicate, apply); } /** * Return a new {@link PFBuilder} with a case statement added. * - * @param apply an action to apply to the argument - * @return a builder with the case statement added + * @param apply an action to apply to the argument + * @return a builder with the case statement added */ public static PFBuilder matchAny(FI.Apply apply) { return Match.matchAny(apply); diff --git a/akka-actor/src/main/java/akka/japi/pf/FI.java b/akka-actor/src/main/java/akka/japi/pf/FI.java index e828268048..0c65e22ea7 100644 --- a/akka-actor/src/main/java/akka/japi/pf/FI.java +++ b/akka-actor/src/main/java/akka/japi/pf/FI.java @@ -5,19 +5,19 @@ package akka.japi.pf; /** - * Class that encapsulates Functional Interfaces - * used for creating partial functions. + * Class that encapsulates Functional Interfaces used for creating partial functions. * - * These classes are kept for compatibility, but for future API's please prefer the ones in {@link akka.japi.function}. + *

These classes are kept for compatibility, but for future API's please prefer the ones in + * {@link akka.japi.function}. */ public final class FI { - private FI() { - } + private FI() {} /** * Functional interface for an application. * - * This class is kept for compatibility, but for future API's please prefer {@link akka.japi.function.Function}. + *

This class is kept for compatibility, but for future API's please prefer {@link + * akka.japi.function.Function}. * * @param the input type, that this Apply will be applied to * @param the return type, that the results of the application will have @@ -26,8 +26,8 @@ public final class FI { /** * The application to perform. * - * @param i an instance that the application is performed on - * @return the result of the application + * @param i an instance that the application is performed on + * @return the result of the application */ public R apply(I i) throws Exception; } @@ -35,7 +35,8 @@ public final class FI { /** * Functional interface for an application. * - * This class is kept for compatibility, but for future API's please prefer {@link akka.japi.function.Function2}. + *

This class is kept for compatibility, but for future API's please prefer {@link + * akka.japi.function.Function2}. * * @param the first input type, that this Apply will be applied to * @param the second input type, that this Apply will be applied to @@ -45,9 +46,9 @@ public final class FI { /** * The application to perform. * - * @param i1 an instance that the application is performed on - * @param i2 an instance that the application is performed on - * @return the result of the application + * @param i1 an instance that the application is performed on + * @param i2 an instance that the application is performed on + * @return the result of the application */ public R apply(I1 i1, I2 i2) throws Exception; } @@ -55,8 +56,8 @@ public final class FI { /** * Functional interface for a predicate. * - * This class is kept for compatibility, but for future API's please prefer {@link java.util.function.Predicate} - * or {@link akka.japi.function.Predicate}. + *

This class is kept for compatibility, but for future API's please prefer {@link + * java.util.function.Predicate} or {@link akka.japi.function.Predicate}. * * @param the type that the predicate will operate on. */ @@ -64,8 +65,8 @@ public final class FI { /** * The predicate to evaluate. * - * @param t an instance that the predicate is evaluated on. - * @return the result of the predicate + * @param t an instance that the predicate is evaluated on. + * @return the result of the predicate */ public boolean defined(T t); } @@ -80,9 +81,9 @@ public final class FI { /** * The predicate to evaluate. * - * @param t an instance that the predicate is evaluated on. - * @param u an instance that the predicate is evaluated on. - * @return the result of the predicate + * @param t an instance that the predicate is evaluated on. + * @param u an instance that the predicate is evaluated on. + * @return the result of the predicate */ public boolean defined(T t, U u); } @@ -90,7 +91,8 @@ public final class FI { /** * Functional interface for an application. * - * This class is kept for compatibility, but for future API's please prefer {@link akka.japi.function.Procedure}. + *

This class is kept for compatibility, but for future API's please prefer {@link + * akka.japi.function.Procedure}. * * @param the input type, that this Apply will be applied to */ @@ -98,7 +100,7 @@ public final class FI { /** * The application to perform. * - * @param i an instance that the application is performed on + * @param i an instance that the application is performed on */ public void apply(I i) throws Exception; } @@ -113,8 +115,8 @@ public final class FI { /** * The application to perform. * - * @param i1 an instance that the application is performed on - * @param i2 an instance that the application is performed on + * @param i1 an instance that the application is performed on + * @param i2 an instance that the application is performed on */ public void apply(I1 i1, I2 i2) throws Exception; } @@ -130,9 +132,9 @@ public final class FI { /** * The application to perform. * - * @param i1 an instance that the application is performed on - * @param i2 an instance that the application is performed on - * @param i3 an instance that the application is performed on + * @param i1 an instance that the application is performed on + * @param i2 an instance that the application is performed on + * @param i3 an instance that the application is performed on */ public void apply(I1 i1, I2 i2, I3 i3) throws Exception; } @@ -160,30 +162,28 @@ public final class FI { /** * Functional interface for an application. * - * This class is kept for compatibility, but for future API's please prefer {@link akka.japi.function.Effect}. + *

This class is kept for compatibility, but for future API's please prefer {@link + * akka.japi.function.Effect}. */ public static interface UnitApplyVoid { - /** - * The application to perform. - */ + /** The application to perform. */ public void apply() throws Exception; } /** - * Package scoped functional interface for a predicate. Used internally to match against arbitrary types. + * Package scoped functional interface for a predicate. Used internally to match against arbitrary + * types. * - * This class is kept for compatibility, but for future API's please prefer {@link java.util.function.Predicate} - * or {@link akka.japi.function.Predicate}. + *

This class is kept for compatibility, but for future API's please prefer {@link + * java.util.function.Predicate} or {@link akka.japi.function.Predicate}. */ static interface Predicate { /** * The predicate to evaluate. * - * @param o an instance that the predicate is evaluated on. - * @return the result of the predicate + * @param o an instance that the predicate is evaluated on. + * @return the result of the predicate */ public boolean defined(Object o); } - - } diff --git a/akka-actor/src/main/java/akka/japi/pf/FSMStateFunctionBuilder.java b/akka-actor/src/main/java/akka/japi/pf/FSMStateFunctionBuilder.java index 75384ffdd7..970ad68473 100644 --- a/akka-actor/src/main/java/akka/japi/pf/FSMStateFunctionBuilder.java +++ b/akka-actor/src/main/java/akka/japi/pf/FSMStateFunctionBuilder.java @@ -13,74 +13,71 @@ import java.util.List; * * @param the state type * @param the data type - * */ @SuppressWarnings("rawtypes") public class FSMStateFunctionBuilder { private PFBuilder, FSM.State> builder = - new PFBuilder, FSM.State>(); + new PFBuilder, FSM.State>(); /** - * An erased processing of the event matcher. The compile time checks are enforced - * by the public typed versions. + * An erased processing of the event matcher. The compile time checks are enforced by the public + * typed versions. * - * It works like this. + *

It works like this. * - * If eventOrType or dataOrType is a Class, then we do a isInstance check, - * otherwise we do an equals check. The null value compares true for anything. - * If the predicate is null, it is skipped otherwise the predicate has to match - * as well. + *

If eventOrType or dataOrType is a Class, then we do a isInstance check, otherwise we do an + * equals check. The null value compares true for anything. If the predicate is null, it is + * skipped otherwise the predicate has to match as well. * - * @param eventOrType an event or a type to match against - * @param dataOrType a data instance or a type to match against - * @param predicate a predicate to match against - * @param apply an action to apply to the event and state data if there is a match - * @return the builder with the case statement added + * @param eventOrType an event or a type to match against + * @param dataOrType a data instance or a type to match against + * @param predicate a predicate to match against + * @param apply an action to apply to the event and state data if there is a match + * @return the builder with the case statement added */ - private FSMStateFunctionBuilder erasedEvent(final Object eventOrType, - final Object dataOrType, - final FI.TypedPredicate2 predicate, - final FI.Apply2 apply) { - builder.match(FSM.Event.class, - new FI.TypedPredicate() { - @Override - public boolean defined(FSM.Event e) { - boolean res = true; - if (eventOrType != null) { - if (eventOrType instanceof Class) { - Class eventType = (Class) eventOrType; - res = eventType.isInstance(e.event()); + private FSMStateFunctionBuilder erasedEvent( + final Object eventOrType, + final Object dataOrType, + final FI.TypedPredicate2 predicate, + final FI.Apply2 apply) { + builder.match( + FSM.Event.class, + new FI.TypedPredicate() { + @Override + public boolean defined(FSM.Event e) { + boolean res = true; + if (eventOrType != null) { + if (eventOrType instanceof Class) { + Class eventType = (Class) eventOrType; + res = eventType.isInstance(e.event()); + } else { + res = eventOrType.equals(e.event()); + } } - else { - res = eventOrType.equals(e.event()); + if (res && dataOrType != null) { + if (dataOrType instanceof Class) { + Class dataType = (Class) dataOrType; + res = dataType.isInstance(e.stateData()); + } else { + res = dataOrType.equals(e.stateData()); + } } + if (res && predicate != null) { + @SuppressWarnings("unchecked") + boolean ures = predicate.defined(e.event(), e.stateData()); + res = ures; + } + return res; } - if (res && dataOrType != null) { - if (dataOrType instanceof Class) { - Class dataType = (Class) dataOrType; - res = dataType.isInstance(e.stateData()); - } - else { - res = dataOrType.equals(e.stateData()); - } - } - if (res && predicate != null) { + }, + new FI.Apply>() { + public FSM.State apply(FSM.Event e) throws Exception { @SuppressWarnings("unchecked") - boolean ures = predicate.defined(e.event(), e.stateData()); - res = ures; + FSM.State res = (FSM.State) apply.apply(e.event(), e.stateData()); + return res; } - return res; - } - }, - new FI.Apply>() { - public FSM.State apply(FSM.Event e) throws Exception { - @SuppressWarnings("unchecked") - FSM.State res = (FSM.State) apply.apply(e.event(), e.stateData()); - return res; - } - } - ); + }); return this; } @@ -88,18 +85,19 @@ public class FSMStateFunctionBuilder { /** * Add a case statement that matches on an event and data type and a predicate. * - * @param eventType the event type to match on - * @param dataType the data type to match on - * @param predicate a predicate to evaluate on the matched types - * @param apply an action to apply to the event and state data if there is a match - * @param

the event type to match on - * @param the data type to match on + * @param eventType the event type to match on + * @param dataType the data type to match on + * @param predicate a predicate to evaluate on the matched types + * @param apply an action to apply to the event and state data if there is a match + * @param

the event type to match on + * @param the data type to match on * @return the builder with the case statement added */ - public final FSMStateFunctionBuilder event(final Class

eventType, - final Class dataType, - final FI.TypedPredicate2 predicate, - final FI.Apply2> apply) { + public final FSMStateFunctionBuilder event( + final Class

eventType, + final Class dataType, + final FI.TypedPredicate2 predicate, + final FI.Apply2> apply) { erasedEvent(eventType, dataType, predicate, apply); return this; } @@ -107,148 +105,149 @@ public class FSMStateFunctionBuilder { /** * Add a case statement that matches on an event and data type. * - * @param eventType the event type to match on - * @param dataType the data type to match on - * @param apply an action to apply to the event and state data if there is a match - * @param

the event type to match on - * @param the data type to match on + * @param eventType the event type to match on + * @param dataType the data type to match on + * @param apply an action to apply to the event and state data if there is a match + * @param

the event type to match on + * @param the data type to match on * @return the builder with the case statement added */ - public FSMStateFunctionBuilder event(final Class

eventType, - final Class dataType, - final FI.Apply2> apply) { + public FSMStateFunctionBuilder event( + final Class

eventType, + final Class dataType, + final FI.Apply2> apply) { return erasedEvent(eventType, dataType, null, apply); } /** * Add a case statement that matches if the event type and predicate matches. * - * @param eventType the event type to match on - * @param predicate a predicate that will be evaluated on the data and the event - * @param apply an action to apply to the event and state data if there is a match + * @param eventType the event type to match on + * @param predicate a predicate that will be evaluated on the data and the event + * @param apply an action to apply to the event and state data if there is a match * @return the builder with the case statement added */ - public

FSMStateFunctionBuilder event(final Class

eventType, - final FI.TypedPredicate2 predicate, - final FI.Apply2> apply) { + public

FSMStateFunctionBuilder event( + final Class

eventType, + final FI.TypedPredicate2 predicate, + final FI.Apply2> apply) { return erasedEvent(eventType, null, predicate, apply); } /** * Add a case statement that matches if the event type and predicate matches. * - * @param eventType the event type to match on - * @param apply an action to apply to the event and state data if there is a match + * @param eventType the event type to match on + * @param apply an action to apply to the event and state data if there is a match * @return the builder with the case statement added */ - public

FSMStateFunctionBuilder event(final Class

eventType, - final FI.Apply2> apply) { + public

FSMStateFunctionBuilder event( + final Class

eventType, final FI.Apply2> apply) { return erasedEvent(eventType, null, null, apply); } /** * Add a case statement that matches if the predicate matches. * - * @param predicate a predicate that will be evaluated on the data and the event - * @param apply an action to apply to the event and state data if there is a match + * @param predicate a predicate that will be evaluated on the data and the event + * @param apply an action to apply to the event and state data if there is a match * @return the builder with the case statement added */ - public FSMStateFunctionBuilder event(final FI.TypedPredicate2 predicate, - final FI.Apply2> apply) { + public FSMStateFunctionBuilder event( + final FI.TypedPredicate2 predicate, + final FI.Apply2> apply) { return erasedEvent(null, null, predicate, apply); } /** - * Add a case statement that matches on the data type and if any of the event types - * in the list match or any of the event instances in the list compares equal. + * Add a case statement that matches on the data type and if any of the event types in the list + * match or any of the event instances in the list compares equal. * - * @param eventMatches a list of types or instances to match against - * @param dataType the data type to match on - * @param apply an action to apply to the event and state data if there is a match - * @param the data type to match on + * @param eventMatches a list of types or instances to match against + * @param dataType the data type to match on + * @param apply an action to apply to the event and state data if there is a match + * @param the data type to match on * @return the builder with the case statement added */ - public FSMStateFunctionBuilder event(final List eventMatches, - final Class dataType, - final FI.Apply2> apply) { - builder.match(FSM.Event.class, - new FI.TypedPredicate() { - @Override - public boolean defined(FSM.Event e) { - if (dataType != null && !dataType.isInstance(e.stateData())) - return false; + public FSMStateFunctionBuilder event( + final List eventMatches, + final Class dataType, + final FI.Apply2> apply) { + builder.match( + FSM.Event.class, + new FI.TypedPredicate() { + @Override + public boolean defined(FSM.Event e) { + if (dataType != null && !dataType.isInstance(e.stateData())) return false; - boolean emMatch = false; - Object event = e.event(); - for (Object em : eventMatches) { - if (em instanceof Class) { - Class emc = (Class) em; - emMatch = emc.isInstance(event); - } else { - emMatch = event.equals(em); + boolean emMatch = false; + Object event = e.event(); + for (Object em : eventMatches) { + if (em instanceof Class) { + Class emc = (Class) em; + emMatch = emc.isInstance(event); + } else { + emMatch = event.equals(em); + } + if (emMatch) break; } - if (emMatch) - break; + return emMatch; } - return emMatch; - } - }, - new FI.Apply>() { - public FSM.State apply(FSM.Event e) throws Exception { - @SuppressWarnings("unchecked") - Q q = (Q) e.stateData(); - return apply.apply(e.event(), q); - } - } - ); + }, + new FI.Apply>() { + public FSM.State apply(FSM.Event e) throws Exception { + @SuppressWarnings("unchecked") + Q q = (Q) e.stateData(); + return apply.apply(e.event(), q); + } + }); return this; } /** - * Add a case statement that matches if any of the event types in the list match or - * any of the event instances in the list compares equal. + * Add a case statement that matches if any of the event types in the list match or any of the + * event instances in the list compares equal. * - * @param eventMatches a list of types or instances to match against - * @param apply an action to apply to the event and state data if there is a match + * @param eventMatches a list of types or instances to match against + * @param apply an action to apply to the event and state data if there is a match * @return the builder with the case statement added */ - public FSMStateFunctionBuilder event(final List eventMatches, - final FI.Apply2> apply) { + public FSMStateFunctionBuilder event( + final List eventMatches, final FI.Apply2> apply) { return event(eventMatches, null, apply); } /** * Add a case statement that matches on the data type and if the event compares equal. * - * @param event an event to compare equal against - * @param dataType the data type to match on - * @param apply an action to apply to the event and state data if there is a match - * @param the data type to match on + * @param event an event to compare equal against + * @param dataType the data type to match on + * @param apply an action to apply to the event and state data if there is a match + * @param the data type to match on * @return the builder with the case statement added */ - public FSMStateFunctionBuilder eventEquals(final P event, - final Class dataType, - final FI.Apply2> apply) { + public FSMStateFunctionBuilder eventEquals( + final P event, final Class dataType, final FI.Apply2> apply) { return erasedEvent(event, dataType, null, apply); } /** * Add a case statement that matches if event compares equal. * - * @param event an event to compare equal against - * @param apply an action to apply to the event and state data if there is a match + * @param event an event to compare equal against + * @param apply an action to apply to the event and state data if there is a match * @return the builder with the case statement added */ - public

FSMStateFunctionBuilder eventEquals(final P event, - final FI.Apply2> apply) { + public

FSMStateFunctionBuilder eventEquals( + final P event, final FI.Apply2> apply) { return erasedEvent(event, null, null, apply); } /** * Add a case statement that matches on any type of event. * - * @param apply an action to apply to the event and state data + * @param apply an action to apply to the event and state data * @return the builder with the case statement added */ public FSMStateFunctionBuilder anyEvent(final FI.Apply2> apply) { @@ -256,10 +255,10 @@ public class FSMStateFunctionBuilder { } /** - * Build a {@link scala.PartialFunction} from this builder. - * After this call the builder will be reset. + * Build a {@link scala.PartialFunction} from this builder. After this call the builder will be + * reset. * - * @return a PartialFunction for this builder. + * @return a PartialFunction for this builder. */ public PartialFunction, FSM.State> build() { return builder.build(); diff --git a/akka-actor/src/main/java/akka/japi/pf/FSMStopBuilder.java b/akka-actor/src/main/java/akka/japi/pf/FSMStopBuilder.java index 08d0839384..521fbcc1a2 100644 --- a/akka-actor/src/main/java/akka/japi/pf/FSMStopBuilder.java +++ b/akka-actor/src/main/java/akka/japi/pf/FSMStopBuilder.java @@ -13,39 +13,36 @@ import scala.runtime.BoxedUnit; * * @param the state type * @param the data type - * */ public class FSMStopBuilder { - private UnitPFBuilder> builder = - new UnitPFBuilder>(); + private UnitPFBuilder> builder = new UnitPFBuilder>(); /** * Add a case statement that matches on an {@link FSM.Reason}. * - * @param reason the reason for the termination - * @param apply an action to apply to the event and state data if there is a match + * @param reason the reason for the termination + * @param apply an action to apply to the event and state data if there is a match * @return the builder with the case statement added */ - public FSMStopBuilder stop(final FSM.Reason reason, - final FI.UnitApply2 apply) { - builder.match(FSM.StopEvent.class, - new FI.TypedPredicate() { - @Override - public boolean defined(FSM.StopEvent e) { - return reason.equals(e.reason()); - } - }, - new FI.UnitApply() { - public void apply(FSM.StopEvent e) throws Exception { - @SuppressWarnings("unchecked") - S s = (S) e.currentState(); - @SuppressWarnings("unchecked") - D d = (D) e.stateData(); - apply.apply(s, d); - } - } - ); + public FSMStopBuilder stop(final FSM.Reason reason, final FI.UnitApply2 apply) { + builder.match( + FSM.StopEvent.class, + new FI.TypedPredicate() { + @Override + public boolean defined(FSM.StopEvent e) { + return reason.equals(e.reason()); + } + }, + new FI.UnitApply() { + public void apply(FSM.StopEvent e) throws Exception { + @SuppressWarnings("unchecked") + S s = (S) e.currentState(); + @SuppressWarnings("unchecked") + D d = (D) e.stateData(); + apply.apply(s, d); + } + }); return this; } @@ -53,68 +50,71 @@ public class FSMStopBuilder { /** * Add a case statement that matches on a reason type. * - * @param reasonType the reason type to match on - * @param apply an action to apply to the reason, event and state data if there is a match - * @param

the reason type to match on + * @param reasonType the reason type to match on + * @param apply an action to apply to the reason, event and state data if there is a match + * @param

the reason type to match on * @return the builder with the case statement added */ - public

FSMStopBuilder stop(final Class

reasonType, - final FI.UnitApply3 apply) { - return this.stop(reasonType, - new FI.TypedPredicate

() { - @Override - public boolean defined(P p) { - return true; - } - }, apply); + public

FSMStopBuilder stop( + final Class

reasonType, final FI.UnitApply3 apply) { + return this.stop( + reasonType, + new FI.TypedPredicate

() { + @Override + public boolean defined(P p) { + return true; + } + }, + apply); } /** * Add a case statement that matches on a reason type and a predicate. * - * @param reasonType the reason type to match on - * @param apply an action to apply to the reason, event and state data if there is a match - * @param predicate a predicate that will be evaluated on the reason if the type matches - * @param

the reason type to match on + * @param reasonType the reason type to match on + * @param apply an action to apply to the reason, event and state data if there is a match + * @param predicate a predicate that will be evaluated on the reason if the type matches + * @param

the reason type to match on * @return the builder with the case statement added */ - public

FSMStopBuilder stop(final Class

reasonType, - final FI.TypedPredicate

predicate, - final FI.UnitApply3 apply) { - builder.match(FSM.StopEvent.class, - new FI.TypedPredicate() { - @Override - public boolean defined(FSM.StopEvent e) { - if (reasonType.isInstance(e.reason())) { + public

FSMStopBuilder stop( + final Class

reasonType, + final FI.TypedPredicate

predicate, + final FI.UnitApply3 apply) { + builder.match( + FSM.StopEvent.class, + new FI.TypedPredicate() { + @Override + public boolean defined(FSM.StopEvent e) { + if (reasonType.isInstance(e.reason())) { + @SuppressWarnings("unchecked") + P p = (P) e.reason(); + return predicate.defined(p); + } else { + return false; + } + } + }, + new FI.UnitApply() { + public void apply(FSM.StopEvent e) throws Exception { @SuppressWarnings("unchecked") P p = (P) e.reason(); - return predicate.defined(p); - } else { - return false; + @SuppressWarnings("unchecked") + S s = (S) e.currentState(); + @SuppressWarnings("unchecked") + D d = (D) e.stateData(); + apply.apply(p, s, d); } - } - }, - new FI.UnitApply() { - public void apply(FSM.StopEvent e) throws Exception { - @SuppressWarnings("unchecked") - P p = (P) e.reason(); - @SuppressWarnings("unchecked") - S s = (S) e.currentState(); - @SuppressWarnings("unchecked") - D d = (D) e.stateData(); - apply.apply(p, s, d); - } - } - ); + }); return this; } /** - * Build a {@link scala.PartialFunction} from this builder. - * After this call the builder will be reset. + * Build a {@link scala.PartialFunction} from this builder. After this call the builder will be + * reset. * - * @return a PartialFunction for this builder. + * @return a PartialFunction for this builder. */ public PartialFunction, BoxedUnit> build() { return builder.build(); diff --git a/akka-actor/src/main/java/akka/japi/pf/FSMTransitionHandlerBuilder.java b/akka-actor/src/main/java/akka/japi/pf/FSMTransitionHandlerBuilder.java index 73a5dfe53b..aa0db96892 100644 --- a/akka-actor/src/main/java/akka/japi/pf/FSMTransitionHandlerBuilder.java +++ b/akka-actor/src/main/java/akka/japi/pf/FSMTransitionHandlerBuilder.java @@ -12,80 +12,76 @@ import scala.Tuple2; * Builder used to create a partial function for {@link akka.actor.FSM#onTransition}. * * @param the state type - * */ public class FSMTransitionHandlerBuilder { - private final UnitPFBuilder> builder = - new UnitPFBuilder>(); + private final UnitPFBuilder> builder = new UnitPFBuilder>(); /** * Add a case statement that matches on a from state and a to state. * - * @param fromState the from state to match on, or null for any - * @param toState the to state to match on, or null for any - * @param apply an action to apply when the states match + * @param fromState the from state to match on, or null for any + * @param toState the to state to match on, or null for any + * @param apply an action to apply when the states match * @return the builder with the case statement added */ - public FSMTransitionHandlerBuilder state(final S fromState, - final S toState, - final FI.UnitApplyVoid apply) { - builder.match(Tuple2.class, - new FI.TypedPredicate() { - @Override - public boolean defined(Tuple2 t) { - return (fromState == null || fromState.equals(t._1())) - && (toState == null || toState.equals(t._2())); - } - }, - new FI.UnitApply() { - @Override - public void apply(Tuple2 t) throws Exception { - apply.apply(); - } - } - ); + public FSMTransitionHandlerBuilder state( + final S fromState, final S toState, final FI.UnitApplyVoid apply) { + builder.match( + Tuple2.class, + new FI.TypedPredicate() { + @Override + public boolean defined(Tuple2 t) { + return (fromState == null || fromState.equals(t._1())) + && (toState == null || toState.equals(t._2())); + } + }, + new FI.UnitApply() { + @Override + public void apply(Tuple2 t) throws Exception { + apply.apply(); + } + }); return this; } /** * Add a case statement that matches on a from state and a to state. * - * @param fromState the from state to match on, or null for any - * @param toState the to state to match on, or null for any - * @param apply an action to apply when the states match + * @param fromState the from state to match on, or null for any + * @param toState the to state to match on, or null for any + * @param apply an action to apply when the states match * @return the builder with the case statement added */ - public FSMTransitionHandlerBuilder state(final S fromState, - final S toState, - final FI.UnitApply2 apply) { - builder.match(Tuple2.class, - new FI.TypedPredicate() { - @Override - public boolean defined(Tuple2 t) { - return (fromState == null || fromState.equals(t._1())) - && (toState == null || toState.equals(t._2())); - } - }, - new FI.UnitApply() { - @Override - public void apply(Tuple2 t) throws Exception { - @SuppressWarnings("unchecked") - S sf = (S) t._1(); - @SuppressWarnings("unchecked") - S st = (S) t._2(); - apply.apply(sf, st); - } - } - ); + public FSMTransitionHandlerBuilder state( + final S fromState, final S toState, final FI.UnitApply2 apply) { + builder.match( + Tuple2.class, + new FI.TypedPredicate() { + @Override + public boolean defined(Tuple2 t) { + return (fromState == null || fromState.equals(t._1())) + && (toState == null || toState.equals(t._2())); + } + }, + new FI.UnitApply() { + @Override + public void apply(Tuple2 t) throws Exception { + @SuppressWarnings("unchecked") + S sf = (S) t._1(); + @SuppressWarnings("unchecked") + S st = (S) t._2(); + apply.apply(sf, st); + } + }); return this; } /** - * Build a {@link scala.PartialFunction} from this builder. - * After this call the builder will be reset. + * Build a {@link scala.PartialFunction} from this builder. After this call the builder will be + * reset. * - * @return a PartialFunction for this builder. + * @return a PartialFunction for this builder. */ public PartialFunction, BoxedUnit> build() { return builder.build(); diff --git a/akka-actor/src/main/java/akka/japi/pf/Match.java b/akka-actor/src/main/java/akka/japi/pf/Match.java index a815ba038d..f87e7fa003 100644 --- a/akka-actor/src/main/java/akka/japi/pf/Match.java +++ b/akka-actor/src/main/java/akka/japi/pf/Match.java @@ -8,91 +8,79 @@ import scala.MatchError; import scala.PartialFunction; /** - * Version of {@link scala.PartialFunction} that can be built during - * runtime from Java. + * Version of {@link scala.PartialFunction} that can be built during runtime from Java. * * @param the input type, that this PartialFunction will be applied to * @param the return type, that the results of the application will have - * */ public class Match extends AbstractMatch { /** - * Convenience function to create a {@link PFBuilder} with the first - * case statement added. + * Convenience function to create a {@link PFBuilder} with the first case statement added. * - * @param type a type to match the argument against + * @param type a type to match the argument against * @param apply an action to apply to the argument if the type matches * @return a builder with the case statement added * @see PFBuilder#match(Class, FI.Apply) */ - public static PFBuilder match(final Class

type, - final FI.Apply apply) { + public static PFBuilder match(final Class

type, final FI.Apply apply) { return new PFBuilder().match(type, apply); } /** - * Convenience function to create a {@link PFBuilder} with the first - * case statement added without compile time type check of the parameters. - * Should normally not be used, but when matching on class with generic type - * argument it can be useful, e.g. List.class and - * (List<String> list) -> {}. + * Convenience function to create a {@link PFBuilder} with the first case statement added without + * compile time type check of the parameters. Should normally not be used, but when matching on + * class with generic type argument it can be useful, e.g. List.class and + * (List<String> list) -> {}. * * @see PFBuilder#matchUnchecked(Class, FI.Apply) */ - public static PFBuilder matchUnchecked(final Class type, - final FI.Apply apply) { + public static PFBuilder matchUnchecked( + final Class type, final FI.Apply apply) { return new PFBuilder().matchUnchecked(type, apply); } /** - * Convenience function to create a {@link PFBuilder} with the first - * case statement added. + * Convenience function to create a {@link PFBuilder} with the first case statement added. * - * @param type a type to match the argument against + * @param type a type to match the argument against * @param predicate a predicate that will be evaluated on the argument if the type matches - * @param apply an action to apply to the argument if the type matches + * @param apply an action to apply to the argument if the type matches * @return a builder with the case statement added * @see PFBuilder#match(Class, FI.TypedPredicate, FI.Apply) */ - public static PFBuilder match(final Class

type, - final FI.TypedPredicate

predicate, - final FI.Apply apply) { + public static PFBuilder match( + final Class

type, final FI.TypedPredicate

predicate, final FI.Apply apply) { return new PFBuilder().match(type, predicate, apply); } /** - * Convenience function to create a {@link PFBuilder} with the first - * case statement added without compile time type check of the parameters. - * Should normally not be used, but when matching on class with generic type - * argument it can be useful, e.g. List.class and - * (List<String> list) -> {}. + * Convenience function to create a {@link PFBuilder} with the first case statement added without + * compile time type check of the parameters. Should normally not be used, but when matching on + * class with generic type argument it can be useful, e.g. List.class and + * (List<String> list) -> {}. * * @see PFBuilder#matchUnchecked(Class, FI.TypedPredicate, FI.Apply) */ - public static PFBuilder matchUnchecked(final Class type, - final FI.TypedPredicate predicate, - final FI.Apply apply) { + public static PFBuilder matchUnchecked( + final Class type, final FI.TypedPredicate predicate, final FI.Apply apply) { return new PFBuilder().matchUnchecked(type, predicate, apply); } /** - * Convenience function to create a {@link PFBuilder} with the first - * case statement added. + * Convenience function to create a {@link PFBuilder} with the first case statement added. * * @param object the object to compare equals with - * @param apply an action to apply to the argument if the object compares equal + * @param apply an action to apply to the argument if the object compares equal * @return a builder with the case statement added * @see PFBuilder#matchEquals(Object, FI.Apply) */ - public static PFBuilder matchEquals(final P object, - final FI.Apply apply) { + public static PFBuilder matchEquals(final P object, final FI.Apply apply) { return new PFBuilder().matchEquals(object, apply); } /** - * Convenience function to create a {@link PFBuilder} with the first - * case statement added. + * Convenience function to create a {@link PFBuilder} with the first case statement added. * * @param apply an action to apply to the argument * @return a builder with the case statement added @@ -118,7 +106,8 @@ public class Match extends AbstractMatch { /** * Convenience function to make the Java code more readable. - *

+ * + *

* *


    *   Match<X, Y> matcher = Match.create(...);
diff --git a/akka-actor/src/main/java/akka/japi/pf/PFBuilder.java b/akka-actor/src/main/java/akka/japi/pf/PFBuilder.java
index 5aed060685..859e59907a 100644
--- a/akka-actor/src/main/java/akka/japi/pf/PFBuilder.java
+++ b/akka-actor/src/main/java/akka/japi/pf/PFBuilder.java
@@ -9,20 +9,16 @@ package akka.japi.pf;
  *
  * @param  the input type, that this PartialFunction will be applied to
  * @param  the return type, that the results of the application will have
- *
  */
 public final class PFBuilder extends AbstractPFBuilder {
 
-  /**
-   * Create a PFBuilder.
-   */
-  public PFBuilder() {
-  }
+  /** Create a PFBuilder. */
+  public PFBuilder() {}
 
   /**
    * Add a new case statement to this builder.
    *
-   * @param type  a type to match the argument against
+   * @param type a type to match the argument against
    * @param apply an action to apply to the argument if the type matches
    * @return a builder with the case statement added
    */
@@ -32,23 +28,23 @@ public final class PFBuilder extends AbstractPFBuilder {
 
   /**
    * Add a new case statement to this builder without compile time type check of the parameters.
-   * Should normally not be used, but when matching on class with generic type
-   * argument it can be useful, e.g. List.class and
-   * (List<String> list) -> {}.
+   * Should normally not be used, but when matching on class with generic type argument it can be
+   * useful, e.g. List.class and (List<String> list) -> {}.
    *
-   * @param type  a type to match the argument against
+   * @param type a type to match the argument against
    * @param apply an action to apply to the argument if the type matches
    * @return a builder with the case statement added
    */
   @SuppressWarnings("unchecked")
   public PFBuilder matchUnchecked(final Class type, FI.Apply apply) {
 
-    FI.Predicate predicate = new FI.Predicate() {
-      @Override
-      public boolean defined(Object o) {
-        return type.isInstance(o);
-      }
-    };
+    FI.Predicate predicate =
+        new FI.Predicate() {
+          @Override
+          public boolean defined(Object o) {
+            return type.isInstance(o);
+          }
+        };
 
     addStatement(new CaseStatement(predicate, (FI.Apply) apply));
     return this;
@@ -57,41 +53,39 @@ public final class PFBuilder extends AbstractPFBuilder {
   /**
    * Add a new case statement to this builder.
    *
-   * @param type      a type to match the argument against
+   * @param type a type to match the argument against
    * @param predicate a predicate that will be evaluated on the argument if the type matches
-   * @param apply     an action to apply to the argument if the type matches and the predicate returns true
+   * @param apply an action to apply to the argument if the type matches and the predicate returns
+   *     true
    * @return a builder with the case statement added
    */
-  public 

PFBuilder match(final Class

type, - final FI.TypedPredicate

predicate, - final FI.Apply apply) { + public

PFBuilder match( + final Class

type, final FI.TypedPredicate

predicate, final FI.Apply apply) { return matchUnchecked(type, predicate, apply); } /** * Add a new case statement to this builder without compile time type check of the parameters. - * Should normally not be used, but when matching on class with generic type - * argument it can be useful, e.g. List.class and - * (List<String> list) -> {}. + * Should normally not be used, but when matching on class with generic type argument it can be + * useful, e.g. List.class and (List<String> list) -> {}. * - * @param type a type to match the argument against + * @param type a type to match the argument against * @param predicate a predicate that will be evaluated on the argument if the type matches - * @param apply an action to apply to the argument if the type matches and the predicate returns true + * @param apply an action to apply to the argument if the type matches and the predicate returns + * true * @return a builder with the case statement added */ @SuppressWarnings("unchecked") - public PFBuilder matchUnchecked(final Class type, - final FI.TypedPredicate predicate, - final FI.Apply apply) { - FI.Predicate fiPredicate = new FI.Predicate() { - @Override - public boolean defined(Object o) { - if (!type.isInstance(o)) - return false; - else - return ((FI.TypedPredicate) predicate).defined(o); - } - }; + public PFBuilder matchUnchecked( + final Class type, final FI.TypedPredicate predicate, final FI.Apply apply) { + FI.Predicate fiPredicate = + new FI.Predicate() { + @Override + public boolean defined(Object o) { + if (!type.isInstance(o)) return false; + else return ((FI.TypedPredicate) predicate).defined(o); + } + }; addStatement(new CaseStatement(fiPredicate, (FI.Apply) apply)); return this; } @@ -100,18 +94,19 @@ public final class PFBuilder extends AbstractPFBuilder { * Add a new case statement to this builder. * * @param object the object to compare equals with - * @param apply an action to apply to the argument if the object compares equal + * @param apply an action to apply to the argument if the object compares equal * @return a builder with the case statement added */ - public

PFBuilder matchEquals(final P object, - final FI.Apply apply) { - addStatement(new CaseStatement( - new FI.Predicate() { - @Override - public boolean defined(Object o) { - return object.equals(o); - } - }, apply)); + public

PFBuilder matchEquals(final P object, final FI.Apply apply) { + addStatement( + new CaseStatement( + new FI.Predicate() { + @Override + public boolean defined(Object o) { + return object.equals(o); + } + }, + apply)); return this; } @@ -122,13 +117,15 @@ public final class PFBuilder extends AbstractPFBuilder { * @return a builder with the case statement added */ public PFBuilder matchAny(final FI.Apply apply) { - addStatement(new CaseStatement( - new FI.Predicate() { - @Override - public boolean defined(Object o) { - return true; - } - }, apply)); + addStatement( + new CaseStatement( + new FI.Predicate() { + @Override + public boolean defined(Object o) { + return true; + } + }, + apply)); return this; } } diff --git a/akka-actor/src/main/java/akka/japi/pf/ReceiveBuilder.java b/akka-actor/src/main/java/akka/japi/pf/ReceiveBuilder.java index b39e28d71e..dd0a94f813 100644 --- a/akka-actor/src/main/java/akka/japi/pf/ReceiveBuilder.java +++ b/akka-actor/src/main/java/akka/japi/pf/ReceiveBuilder.java @@ -12,12 +12,12 @@ import akka.actor.AbstractActor.Receive; /** * Used for building a partial function for {@link akka.actor.Actor#receive() Actor.receive()}. * - * There is both a match on type only, and a match on type and predicate. + *

There is both a match on type only, and a match on type and predicate. + * + *

Inside an actor you can use it like this with Java 8 to define your receive method. + * + *

Example: * - * Inside an actor you can use it like this with Java 8 to define your receive method. - *

- * Example: - *

*
  * @Override
  * public Actor() {
@@ -34,37 +34,32 @@ import akka.actor.AbstractActor.Receive;
  *   );
  * }
  * 
- * */ public class ReceiveBuilder { private PartialFunction statements = null; protected void addStatement(PartialFunction statement) { - if (statements == null) - statements = statement; - else - statements = statements.orElse(statement); + if (statements == null) statements = statement; + else statements = statements.orElse(statement); } /** - * Build a {@link scala.PartialFunction} from this builder. After this call - * the builder will be reset. + * Build a {@link scala.PartialFunction} from this builder. After this call the builder will be + * reset. * * @return a PartialFunction for this builder. */ public Receive build() { PartialFunction empty = CaseStatement.empty(); - if (statements == null) - return new Receive(empty); - else - return new Receive(statements.orElse(empty)); // FIXME why no new Receive(statements)? + if (statements == null) return new Receive(empty); + else return new Receive(statements.orElse(empty)); // FIXME why no new Receive(statements)? } /** - * Return a new {@link ReceiveBuilder} with no case statements. They can be - * added later as the returned {@link ReceiveBuilder} is a mutable object. + * Return a new {@link ReceiveBuilder} with no case statements. They can be added later as the + * returned {@link ReceiveBuilder} is a mutable object. * * @return a builder with no case statements */ @@ -75,10 +70,8 @@ public class ReceiveBuilder { /** * Add a new case statement to this builder. * - * @param type - * a type to match the argument against - * @param apply - * an action to apply to the argument if the type matches + * @param type a type to match the argument against + * @param apply an action to apply to the argument if the type matches * @return a builder with the case statement added */ public

ReceiveBuilder match(final Class

type, final FI.UnitApply

apply) { @@ -86,26 +79,24 @@ public class ReceiveBuilder { } /** - * Add a new case statement to this builder without compile time type check. - * Should normally not be used, but when matching on class with generic type - * argument it can be useful, e.g. List.class and - * (List<String> list) -> {}. + * Add a new case statement to this builder without compile time type check. Should normally not + * be used, but when matching on class with generic type argument it can be useful, e.g. + * List.class and (List<String> list) -> {}. * - * @param type - * a type to match the argument against - * @param apply - * an action to apply to the argument if the type matches + * @param type a type to match the argument against + * @param apply an action to apply to the argument if the type matches * @return a builder with the case statement added */ @SuppressWarnings("unchecked") public ReceiveBuilder matchUnchecked(final Class type, final FI.UnitApply apply) { - FI.Predicate predicate = new FI.Predicate() { - @Override - public boolean defined(Object o) { - return type.isInstance(o); - } - }; + FI.Predicate predicate = + new FI.Predicate() { + @Override + public boolean defined(Object o) { + return type.isInstance(o); + } + }; addStatement(new UnitCaseStatement(predicate, (FI.UnitApply) apply)); @@ -115,168 +106,154 @@ public class ReceiveBuilder { /** * Add a new case statement to this builder. * - * @param type - * a type to match the argument against - * @param predicate - * a predicate that will be evaluated on the argument if the type - * matches - * @param apply - * an action to apply to the argument if the type matches and the - * predicate returns true + * @param type a type to match the argument against + * @param predicate a predicate that will be evaluated on the argument if the type matches + * @param apply an action to apply to the argument if the type matches and the predicate returns + * true * @return a builder with the case statement added */ - public

ReceiveBuilder match(final Class

type, final FI.TypedPredicate

predicate, - final FI.UnitApply

apply) { + public

ReceiveBuilder match( + final Class

type, final FI.TypedPredicate

predicate, final FI.UnitApply

apply) { return matchUnchecked(type, predicate, apply); } /** * Add a new case statement to this builder. * - * @param type - * a type to match the argument against - * @param externalPredicate - * a external predicate that will be evaluated if the type matches - * @param apply - * an action to apply to the argument if the type matches and the - * predicate returns true + * @param type a type to match the argument against + * @param externalPredicate a external predicate that will be evaluated if the type matches + * @param apply an action to apply to the argument if the type matches and the predicate returns + * true * @return a builder with the case statement added */ - public

ReceiveBuilder match(final Class

type, - final java.util.function.BooleanSupplier externalPredicate, - final FI.UnitApply

apply) { + public

ReceiveBuilder match( + final Class

type, + final java.util.function.BooleanSupplier externalPredicate, + final FI.UnitApply

apply) { return matchUnchecked(type, externalPredicate, apply); } - /** - * Add a new case statement to this builder without compile time type check. - * Should normally not be used, but when matching on class with generic type - * argument it can be useful, e.g. List.class and - * (List<String> list) -> {}. - * - * @param type - * a type to match the argument against - * @param predicate - * a predicate that will be evaluated on the argument if the type - * matches - * @param apply - * an action to apply to the argument if the type matches and the - * predicate returns true - * @return a builder with the case statement added - */ - @SuppressWarnings("unchecked") - public

ReceiveBuilder matchUnchecked(final Class type, final FI.TypedPredicate predicate, - final FI.UnitApply

apply) { - FI.Predicate fiPredicate = new FI.Predicate() { - @Override - public boolean defined(Object o) { - if (!type.isInstance(o)) - return false; - else - return ((FI.TypedPredicate) predicate).defined(o); - } - }; + /** + * Add a new case statement to this builder without compile time type check. Should normally not + * be used, but when matching on class with generic type argument it can be useful, e.g. + * List.class and (List<String> list) -> {}. + * + * @param type a type to match the argument against + * @param predicate a predicate that will be evaluated on the argument if the type matches + * @param apply an action to apply to the argument if the type matches and the predicate returns + * true + * @return a builder with the case statement added + */ + @SuppressWarnings("unchecked") + public

ReceiveBuilder matchUnchecked( + final Class type, final FI.TypedPredicate predicate, final FI.UnitApply

apply) { + FI.Predicate fiPredicate = + new FI.Predicate() { + @Override + public boolean defined(Object o) { + if (!type.isInstance(o)) return false; + else return ((FI.TypedPredicate) predicate).defined(o); + } + }; addStatement(new UnitCaseStatement(fiPredicate, (FI.UnitApply) apply)); return this; } - /** - * Add a new case statement to this builder without compile time type check. - * Should normally not be used, but when matching on class with generic type - * argument it can be useful, e.g. List.class and - * (List<String> list) -> {}. - * - * @param type - * a type to match the argument against - * @param externalPredicate - * a external predicate that will be evaluated if the type matches - * @param apply - * an action to apply to the argument if the type matches and the - * predicate returns true - * @return a builder with the case statement added - */ - @SuppressWarnings("unchecked") - public

ReceiveBuilder matchUnchecked(final Class type, - final java.util.function.BooleanSupplier externalPredicate, - final FI.UnitApply

apply) { - FI.Predicate fiPredicate = new FI.Predicate() { - @Override - public boolean defined(Object o) { - return type.isInstance(o) && - externalPredicate.getAsBoolean(); - } - }; - - addStatement(new UnitCaseStatement(fiPredicate, (FI.UnitApply) apply)); - - return this; - } - /** - * Add a new case statement to this builder. + * Add a new case statement to this builder without compile time type check. Should normally not + * be used, but when matching on class with generic type argument it can be useful, e.g. + * List.class and (List<String> list) -> {}. * - * @param object - * the object to compare equals with - * @param apply - * an action to apply to the argument if the object compares equal + * @param type a type to match the argument against + * @param externalPredicate a external predicate that will be evaluated if the type matches + * @param apply an action to apply to the argument if the type matches and the predicate returns + * true * @return a builder with the case statement added */ - public

ReceiveBuilder matchEquals(final P object, final FI.UnitApply

apply) { - addStatement(new UnitCaseStatement(new FI.Predicate() { - @Override - public boolean defined(Object o) { - return object.equals(o); - } - }, apply)); + @SuppressWarnings("unchecked") + public

ReceiveBuilder matchUnchecked( + final Class type, + final java.util.function.BooleanSupplier externalPredicate, + final FI.UnitApply

apply) { + FI.Predicate fiPredicate = + new FI.Predicate() { + @Override + public boolean defined(Object o) { + return type.isInstance(o) && externalPredicate.getAsBoolean(); + } + }; + + addStatement(new UnitCaseStatement(fiPredicate, (FI.UnitApply) apply)); + return this; } /** * Add a new case statement to this builder. * - * @param object - * the object to compare equals with - * @param predicate - * a predicate that will be evaluated on the argument if the object - * compares equal - * @param apply - * an action to apply to the argument if the object compares equal + * @param object the object to compare equals with + * @param apply an action to apply to the argument if the object compares equal * @return a builder with the case statement added */ - public

ReceiveBuilder matchEquals(final P object, final FI.TypedPredicate

predicate, - final FI.UnitApply

apply) { - addStatement(new UnitCaseStatement(new FI.Predicate() { - @Override - public boolean defined(Object o) { - if (!object.equals(o)) - return false; - else { - @SuppressWarnings("unchecked") - P p = (P) o; - return predicate.defined(p); - } - } - }, apply)); + public

ReceiveBuilder matchEquals(final P object, final FI.UnitApply

apply) { + addStatement( + new UnitCaseStatement( + new FI.Predicate() { + @Override + public boolean defined(Object o) { + return object.equals(o); + } + }, + apply)); + return this; + } + + /** + * Add a new case statement to this builder. + * + * @param object the object to compare equals with + * @param predicate a predicate that will be evaluated on the argument if the object compares + * equal + * @param apply an action to apply to the argument if the object compares equal + * @return a builder with the case statement added + */ + public

ReceiveBuilder matchEquals( + final P object, final FI.TypedPredicate

predicate, final FI.UnitApply

apply) { + addStatement( + new UnitCaseStatement( + new FI.Predicate() { + @Override + public boolean defined(Object o) { + if (!object.equals(o)) return false; + else { + @SuppressWarnings("unchecked") + P p = (P) o; + return predicate.defined(p); + } + } + }, + apply)); return this; } /** * Add a new case statement to this builder, that matches any argument. * - * @param apply - * an action to apply to the argument + * @param apply an action to apply to the argument * @return a builder with the case statement added */ public ReceiveBuilder matchAny(final FI.UnitApply apply) { - addStatement(new UnitCaseStatement(new FI.Predicate() { - @Override - public boolean defined(Object o) { - return true; - } - }, apply)); + addStatement( + new UnitCaseStatement( + new FI.Predicate() { + @Override + public boolean defined(Object o) { + return true; + } + }, + apply)); return this; } - } diff --git a/akka-actor/src/main/java/akka/japi/pf/UnitMatch.java b/akka-actor/src/main/java/akka/japi/pf/UnitMatch.java index d4ac6fff63..bf0951af9c 100644 --- a/akka-actor/src/main/java/akka/japi/pf/UnitMatch.java +++ b/akka-actor/src/main/java/akka/japi/pf/UnitMatch.java @@ -9,21 +9,18 @@ import scala.PartialFunction; import scala.runtime.BoxedUnit; /** - * Version of {@link scala.PartialFunction} that can be built during - * runtime from Java. - * This is a specialized version of {@link UnitMatch} to map java - * void methods to {@link scala.runtime.BoxedUnit}. + * Version of {@link scala.PartialFunction} that can be built during runtime from Java. This is a + * specialized version of {@link UnitMatch} to map java void methods to {@link + * scala.runtime.BoxedUnit}. * * @param the input type, that this PartialFunction will be applied to - * */ public class UnitMatch extends AbstractMatch { /** - * Convenience function to create a {@link UnitPFBuilder} with the first - * case statement added. + * Convenience function to create a {@link UnitPFBuilder} with the first case statement added. * - * @param type a type to match the argument against + * @param type a type to match the argument against * @param apply an action to apply to the argument if the type matches * @return a builder with the case statement added * @see UnitPFBuilder#match(Class, FI.UnitApply) @@ -33,76 +30,69 @@ public class UnitMatch extends AbstractMatch { } /** - * Convenience function to create a {@link UnitPFBuilder} with the first - * case statement added. Should normally not be used. + * Convenience function to create a {@link UnitPFBuilder} with the first case statement added. + * Should normally not be used. * * @see UnitPFBuilder#matchUnchecked(Class, FI.UnitApply) */ - public static UnitPFBuilder matchUnchecked(final Class type, final FI.UnitApply apply) { + public static UnitPFBuilder matchUnchecked( + final Class type, final FI.UnitApply apply) { return new UnitPFBuilder().matchUnchecked(type, apply); } /** - * Convenience function to create a {@link UnitPFBuilder} with the first - * case statement added. + * Convenience function to create a {@link UnitPFBuilder} with the first case statement added. * - * @param type a type to match the argument against + * @param type a type to match the argument against * @param predicate a predicate that will be evaluated on the argument if the type matches - * @param apply an action to apply to the argument if the type and predicate matches + * @param apply an action to apply to the argument if the type and predicate matches * @return a builder with the case statement added * @see UnitPFBuilder#match(Class, FI.TypedPredicate, FI.UnitApply) */ - public static UnitPFBuilder match(final Class

type, - final FI.TypedPredicate

predicate, - final FI.UnitApply

apply) { + public static UnitPFBuilder match( + final Class

type, final FI.TypedPredicate

predicate, final FI.UnitApply

apply) { return new UnitPFBuilder().match(type, predicate, apply); } /** - * Convenience function to create a {@link UnitPFBuilder} with the first - * case statement added. Should normally not be used. + * Convenience function to create a {@link UnitPFBuilder} with the first case statement added. + * Should normally not be used. * * @see UnitPFBuilder#matchUnchecked(Class, FI.TypedPredicate, FI.UnitApply) */ - public static UnitPFBuilder matchUnchecked(final Class type, - final FI.TypedPredicate predicate, - final FI.UnitApply apply) { + public static UnitPFBuilder matchUnchecked( + final Class type, final FI.TypedPredicate predicate, final FI.UnitApply apply) { return new UnitPFBuilder().matchUnchecked(type, predicate, apply); } /** - * Convenience function to create a {@link UnitPFBuilder} with the first - * case statement added. + * Convenience function to create a {@link UnitPFBuilder} with the first case statement added. * * @param object the object to compare equals with - * @param apply an action to apply to the argument if the object compares equal + * @param apply an action to apply to the argument if the object compares equal * @return a builder with the case statement added * @see UnitPFBuilder#matchEquals(Object, FI.UnitApply) */ - public static UnitPFBuilder matchEquals(final P object, - final FI.UnitApply

apply) { + public static UnitPFBuilder matchEquals(final P object, final FI.UnitApply

apply) { return new UnitPFBuilder().matchEquals(object, apply); } /** - * Convenience function to create a {@link UnitPFBuilder} with the first - * case statement added. + * Convenience function to create a {@link UnitPFBuilder} with the first case statement added. * - * @param object the object to compare equals with + * @param object the object to compare equals with * @param predicate a predicate that will be evaluated on the argument the object compares equal - * @param apply an action to apply to the argument if the object compares equal + * @param apply an action to apply to the argument if the object compares equal * @return a builder with the case statement added * @see UnitPFBuilder#matchEquals(Object, FI.UnitApply) */ - public static UnitPFBuilder matchEquals(final P object, - final FI.TypedPredicate

predicate, - final FI.UnitApply

apply) { + public static UnitPFBuilder matchEquals( + final P object, final FI.TypedPredicate

predicate, final FI.UnitApply

apply) { return new UnitPFBuilder().matchEquals(object, predicate, apply); } /** - * Convenience function to create a {@link UnitPFBuilder} with the first - * case statement added. + * Convenience function to create a {@link UnitPFBuilder} with the first case statement added. * * @param apply an action to apply to the argument * @return a builder with the case statement added @@ -128,7 +118,9 @@ public class UnitMatch extends AbstractMatch { /** * Convenience function to make the Java code more readable. + * *

+ * *


    *   UnitMatcher<X> matcher = UnitMatcher.create(...);
    *
diff --git a/akka-actor/src/main/java/akka/japi/pf/UnitPFBuilder.java b/akka-actor/src/main/java/akka/japi/pf/UnitPFBuilder.java
index 007e1f84bd..90c1ec4089 100644
--- a/akka-actor/src/main/java/akka/japi/pf/UnitPFBuilder.java
+++ b/akka-actor/src/main/java/akka/japi/pf/UnitPFBuilder.java
@@ -7,54 +7,46 @@ package akka.japi.pf;
 import scala.runtime.BoxedUnit;
 
 /**
- * A builder for {@link scala.PartialFunction}.
- * This is a specialized version of {@link PFBuilder} to map java
- * void methods to {@link scala.runtime.BoxedUnit}.
+ * A builder for {@link scala.PartialFunction}. This is a specialized version of {@link PFBuilder}
+ * to map java void methods to {@link scala.runtime.BoxedUnit}.
  *
  * @param  the input type, that this PartialFunction to be applied to
- *
  */
 public final class UnitPFBuilder extends AbstractPFBuilder {
 
-  /**
-   * Create a UnitPFBuilder.
-   */
-  public UnitPFBuilder() {
-  }
+  /** Create a UnitPFBuilder. */
+  public UnitPFBuilder() {}
 
   /**
    * Add a new case statement to this builder.
    *
-   * @param type  a type to match the argument against
+   * @param type a type to match the argument against
    * @param apply an action to apply to the argument if the type matches
    * @return a builder with the case statement added
    */
-  public 

UnitPFBuilder match(final Class

type, - final FI.UnitApply

apply) { + public

UnitPFBuilder match(final Class

type, final FI.UnitApply

apply) { return matchUnchecked(type, apply); } /** - * Add a new case statement to this builder without compile time type check. - * Should normally not be used, but when matching on class with generic type - * argument it can be useful, e.g. List.class and - * (List<String> list) -> {}. + * Add a new case statement to this builder without compile time type check. Should normally not + * be used, but when matching on class with generic type argument it can be useful, e.g. + * List.class and (List<String> list) -> {}. * - * @param type - * a type to match the argument against - * @param apply - * an action to apply to the argument if the type matches + * @param type a type to match the argument against + * @param apply an action to apply to the argument if the type matches * @return a builder with the case statement added */ @SuppressWarnings("unchecked") public UnitPFBuilder matchUnchecked(final Class type, final FI.UnitApply apply) { - FI.Predicate predicate = new FI.Predicate() { - @Override - public boolean defined(Object o) { - return type.isInstance(o); - } - }; + FI.Predicate predicate = + new FI.Predicate() { + @Override + public boolean defined(Object o) { + return type.isInstance(o); + } + }; addStatement(new UnitCaseStatement(predicate, (FI.UnitApply) apply)); @@ -64,42 +56,41 @@ public final class UnitPFBuilder extends AbstractPFBuilder { /** * Add a new case statement to this builder. * - * @param type a type to match the argument against + * @param type a type to match the argument against * @param predicate a predicate that will be evaluated on the argument if the type matches - * @param apply an action to apply to the argument if the type matches and the predicate returns true + * @param apply an action to apply to the argument if the type matches and the predicate returns + * true * @return a builder with the case statement added */ - public

UnitPFBuilder match(final Class

type, - final FI.TypedPredicate

predicate, - final FI.UnitApply

apply) { + public

UnitPFBuilder match( + final Class

type, final FI.TypedPredicate

predicate, final FI.UnitApply

apply) { return matchUnchecked(type, predicate, apply); } /** - * Add a new case statement to this builder without compile time type check. - * Should normally not be used, but when matching on class with generic type - * argument it can be useful, e.g. List.class and - * (List<String> list) -> {}. + * Add a new case statement to this builder without compile time type check. Should normally not + * be used, but when matching on class with generic type argument it can be useful, e.g. + * List.class and (List<String> list) -> {}. * - * @param type a type to match the argument against + * @param type a type to match the argument against * @param predicate a predicate that will be evaluated on the argument if the type matches - * @param apply an action to apply to the argument if the type matches and the predicate returns true + * @param apply an action to apply to the argument if the type matches and the predicate returns + * true * @return a builder with the case statement added */ @SuppressWarnings("unchecked") - public UnitPFBuilder matchUnchecked(final Class type, - final FI.TypedPredicate predicate, - final FI.UnitApply apply) { - FI.Predicate fiPredicate = new FI.Predicate() { - @Override - public boolean defined(Object o) { - if (!type.isInstance(o)) - return false; - else { - return ((FI.TypedPredicate) predicate).defined(o); - } - } - }; + public UnitPFBuilder matchUnchecked( + final Class type, final FI.TypedPredicate predicate, final FI.UnitApply apply) { + FI.Predicate fiPredicate = + new FI.Predicate() { + @Override + public boolean defined(Object o) { + if (!type.isInstance(o)) return false; + else { + return ((FI.TypedPredicate) predicate).defined(o); + } + } + }; addStatement(new UnitCaseStatement(fiPredicate, (FI.UnitApply) apply)); @@ -110,45 +101,47 @@ public final class UnitPFBuilder extends AbstractPFBuilder { * Add a new case statement to this builder. * * @param object the object to compare equals with - * @param apply an action to apply to the argument if the object compares equal + * @param apply an action to apply to the argument if the object compares equal * @return a builder with the case statement added */ - public

UnitPFBuilder matchEquals(final P object, - final FI.UnitApply

apply) { - addStatement(new UnitCaseStatement( - new FI.Predicate() { - @Override - public boolean defined(Object o) { - return object.equals(o); - } - }, apply)); + public

UnitPFBuilder matchEquals(final P object, final FI.UnitApply

apply) { + addStatement( + new UnitCaseStatement( + new FI.Predicate() { + @Override + public boolean defined(Object o) { + return object.equals(o); + } + }, + apply)); return this; } /** * Add a new case statement to this builder. * - * @param object the object to compare equals with - * @param predicate a predicate that will be evaluated on the argument if the object compares equal - * @param apply an action to apply to the argument if the object compares equal + * @param object the object to compare equals with + * @param predicate a predicate that will be evaluated on the argument if the object compares + * equal + * @param apply an action to apply to the argument if the object compares equal * @return a builder with the case statement added */ - public

UnitPFBuilder matchEquals(final P object, - final FI.TypedPredicate

predicate, - final FI.UnitApply

apply) { - addStatement(new UnitCaseStatement( - new FI.Predicate() { - @Override - public boolean defined(Object o) { - if (!object.equals(o)) - return false; - else { - @SuppressWarnings("unchecked") - P p = (P) o; - return predicate.defined(p); - } - } - }, apply)); + public

UnitPFBuilder matchEquals( + final P object, final FI.TypedPredicate

predicate, final FI.UnitApply

apply) { + addStatement( + new UnitCaseStatement( + new FI.Predicate() { + @Override + public boolean defined(Object o) { + if (!object.equals(o)) return false; + else { + @SuppressWarnings("unchecked") + P p = (P) o; + return predicate.defined(p); + } + } + }, + apply)); return this; } @@ -159,13 +152,15 @@ public final class UnitPFBuilder extends AbstractPFBuilder { * @return a builder with the case statement added */ public UnitPFBuilder matchAny(final FI.UnitApply apply) { - addStatement(new UnitCaseStatement( - new FI.Predicate() { - @Override - public boolean defined(Object o) { - return true; - } - }, apply)); + addStatement( + new UnitCaseStatement( + new FI.Predicate() { + @Override + public boolean defined(Object o) { + return true; + } + }, + apply)); return this; } } diff --git a/akka-actor/src/main/java/akka/pattern/AbstractCircuitBreaker.java b/akka-actor/src/main/java/akka/pattern/AbstractCircuitBreaker.java index 33ecd8758f..cfcab40f41 100644 --- a/akka-actor/src/main/java/akka/pattern/AbstractCircuitBreaker.java +++ b/akka-actor/src/main/java/akka/pattern/AbstractCircuitBreaker.java @@ -7,15 +7,19 @@ package akka.pattern; import akka.util.Unsafe; class AbstractCircuitBreaker { - protected final static long stateOffset; - protected final static long resetTimeoutOffset; + protected static final long stateOffset; + protected static final long resetTimeoutOffset; - static { - try { - stateOffset = Unsafe.instance.objectFieldOffset(CircuitBreaker.class.getDeclaredField("_currentStateDoNotCallMeDirectly")); - resetTimeoutOffset = Unsafe.instance.objectFieldOffset(CircuitBreaker.class.getDeclaredField("_currentResetTimeoutDoNotCallMeDirectly")); - } catch(Throwable t){ - throw new ExceptionInInitializerError(t); - } + static { + try { + stateOffset = + Unsafe.instance.objectFieldOffset( + CircuitBreaker.class.getDeclaredField("_currentStateDoNotCallMeDirectly")); + resetTimeoutOffset = + Unsafe.instance.objectFieldOffset( + CircuitBreaker.class.getDeclaredField("_currentResetTimeoutDoNotCallMeDirectly")); + } catch (Throwable t) { + throw new ExceptionInInitializerError(t); } + } } diff --git a/akka-actor/src/main/java/akka/pattern/AbstractPromiseActorRef.java b/akka-actor/src/main/java/akka/pattern/AbstractPromiseActorRef.java index 49950c689e..360fd325c4 100644 --- a/akka-actor/src/main/java/akka/pattern/AbstractPromiseActorRef.java +++ b/akka-actor/src/main/java/akka/pattern/AbstractPromiseActorRef.java @@ -7,15 +7,19 @@ package akka.pattern; import akka.util.Unsafe; final class AbstractPromiseActorRef { - final static long stateOffset; - final static long watchedByOffset; + static final long stateOffset; + static final long watchedByOffset; - static { - try { - stateOffset = Unsafe.instance.objectFieldOffset(PromiseActorRef.class.getDeclaredField("_stateDoNotCallMeDirectly")); - watchedByOffset = Unsafe.instance.objectFieldOffset(PromiseActorRef.class.getDeclaredField("_watchedByDoNotCallMeDirectly")); - } catch(Throwable t){ - throw new ExceptionInInitializerError(t); - } + static { + try { + stateOffset = + Unsafe.instance.objectFieldOffset( + PromiseActorRef.class.getDeclaredField("_stateDoNotCallMeDirectly")); + watchedByOffset = + Unsafe.instance.objectFieldOffset( + PromiseActorRef.class.getDeclaredField("_watchedByDoNotCallMeDirectly")); + } catch (Throwable t) { + throw new ExceptionInInitializerError(t); } + } } diff --git a/akka-camel/src/test/java/akka/camel/ConsumerJavaTest.java b/akka-camel/src/test/java/akka/camel/ConsumerJavaTest.java index b3be9d1fb6..2597e0a913 100644 --- a/akka-camel/src/test/java/akka/camel/ConsumerJavaTest.java +++ b/akka-camel/src/test/java/akka/camel/ConsumerJavaTest.java @@ -25,29 +25,41 @@ public class ConsumerJavaTest extends JUnitSuite { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("ConsumerJavaTest", AkkaSpec.testConf()); + new AkkaJUnitActorSystemResource("ConsumerJavaTest", AkkaSpec.testConf()); private final ActorSystem system = actorSystemResource.getSystem(); @Test public void shouldHandleExceptionThrownByActorAndGenerateCustomResponse() throws Exception { - new TestKit(system) {{ - String result = new EventFilter(Exception.class, system).occurrences(1).intercept(() -> { - FiniteDuration duration = Duration.create(1, TimeUnit.SECONDS); - Timeout timeout = new Timeout(duration); - Camel camel = CamelExtension.get(system); - ExecutionContext executionContext = system.dispatcher(); - try { - Await.result( - camel.activationFutureFor(system.actorOf(Props.create(SampleErrorHandlingConsumer.class), "sample-error-handling-consumer"), timeout, executionContext), - duration); - return camel.template().requestBody("direct:error-handler-test-java", "hello", String.class); - } - catch (Exception e) { - return e.getMessage(); - } - }); - assertEquals("error: hello", result); - }}; + new TestKit(system) { + { + String result = + new EventFilter(Exception.class, system) + .occurrences(1) + .intercept( + () -> { + FiniteDuration duration = Duration.create(1, TimeUnit.SECONDS); + Timeout timeout = new Timeout(duration); + Camel camel = CamelExtension.get(system); + ExecutionContext executionContext = system.dispatcher(); + try { + Await.result( + camel.activationFutureFor( + system.actorOf( + Props.create(SampleErrorHandlingConsumer.class), + "sample-error-handling-consumer"), + timeout, + executionContext), + duration); + return camel + .template() + .requestBody("direct:error-handler-test-java", "hello", String.class); + } catch (Exception e) { + return e.getMessage(); + } + }); + assertEquals("error: hello", result); + } + }; } } diff --git a/akka-camel/src/test/java/akka/camel/CustomRouteTest.java b/akka-camel/src/test/java/akka/camel/CustomRouteTest.java index cf79eef7c0..66f5bd7496 100644 --- a/akka-camel/src/test/java/akka/camel/CustomRouteTest.java +++ b/akka-camel/src/test/java/akka/camel/CustomRouteTest.java @@ -27,7 +27,8 @@ import java.util.concurrent.TimeUnit; public class CustomRouteTest extends JUnitSuite { @Rule - public AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("CustomRouteTest"); + public AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("CustomRouteTest"); private ActorSystem system = null; private Camel camel = null; @@ -47,9 +48,10 @@ public class CustomRouteTest extends JUnitSuite { @Test public void testCustomProducerRoute() throws Exception { - MockEndpoint mockEndpoint = camel.context().getEndpoint("mock:mockProducer", MockEndpoint.class); + MockEndpoint mockEndpoint = + camel.context().getEndpoint("mock:mockProducer", MockEndpoint.class); ActorRef producer = system.actorOf(Props.create(MockEndpointProducer.class), "mockEndpoint"); - camel.context().addRoutes(new CustomRouteBuilder("direct:test",producer)); + camel.context().addRoutes(new CustomRouteBuilder("direct:test", producer)); camel.template().sendBody("direct:test", "test"); assertMockEndpoint(mockEndpoint); system.stop(producer); @@ -57,9 +59,12 @@ public class CustomRouteTest extends JUnitSuite { @Test public void testCustomProducerUriRoute() throws Exception { - MockEndpoint mockEndpoint = camel.context().getEndpoint("mock:mockProducerUri", MockEndpoint.class); - ActorRef producer = system.actorOf(Props.create(EndpointProducer.class, "mock:mockProducerUri"), "mockEndpointUri"); - camel.context().addRoutes(new CustomRouteBuilder("direct:test",producer)); + MockEndpoint mockEndpoint = + camel.context().getEndpoint("mock:mockProducerUri", MockEndpoint.class); + ActorRef producer = + system.actorOf( + Props.create(EndpointProducer.class, "mock:mockProducerUri"), "mockEndpointUri"); + camel.context().addRoutes(new CustomRouteBuilder("direct:test", producer)); camel.template().sendBody("direct:test", "test"); assertMockEndpoint(mockEndpoint); system.stop(producer); @@ -67,14 +72,19 @@ public class CustomRouteTest extends JUnitSuite { @Test public void testCustomConsumerRoute() throws Exception { - MockEndpoint mockEndpoint = camel.context().getEndpoint("mock:mockConsumer", MockEndpoint.class); + MockEndpoint mockEndpoint = + camel.context().getEndpoint("mock:mockConsumer", MockEndpoint.class); FiniteDuration duration = Duration.create(10, TimeUnit.SECONDS); Timeout timeout = new Timeout(duration); ExecutionContext executionContext = system.dispatcher(); - ActorRef consumer = Await.result( - camel.activationFutureFor(system.actorOf(Props.create(TestConsumer.class), "testConsumer"), timeout, executionContext), + ActorRef consumer = + Await.result( + camel.activationFutureFor( + system.actorOf(Props.create(TestConsumer.class), "testConsumer"), + timeout, + executionContext), duration); - camel.context().addRoutes(new CustomRouteBuilder("direct:testRouteConsumer",consumer)); + camel.context().addRoutes(new CustomRouteBuilder("direct:testRouteConsumer", consumer)); camel.template().sendBody("direct:testRouteConsumer", "test"); assertMockEndpoint(mockEndpoint); system.stop(consumer); @@ -86,12 +96,15 @@ public class CustomRouteTest extends JUnitSuite { FiniteDuration duration = Duration.create(10, TimeUnit.SECONDS); Timeout timeout = new Timeout(duration); ExecutionContext executionContext = system.dispatcher(); - ActorRef consumer = Await.result( - camel.activationFutureFor( - system.actorOf( - Props.create(TestAckConsumer.class, "direct:testConsumerAck","mock:mockAck"), "testConsumerAck"), - timeout, executionContext), - duration); + ActorRef consumer = + Await.result( + camel.activationFutureFor( + system.actorOf( + Props.create(TestAckConsumer.class, "direct:testConsumerAck", "mock:mockAck"), + "testConsumerAck"), + timeout, + executionContext), + duration); camel.context().addRoutes(new CustomRouteBuilder("direct:testAck", consumer, false, duration)); camel.template().sendBody("direct:testAck", "test"); assertMockEndpoint(mockEndpoint); @@ -101,40 +114,64 @@ public class CustomRouteTest extends JUnitSuite { @Test public void testCustomAckConsumerRouteFromUri() throws Exception { MockEndpoint mockEndpoint = camel.context().getEndpoint("mock:mockAckUri", MockEndpoint.class); - ExecutionContext executionContext = system.dispatcher(); + ExecutionContext executionContext = system.dispatcher(); FiniteDuration duration = Duration.create(10, TimeUnit.SECONDS); Timeout timeout = new Timeout(duration); - ActorRef consumer = Await.result( - camel.activationFutureFor(system.actorOf(Props.create(TestAckConsumer.class, "direct:testConsumerAckFromUri","mock:mockAckUri"), "testConsumerAckUri"), - timeout, executionContext), - duration); - camel.context().addRoutes(new CustomRouteBuilder("direct:testAckFromUri","akka://CustomRouteTest/user/testConsumerAckUri?autoAck=false")); + ActorRef consumer = + Await.result( + camel.activationFutureFor( + system.actorOf( + Props.create( + TestAckConsumer.class, "direct:testConsumerAckFromUri", "mock:mockAckUri"), + "testConsumerAckUri"), + timeout, + executionContext), + duration); + camel + .context() + .addRoutes( + new CustomRouteBuilder( + "direct:testAckFromUri", + "akka://CustomRouteTest/user/testConsumerAckUri?autoAck=false")); camel.template().sendBody("direct:testAckFromUri", "test"); assertMockEndpoint(mockEndpoint); system.stop(consumer); } - @Test(expected=CamelExecutionException.class) + @Test(expected = CamelExecutionException.class) public void testCustomTimeoutConsumerRoute() throws Exception { FiniteDuration duration = Duration.create(10, TimeUnit.SECONDS); Timeout timeout = new Timeout(duration); ExecutionContext executionContext = system.dispatcher(); - ActorRef consumer = Await.result( - camel.activationFutureFor(system.actorOf(Props.create(TestAckConsumer.class, "direct:testConsumerException","mock:mockException"), "testConsumerException"), - timeout, executionContext), - duration); - camel.context().addRoutes(new CustomRouteBuilder("direct:testException", consumer, false, Duration.create(0, TimeUnit.SECONDS))); + ActorRef consumer = + Await.result( + camel.activationFutureFor( + system.actorOf( + Props.create( + TestAckConsumer.class, + "direct:testConsumerException", + "mock:mockException"), + "testConsumerException"), + timeout, + executionContext), + duration); + camel + .context() + .addRoutes( + new CustomRouteBuilder( + "direct:testException", consumer, false, Duration.create(0, TimeUnit.SECONDS))); camel.template().sendBody("direct:testException", "test"); } private void assertMockEndpoint(MockEndpoint mockEndpoint) throws InterruptedException { mockEndpoint.expectedMessageCount(1); - mockEndpoint.expectedMessagesMatches(new Predicate() { - @Override - public boolean matches(Exchange exchange) { - return exchange.getIn().getBody().equals("test"); - } - }); + mockEndpoint.expectedMessagesMatches( + new Predicate() { + @Override + public boolean matches(Exchange exchange) { + return exchange.getIn().getBody().equals("test"); + } + }); mockEndpoint.assertIsSatisfied(); } @@ -163,7 +200,6 @@ public class CustomRouteTest extends JUnitSuite { } } - public static class TestConsumer extends UntypedConsumerActor { @Override public String getEndpointUri() { @@ -172,7 +208,7 @@ public class CustomRouteTest extends JUnitSuite { @Override public void onReceive(Object message) { - this.getProducerTemplate().sendBody("mock:mockConsumer","test"); + this.getProducerTemplate().sendBody("mock:mockConsumer", "test"); } } @@ -208,7 +244,7 @@ public class CustomRouteTest extends JUnitSuite { private final String myuri; private final String to; - public TestAckConsumer(String uri, String to){ + public TestAckConsumer(String uri, String to) { myuri = uri; this.to = to; } diff --git a/akka-camel/src/test/java/akka/camel/MessageJavaTest.java b/akka-camel/src/test/java/akka/camel/MessageJavaTest.java index 110d83251c..5e3204c0f5 100644 --- a/akka-camel/src/test/java/akka/camel/MessageJavaTest.java +++ b/akka-camel/src/test/java/akka/camel/MessageJavaTest.java @@ -18,81 +18,91 @@ import java.util.*; import static org.junit.Assert.assertEquals; -/** - * - */ +/** */ public class MessageJavaTest extends JUnitSuite { - private Map empty = new HashMap(); + private Map empty = new HashMap(); @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("MessageJavaTest"); + new AkkaJUnitActorSystemResource("MessageJavaTest"); private final ActorSystem system = actorSystemResource.getSystem(); private Camel camel = (Camel) CamelExtension.get(system); - CamelMessage message(Object body){ return new CamelMessage(body, new HashMap()); } - CamelMessage message(Object body, Map headers){ return new CamelMessage(body, headers); } - - - @Test public void shouldConvertDoubleBodyToString() { - assertEquals("1.4", message("1.4", empty).getBodyAs(String.class,camel.context())); + CamelMessage message(Object body) { + return new CamelMessage(body, new HashMap()); } - @Test(expected=NoTypeConversionAvailableException.class) + CamelMessage message(Object body, Map headers) { + return new CamelMessage(body, headers); + } + + @Test + public void shouldConvertDoubleBodyToString() { + assertEquals("1.4", message("1.4", empty).getBodyAs(String.class, camel.context())); + } + + @Test(expected = NoTypeConversionAvailableException.class) public void shouldThrowExceptionWhenConvertingDoubleBodyToInputStream() { - message(1.4).getBodyAs(InputStream.class,camel.context()); + message(1.4).getBodyAs(InputStream.class, camel.context()); } - @Test public void shouldConvertDoubleHeaderToString() { - CamelMessage message = message("test" , createMap("test", 1.4)); - assertEquals("1.4", message.getHeaderAs("test", String.class,camel.context())); + @Test + public void shouldConvertDoubleHeaderToString() { + CamelMessage message = message("test", createMap("test", 1.4)); + assertEquals("1.4", message.getHeaderAs("test", String.class, camel.context())); } - @Test public void shouldReturnSubsetOfHeaders() { - CamelMessage message = message("test" , createMap("A", "1", "B", "2")); + @Test + public void shouldReturnSubsetOfHeaders() { + CamelMessage message = message("test", createMap("A", "1", "B", "2")); assertEquals(createMap("B", "2"), message.getHeaders(createSet("B"))); } - @Test(expected=UnsupportedOperationException.class) + @Test(expected = UnsupportedOperationException.class) public void shouldReturnSubsetOfHeadersUnmodifiable() { - CamelMessage message = message("test" , createMap("A", "1", "B", "2")); + CamelMessage message = message("test", createMap("A", "1", "B", "2")); message.getHeaders(createSet("B")).put("x", "y"); } - @Test public void shouldReturnAllHeaders() { - CamelMessage message = message("test" , createMap("A", "1", "B", "2")); + @Test + public void shouldReturnAllHeaders() { + CamelMessage message = message("test", createMap("A", "1", "B", "2")); assertEquals(createMap("A", "1", "B", "2"), message.getHeaders()); } - @Test(expected=UnsupportedOperationException.class) + @Test(expected = UnsupportedOperationException.class) public void shouldReturnAllHeadersUnmodifiable() { - CamelMessage message = message("test" , createMap("A", "1", "B", "2")); + CamelMessage message = message("test", createMap("A", "1", "B", "2")); message.getHeaders().put("x", "y"); } - @Test public void shouldTransformBodyAndPreserveHeaders() { + @Test + public void shouldTransformBodyAndPreserveHeaders() { assertEquals( - message("ab", createMap("A", "1")), - message("a" , createMap("A", "1")).mapBody(new TestTransformer())); + message("ab", createMap("A", "1")), + message("a", createMap("A", "1")).mapBody(new TestTransformer())); } - @Test public void shouldConvertBodyAndPreserveHeaders() { + @Test + public void shouldConvertBodyAndPreserveHeaders() { assertEquals( - message("1.4", createMap("A", "1")), - message(1.4 , createMap("A", "1")).withBodyAs(String.class,camel.context())); + message("1.4", createMap("A", "1")), + message(1.4, createMap("A", "1")).withBodyAs(String.class, camel.context())); } - @Test public void shouldSetBodyAndPreserveHeaders() { + @Test + public void shouldSetBodyAndPreserveHeaders() { assertEquals( - message("test2" , createMap("A", "1")), - message("test1" , createMap("A", "1")).withBody("test2")); + message("test2", createMap("A", "1")), + message("test1", createMap("A", "1")).withBody("test2")); } - @Test public void shouldSetHeadersAndPreserveBody() { + @Test + public void shouldSetHeadersAndPreserveBody() { assertEquals( - message("test1" , createMap("C", "3")), - message("test1" , createMap("A", "1")).withHeaders(createMap("C", "3"))); + message("test1", createMap("C", "3")), + message("test1", createMap("A", "1")).withHeaders(createMap("C", "3"))); } @Test @@ -112,7 +122,7 @@ public class MessageJavaTest extends JUnitSuite { private static Map createMap(Object... pairs) { HashMap map = new HashMap(); for (int i = 0; i < pairs.length; i += 2) { - map.put((String)pairs[i], pairs[i+1]); + map.put((String) pairs[i], pairs[i + 1]); } return map; } @@ -123,5 +133,4 @@ public class MessageJavaTest extends JUnitSuite { return param + "b"; } } - } diff --git a/akka-camel/src/test/java/akka/camel/SampleErrorHandlingConsumer.java b/akka-camel/src/test/java/akka/camel/SampleErrorHandlingConsumer.java index 01e5778af0..495fa13fd7 100644 --- a/akka-camel/src/test/java/akka/camel/SampleErrorHandlingConsumer.java +++ b/akka-camel/src/test/java/akka/camel/SampleErrorHandlingConsumer.java @@ -14,39 +14,40 @@ import org.apache.camel.model.RouteDefinition; import scala.Option; import scala.concurrent.duration.FiniteDuration; -/** - * - */ +/** */ public class SampleErrorHandlingConsumer extends UntypedConsumerActor { - private static Mapper> mapper = new Mapper>() { + private static Mapper> mapper = + new Mapper>() { public ProcessorDefinition apply(RouteDefinition rd) { - return rd.onException(Exception.class).handled(true).transform(Builder.exceptionMessage()).end(); + return rd.onException(Exception.class) + .handled(true) + .transform(Builder.exceptionMessage()) + .end(); } - }; + }; - public String getEndpointUri() { - return "direct:error-handler-test-java"; - } + public String getEndpointUri() { + return "direct:error-handler-test-java"; + } - @Override - public Mapper> onRouteDefinition() { - return mapper; - } + @Override + public Mapper> onRouteDefinition() { + return mapper; + } - @Override - public FiniteDuration replyTimeout(){ - return Duration.create(1, "second"); - } + @Override + public FiniteDuration replyTimeout() { + return Duration.create(1, "second"); + } - public void onReceive(Object message) throws Exception { - CamelMessage msg = (CamelMessage) message; - String body = msg.getBodyAs(String.class,this.getCamelContext()); - throw new Exception(String.format("error: %s", body)); - } - - @Override - public void preRestart(Throwable reason, Option message){ - getSender().tell(new Status.Failure(reason), getSelf()); - } + public void onReceive(Object message) throws Exception { + CamelMessage msg = (CamelMessage) message; + String body = msg.getBodyAs(String.class, this.getCamelContext()); + throw new Exception(String.format("error: %s", body)); + } + @Override + public void preRestart(Throwable reason, Option message) { + getSender().tell(new Status.Failure(reason), getSelf()); + } } diff --git a/akka-camel/src/test/java/akka/camel/SampleUntypedConsumer.java b/akka-camel/src/test/java/akka/camel/SampleUntypedConsumer.java index 3151ba947e..bebceced0f 100644 --- a/akka-camel/src/test/java/akka/camel/SampleUntypedConsumer.java +++ b/akka-camel/src/test/java/akka/camel/SampleUntypedConsumer.java @@ -6,20 +6,17 @@ package akka.camel; import akka.camel.javaapi.UntypedConsumerActor; -/** - * - */ +/** */ public class SampleUntypedConsumer extends UntypedConsumerActor { - public String getEndpointUri() { - return "direct:test-untyped-consumer"; - } - - public void onReceive(Object message) { - CamelMessage msg = (CamelMessage)message; - String body = msg.getBodyAs(String.class, getCamelContext()); - String header = msg.getHeaderAs("test", String.class,getCamelContext()); - sender().tell(String.format("%s %s", body, header), getSelf()); - } + public String getEndpointUri() { + return "direct:test-untyped-consumer"; + } + public void onReceive(Object message) { + CamelMessage msg = (CamelMessage) message; + String body = msg.getBodyAs(String.class, getCamelContext()); + String header = msg.getHeaderAs("test", String.class, getCamelContext()); + sender().tell(String.format("%s %s", body, header), getSelf()); + } } diff --git a/akka-camel/src/test/java/akka/camel/SampleUntypedForwardingProducer.java b/akka-camel/src/test/java/akka/camel/SampleUntypedForwardingProducer.java index 2952099938..e9e41dae26 100644 --- a/akka-camel/src/test/java/akka/camel/SampleUntypedForwardingProducer.java +++ b/akka-camel/src/test/java/akka/camel/SampleUntypedForwardingProducer.java @@ -5,19 +5,17 @@ package akka.camel; import akka.camel.javaapi.UntypedProducerActor; -/** - * - */ +/** */ public class SampleUntypedForwardingProducer extends UntypedProducerActor { - public String getEndpointUri() { - return "direct:producer-test-1"; - } + public String getEndpointUri() { + return "direct:producer-test-1"; + } - @Override - public void onRouteResponse(Object message) { - CamelMessage msg = (CamelMessage)message; - String body = msg.getBodyAs(String.class,getCamelContext()); - getProducerTemplate().sendBody("direct:forward-test-1", body); - } + @Override + public void onRouteResponse(Object message) { + CamelMessage msg = (CamelMessage) message; + String body = msg.getBodyAs(String.class, getCamelContext()); + getProducerTemplate().sendBody("direct:forward-test-1", body); + } } diff --git a/akka-camel/src/test/java/akka/camel/SampleUntypedReplyingProducer.java b/akka-camel/src/test/java/akka/camel/SampleUntypedReplyingProducer.java index 5e91a5b79d..45a962caf4 100644 --- a/akka-camel/src/test/java/akka/camel/SampleUntypedReplyingProducer.java +++ b/akka-camel/src/test/java/akka/camel/SampleUntypedReplyingProducer.java @@ -6,13 +6,10 @@ package akka.camel; import akka.camel.javaapi.UntypedProducerActor; -/** - * - */ +/** */ public class SampleUntypedReplyingProducer extends UntypedProducerActor { - public String getEndpointUri() { - return "direct:producer-test-1"; - } - + public String getEndpointUri() { + return "direct:producer-test-1"; + } } diff --git a/akka-cluster-sharding-typed/src/test/java/akka/cluster/sharding/typed/javadsl/ClusterShardingPersistenceTest.java b/akka-cluster-sharding-typed/src/test/java/akka/cluster/sharding/typed/javadsl/ClusterShardingPersistenceTest.java index 9a41b12659..f02b4d6b8b 100644 --- a/akka-cluster-sharding-typed/src/test/java/akka/cluster/sharding/typed/javadsl/ClusterShardingPersistenceTest.java +++ b/akka-cluster-sharding-typed/src/test/java/akka/cluster/sharding/typed/javadsl/ClusterShardingPersistenceTest.java @@ -25,17 +25,18 @@ import java.util.concurrent.CompletionStage; public class ClusterShardingPersistenceTest extends JUnitSuite { - public static final Config config = ConfigFactory.parseString( - "akka.actor.provider = cluster \n" + - "akka.remote.netty.tcp.port = 0 \n" + - "akka.remote.artery.canonical.port = 0 \n" + - "akka.remote.artery.canonical.hostname = 127.0.0.1 \n" + - "akka.persistence.journal.plugin = \"akka.persistence.journal.inmem\" \n"); + public static final Config config = + ConfigFactory.parseString( + "akka.actor.provider = cluster \n" + + "akka.remote.netty.tcp.port = 0 \n" + + "akka.remote.artery.canonical.port = 0 \n" + + "akka.remote.artery.canonical.hostname = 127.0.0.1 \n" + + "akka.persistence.journal.plugin = \"akka.persistence.journal.inmem\" \n"); - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(config); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(config); interface Command {} + static class Add implements Command { public final String s; @@ -43,6 +44,7 @@ public class ClusterShardingPersistenceTest extends JUnitSuite { this.s = s; } } + static class AddWithConfirmation implements Command, ExpectingReply { final String s; private final ActorRef replyTo; @@ -57,6 +59,7 @@ public class ClusterShardingPersistenceTest extends JUnitSuite { return replyTo; } } + static class Get implements Command { final ActorRef replyTo; @@ -64,16 +67,15 @@ public class ClusterShardingPersistenceTest extends JUnitSuite { this.replyTo = replyTo; } } + static enum StopPlz implements Command { INSTANCE } - - static class TestPersistentEntity extends EventSourcedEntity { public static final EntityTypeKey ENTITY_TYPE_KEY = - EntityTypeKey.create(Command.class, "HelloWorld"); + EntityTypeKey.create(Command.class, "HelloWorld"); public TestPersistentEntity(String entityId) { super(ENTITY_TYPE_KEY, entityId); @@ -87,10 +89,10 @@ public class ClusterShardingPersistenceTest extends JUnitSuite { @Override public CommandHandler commandHandler() { return commandHandlerBuilder(String.class) - .matchCommand(Add.class, this::add) - .matchCommand(AddWithConfirmation.class, this::addWithConfirmation) - .matchCommand(Get.class, this::getState) - .build(); + .matchCommand(Add.class, this::add) + .matchCommand(AddWithConfirmation.class, this::addWithConfirmation) + .matchCommand(Get.class, this::getState) + .build(); } private Effect add(String state, Add cmd) { @@ -98,8 +100,7 @@ public class ClusterShardingPersistenceTest extends JUnitSuite { } private Effect addWithConfirmation(String state, AddWithConfirmation cmd) { - return Effect().persist(cmd.s) - .thenReply(cmd, newState -> Done.getInstance()); + return Effect().persist(cmd.s).thenReply(cmd, newState -> Done.getInstance()); } private Effect getState(String state, Get cmd) { @@ -109,16 +110,12 @@ public class ClusterShardingPersistenceTest extends JUnitSuite { @Override public EventHandler eventHandler() { - return eventHandlerBuilder() - .matchEvent(String.class, this::applyEvent) - .build(); + return eventHandlerBuilder().matchEvent(String.class, this::applyEvent).build(); } private String applyEvent(String state, String evt) { - if (state.equals("")) - return evt; - else - return state + "|" + evt; + if (state.equals("")) return evt; + else return state + "|" + evt; } } @@ -132,9 +129,11 @@ public class ClusterShardingPersistenceTest extends JUnitSuite { ClusterSharding sharding = ClusterSharding.get(testKit.system()); - sharding.init(Entity.ofPersistentEntity(TestPersistentEntity.ENTITY_TYPE_KEY, - entityContext -> new TestPersistentEntity(entityContext.getEntityId())) - .withStopMessage(StopPlz.INSTANCE)); + sharding.init( + Entity.ofPersistentEntity( + TestPersistentEntity.ENTITY_TYPE_KEY, + entityContext -> new TestPersistentEntity(entityContext.getEntityId())) + .withStopMessage(StopPlz.INSTANCE)); _sharding = sharding; } @@ -157,11 +156,13 @@ public class ClusterShardingPersistenceTest extends JUnitSuite { TestProbe p1 = testKit.createTestProbe(); EntityRef ref = sharding().entityRefFor(TestPersistentEntity.ENTITY_TYPE_KEY, "456"); Timeout askTimeout = Timeout.create(p1.getRemainingOrDefault()); - CompletionStage done1 =ref.ask(replyTo -> new AddWithConfirmation("a", replyTo), askTimeout); + CompletionStage done1 = + ref.ask(replyTo -> new AddWithConfirmation("a", replyTo), askTimeout); done1.thenAccept(d -> p1.getRef().tell(d)); p1.expectMessage(Done.getInstance()); - CompletionStage done2 =ref.ask(replyTo -> new AddWithConfirmation("b", replyTo), askTimeout); + CompletionStage done2 = + ref.ask(replyTo -> new AddWithConfirmation("b", replyTo), askTimeout); done1.thenAccept(d -> p1.getRef().tell(d)); p1.expectMessage(Done.getInstance()); @@ -169,5 +170,4 @@ public class ClusterShardingPersistenceTest extends JUnitSuite { ref.tell(new Get(p2.getRef())); p2.expectMessage("456:a|b"); } - } diff --git a/akka-cluster-sharding-typed/src/test/java/jdocs/akka/cluster/sharding/typed/HelloWorldEventSourcedEntityExampleTest.java b/akka-cluster-sharding-typed/src/test/java/jdocs/akka/cluster/sharding/typed/HelloWorldEventSourcedEntityExampleTest.java index 59970b8165..24e7909561 100644 --- a/akka-cluster-sharding-typed/src/test/java/jdocs/akka/cluster/sharding/typed/HelloWorldEventSourcedEntityExampleTest.java +++ b/akka-cluster-sharding-typed/src/test/java/jdocs/akka/cluster/sharding/typed/HelloWorldEventSourcedEntityExampleTest.java @@ -22,15 +22,15 @@ import static org.junit.Assert.assertEquals; public class HelloWorldEventSourcedEntityExampleTest extends JUnitSuite { - public static final Config config = ConfigFactory.parseString( - "akka.actor.provider = cluster \n" + - "akka.remote.netty.tcp.port = 0 \n" + - "akka.remote.artery.canonical.port = 0 \n" + - "akka.remote.artery.canonical.hostname = 127.0.0.1 \n" + - "akka.persistence.journal.plugin = \"akka.persistence.journal.inmem\" \n"); + public static final Config config = + ConfigFactory.parseString( + "akka.actor.provider = cluster \n" + + "akka.remote.netty.tcp.port = 0 \n" + + "akka.remote.artery.canonical.port = 0 \n" + + "akka.remote.artery.canonical.hostname = 127.0.0.1 \n" + + "akka.persistence.journal.plugin = \"akka.persistence.journal.inmem\" \n"); - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(config); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(config); private ClusterSharding _sharding = null; @@ -42,9 +42,9 @@ public class HelloWorldEventSourcedEntityExampleTest extends JUnitSuite { ClusterSharding sharding = ClusterSharding.get(testKit.system()); sharding.init( - Entity.ofPersistentEntity( - HelloWorld.ENTITY_TYPE_KEY, - ctx -> new HelloWorld(ctx.getActorContext(), ctx.getEntityId()))); + Entity.ofPersistentEntity( + HelloWorld.ENTITY_TYPE_KEY, + ctx -> new HelloWorld(ctx.getActorContext(), ctx.getEntityId()))); _sharding = sharding; } return _sharding; @@ -64,5 +64,4 @@ public class HelloWorldEventSourcedEntityExampleTest extends JUnitSuite { assertEquals("Bob", greeting2.whom); assertEquals(2, greeting2.numberOfPeople); } - } diff --git a/akka-cluster-sharding-typed/src/test/java/jdocs/akka/cluster/sharding/typed/HelloWorldPersistentEntityExample.java b/akka-cluster-sharding-typed/src/test/java/jdocs/akka/cluster/sharding/typed/HelloWorldPersistentEntityExample.java index b400a9a359..9be978974e 100644 --- a/akka-cluster-sharding-typed/src/test/java/jdocs/akka/cluster/sharding/typed/HelloWorldPersistentEntityExample.java +++ b/akka-cluster-sharding-typed/src/test/java/jdocs/akka/cluster/sharding/typed/HelloWorldPersistentEntityExample.java @@ -13,24 +13,24 @@ import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletionStage; -//#persistent-entity-import +// #persistent-entity-import import akka.cluster.sharding.typed.javadsl.EntityTypeKey; import akka.cluster.sharding.typed.javadsl.EventSourcedEntity; import akka.persistence.typed.javadsl.CommandHandler; import akka.persistence.typed.javadsl.Effect; import akka.persistence.typed.javadsl.EventHandler; -//#persistent-entity-import +// #persistent-entity-import -//#persistent-entity-usage-import +// #persistent-entity-usage-import import akka.cluster.sharding.typed.javadsl.ClusterSharding; import akka.cluster.sharding.typed.javadsl.EntityRef; import akka.cluster.sharding.typed.javadsl.Entity; import akka.util.Timeout; -//#persistent-entity-usage-import +// #persistent-entity-usage-import public class HelloWorldPersistentEntityExample { - //#persistent-entity-usage + // #persistent-entity-usage public static class HelloWorldService { private final ActorSystem system; @@ -43,29 +43,29 @@ public class HelloWorldPersistentEntityExample { sharding = ClusterSharding.get(system); sharding.init( - Entity.ofPersistentEntity( - HelloWorld.ENTITY_TYPE_KEY, - ctx -> new HelloWorld(ctx.getActorContext(), ctx.getEntityId()))); + Entity.ofPersistentEntity( + HelloWorld.ENTITY_TYPE_KEY, + ctx -> new HelloWorld(ctx.getActorContext(), ctx.getEntityId()))); } // usage example public CompletionStage sayHello(String worldId, String whom) { EntityRef entityRef = - sharding.entityRefFor(HelloWorld.ENTITY_TYPE_KEY, worldId); + sharding.entityRefFor(HelloWorld.ENTITY_TYPE_KEY, worldId); CompletionStage result = entityRef.ask(replyTo -> new HelloWorld.Greet(whom, replyTo), askTimeout); return result.thenApply(greeting -> greeting.numberOfPeople); } } - //#persistent-entity-usage + // #persistent-entity-usage - //#persistent-entity + // #persistent-entity - public static class HelloWorld extends EventSourcedEntity { + public static class HelloWorld + extends EventSourcedEntity { // Command - interface Command { - } + interface Command {} public static final class Greet implements Command { public final String whom; @@ -101,8 +101,7 @@ public class HelloWorldPersistentEntityExample { static final class KnownPeople { private Set names = Collections.emptySet(); - KnownPeople() { - } + KnownPeople() {} private KnownPeople(Set names) { this.names = names; @@ -120,7 +119,7 @@ public class HelloWorldPersistentEntityExample { } public static final EntityTypeKey ENTITY_TYPE_KEY = - EntityTypeKey.create(Command.class, "HelloWorld"); + EntityTypeKey.create(Command.class, "HelloWorld"); public HelloWorld(ActorContext ctx, String entityId) { super(ENTITY_TYPE_KEY, entityId); @@ -134,20 +133,20 @@ public class HelloWorldPersistentEntityExample { @Override public CommandHandler commandHandler() { return commandHandlerBuilder(KnownPeople.class) - .matchCommand(Greet.class, this::greet) - .build(); + .matchCommand(Greet.class, this::greet) + .build(); } private Effect greet(KnownPeople state, Greet cmd) { - return Effect().persist(new Greeted(cmd.whom)) - .thenRun(newState -> cmd.replyTo.tell(new Greeting(cmd.whom, newState.numberOfPeople()))); + return Effect() + .persist(new Greeted(cmd.whom)) + .thenRun(newState -> cmd.replyTo.tell(new Greeting(cmd.whom, newState.numberOfPeople()))); } @Override public EventHandler eventHandler() { return (state, evt) -> state.add(evt.whom); } - } - //#persistent-entity + // #persistent-entity } diff --git a/akka-cluster-sharding-typed/src/test/java/jdocs/akka/cluster/sharding/typed/ShardingCompileOnlyTest.java b/akka-cluster-sharding-typed/src/test/java/jdocs/akka/cluster/sharding/typed/ShardingCompileOnlyTest.java index bd5517173d..890efd7f53 100644 --- a/akka-cluster-sharding-typed/src/test/java/jdocs/akka/cluster/sharding/typed/ShardingCompileOnlyTest.java +++ b/akka-cluster-sharding-typed/src/test/java/jdocs/akka/cluster/sharding/typed/ShardingCompileOnlyTest.java @@ -11,142 +11,143 @@ import akka.actor.typed.ActorSystem; import akka.actor.typed.Behavior; import akka.actor.typed.javadsl.Behaviors; -//#import +// #import import akka.cluster.sharding.typed.ShardingEnvelope; import akka.cluster.sharding.typed.javadsl.ClusterSharding; import akka.cluster.sharding.typed.javadsl.EntityTypeKey; import akka.cluster.sharding.typed.javadsl.EntityRef; import akka.cluster.sharding.typed.javadsl.Entity; -//#import +// #import import jdocs.akka.persistence.typed.BlogPostExample.BlogCommand; import jdocs.akka.persistence.typed.BlogPostExample.BlogBehavior; public class ShardingCompileOnlyTest { - //#counter-messages + // #counter-messages interface CounterCommand {} - public static class Increment implements CounterCommand { } + + public static class Increment implements CounterCommand {} public static class GetValue implements CounterCommand { private final ActorRef replyTo; + public GetValue(ActorRef replyTo) { this.replyTo = replyTo; } } - //#counter-messages + // #counter-messages - //#counter + // #counter public static Behavior counter(String entityId, Integer value) { return Behaviors.receive(CounterCommand.class) - .onMessage(Increment.class, (ctx, msg) -> { - return counter(entityId,value + 1); - }) - .onMessage(GetValue.class, (ctx, msg) -> { - msg.replyTo.tell(value); - return Behaviors.same(); - }) - .build(); + .onMessage( + Increment.class, + (ctx, msg) -> { + return counter(entityId, value + 1); + }) + .onMessage( + GetValue.class, + (ctx, msg) -> { + msg.replyTo.tell(value); + return Behaviors.same(); + }) + .build(); } - //#counter + // #counter - //#counter-passivate - public static class Idle implements CounterCommand { } + // #counter-passivate + public static class Idle implements CounterCommand {} - public static class GoodByeCounter implements CounterCommand { } + public static class GoodByeCounter implements CounterCommand {} - public static Behavior counter2(ActorRef shard, String entityId) { - return Behaviors.setup(ctx -> { - ctx.setReceiveTimeout(Duration.ofSeconds(30), new Idle()); - return counter2(shard, entityId, 0); - }); + public static Behavior counter2( + ActorRef shard, String entityId) { + return Behaviors.setup( + ctx -> { + ctx.setReceiveTimeout(Duration.ofSeconds(30), new Idle()); + return counter2(shard, entityId, 0); + }); } private static Behavior counter2( - ActorRef shard, - String entityId, - Integer value) { + ActorRef shard, String entityId, Integer value) { return Behaviors.receive(CounterCommand.class) - .onMessage(Increment.class, (ctx, msg) -> { - return counter(entityId,value + 1); - }) - .onMessage(GetValue.class, (ctx, msg) -> { - msg.replyTo.tell(value); - return Behaviors.same(); - }) - .onMessage(Idle.class, (ctx, msg) -> { - // after receive timeout - shard.tell(new ClusterSharding.Passivate<>(ctx.getSelf())); - return Behaviors.same(); - }) - .onMessage(GoodByeCounter.class, (ctx, msg) -> { - // the stopMessage, used for rebalance and passivate - return Behaviors.stopped(); - }) + .onMessage( + Increment.class, + (ctx, msg) -> { + return counter(entityId, value + 1); + }) + .onMessage( + GetValue.class, + (ctx, msg) -> { + msg.replyTo.tell(value); + return Behaviors.same(); + }) + .onMessage( + Idle.class, + (ctx, msg) -> { + // after receive timeout + shard.tell(new ClusterSharding.Passivate<>(ctx.getSelf())); + return Behaviors.same(); + }) + .onMessage( + GoodByeCounter.class, + (ctx, msg) -> { + // the stopMessage, used for rebalance and passivate + return Behaviors.stopped(); + }) .build(); } - //#counter-passivate + // #counter-passivate public static void initPassivateExample() { - ActorSystem system = ActorSystem.create( - Behaviors.empty(), "ShardingExample" - ); + ActorSystem system = ActorSystem.create(Behaviors.empty(), "ShardingExample"); ClusterSharding sharding = ClusterSharding.get(system); - //#counter-passivate-init - + // #counter-passivate-init + EntityTypeKey typeKey = EntityTypeKey.create(CounterCommand.class, "Counter"); sharding.init( - Entity.of( - typeKey, - ctx -> counter2(ctx.getShard(), ctx.getEntityId())) - .withStopMessage(new GoodByeCounter())); - //#counter-passivate-init + Entity.of(typeKey, ctx -> counter2(ctx.getShard(), ctx.getEntityId())) + .withStopMessage(new GoodByeCounter())); + // #counter-passivate-init } public static void example() { - ActorSystem system = ActorSystem.create( - Behaviors.empty(), "ShardingExample" - ); + ActorSystem system = ActorSystem.create(Behaviors.empty(), "ShardingExample"); - //#sharding-extension + // #sharding-extension ClusterSharding sharding = ClusterSharding.get(system); - //#sharding-extension + // #sharding-extension - //#init + // #init EntityTypeKey typeKey = EntityTypeKey.create(CounterCommand.class, "Counter"); - ActorRef> shardRegion = sharding.init( - Entity.of( - typeKey, - ctx -> counter(ctx.getEntityId(),0))); - //#init + ActorRef> shardRegion = + sharding.init(Entity.of(typeKey, ctx -> counter(ctx.getEntityId(), 0))); + // #init - //#send + // #send EntityRef counterOne = sharding.entityRefFor(typeKey, "counter-`"); counterOne.tell(new Increment()); shardRegion.tell(new ShardingEnvelope<>("counter-1", new Increment())); - //#send + // #send } public static void persistenceExample() { - ActorSystem system = ActorSystem.create( - Behaviors.empty(), "ShardingExample" - ); + ActorSystem system = ActorSystem.create(Behaviors.empty(), "ShardingExample"); ClusterSharding sharding = ClusterSharding.get(system); - //#persistence + // #persistence EntityTypeKey blogTypeKey = EntityTypeKey.create(BlogCommand.class, "BlogPost"); - sharding.init( - Entity.of( - blogTypeKey, - ctx -> BlogBehavior.behavior(ctx.getEntityId()))); - //#persistence + sharding.init(Entity.of(blogTypeKey, ctx -> BlogBehavior.behavior(ctx.getEntityId()))); + // #persistence } } diff --git a/akka-cluster-tools/src/test/java/akka/cluster/client/ClusterClientTest.java b/akka-cluster-tools/src/test/java/akka/cluster/client/ClusterClientTest.java index 73ac3b44b2..c99e91b94c 100644 --- a/akka-cluster-tools/src/test/java/akka/cluster/client/ClusterClientTest.java +++ b/akka-cluster-tools/src/test/java/akka/cluster/client/ClusterClientTest.java @@ -19,52 +19,56 @@ public class ClusterClientTest extends JUnitSuite { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("DistributedPubSubMediatorTest", - ConfigFactory.parseString( - "akka.actor.provider = \"cluster\"\n" + - "akka.remote.netty.tcp.port=0\n" + - "akka.remote.artery.canonical.port=0")); + new AkkaJUnitActorSystemResource( + "DistributedPubSubMediatorTest", + ConfigFactory.parseString( + "akka.actor.provider = \"cluster\"\n" + + "akka.remote.netty.tcp.port=0\n" + + "akka.remote.artery.canonical.port=0")); private final ActorSystem system = actorSystemResource.getSystem(); - //#initialContacts + // #initialContacts Set initialContacts() { - return new HashSet(Arrays.asList( - ActorPaths.fromString("akka.tcp://OtherSys@host1:2552/system/receptionist"), - ActorPaths.fromString("akka.tcp://OtherSys@host2:2552/system/receptionist"))); + return new HashSet( + Arrays.asList( + ActorPaths.fromString("akka.tcp://OtherSys@host1:2552/system/receptionist"), + ActorPaths.fromString("akka.tcp://OtherSys@host2:2552/system/receptionist"))); } - //#initialContacts - + // #initialContacts @Test public void demonstrateUsage() { - //#server + // #server ActorRef serviceA = system.actorOf(Props.create(Service.class), "serviceA"); ClusterClientReceptionist.get(system).registerService(serviceA); ActorRef serviceB = system.actorOf(Props.create(Service.class), "serviceB"); ClusterClientReceptionist.get(system).registerService(serviceB); - //#server + // #server - //#client - final ActorRef c = system.actorOf(ClusterClient.props( - ClusterClientSettings.create(system).withInitialContacts(initialContacts())), - "client"); + // #client + final ActorRef c = + system.actorOf( + ClusterClient.props( + ClusterClientSettings.create(system).withInitialContacts(initialContacts())), + "client"); c.tell(new ClusterClient.Send("/user/serviceA", "hello", true), ActorRef.noSender()); c.tell(new ClusterClient.SendToAll("/user/serviceB", "hi"), ActorRef.noSender()); - //#client + // #client system.actorOf(Props.create(ClientListener.class, c)); - system.actorOf(Props.create(ReceptionistListener.class, ClusterClientReceptionist.get(system).underlying())); + system.actorOf( + Props.create( + ReceptionistListener.class, ClusterClientReceptionist.get(system).underlying())); } - static public class Service extends UntypedAbstractActor { - public void onReceive(Object msg) { - } + public static class Service extends UntypedAbstractActor { + public void onReceive(Object msg) {} } - //#clientEventsListener - static public class ClientListener extends AbstractActor { + // #clientEventsListener + public static class ClientListener extends AbstractActor { private final ActorRef targetClient; private final Set contactPoints = new HashSet<>(); @@ -80,26 +84,31 @@ public class ClusterClientTest extends JUnitSuite { @Override public Receive createReceive() { return receiveBuilder() - .match(ContactPoints.class, msg -> { - contactPoints.addAll(msg.getContactPoints()); - // Now do something with an up-to-date "contactPoints" - }) - .match(ContactPointAdded.class, msg -> { - contactPoints.add(msg.contactPoint()); - // Now do something with an up-to-date "contactPoints" - }) - .match(ContactPointRemoved.class, msg -> { - contactPoints.remove(msg.contactPoint()); - // Now do something with an up-to-date "contactPoints" - }) - .build(); + .match( + ContactPoints.class, + msg -> { + contactPoints.addAll(msg.getContactPoints()); + // Now do something with an up-to-date "contactPoints" + }) + .match( + ContactPointAdded.class, + msg -> { + contactPoints.add(msg.contactPoint()); + // Now do something with an up-to-date "contactPoints" + }) + .match( + ContactPointRemoved.class, + msg -> { + contactPoints.remove(msg.contactPoint()); + // Now do something with an up-to-date "contactPoints" + }) + .build(); } - } - //#clientEventsListener + // #clientEventsListener - //#receptionistEventsListener - static public class ReceptionistListener extends AbstractActor { + // #receptionistEventsListener + public static class ReceptionistListener extends AbstractActor { private final ActorRef targetReceptionist; private final Set clusterClients = new HashSet<>(); @@ -115,22 +124,27 @@ public class ClusterClientTest extends JUnitSuite { @Override public Receive createReceive() { return receiveBuilder() - .match(ClusterClients.class, msg -> { - clusterClients.addAll(msg.getClusterClients()); - // Now do something with an up-to-date "clusterClients" - }) - .match(ClusterClientUp.class, msg -> { - clusterClients.add(msg.clusterClient()); - // Now do something with an up-to-date "clusterClients" - }) - .match(ClusterClientUnreachable.class, msg -> { - clusterClients.remove(msg.clusterClient()); - // Now do something with an up-to-date "clusterClients" - }) - .build(); + .match( + ClusterClients.class, + msg -> { + clusterClients.addAll(msg.getClusterClients()); + // Now do something with an up-to-date "clusterClients" + }) + .match( + ClusterClientUp.class, + msg -> { + clusterClients.add(msg.clusterClient()); + // Now do something with an up-to-date "clusterClients" + }) + .match( + ClusterClientUnreachable.class, + msg -> { + clusterClients.remove(msg.clusterClient()); + // Now do something with an up-to-date "clusterClients" + }) + .build(); } - } - //#receptionistEventsListener + // #receptionistEventsListener } diff --git a/akka-cluster-tools/src/test/java/akka/cluster/pubsub/DistributedPubSubMediatorTest.java b/akka-cluster-tools/src/test/java/akka/cluster/pubsub/DistributedPubSubMediatorTest.java index 63f9b8b206..c93bf686b5 100644 --- a/akka-cluster-tools/src/test/java/akka/cluster/pubsub/DistributedPubSubMediatorTest.java +++ b/akka-cluster-tools/src/test/java/akka/cluster/pubsub/DistributedPubSubMediatorTest.java @@ -23,135 +23,126 @@ public class DistributedPubSubMediatorTest extends JUnitSuite { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("DistributedPubSubMediatorTest", - ConfigFactory.parseString( - "akka.actor.provider = \"cluster\"\n" + - "akka.remote.netty.tcp.port=0\n" + - "akka.remote.artery.canonical.port=0")); + new AkkaJUnitActorSystemResource( + "DistributedPubSubMediatorTest", + ConfigFactory.parseString( + "akka.actor.provider = \"cluster\"\n" + + "akka.remote.netty.tcp.port=0\n" + + "akka.remote.artery.canonical.port=0")); private final ActorSystem system = actorSystemResource.getSystem(); - @Test public void demonstratePublishUsage() { - //#start-subscribers + // #start-subscribers system.actorOf(Props.create(Subscriber.class), "subscriber1"); - //another node + // another node system.actorOf(Props.create(Subscriber.class), "subscriber2"); system.actorOf(Props.create(Subscriber.class), "subscriber3"); - //#start-subscribers + // #start-subscribers - //#publish-message - //somewhere else + // #publish-message + // somewhere else ActorRef publisher = system.actorOf(Props.create(Publisher.class), "publisher"); // after a while the subscriptions are replicated publisher.tell("hello", null); - //#publish-message + // #publish-message } public void demonstrateSendUsage() { - //#start-send-destinations + // #start-send-destinations system.actorOf(Props.create(Destination.class), "destination"); - //another node + // another node system.actorOf(Props.create(Destination.class), "destination"); - //#start-send-destinations + // #start-send-destinations - //#send-message - //somewhere else + // #send-message + // somewhere else ActorRef sender = system.actorOf(Props.create(Publisher.class), "sender"); // after a while the destinations are replicated sender.tell("hello", null); - //#send-message + // #send-message } - static//#subscriber - public class Subscriber extends AbstractActor { + public // #subscriber + static class Subscriber extends AbstractActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public Subscriber() { - ActorRef mediator = - DistributedPubSub.get(getContext().system()).mediator(); + ActorRef mediator = DistributedPubSub.get(getContext().system()).mediator(); // subscribe to the topic named "content" - mediator.tell(new DistributedPubSubMediator.Subscribe("content", getSelf()), - getSelf()); + mediator.tell(new DistributedPubSubMediator.Subscribe("content", getSelf()), getSelf()); } @Override public Receive createReceive() { return receiveBuilder() - .match(String.class, msg -> - log.info("Got: {}", msg)) - .match(DistributedPubSubMediator.SubscribeAck.class, msg -> - log.info("subscribed")) - .build(); + .match(String.class, msg -> log.info("Got: {}", msg)) + .match(DistributedPubSubMediator.SubscribeAck.class, msg -> log.info("subscribed")) + .build(); } } - //#subscriber + // #subscriber - static//#publisher - public class Publisher extends AbstractActor { + public // #publisher + static class Publisher extends AbstractActor { // activate the extension - ActorRef mediator = - DistributedPubSub.get(getContext().system()).mediator(); + ActorRef mediator = DistributedPubSub.get(getContext().system()).mediator(); @Override - public Receive createReceive() { - return receiveBuilder() - .match(String.class, in -> { - String out = in.toUpperCase(); - mediator.tell(new DistributedPubSubMediator.Publish("content", out), - getSelf()); - }) + public Receive createReceive() { + return receiveBuilder() + .match( + String.class, + in -> { + String out = in.toUpperCase(); + mediator.tell(new DistributedPubSubMediator.Publish("content", out), getSelf()); + }) .build(); - } - + } } - //#publisher + // #publisher - static//#send-destination - public class Destination extends AbstractActor { + public // #send-destination + static class Destination extends AbstractActor { LoggingAdapter log = Logging.getLogger(getContext().system(), this); public Destination() { - ActorRef mediator = - DistributedPubSub.get(getContext().system()).mediator(); + ActorRef mediator = DistributedPubSub.get(getContext().system()).mediator(); // register to the path mediator.tell(new DistributedPubSubMediator.Put(getSelf()), getSelf()); } @Override public Receive createReceive() { - return receiveBuilder() - .match(String.class, msg -> - log.info("Got: {}", msg)) - .build(); + return receiveBuilder().match(String.class, msg -> log.info("Got: {}", msg)).build(); } - } - //#send-destination + // #send-destination - static//#sender - public class Sender extends AbstractActor { + public // #sender + static class Sender extends AbstractActor { // activate the extension - ActorRef mediator = - DistributedPubSub.get(getContext().system()).mediator(); + ActorRef mediator = DistributedPubSub.get(getContext().system()).mediator(); @Override public Receive createReceive() { return receiveBuilder() - .match(String.class, in -> { - String out = in.toUpperCase(); - boolean localAffinity = true; - mediator.tell(new DistributedPubSubMediator.Send("/user/destination", out, - localAffinity), getSelf()); - }) - .build(); + .match( + String.class, + in -> { + String out = in.toUpperCase(); + boolean localAffinity = true; + mediator.tell( + new DistributedPubSubMediator.Send("/user/destination", out, localAffinity), + getSelf()); + }) + .build(); } - } - //#sender + // #sender } diff --git a/akka-cluster-tools/src/test/java/akka/cluster/singleton/ClusterSingletonManagerTest.java b/akka-cluster-tools/src/test/java/akka/cluster/singleton/ClusterSingletonManagerTest.java index 55b399881d..532efd0665 100644 --- a/akka-cluster-tools/src/test/java/akka/cluster/singleton/ClusterSingletonManagerTest.java +++ b/akka-cluster-tools/src/test/java/akka/cluster/singleton/ClusterSingletonManagerTest.java @@ -20,33 +20,36 @@ public class ClusterSingletonManagerTest { final ActorRef queue = null; final ActorRef testActor = null; - //#create-singleton-manager + // #create-singleton-manager final ClusterSingletonManagerSettings settings = - ClusterSingletonManagerSettings.create(system).withRole("worker"); + ClusterSingletonManagerSettings.create(system).withRole("worker"); system.actorOf( - ClusterSingletonManager.props( - Props.create(Consumer.class, () -> new Consumer(queue, testActor)), - TestSingletonMessages.end(), - settings), - "consumer"); - //#create-singleton-manager + ClusterSingletonManager.props( + Props.create(Consumer.class, () -> new Consumer(queue, testActor)), + TestSingletonMessages.end(), + settings), + "consumer"); + // #create-singleton-manager - //#create-singleton-proxy + // #create-singleton-proxy ClusterSingletonProxySettings proxySettings = ClusterSingletonProxySettings.create(system).withRole("worker"); ActorRef proxy = - system.actorOf(ClusterSingletonProxy.props("/user/consumer", proxySettings), - "consumerProxy"); - //#create-singleton-proxy + system.actorOf( + ClusterSingletonProxy.props("/user/consumer", proxySettings), "consumerProxy"); + // #create-singleton-proxy - //#create-singleton-proxy-dc + // #create-singleton-proxy-dc ActorRef proxyDcB = - system.actorOf(ClusterSingletonProxy.props("/user/consumer", - ClusterSingletonProxySettings.create(system) - .withRole("worker") - .withDataCenter("B")), "consumerProxyDcB"); - //#create-singleton-proxy-dc + system.actorOf( + ClusterSingletonProxy.props( + "/user/consumer", + ClusterSingletonProxySettings.create(system) + .withRole("worker") + .withDataCenter("B")), + "consumerProxyDcB"); + // #create-singleton-proxy-dc } } diff --git a/akka-cluster-tools/src/test/java/akka/cluster/singleton/Consumer.java b/akka-cluster-tools/src/test/java/akka/cluster/singleton/Consumer.java index 5e480eb717..dfc7f4456e 100644 --- a/akka-cluster-tools/src/test/java/akka/cluster/singleton/Consumer.java +++ b/akka-cluster-tools/src/test/java/akka/cluster/singleton/Consumer.java @@ -16,8 +16,8 @@ public class Consumer extends AbstractActor { ActorRef queue; ActorRef delegateTo; - int current = 0; - boolean stoppedBeforeUnregistration = true; + int current = 0; + boolean stoppedBeforeUnregistration = true; public Consumer(ActorRef _queue, ActorRef _delegateTo) { queue = _queue; @@ -31,43 +31,34 @@ public class Consumer extends AbstractActor { @Override public void postStop() { - if (stoppedBeforeUnregistration) - log.warning("Stopped before unregistration"); + if (stoppedBeforeUnregistration) log.warning("Stopped before unregistration"); } @Override public Receive createReceive() { return receiveBuilder() - .match(Integer.class, n -> { - if(n <= current) - getContext().stop(self()); - else { - current = n; - delegateTo.tell(n, getSelf()); - } - }) - .match(RegistrationOk.class, message -> - delegateTo.tell(message, getSelf()) - ) - .match(UnexpectedRegistration.class, message -> - delegateTo.tell(message, getSelf()) - ) - .match(GetCurrent.class, message -> - getSender().tell(current, getSelf()) - ) - //#consumer-end - .match(End.class, message -> - queue.tell(UnregisterConsumer.class, getSelf()) - ) - .match(UnregistrationOk.class, message -> { - stoppedBeforeUnregistration = false; - getContext().stop(getSelf()); - } - ) - .match(Ping.class, message -> - getSender().tell(TestSingletonMessages.pong(), getSelf()) - ) - //#consumer-end - .build(); + .match( + Integer.class, + n -> { + if (n <= current) getContext().stop(self()); + else { + current = n; + delegateTo.tell(n, getSelf()); + } + }) + .match(RegistrationOk.class, message -> delegateTo.tell(message, getSelf())) + .match(UnexpectedRegistration.class, message -> delegateTo.tell(message, getSelf())) + .match(GetCurrent.class, message -> getSender().tell(current, getSelf())) + // #consumer-end + .match(End.class, message -> queue.tell(UnregisterConsumer.class, getSelf())) + .match( + UnregistrationOk.class, + message -> { + stoppedBeforeUnregistration = false; + getContext().stop(getSelf()); + }) + .match(Ping.class, message -> getSender().tell(TestSingletonMessages.pong(), getSelf())) + // #consumer-end + .build(); } } diff --git a/akka-cluster-tools/src/test/java/akka/cluster/singleton/TestSingletonMessages.java b/akka-cluster-tools/src/test/java/akka/cluster/singleton/TestSingletonMessages.java index 6003b81dbf..6e5091ee41 100644 --- a/akka-cluster-tools/src/test/java/akka/cluster/singleton/TestSingletonMessages.java +++ b/akka-cluster-tools/src/test/java/akka/cluster/singleton/TestSingletonMessages.java @@ -4,37 +4,80 @@ package akka.cluster.singleton; -//#singleton-message-classes +// #singleton-message-classes public class TestSingletonMessages { - public static class UnregistrationOk{} - public static class End{} - public static class Ping{} - public static class Pong{} - public static class GetCurrent{} + public static class UnregistrationOk {} - //#singleton-message-classes - public static class RegisterConsumer{} - public static class UnregisterConsumer{} - public static class RegistrationOk{} - public static class UnexpectedRegistration{} - public static class UnexpectedUnregistration{} - public static class Reset{} - public static class ResetOk{} + public static class End {} - public static RegisterConsumer registerConsumer() { return new RegisterConsumer(); } - public static UnregisterConsumer unregisterConsumer() { return new UnregisterConsumer(); } - public static RegistrationOk registrationOk() { return new RegistrationOk(); } - public static UnexpectedRegistration unexpectedRegistration() { return new UnexpectedRegistration(); } - public static UnexpectedUnregistration unexpectedUnregistration() { return new UnexpectedUnregistration(); } - public static Reset reset() { return new Reset(); } - public static ResetOk resetOk() { return new ResetOk(); } + public static class Ping {} - //#singleton-message-classes - public static UnregistrationOk unregistrationOk() { return new UnregistrationOk(); } - public static End end() { return new End(); } - public static Ping ping() { return new Ping(); } - public static Pong pong() { return new Pong(); } - public static GetCurrent getCurrent() { return new GetCurrent(); } + public static class Pong {} + + public static class GetCurrent {} + + // #singleton-message-classes + public static class RegisterConsumer {} + + public static class UnregisterConsumer {} + + public static class RegistrationOk {} + + public static class UnexpectedRegistration {} + + public static class UnexpectedUnregistration {} + + public static class Reset {} + + public static class ResetOk {} + + public static RegisterConsumer registerConsumer() { + return new RegisterConsumer(); + } + + public static UnregisterConsumer unregisterConsumer() { + return new UnregisterConsumer(); + } + + public static RegistrationOk registrationOk() { + return new RegistrationOk(); + } + + public static UnexpectedRegistration unexpectedRegistration() { + return new UnexpectedRegistration(); + } + + public static UnexpectedUnregistration unexpectedUnregistration() { + return new UnexpectedUnregistration(); + } + + public static Reset reset() { + return new Reset(); + } + + public static ResetOk resetOk() { + return new ResetOk(); + } + + // #singleton-message-classes + public static UnregistrationOk unregistrationOk() { + return new UnregistrationOk(); + } + + public static End end() { + return new End(); + } + + public static Ping ping() { + return new Ping(); + } + + public static Pong pong() { + return new Pong(); + } + + public static GetCurrent getCurrent() { + return new GetCurrent(); + } } -//#singleton-message-classes - +// #singleton-message-classes diff --git a/akka-cluster-typed/src/test/java/akka/cluster/ddata/typed/javadsl/ReplicatorTest.java b/akka-cluster-typed/src/test/java/akka/cluster/ddata/typed/javadsl/ReplicatorTest.java index b0ae2522ac..58c24b8913 100644 --- a/akka-cluster-typed/src/test/java/akka/cluster/ddata/typed/javadsl/ReplicatorTest.java +++ b/akka-cluster-typed/src/test/java/akka/cluster/ddata/typed/javadsl/ReplicatorTest.java @@ -30,7 +30,7 @@ import akka.actor.typed.javadsl.Receive; public class ReplicatorTest extends JUnitSuite { // #sample - interface ClientCommand { } + interface ClientCommand {} enum Increment implements ClientCommand { INSTANCE @@ -52,7 +52,7 @@ public class ReplicatorTest extends JUnitSuite { } } - private interface InternalMsg extends ClientCommand { } + private interface InternalMsg extends ClientCommand {} private static final class InternalUpdateResponse implements InternalMsg { final Replicator.UpdateResponse rsp; @@ -95,33 +95,39 @@ public class ReplicatorTest extends JUnitSuite { // adapters turning the messages from the replicator // into our own protocol - updateResponseAdapter = ctx.messageAdapter( - (Class>) (Object) Replicator.UpdateResponse.class, - msg -> new InternalUpdateResponse(msg)); + updateResponseAdapter = + ctx.messageAdapter( + (Class>) (Object) Replicator.UpdateResponse.class, + msg -> new InternalUpdateResponse(msg)); - getResponseAdapter = ctx.messageAdapter( - (Class>) (Object) Replicator.GetResponse.class, - msg -> new InternalGetResponse(msg)); + getResponseAdapter = + ctx.messageAdapter( + (Class>) (Object) Replicator.GetResponse.class, + msg -> new InternalGetResponse(msg)); - changedAdapter = ctx.messageAdapter( - (Class>) (Object) Replicator.Changed.class, - msg -> new InternalChanged(msg)); + changedAdapter = + ctx.messageAdapter( + (Class>) (Object) Replicator.Changed.class, + msg -> new InternalChanged(msg)); replicator.tell(new Replicator.Subscribe<>(Key, changedAdapter)); } public static Behavior create() { - return Behaviors.setup((ctx) -> { - SelfUniqueAddress node = DistributedData.get(ctx.getSystem()).selfUniqueAddress(); - ActorRef replicator = DistributedData.get(ctx.getSystem()).replicator(); + return Behaviors.setup( + (ctx) -> { + SelfUniqueAddress node = DistributedData.get(ctx.getSystem()).selfUniqueAddress(); + ActorRef replicator = + DistributedData.get(ctx.getSystem()).replicator(); - return new Counter(replicator, node, ctx); - }); + return new Counter(replicator, node, ctx); + }); } // #sample // omitted from sample, needed for tests, factory above is for the docs sample - public static Behavior create(ActorRef replicator, SelfUniqueAddress node) { + public static Behavior create( + ActorRef replicator, SelfUniqueAddress node) { return Behaviors.setup(ctx -> new Counter(replicator, node, ctx)); } // #sample @@ -129,29 +135,30 @@ public class ReplicatorTest extends JUnitSuite { @Override public Receive createReceive() { return receiveBuilder() - .onMessage(Increment.class, this::onIncrement) - .onMessage(InternalUpdateResponse.class, msg -> Behaviors.same()) - .onMessage(GetValue.class, this::onGetValue) - .onMessage(GetCachedValue.class, this::onGetCachedValue) - .onMessage(InternalGetResponse.class, this::onInternalGetResponse) - .onMessage(InternalChanged.class, this::onInternalChanged) - .build(); + .onMessage(Increment.class, this::onIncrement) + .onMessage(InternalUpdateResponse.class, msg -> Behaviors.same()) + .onMessage(GetValue.class, this::onGetValue) + .onMessage(GetCachedValue.class, this::onGetCachedValue) + .onMessage(InternalGetResponse.class, this::onInternalGetResponse) + .onMessage(InternalChanged.class, this::onInternalChanged) + .build(); } private Behavior onIncrement(Increment cmd) { replicator.tell( - new Replicator.Update<>( - Key, - GCounter.empty(), - Replicator.writeLocal(), - updateResponseAdapter, - curr -> curr.increment(node, 1))); + new Replicator.Update<>( + Key, + GCounter.empty(), + Replicator.writeLocal(), + updateResponseAdapter, + curr -> curr.increment(node, 1))); return Behaviors.same(); } private Behavior onGetValue(GetValue cmd) { replicator.tell( - new Replicator.Get<>(Key, Replicator.readLocal(), getResponseAdapter, Optional.of(cmd.replyTo))); + new Replicator.Get<>( + Key, Replicator.readLocal(), getResponseAdapter, Optional.of(cmd.replyTo))); return Behaviors.same(); } @@ -177,21 +184,20 @@ public class ReplicatorTest extends JUnitSuite { cachedValue = counter.getValue().intValue(); return this; } + } -} + // #sample -// #sample - - - static Config config = ConfigFactory.parseString( - "akka.actor.provider = cluster \n" + - "akka.remote.netty.tcp.port = 0 \n" + - "akka.remote.artery.canonical.port = 0 \n" + - "akka.remote.artery.canonical.hostname = 127.0.0.1 \n"); + static Config config = + ConfigFactory.parseString( + "akka.actor.provider = cluster \n" + + "akka.remote.netty.tcp.port = 0 \n" + + "akka.remote.artery.canonical.port = 0 \n" + + "akka.remote.artery.canonical.hostname = 127.0.0.1 \n"); @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("ReplicatorTest", - config); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("ReplicatorTest", config); private final akka.actor.ActorSystem system = actorSystemResource.getSystem(); @@ -199,7 +205,6 @@ public class ReplicatorTest extends JUnitSuite { return Adapter.toTyped(system); } - @Test public void shouldHaveApiForUpdateAndGet() { TestKit probe = new TestKit(system); @@ -207,7 +212,9 @@ public class ReplicatorTest extends JUnitSuite { ActorRef replicator = Adapter.spawnAnonymous(system, Replicator.behavior(settings)); ActorRef client = - Adapter.spawnAnonymous(system, Counter.create(replicator, DistributedData.get(typedSystem()).selfUniqueAddress())); + Adapter.spawnAnonymous( + system, + Counter.create(replicator, DistributedData.get(typedSystem()).selfUniqueAddress())); client.tell(Increment.INSTANCE); client.tell(new GetValue(Adapter.toTyped(probe.getRef()))); @@ -221,22 +228,25 @@ public class ReplicatorTest extends JUnitSuite { ActorRef replicator = Adapter.spawnAnonymous(system, Replicator.behavior(settings)); ActorRef client = - Adapter.spawnAnonymous(system, Counter.create(replicator, DistributedData.get(typedSystem()).selfUniqueAddress())); + Adapter.spawnAnonymous( + system, + Counter.create(replicator, DistributedData.get(typedSystem()).selfUniqueAddress())); client.tell(Increment.INSTANCE); client.tell(Increment.INSTANCE); - probe.awaitAssert(() -> { - client.tell(new GetCachedValue(Adapter.toTyped(probe.getRef()))); - probe.expectMsg(2); - return null; - }); + probe.awaitAssert( + () -> { + client.tell(new GetCachedValue(Adapter.toTyped(probe.getRef()))); + probe.expectMsg(2); + return null; + }); client.tell(Increment.INSTANCE); - probe.awaitAssert(() -> { - client.tell(new GetCachedValue(Adapter.toTyped(probe.getRef()))); - probe.expectMsg(3); - return null; - }); + probe.awaitAssert( + () -> { + client.tell(new GetCachedValue(Adapter.toTyped(probe.getRef()))); + probe.expectMsg(3); + return null; + }); } - } diff --git a/akka-cluster-typed/src/test/java/akka/cluster/typed/ClusterApiTest.java b/akka-cluster-typed/src/test/java/akka/cluster/typed/ClusterApiTest.java index 61cff29da5..88d0be86cf 100644 --- a/akka-cluster-typed/src/test/java/akka/cluster/typed/ClusterApiTest.java +++ b/akka-cluster-typed/src/test/java/akka/cluster/typed/ClusterApiTest.java @@ -18,21 +18,23 @@ public class ClusterApiTest extends JUnitSuite { @Test public void joinLeaveAndObserve() throws Exception { - Config config = ConfigFactory.parseString( - "akka.actor.provider = cluster \n" + - "akka.remote.netty.tcp.port = 0 \n"+ - "akka.remote.artery.canonical.port = 0 \n"+ - "akka.remote.artery.canonical.hostname = 127.0.0.1 \n" + - "akka.cluster.jmx.multi-mbeans-in-same-jvm = on \n"+ - "akka.coordinated-shutdown.terminate-actor-system = off \n"+ - "akka.actor { \n"+ - " serialize-messages = off \n"+ - " allow-java-serialization = off \n"+ - "}" - ); + Config config = + ConfigFactory.parseString( + "akka.actor.provider = cluster \n" + + "akka.remote.netty.tcp.port = 0 \n" + + "akka.remote.artery.canonical.port = 0 \n" + + "akka.remote.artery.canonical.hostname = 127.0.0.1 \n" + + "akka.cluster.jmx.multi-mbeans-in-same-jvm = on \n" + + "akka.coordinated-shutdown.terminate-actor-system = off \n" + + "akka.actor { \n" + + " serialize-messages = off \n" + + " allow-java-serialization = off \n" + + "}"); - ActorSystem system1 = ActorSystem.wrap(akka.actor.ActorSystem.create("ClusterApiTest", config)); - ActorSystem system2 = ActorSystem.wrap(akka.actor.ActorSystem.create("ClusterApiTest", config)); + ActorSystem system1 = + ActorSystem.wrap(akka.actor.ActorSystem.create("ClusterApiTest", config)); + ActorSystem system2 = + ActorSystem.wrap(akka.actor.ActorSystem.create("ClusterApiTest", config)); try { Cluster cluster1 = Cluster.get(system1); @@ -49,7 +51,6 @@ public class ClusterApiTest extends JUnitSuite { cluster2.manager().tell(new Join(cluster1.selfMember().address())); probe2.expectMessageClass(SelfUp.class); - cluster2.subscriptions().tell(new Subscribe<>(probe2.ref().narrow(), SelfRemoved.class)); cluster2.manager().tell(new Leave(cluster2.selfMember().address())); @@ -58,7 +59,5 @@ public class ClusterApiTest extends JUnitSuite { // TODO no java API to terminate actor system Await.result(system1.terminate().zip(system2.terminate()), Duration.create("5 seconds")); } - } - } diff --git a/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/BasicClusterExampleTest.java b/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/BasicClusterExampleTest.java index e2e9a6b868..f8f38eadf6 100644 --- a/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/BasicClusterExampleTest.java +++ b/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/BasicClusterExampleTest.java @@ -4,58 +4,61 @@ package jdocs.akka.cluster.typed; -//#cluster-imports +// #cluster-imports import akka.actor.typed.*; import akka.actor.typed.javadsl.*; import akka.cluster.ClusterEvent; import akka.cluster.typed.*; -//#cluster-imports +// #cluster-imports import akka.actor.testkit.typed.javadsl.TestProbe; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; -// FIXME these tests are awaiting typed Java testkit to be able to await cluster forming like in BasicClusterExampleSpec +// FIXME these tests are awaiting typed Java testkit to be able to await cluster forming like in +// BasicClusterExampleSpec public class BasicClusterExampleTest { // extends JUnitSuite { - private Config clusterConfig = ConfigFactory.parseString( - "akka { \n" + - " actor.provider = cluster \n" + - " remote { \n" + - " netty.tcp { \n" + - " hostname = \"127.0.0.1\" \n" + - " port = 2551 \n" + - " } \n" + - " } \n" + - "} \n"); + private Config clusterConfig = + ConfigFactory.parseString( + "akka { \n" + + " actor.provider = cluster \n" + + " remote { \n" + + " netty.tcp { \n" + + " hostname = \"127.0.0.1\" \n" + + " port = 2551 \n" + + " } \n" + + " } \n" + + "} \n"); - private Config noPort = ConfigFactory.parseString( - " akka.remote.netty.tcp.port = 0 \n" + - " akka.remote.artery.canonical.port = 0 \n"); + private Config noPort = + ConfigFactory.parseString( + " akka.remote.netty.tcp.port = 0 \n" + + " akka.remote.artery.canonical.port = 0 \n"); // @Test public void clusterApiExample() { - ActorSystem system = ActorSystem.create(Behaviors.empty(), "ClusterSystem", - noPort.withFallback(clusterConfig)); - ActorSystem system2 = ActorSystem.create(Behaviors.empty(), "ClusterSystem", - noPort.withFallback(clusterConfig)); + ActorSystem system = + ActorSystem.create(Behaviors.empty(), "ClusterSystem", noPort.withFallback(clusterConfig)); + ActorSystem system2 = + ActorSystem.create(Behaviors.empty(), "ClusterSystem", noPort.withFallback(clusterConfig)); try { - //#cluster-create + // #cluster-create Cluster cluster = Cluster.get(system); - //#cluster-create + // #cluster-create Cluster cluster2 = Cluster.get(system2); - //#cluster-join + // #cluster-join cluster.manager().tell(Join.create(cluster.selfMember().address())); - //#cluster-join + // #cluster-join cluster2.manager().tell(Join.create(cluster.selfMember().address())); // TODO wait for/verify cluster to form - //#cluster-leave + // #cluster-leave cluster2.manager().tell(Leave.create(cluster2.selfMember().address())); - //#cluster-leave + // #cluster-leave // TODO wait for/verify node 2 leaving @@ -67,26 +70,28 @@ public class BasicClusterExampleTest { // extends JUnitSuite { // @Test public void clusterLeave() throws Exception { - ActorSystem system = ActorSystem.create(Behaviors.empty(), "ClusterSystem", - noPort.withFallback(clusterConfig)); - ActorSystem system2 = ActorSystem.create(Behaviors.empty(), "ClusterSystem", - noPort.withFallback(clusterConfig)); + ActorSystem system = + ActorSystem.create(Behaviors.empty(), "ClusterSystem", noPort.withFallback(clusterConfig)); + ActorSystem system2 = + ActorSystem.create(Behaviors.empty(), "ClusterSystem", noPort.withFallback(clusterConfig)); try { Cluster cluster = Cluster.get(system); Cluster cluster2 = Cluster.get(system2); - //#cluster-subscribe + // #cluster-subscribe TestProbe testProbe = TestProbe.create(system); - cluster.subscriptions().tell(Subscribe.create(testProbe.ref(), ClusterEvent.MemberEvent.class)); - //#cluster-subscribe + cluster + .subscriptions() + .tell(Subscribe.create(testProbe.ref(), ClusterEvent.MemberEvent.class)); + // #cluster-subscribe - //#cluster-leave-example + // #cluster-leave-example cluster.manager().tell(Leave.create(cluster2.selfMember().address())); testProbe.expectMessageClass(ClusterEvent.MemberLeft.class); testProbe.expectMessageClass(ClusterEvent.MemberExited.class); testProbe.expectMessageClass(ClusterEvent.MemberRemoved.class); - //#cluster-leave-example + // #cluster-leave-example } finally { system.terminate(); diff --git a/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/PingSerializerExampleTest.java b/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/PingSerializerExampleTest.java index 9102a95277..464608fa33 100644 --- a/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/PingSerializerExampleTest.java +++ b/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/PingSerializerExampleTest.java @@ -25,7 +25,7 @@ public class PingSerializerExampleTest { } } - //#serializer + // #serializer public class PingSerializer extends SerializerWithStringManifest { final ExtendedActorSystem system; @@ -46,22 +46,19 @@ public class PingSerializerExampleTest { @Override public String manifest(Object obj) { - if (obj instanceof Ping) - return PING_MANIFEST; - else if (obj instanceof Pong) - return PONG_MANIFEST; - else - throw new IllegalArgumentException("Unknown type: " + obj); + if (obj instanceof Ping) return PING_MANIFEST; + else if (obj instanceof Pong) return PONG_MANIFEST; + else throw new IllegalArgumentException("Unknown type: " + obj); } @Override public byte[] toBinary(Object obj) { if (obj instanceof Ping) - return actorRefResolver.toSerializationFormat(((Ping) obj).replyTo).getBytes(StandardCharsets.UTF_8); - else if (obj instanceof Pong) - return new byte[0]; - else - throw new IllegalArgumentException("Unknown type: " + obj); + return actorRefResolver + .toSerializationFormat(((Ping) obj).replyTo) + .getBytes(StandardCharsets.UTF_8); + else if (obj instanceof Pong) return new byte[0]; + else throw new IllegalArgumentException("Unknown type: " + obj); } @Override @@ -77,5 +74,5 @@ public class PingSerializerExampleTest { } } } - //#serializer + // #serializer } diff --git a/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/ReceptionistExampleTest.java b/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/ReceptionistExampleTest.java index 956edbfa07..ad42219bfb 100644 --- a/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/ReceptionistExampleTest.java +++ b/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/ReceptionistExampleTest.java @@ -37,25 +37,36 @@ public class ReceptionistExampleTest extends JUnitSuite { private final Class messageClass; private final ServiceKey serviceKey; private final List> routees = new ArrayList<>(); - public RouterBehavior(ActorContext ctx, Class messageClass, ServiceKey serviceKey) { + + public RouterBehavior( + ActorContext ctx, Class messageClass, ServiceKey serviceKey) { this.messageClass = messageClass; this.serviceKey = serviceKey; - ctx.getSystem().receptionist().tell(Receptionist.subscribe(serviceKey, ctx.getSelf().narrow())); + ctx.getSystem() + .receptionist() + .tell(Receptionist.subscribe(serviceKey, ctx.getSelf().narrow())); } @Override public Receive createReceive() { return receiveBuilder() - .onMessage(Receptionist.Listing.class, listing -> listing.isForKey(serviceKey), (listing) -> { - routees.clear(); - routees.addAll(listing.getServiceInstances(serviceKey)); - return this; - }).onMessage(messageClass, (msg) -> { - int i = ThreadLocalRandom.current().nextInt(routees.size()); - routees.get(i).tell(msg); - return this; - }).build(); + .onMessage( + Receptionist.Listing.class, + listing -> listing.isForKey(serviceKey), + (listing) -> { + routees.clear(); + routees.addAll(listing.getServiceInstances(serviceKey)); + return this; + }) + .onMessage( + messageClass, + (msg) -> { + int i = ThreadLocalRandom.current().nextInt(routees.size()); + routees.get(i).tell(msg); + return this; + }) + .build(); } } @@ -70,6 +81,7 @@ public class ReceptionistExampleTest extends JUnitSuite { private static class WrappedReachabilityEvent { final ClusterEvent.ReachabilityEvent event; + public WrappedReachabilityEvent(ClusterEvent.ReachabilityEvent event) { this.event = event; } @@ -82,10 +94,13 @@ public class ReceptionistExampleTest extends JUnitSuite { private final Set
unreachable = new HashSet<>(); private final List> reachable = new ArrayList<>(); - public ClusterRouterBehavior(ActorContext ctx, Class messageClass, ServiceKey serviceKey) { + public ClusterRouterBehavior( + ActorContext ctx, Class messageClass, ServiceKey serviceKey) { this.messageClass = messageClass; this.serviceKey = serviceKey; - ctx.getSystem().receptionist().tell(Receptionist.subscribe(serviceKey, ctx.getSelf().narrow())); + ctx.getSystem() + .receptionist() + .tell(Receptionist.subscribe(serviceKey, ctx.getSelf().narrow())); Cluster cluster = Cluster.get(ctx.getSystem()); // typically you have to map such external messages into this @@ -97,13 +112,17 @@ public class ReceptionistExampleTest extends JUnitSuite { (event) -> new WrappedReachabilityEvent(event)); cluster.subscriptions().tell(Subscribe.create(reachabilityAdapter, ClusterEvent.ReachabilityEvent.class)); */ - cluster.subscriptions().tell(Subscribe.create(ctx.getSelf().narrow(), ClusterEvent.UnreachableMember.class)); - cluster.subscriptions().tell(Subscribe.create(ctx.getSelf().narrow(), ClusterEvent.ReachableMember.class)); + cluster + .subscriptions() + .tell(Subscribe.create(ctx.getSelf().narrow(), ClusterEvent.UnreachableMember.class)); + cluster + .subscriptions() + .tell(Subscribe.create(ctx.getSelf().narrow(), ClusterEvent.ReachableMember.class)); } private void updateReachable() { reachable.clear(); - for (ActorRef routee: routees) { + for (ActorRef routee : routees) { if (!unreachable.contains(routee.path().address())) { reachable.add(routee); } @@ -113,93 +132,124 @@ public class ReceptionistExampleTest extends JUnitSuite { @Override public Receive createReceive() { return receiveBuilder() - .onMessage(Receptionist.Listing.class, listing -> listing.isForKey(serviceKey), listing -> { - routees.clear(); - routees.addAll(listing.getServiceInstances(serviceKey)); - updateReachable(); - return this; - }).onMessage(ClusterEvent.ReachableMember.class, reachableMember -> { - unreachable.remove(reachableMember.member().address()); - updateReachable(); - return this; - }).onMessage(ClusterEvent.UnreachableMember.class, unreachableMember -> { - unreachable.add(unreachableMember.member().address()); - updateReachable(); - return this; - }).onMessage(messageClass, msg -> { - int i = ThreadLocalRandom.current().nextInt(reachable.size()); - reachable.get(i).tell(msg); - return this; - }).build(); + .onMessage( + Receptionist.Listing.class, + listing -> listing.isForKey(serviceKey), + listing -> { + routees.clear(); + routees.addAll(listing.getServiceInstances(serviceKey)); + updateReachable(); + return this; + }) + .onMessage( + ClusterEvent.ReachableMember.class, + reachableMember -> { + unreachable.remove(reachableMember.member().address()); + updateReachable(); + return this; + }) + .onMessage( + ClusterEvent.UnreachableMember.class, + unreachableMember -> { + unreachable.add(unreachableMember.member().address()); + updateReachable(); + return this; + }) + .onMessage( + messageClass, + msg -> { + int i = ThreadLocalRandom.current().nextInt(reachable.size()); + reachable.get(i).tell(msg); + return this; + }) + .build(); } } public static Behavior clusterRouter(ServiceKey serviceKey, Class messageClass) { - return Behaviors.setup((ctx) -> new ClusterRouterBehavior(ctx, messageClass, serviceKey)).narrow(); + return Behaviors.setup((ctx) -> new ClusterRouterBehavior(ctx, messageClass, serviceKey)) + .narrow(); } } - public static class PingPongExample { - //#ping-service - static final ServiceKey PingServiceKey = - ServiceKey.create(Ping.class, "pingService"); + // #ping-service + static final ServiceKey PingServiceKey = ServiceKey.create(Ping.class, "pingService"); public static class Pong {} + public static class Ping { private final ActorRef replyTo; + Ping(ActorRef replyTo) { this.replyTo = replyTo; } } static Behavior pingService() { - return Behaviors.setup((ctx) -> { - ctx.getSystem().receptionist() - .tell(Receptionist.register(PingServiceKey, ctx.getSelf())); - return Behaviors.receive(Ping.class) - .onMessage(Ping.class, (c, msg) -> { - msg.replyTo.tell(new Pong()); - return Behaviors.same(); - }).build(); - }); + return Behaviors.setup( + (ctx) -> { + ctx.getSystem() + .receptionist() + .tell(Receptionist.register(PingServiceKey, ctx.getSelf())); + return Behaviors.receive(Ping.class) + .onMessage( + Ping.class, + (c, msg) -> { + msg.replyTo.tell(new Pong()); + return Behaviors.same(); + }) + .build(); + }); } - //#ping-service + // #ping-service - //#pinger + // #pinger static Behavior pinger(ActorRef pingService) { - return Behaviors.setup((ctx) -> { - pingService.tell(new Ping(ctx.getSelf())); - return Behaviors.receive(Pong.class) - .onMessage(Pong.class, (c, msg) -> { - System.out.println("I was ponged! " + msg); - return Behaviors.same(); - }).build(); - }); + return Behaviors.setup( + (ctx) -> { + pingService.tell(new Ping(ctx.getSelf())); + return Behaviors.receive(Pong.class) + .onMessage( + Pong.class, + (c, msg) -> { + System.out.println("I was ponged! " + msg); + return Behaviors.same(); + }) + .build(); + }); } - //#pinger + // #pinger - //#pinger-guardian + // #pinger-guardian static Behavior guardian() { - return Behaviors.setup((ctx) -> { - ctx.getSystem().receptionist() - .tell(Receptionist.subscribe(PingServiceKey, ctx.getSelf().narrow())); - ActorRef ps = ctx.spawnAnonymous(pingService()); - ctx.watch(ps); - return Behaviors.receive(Object.class) - .onMessage(Receptionist.Listing.class, listing -> listing.isForKey(PingServiceKey), (c, msg) -> { - msg.getServiceInstances(PingServiceKey).forEach(ar -> ctx.spawnAnonymous(pinger(ar))); - return Behaviors.same(); - }).build(); - }).narrow(); + return Behaviors.setup( + (ctx) -> { + ctx.getSystem() + .receptionist() + .tell(Receptionist.subscribe(PingServiceKey, ctx.getSelf().narrow())); + ActorRef ps = ctx.spawnAnonymous(pingService()); + ctx.watch(ps); + return Behaviors.receive(Object.class) + .onMessage( + Receptionist.Listing.class, + listing -> listing.isForKey(PingServiceKey), + (c, msg) -> { + msg.getServiceInstances(PingServiceKey) + .forEach(ar -> ctx.spawnAnonymous(pinger(ar))); + return Behaviors.same(); + }) + .build(); + }) + .narrow(); } - //#pinger-guardian + // #pinger-guardian } @Test public void workPlease() throws Exception { ActorSystem system = - ActorSystem.create(PingPongExample.guardian(), "ReceptionistExample"); + ActorSystem.create(PingPongExample.guardian(), "ReceptionistExample"); Await.ready(system.terminate(), Duration.create(2, TimeUnit.SECONDS)); } diff --git a/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/SingletonCompileOnlyTest.java b/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/SingletonCompileOnlyTest.java index 05a7aead19..f271fb5856 100644 --- a/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/SingletonCompileOnlyTest.java +++ b/akka-cluster-typed/src/test/java/jdocs/akka/cluster/typed/SingletonCompileOnlyTest.java @@ -7,83 +7,80 @@ package jdocs.akka.cluster.typed; import akka.actor.typed.*; import akka.actor.typed.javadsl.Behaviors; -//#import +// #import import akka.cluster.typed.*; import java.time.Duration; -//#import +// #import public class SingletonCompileOnlyTest { - //#counter - interface CounterCommand { + // #counter + interface CounterCommand {} + + public static class Increment implements CounterCommand {} + + public static class GoodByeCounter implements CounterCommand {} + + public static class GetValue implements CounterCommand { + private final ActorRef replyTo; + + public GetValue(ActorRef replyTo) { + this.replyTo = replyTo; } + } - public static class Increment implements CounterCommand { - } + public static Behavior counter(String entityId, Integer value) { + return Behaviors.receive(CounterCommand.class) + .onMessage(Increment.class, (ctx, msg) -> counter(entityId, value + 1)) + .onMessage( + GetValue.class, + (ctx, msg) -> { + msg.replyTo.tell(value); + return Behaviors.same(); + }) + .onMessage(GoodByeCounter.class, (ctx, msg) -> Behaviors.stopped()) + .build(); + } + // #counter - public static class GoodByeCounter implements CounterCommand { - } + ActorSystem system = ActorSystem.create(Behaviors.empty(), "SingletonExample"); - public static class GetValue implements CounterCommand { - private final ActorRef replyTo; + public void example() { - public GetValue(ActorRef replyTo) { - this.replyTo = replyTo; - } - } + // #singleton + ClusterSingleton singleton = ClusterSingleton.get(system); + // Start if needed and provide a proxy to a named singleton + ActorRef proxy = + singleton.init(SingletonActor.of(counter("TheCounter", 0), "GlobalCounter")); - public static Behavior counter(String entityId, Integer value) { - return Behaviors.receive(CounterCommand.class) - .onMessage(Increment.class, (ctx, msg) -> counter(entityId, value + 1)) - .onMessage(GetValue.class, (ctx, msg) -> { - msg.replyTo.tell(value); - return Behaviors.same(); - }) - .onMessage(GoodByeCounter.class, (ctx, msg) -> Behaviors.stopped()) - .build(); - } - //#counter + proxy.tell(new Increment()); + // #singleton - ActorSystem system = ActorSystem.create( - Behaviors.empty(), "SingletonExample" - ); + } - public void example() { - - - //#singleton - ClusterSingleton singleton = ClusterSingleton.get(system); - // Start if needed and provide a proxy to a named singleton - ActorRef proxy = singleton.init( - SingletonActor.of(counter("TheCounter", 0), "GlobalCounter") - ); - - proxy.tell(new Increment()); - //#singleton - - } - - public void customStopMessage() { - ClusterSingleton singleton = ClusterSingleton.get(system); - //#stop-message - SingletonActor counterSingleton = SingletonActor.of(counter("TheCounter", 0), "GlobalCounter") + public void customStopMessage() { + ClusterSingleton singleton = ClusterSingleton.get(system); + // #stop-message + SingletonActor counterSingleton = + SingletonActor.of(counter("TheCounter", 0), "GlobalCounter") .withStopMessage(new GoodByeCounter()); - ActorRef proxy = singleton.init( - counterSingleton - ); - //#stop-message - proxy.tell(new Increment()); // avoid unused warning - } + ActorRef proxy = singleton.init(counterSingleton); + // #stop-message + proxy.tell(new Increment()); // avoid unused warning + } - public void backoff() { - //#backoff - ClusterSingleton singleton = ClusterSingleton.get(system); - ActorRef proxy = singleton.init( - SingletonActor.of(Behaviors.supervise(counter("TheCounter", 0)) - .onFailure(SupervisorStrategy.restartWithBackoff(Duration.ofSeconds(1), Duration.ofSeconds(10), 0.2)), "GlobalCounter" - ) - ); - //#backoff - proxy.tell(new Increment()); // avoid unused warning - } + public void backoff() { + // #backoff + ClusterSingleton singleton = ClusterSingleton.get(system); + ActorRef proxy = + singleton.init( + SingletonActor.of( + Behaviors.supervise(counter("TheCounter", 0)) + .onFailure( + SupervisorStrategy.restartWithBackoff( + Duration.ofSeconds(1), Duration.ofSeconds(10), 0.2)), + "GlobalCounter")); + // #backoff + proxy.tell(new Increment()); // avoid unused warning + } } diff --git a/akka-cluster/src/test/java/akka/cluster/ClusterJavaCompileTest.java b/akka-cluster/src/test/java/akka/cluster/ClusterJavaCompileTest.java index 7b95aed2b5..899b6f2c60 100644 --- a/akka-cluster/src/test/java/akka/cluster/ClusterJavaCompileTest.java +++ b/akka-cluster/src/test/java/akka/cluster/ClusterJavaCompileTest.java @@ -17,10 +17,8 @@ public class ClusterJavaCompileTest { final ActorSystem system = null; final Cluster cluster = null; - public void compileJoinSeedNodesInJava() { final List
addresses = Collections.singletonList(new Address("akka.tcp", "MySystem")); cluster.joinSeedNodes(addresses); } - } diff --git a/akka-contrib/src/test/java/akka/contrib/pattern/ReliableProxyTest.java b/akka-contrib/src/test/java/akka/contrib/pattern/ReliableProxyTest.java index 6f1310c4e0..5cd10b689e 100644 --- a/akka-contrib/src/test/java/akka/contrib/pattern/ReliableProxyTest.java +++ b/akka-contrib/src/test/java/akka/contrib/pattern/ReliableProxyTest.java @@ -16,76 +16,85 @@ import org.scalatest.junit.JUnitSuite; import scala.concurrent.duration.Duration; import akka.testkit.TestProbe; -//#import +// #import import akka.contrib.pattern.ReliableProxy; - -//#import +// #import public class ReliableProxyTest extends JUnitSuite { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("ReliableProxyTest"); + new AkkaJUnitActorSystemResource("ReliableProxyTest"); private final ActorSystem system = actorSystemResource.getSystem(); - static//#demo-proxy - public class ProxyParent extends AbstractActor { + public // #demo-proxy + static class ProxyParent extends AbstractActor { private final ActorRef proxy; public ProxyParent(ActorPath targetPath) { - proxy = getContext().actorOf( - ReliableProxy.props(targetPath, - Duration.create(100, TimeUnit.MILLISECONDS))); + proxy = + getContext() + .actorOf( + ReliableProxy.props(targetPath, Duration.create(100, TimeUnit.MILLISECONDS))); } @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("hello", m -> { - proxy.tell("world!", self()); - }) - .build(); + .matchEquals( + "hello", + m -> { + proxy.tell("world!", self()); + }) + .build(); } } - //#demo-proxy + // #demo-proxy - static//#demo-transition - public class ProxyTransitionParent extends AbstractActor { + public // #demo-transition + static class ProxyTransitionParent extends AbstractActor { private final ActorRef proxy; private ActorRef client = null; public ProxyTransitionParent(ActorPath targetPath) { - proxy = getContext().actorOf( - ReliableProxy.props(targetPath, - Duration.create(100, TimeUnit.MILLISECONDS))); + proxy = + getContext() + .actorOf( + ReliableProxy.props(targetPath, Duration.create(100, TimeUnit.MILLISECONDS))); proxy.tell(new FSM.SubscribeTransitionCallBack(getSelf()), getSelf()); } @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("hello", message -> { - proxy.tell("world!", self()); - client = sender(); - }) - .matchUnchecked(FSM.CurrentState.class, (FSM.CurrentState state) -> { - // get initial state - }) - .matchUnchecked(FSM.Transition.class, (FSM.Transition transition) -> { - assert transition.fsmRef().equals(proxy); - if (transition.from().equals(ReliableProxy.active()) && - transition.to().equals(ReliableProxy.idle())) { - client.tell("done", self()); - } - }) - .build(); + .matchEquals( + "hello", + message -> { + proxy.tell("world!", self()); + client = sender(); + }) + .matchUnchecked( + FSM.CurrentState.class, + (FSM.CurrentState state) -> { + // get initial state + }) + .matchUnchecked( + FSM.Transition.class, + (FSM.Transition transition) -> { + assert transition.fsmRef().equals(proxy); + if (transition.from().equals(ReliableProxy.active()) + && transition.to().equals(ReliableProxy.idle())) { + client.tell("done", self()); + } + }) + .build(); } } - //#demo-transition + // #demo-transition @Test public void demonstrateUsage() { @@ -99,7 +108,8 @@ public class ReliableProxyTest extends JUnitSuite { @Test public void demonstrateTransitions() { final ActorRef target = TestProbe.apply(system).ref(); - final ActorRef parent = system.actorOf(Props.create(ProxyTransitionParent.class, target.path())); + final ActorRef parent = + system.actorOf(Props.create(ProxyTransitionParent.class, target.path())); final TestProbe probe = TestProbe.apply(system); parent.tell("hello", probe.ref()); probe.expectMsg("done"); diff --git a/akka-contrib/src/test/java/akka/contrib/throttle/TimerBasedThrottlerTest.java b/akka-contrib/src/test/java/akka/contrib/throttle/TimerBasedThrottlerTest.java index 0182c2f366..d9caa59bfb 100644 --- a/akka-contrib/src/test/java/akka/contrib/throttle/TimerBasedThrottlerTest.java +++ b/akka-contrib/src/test/java/akka/contrib/throttle/TimerBasedThrottlerTest.java @@ -21,19 +21,23 @@ import akka.testkit.AkkaJUnitActorSystemResource; public class TimerBasedThrottlerTest extends JUnitSuite { @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource( - "TimerBasedThrottlerTest", ConfigFactory.parseString("akka.log-dead-letters=off")); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource( + "TimerBasedThrottlerTest", ConfigFactory.parseString("akka.log-dead-letters=off")); private final ActorSystem system = actorSystemResource.getSystem(); @Test public void demonstrateUsage() { - //#demo-code + // #demo-code // A simple actor that prints whatever it receives ActorRef printer = system.actorOf(Props.create(Printer.class)); // The throttler for this example, setting the rate - ActorRef throttler = system.actorOf(Props.create(TimerBasedThrottler.class, - new Throttler.Rate(3, Duration.create(1, TimeUnit.SECONDS)))); + ActorRef throttler = + system.actorOf( + Props.create( + TimerBasedThrottler.class, + new Throttler.Rate(3, Duration.create(1, TimeUnit.SECONDS)))); // Set the target throttler.tell(new Throttler.SetTarget(printer), null); // These three messages will be sent to the target immediately @@ -44,32 +48,31 @@ public class TimerBasedThrottlerTest extends JUnitSuite { throttler.tell("4", null); throttler.tell("5", null); - //#demo-code + // #demo-code } - static//#demo-code - //A simple actor that prints whatever it receives - public class Printer extends AbstractActor { + public // #demo-code + // A simple actor that prints whatever it receives + static class Printer extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .matchAny(message -> { - System.out.println(message); - }) - .build(); + .matchAny( + message -> { + System.out.println(message); + }) + .build(); } } - //#demo-code + // #demo-code static class System { static Out out = new Out(); static class Out { - void println(Object s) { - } + void println(Object s) {} } } - } diff --git a/akka-discovery/src/test/java/jdoc/akka/discovery/CompileOnlyTest.java b/akka-discovery/src/test/java/jdoc/akka/discovery/CompileOnlyTest.java index 5c98543a8c..f0c5844872 100644 --- a/akka-discovery/src/test/java/jdoc/akka/discovery/CompileOnlyTest.java +++ b/akka-discovery/src/test/java/jdoc/akka/discovery/CompileOnlyTest.java @@ -13,24 +13,26 @@ import java.time.Duration; import java.util.concurrent.CompletionStage; public class CompileOnlyTest { - public static void example() { - //#loading - ActorSystem as = ActorSystem.create(); - ServiceDiscovery serviceDiscovery = Discovery.get(as).discovery(); - //#loading + public static void example() { + // #loading + ActorSystem as = ActorSystem.create(); + ServiceDiscovery serviceDiscovery = Discovery.get(as).discovery(); + // #loading - //#basic - serviceDiscovery.lookup(Lookup.create("akka.io"), Duration.ofSeconds(1)); - // convenience for a Lookup with only a serviceName - serviceDiscovery.lookup("akka.io", Duration.ofSeconds(1)); - //#basic + // #basic + serviceDiscovery.lookup(Lookup.create("akka.io"), Duration.ofSeconds(1)); + // convenience for a Lookup with only a serviceName + serviceDiscovery.lookup("akka.io", Duration.ofSeconds(1)); + // #basic - //#full - CompletionStage lookup = serviceDiscovery.lookup(Lookup.create("akka.io").withPortName("remoting").withProtocol("tcp"), Duration.ofSeconds(1)); - //#full + // #full + CompletionStage lookup = + serviceDiscovery.lookup( + Lookup.create("akka.io").withPortName("remoting").withProtocol("tcp"), + Duration.ofSeconds(1)); + // #full - // not-used warning - lookup.thenAccept(System.out::println); - - } + // not-used warning + lookup.thenAccept(System.out::println); + } } diff --git a/akka-distributed-data/src/test/java/akka/cluster/ddata/JavaImplOfDeltaReplicatedData.java b/akka-distributed-data/src/test/java/akka/cluster/ddata/JavaImplOfDeltaReplicatedData.java index 80f975c7bf..55a6304de8 100644 --- a/akka-distributed-data/src/test/java/akka/cluster/ddata/JavaImplOfDeltaReplicatedData.java +++ b/akka-distributed-data/src/test/java/akka/cluster/ddata/JavaImplOfDeltaReplicatedData.java @@ -4,12 +4,13 @@ package akka.cluster.ddata; - import java.util.Optional; // same delta type -public class JavaImplOfDeltaReplicatedData extends AbstractDeltaReplicatedData - implements ReplicatedDelta { +public class JavaImplOfDeltaReplicatedData + extends AbstractDeltaReplicatedData< + JavaImplOfDeltaReplicatedData, JavaImplOfDeltaReplicatedData> + implements ReplicatedDelta { @Override public JavaImplOfDeltaReplicatedData mergeData(JavaImplOfDeltaReplicatedData other) { @@ -35,5 +36,4 @@ public class JavaImplOfDeltaReplicatedData extends AbstractDeltaReplicatedData { + extends AbstractDeltaReplicatedData< + JavaImplOfDeltaReplicatedData2, JavaImplOfDeltaReplicatedData2.Delta> { - public static class Delta extends AbstractReplicatedData implements ReplicatedDelta, RequiresCausalDeliveryOfDeltas { + public static class Delta extends AbstractReplicatedData + implements ReplicatedDelta, RequiresCausalDeliveryOfDeltas { @Override public Delta mergeData(Delta other) { return this; @@ -44,7 +45,4 @@ public class JavaImplOfDeltaReplicatedData2 public JavaImplOfDeltaReplicatedData2 resetDelta() { return this; } - - - } diff --git a/akka-distributed-data/src/test/java/akka/cluster/ddata/JavaImplOfReplicatedData.java b/akka-distributed-data/src/test/java/akka/cluster/ddata/JavaImplOfReplicatedData.java index c56b251095..87a101239d 100644 --- a/akka-distributed-data/src/test/java/akka/cluster/ddata/JavaImplOfReplicatedData.java +++ b/akka-distributed-data/src/test/java/akka/cluster/ddata/JavaImplOfReplicatedData.java @@ -6,8 +6,8 @@ package akka.cluster.ddata; import akka.cluster.UniqueAddress; -public class JavaImplOfReplicatedData extends AbstractReplicatedData implements - RemovedNodePruning { +public class JavaImplOfReplicatedData extends AbstractReplicatedData + implements RemovedNodePruning { @Override public JavaImplOfReplicatedData mergeData(JavaImplOfReplicatedData other) { diff --git a/akka-distributed-data/src/test/java/akka/cluster/ddata/ORMapTest.java b/akka-distributed-data/src/test/java/akka/cluster/ddata/ORMapTest.java index 42edaee37c..2f6033bceb 100644 --- a/akka-distributed-data/src/test/java/akka/cluster/ddata/ORMapTest.java +++ b/akka-distributed-data/src/test/java/akka/cluster/ddata/ORMapTest.java @@ -12,8 +12,8 @@ public class ORMapTest { ORMap> orMap = ORMap.create(); // updated needs a cast - ORMap> updated = orMap.update(node1, "key", PNCounterMap.create(), curr -> curr.decrement(node1, "key", 10)); + ORMap> updated = + orMap.update(node1, "key", PNCounterMap.create(), curr -> curr.decrement(node1, "key", 10)); updated.getEntries(); - } } diff --git a/akka-distributed-data/src/test/java/akka/cluster/ddata/ORMultiMapTest.java b/akka-distributed-data/src/test/java/akka/cluster/ddata/ORMultiMapTest.java index 1cc882cdca..2adf39cb5b 100644 --- a/akka-distributed-data/src/test/java/akka/cluster/ddata/ORMultiMapTest.java +++ b/akka-distributed-data/src/test/java/akka/cluster/ddata/ORMultiMapTest.java @@ -12,6 +12,5 @@ public class ORMultiMapTest { ORMultiMap orMultiMap = ORMultiMap.create(); orMultiMap.addBinding(node, "a", "1"); orMultiMap.removeBinding(node, "a", "1"); - } } diff --git a/akka-distributed-data/src/test/java/akka/cluster/ddata/PNCounterTest.java b/akka-distributed-data/src/test/java/akka/cluster/ddata/PNCounterTest.java index 55cd151740..981f0c256c 100644 --- a/akka-distributed-data/src/test/java/akka/cluster/ddata/PNCounterTest.java +++ b/akka-distributed-data/src/test/java/akka/cluster/ddata/PNCounterTest.java @@ -8,7 +8,6 @@ import java.math.BigInteger; public class PNCounterTest { - public void compileOnlyPNCounterApiTest() { // primarily to check API accessibility with overloads/types SelfUniqueAddress node1 = null; @@ -21,6 +20,5 @@ public class PNCounterTest { PNCounter c4 = c3.decrement(node2, BigInteger.valueOf(2)); PNCounter c5 = c4.decrement(node2, 7L); - } } diff --git a/akka-docs/src/test/java/jdocs/AbstractJavaTest.java b/akka-docs/src/test/java/jdocs/AbstractJavaTest.java index 07115fa3da..989bdd2bb4 100644 --- a/akka-docs/src/test/java/jdocs/AbstractJavaTest.java +++ b/akka-docs/src/test/java/jdocs/AbstractJavaTest.java @@ -6,9 +6,5 @@ package jdocs; import org.scalatest.junit.JUnitSuite; -/** - * Base class for all runnable example tests written in Java - */ -public abstract class AbstractJavaTest extends JUnitSuite { - -} +/** Base class for all runnable example tests written in Java */ +public abstract class AbstractJavaTest extends JUnitSuite {} diff --git a/akka-docs/src/test/java/jdocs/actor/ActorDocTest.java b/akka-docs/src/test/java/jdocs/actor/ActorDocTest.java index 57df6da905..c4f2e3fa2b 100644 --- a/akka-docs/src/test/java/jdocs/actor/ActorDocTest.java +++ b/akka-docs/src/test/java/jdocs/actor/ActorDocTest.java @@ -26,43 +26,43 @@ import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; -//#import-props +// #import-props import akka.actor.Props; -//#import-props -//#import-actorRef +// #import-props +// #import-actorRef import akka.actor.ActorRef; import akka.actor.ActorSystem; -//#import-actorRef -//#import-identify +// #import-actorRef +// #import-identify import akka.actor.ActorIdentity; import akka.actor.ActorSelection; import akka.actor.Identify; -//#import-identify -//#import-ask +// #import-identify +// #import-ask import static akka.pattern.Patterns.ask; import static akka.pattern.Patterns.pipe; import java.util.concurrent.CompletableFuture; -//#import-ask -//#import-gracefulStop +// #import-ask +// #import-gracefulStop import static akka.pattern.Patterns.gracefulStop; import akka.pattern.AskTimeoutException; import java.util.concurrent.CompletionStage; -//#import-gracefulStop -//#import-terminated +// #import-gracefulStop +// #import-terminated import akka.actor.Terminated; -//#import-terminated +// #import-terminated public class ActorDocTest extends AbstractJavaTest { - public static Config config = ConfigFactory.parseString( - "akka {\n" + - " loggers = [\"akka.testkit.TestEventListener\"]\n" + - " loglevel = \"WARNING\"\n" + - " stdout-loglevel = \"WARNING\"\n" + - "}\n" - ); + public static Config config = + ConfigFactory.parseString( + "akka {\n" + + " loggers = [\"akka.testkit.TestEventListener\"]\n" + + " loglevel = \"WARNING\"\n" + + " stdout-loglevel = \"WARNING\"\n" + + "}\n"); static ActorSystem system = null; @@ -76,48 +76,46 @@ public class ActorDocTest extends AbstractJavaTest { TestKit.shutdownActorSystem(system); } - static - //#context-actorOf - public class FirstActor extends AbstractActor { + public + // #context-actorOf + static class FirstActor extends AbstractActor { final ActorRef child = getContext().actorOf(Props.create(MyActor.class), "myChild"); - //#plus-some-behavior + // #plus-some-behavior @Override public Receive createReceive() { - return receiveBuilder() - .matchAny(x -> getSender().tell(x, getSelf())) - .build(); + return receiveBuilder().matchAny(x -> getSender().tell(x, getSelf())).build(); } - //#plus-some-behavior + // #plus-some-behavior } - //#context-actorOf + // #context-actorOf - static public class SomeActor extends AbstractActor { - //#createReceive + public static class SomeActor extends AbstractActor { + // #createReceive @Override public Receive createReceive() { - return receiveBuilder() - .match(String.class, s -> System.out.println(s.toLowerCase())) - .build(); + return receiveBuilder().match(String.class, s -> System.out.println(s.toLowerCase())).build(); } - //#createReceive + // #createReceive } - static - //#well-structured - public class WellStructuredActor extends AbstractActor { + public + // #well-structured + static class WellStructuredActor extends AbstractActor { public static class Msg1 {} + public static class Msg2 {} + public static class Msg3 {} @Override public Receive createReceive() { return receiveBuilder() - .match(Msg1.class, this::receiveMsg1) - .match(Msg2.class, this::receiveMsg2) - .match(Msg3.class, this::receiveMsg3) - .build(); + .match(Msg1.class, this::receiveMsg1) + .match(Msg2.class, this::receiveMsg2) + .match(Msg3.class, this::receiveMsg3) + .build(); } private void receiveMsg1(Msg1 msg) { @@ -132,26 +130,24 @@ public class ActorDocTest extends AbstractJavaTest { // actual work } } - //#well-structured + // #well-structured - static - //#optimized - public class OptimizedActor extends UntypedAbstractActor { + public + // #optimized + static class OptimizedActor extends UntypedAbstractActor { public static class Msg1 {} + public static class Msg2 {} + public static class Msg3 {} @Override public void onReceive(Object msg) throws Exception { - if (msg instanceof Msg1) - receiveMsg1((Msg1) msg); - else if (msg instanceof Msg2) - receiveMsg2((Msg2) msg); - else if (msg instanceof Msg3) - receiveMsg3((Msg3) msg); - else - unhandled(msg); + if (msg instanceof Msg1) receiveMsg1((Msg1) msg); + else if (msg instanceof Msg2) receiveMsg2((Msg2) msg); + else if (msg instanceof Msg3) receiveMsg3((Msg3) msg); + else unhandled(msg); } private void receiveMsg1(Msg1 msg) { @@ -166,9 +162,9 @@ public class ActorDocTest extends AbstractJavaTest { // actual work } } - //#optimized + // #optimized - static public class ActorWithArgs extends AbstractActor { + public static class ActorWithArgs extends AbstractActor { private final String args; public ActorWithArgs(String args) { @@ -177,18 +173,19 @@ public class ActorDocTest extends AbstractJavaTest { @Override public Receive createReceive() { - return receiveBuilder().matchAny(x -> { }).build(); + return receiveBuilder().matchAny(x -> {}).build(); } } - static - //#props-factory - public class DemoActor extends AbstractActor { + public + // #props-factory + static class DemoActor extends AbstractActor { /** * Create Props for an actor of this type. + * * @param magicNumber The magic number to be passed to this actor’s constructor. - * @return a Props for creating this actor, which can then be further configured - * (e.g. calling `.withDispatcher()` on it) + * @return a Props for creating this actor, which can then be further configured (e.g. calling + * `.withDispatcher()` on it) */ static Props props(Integer magicNumber) { // You need to specify the actual type of the returned actor @@ -205,34 +202,36 @@ public class ActorDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .match(Integer.class, i -> { - getSender().tell(i + magicNumber, getSelf()); - }) - .build(); + .match( + Integer.class, + i -> { + getSender().tell(i + magicNumber, getSelf()); + }) + .build(); } } - //#props-factory - static - //#props-factory - public class SomeOtherActor extends AbstractActor { + // #props-factory + public + // #props-factory + static class SomeOtherActor extends AbstractActor { // Props(new DemoActor(42)) would not be safe ActorRef demoActor = getContext().actorOf(DemoActor.props(42), "demo"); // ... - //#props-factory + // #props-factory @Override public Receive createReceive() { return AbstractActor.emptyBehavior(); } - //#props-factory + // #props-factory } - //#props-factory + // #props-factory - static - //#messages-in-companion - public class DemoMessagesActor extends AbstractLoggingActor { + public + // #messages-in-companion + static class DemoMessagesActor extends AbstractLoggingActor { - static public class Greeting { + public static class Greeting { private final String from; public Greeting(String from) { @@ -247,14 +246,15 @@ public class ActorDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .match(Greeting.class, g -> { - log().info("I was greeted by {}", g.getGreeter()); - }) - .build(); + .match( + Greeting.class, + g -> { + log().info("I was greeted by {}", g.getGreeter()); + }) + .build(); } } - //#messages-in-companion - + // #messages-in-companion public static class LifecycleMethods extends AbstractActor { @@ -268,9 +268,8 @@ public class ActorDocTest extends AbstractJavaTest { * * BOYSCOUT RULE: whenever you read this, verify that! */ - //#lifecycle-callbacks - public void preStart() { - } + // #lifecycle-callbacks + public void preStart() {} public void preRestart(Throwable reason, Optional message) { for (ActorRef each : getContext().getChildren()) { @@ -284,9 +283,8 @@ public class ActorDocTest extends AbstractJavaTest { preStart(); } - public void postStop() { - } - //#lifecycle-callbacks + public void postStop() {} + // #lifecycle-callbacks } @@ -298,49 +296,49 @@ public class ActorDocTest extends AbstractJavaTest { return AbstractActor.emptyBehavior(); } - //#preStart + // #preStart @Override public void preStart() { target = getContext().actorOf(Props.create(MyActor.class, "target")); } - //#preStart - //#postStop + // #preStart + // #postStop @Override public void postStop() { - //#clean-up-some-resources + // #clean-up-some-resources final String message = "stopped"; - //#tell + // #tell // don’t forget to think about who is the sender (2nd argument) target.tell(message, getSelf()); - //#tell + // #tell final Object result = ""; - //#forward + // #forward target.forward(result, getContext()); - //#forward + // #forward target = null; - //#clean-up-some-resources + // #clean-up-some-resources } - //#postStop + // #postStop // compilation test only public void compileSelections() { - //#selection-local + // #selection-local // will look up this absolute path getContext().actorSelection("/user/serviceA/actor"); // will look up sibling beneath same supervisor getContext().actorSelection("../joe"); - //#selection-local + // #selection-local - //#selection-wildcard + // #selection-wildcard // will look all children to serviceB with names starting with worker getContext().actorSelection("/user/serviceB/worker*"); // will look up all siblings beneath same supervisor getContext().actorSelection("../*"); - //#selection-wildcard + // #selection-wildcard - //#selection-remote + // #selection-remote getContext().actorSelection("akka.tcp://app@otherhost:1234/user/serviceB"); - //#selection-remote + // #selection-remote } } @@ -349,18 +347,19 @@ public class ActorDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .matchAny(x -> { - //#reply-exception - try { - String result = operation(); - getSender().tell(result, getSelf()); - } catch (Exception e) { - getSender().tell(new akka.actor.Status.Failure(e), getSelf()); - throw e; - } - //#reply-exception - }) - .build(); + .matchAny( + x -> { + // #reply-exception + try { + String result = operation(); + getSender().tell(result, getSelf()); + } catch (Exception e) { + getSender().tell(new akka.actor.Status.Failure(e), getSelf()); + throw e; + } + // #reply-exception + }) + .build(); } private String operation() { @@ -368,87 +367,98 @@ public class ActorDocTest extends AbstractJavaTest { } } - static - //#gracefulStop-actor - public class Manager extends AbstractActor { + public + // #gracefulStop-actor + static class Manager extends AbstractActor { private static enum Shutdown { Shutdown } + public static final Shutdown SHUTDOWN = Shutdown.Shutdown; private ActorRef worker = - getContext().watch(getContext().actorOf(Props.create(Cruncher.class), "worker")); + getContext().watch(getContext().actorOf(Props.create(Cruncher.class), "worker")); @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("job", s -> { - worker.tell("crunch", getSelf()); - }) - .matchEquals(SHUTDOWN, x -> { - worker.tell(PoisonPill.getInstance(), getSelf()); - getContext().become(shuttingDown()); - }) - .build(); + .matchEquals( + "job", + s -> { + worker.tell("crunch", getSelf()); + }) + .matchEquals( + SHUTDOWN, + x -> { + worker.tell(PoisonPill.getInstance(), getSelf()); + getContext().become(shuttingDown()); + }) + .build(); } private AbstractActor.Receive shuttingDown() { return receiveBuilder() - .matchEquals("job", s -> - getSender().tell("service unavailable, shutting down", getSelf()) - ) - .match(Terminated.class, t -> t.actor().equals(worker), t -> - getContext().stop(getSelf()) - ) - .build(); + .matchEquals( + "job", s -> getSender().tell("service unavailable, shutting down", getSelf())) + .match(Terminated.class, t -> t.actor().equals(worker), t -> getContext().stop(getSelf())) + .build(); } } - //#gracefulStop-actor + // #gracefulStop-actor @Test public void usePatternsGracefulStop() throws Exception { ActorRef actorRef = system.actorOf(Props.create(Manager.class)); - //#gracefulStop + // #gracefulStop try { CompletionStage stopped = - gracefulStop(actorRef, Duration.ofSeconds(5), Manager.SHUTDOWN); + gracefulStop(actorRef, Duration.ofSeconds(5), Manager.SHUTDOWN); stopped.toCompletableFuture().get(6, TimeUnit.SECONDS); // the actor has been stopped } catch (AskTimeoutException e) { // the actor wasn't stopped within 5 seconds } - //#gracefulStop + // #gracefulStop } - public static class Cruncher extends AbstractActor { @Override public Receive createReceive() { - return receiveBuilder().matchEquals("crunch", s -> { }).build(); + return receiveBuilder().matchEquals("crunch", s -> {}).build(); } } - static - //#swapper - public class Swapper extends AbstractLoggingActor { + public + // #swapper + static class Swapper extends AbstractLoggingActor { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals(Swap, s -> { - log().info("Hi"); - getContext().become(receiveBuilder(). - matchEquals(Swap, x -> { - log().info("Ho"); - getContext().unbecome(); // resets the latest 'become' (just for fun) - }).build(), false); // push on top instead of replace - }).build(); + .matchEquals( + Swap, + s -> { + log().info("Hi"); + getContext() + .become( + receiveBuilder() + .matchEquals( + Swap, + x -> { + log().info("Ho"); + getContext() + .unbecome(); // resets the latest 'become' (just for fun) + }) + .build(), + false); // push on top instead of replace + }) + .build(); } } - //#swapper - static - //#swapper - public class SwapperApp { + // #swapper + public + // #swapper + static class SwapperApp { public static void main(String[] args) { ActorSystem system = ActorSystem.create("SwapperSystem"); ActorRef swapper = system.actorOf(Props.create(Swapper.class), "swapper"); @@ -461,16 +471,15 @@ public class ActorDocTest extends AbstractJavaTest { system.terminate(); } } - //#swapper - + // #swapper @Test public void creatingActorWithSystemActorOf() { - //#system-actorOf + // #system-actorOf // ActorSystem is a heavy object: create only one per application final ActorSystem system = ActorSystem.create("MySystem", config); final ActorRef myActor = system.actorOf(Props.create(MyActor.class), "myactor"); - //#system-actorOf + // #system-actorOf try { new TestKit(system) { { @@ -486,7 +495,8 @@ public class ActorDocTest extends AbstractJavaTest { @Test public void creatingGraduallyBuiltActorWithSystemActorOf() { final ActorSystem system = ActorSystem.create("MySystem", config); - final ActorRef actor = system.actorOf(Props.create(GraduallyBuiltActor.class), "graduallyBuiltActor"); + final ActorRef actor = + system.actorOf(Props.create(GraduallyBuiltActor.class), "graduallyBuiltActor"); try { new TestKit(system) { { @@ -501,37 +511,36 @@ public class ActorDocTest extends AbstractJavaTest { @Test public void creatingPropsConfig() { - //#creating-props + // #creating-props Props props1 = Props.create(MyActor.class); - Props props2 = Props.create(ActorWithArgs.class, - () -> new ActorWithArgs("arg")); // careful, see below + Props props2 = + Props.create(ActorWithArgs.class, () -> new ActorWithArgs("arg")); // careful, see below Props props3 = Props.create(ActorWithArgs.class, "arg"); - //#creating-props + // #creating-props - //#creating-props-deprecated + // #creating-props-deprecated // NOT RECOMMENDED within another actor: // encourages to close over enclosing class - Props props7 = Props.create(ActorWithArgs.class, - () -> new ActorWithArgs("arg")); - //#creating-props-deprecated + Props props7 = Props.create(ActorWithArgs.class, () -> new ActorWithArgs("arg")); + // #creating-props-deprecated } - @Test(expected=IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) public void creatingPropsIllegal() { - //#creating-props-illegal + // #creating-props-illegal // This will throw an IllegalArgumentException since some runtime // type information of the lambda is erased. // Use Props.create(actorClass, Creator) instead. Props props = Props.create(() -> new ActorWithArgs("arg")); - //#creating-props-illegal + // #creating-props-illegal } - static - //#receive-timeout - public class ReceiveTimeoutActor extends AbstractActor { - //#receive-timeout + public + // #receive-timeout + static class ReceiveTimeoutActor extends AbstractActor { + // #receive-timeout ActorRef target = getContext().getSystem().deadLetters(); - //#receive-timeout + // #receive-timeout public ReceiveTimeoutActor() { // To set an initial delay getContext().setReceiveTimeout(Duration.ofSeconds(10)); @@ -540,25 +549,29 @@ public class ActorDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("Hello", s -> { - // To set in a response to a message - getContext().setReceiveTimeout(Duration.ofSeconds(1)); - //#receive-timeout - target = getSender(); - target.tell("Hello world", getSelf()); - //#receive-timeout - }) - .match(ReceiveTimeout.class, r -> { - // To turn it off - getContext().cancelReceiveTimeout(); - //#receive-timeout - target.tell("timeout", getSelf()); - //#receive-timeout - }) - .build(); + .matchEquals( + "Hello", + s -> { + // To set in a response to a message + getContext().setReceiveTimeout(Duration.ofSeconds(1)); + // #receive-timeout + target = getSender(); + target.tell("Hello world", getSelf()); + // #receive-timeout + }) + .match( + ReceiveTimeout.class, + r -> { + // To turn it off + getContext().cancelReceiveTimeout(); + // #receive-timeout + target.tell("timeout", getSelf()); + // #receive-timeout + }) + .build(); } } - //#receive-timeout + // #receive-timeout @Test public void using_receiveTimeout() { @@ -572,46 +585,51 @@ public class ActorDocTest extends AbstractJavaTest { }; } - static - //#hot-swap-actor - public class HotSwapActor extends AbstractActor { + public + // #hot-swap-actor + static class HotSwapActor extends AbstractActor { private AbstractActor.Receive angry; private AbstractActor.Receive happy; public HotSwapActor() { angry = - receiveBuilder() - .matchEquals("foo", s -> { - getSender().tell("I am already angry?", getSelf()); - }) - .matchEquals("bar", s -> { - getContext().become(happy); - }) - .build(); + receiveBuilder() + .matchEquals( + "foo", + s -> { + getSender().tell("I am already angry?", getSelf()); + }) + .matchEquals( + "bar", + s -> { + getContext().become(happy); + }) + .build(); - happy = receiveBuilder() - .matchEquals("bar", s -> { - getSender().tell("I am already happy :-)", getSelf()); - }) - .matchEquals("foo", s -> { - getContext().become(angry); - }) - .build(); + happy = + receiveBuilder() + .matchEquals( + "bar", + s -> { + getSender().tell("I am already happy :-)", getSelf()); + }) + .matchEquals( + "foo", + s -> { + getContext().become(angry); + }) + .build(); } @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("foo", s -> - getContext().become(angry) - ) - .matchEquals("bar", s -> - getContext().become(happy) - ) - .build(); + .matchEquals("foo", s -> getContext().become(angry)) + .matchEquals("bar", s -> getContext().become(happy)) + .build(); } } - //#hot-swap-actor + // #hot-swap-actor @Test public void using_hot_swap() { @@ -632,37 +650,47 @@ public class ActorDocTest extends AbstractJavaTest { }; } - - static - //#stash - public class ActorWithProtocol extends AbstractActorWithStash { + public + // #stash + static class ActorWithProtocol extends AbstractActorWithStash { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("open", s -> { - getContext().become(receiveBuilder() - .matchEquals("write", ws -> { /* do writing */ }) - .matchEquals("close", cs -> { - unstashAll(); - getContext().unbecome(); - }) - .matchAny(msg -> stash()) - .build(), false); - }) - .matchAny(msg -> stash()) - .build(); + .matchEquals( + "open", + s -> { + getContext() + .become( + receiveBuilder() + .matchEquals( + "write", + ws -> { + /* do writing */ + }) + .matchEquals( + "close", + cs -> { + unstashAll(); + getContext().unbecome(); + }) + .matchAny(msg -> stash()) + .build(), + false); + }) + .matchAny(msg -> stash()) + .build(); } } - //#stash + // #stash @Test public void using_Stash() { final ActorRef actor = system.actorOf(Props.create(ActorWithProtocol.class), "stash"); } - static - //#watch - public class WatchActor extends AbstractActor { + public + // #watch + static class WatchActor extends AbstractActor { private final ActorRef child = getContext().actorOf(Props.empty(), "target"); private ActorRef lastSender = system.deadLetters(); @@ -673,17 +701,22 @@ public class ActorDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("kill", s -> { - getContext().stop(child); - lastSender = getSender(); - }) - .match(Terminated.class, t -> t.actor().equals(child), t -> { - lastSender.tell("finished", getSelf()); - }) - .build(); + .matchEquals( + "kill", + s -> { + getContext().stop(child); + lastSender = getSender(); + }) + .match( + Terminated.class, + t -> t.actor().equals(child), + t -> { + lastSender.tell("finished", getSelf()); + }) + .build(); } } - //#watch + // #watch @Test public void using_watch() { @@ -697,12 +730,12 @@ public class ActorDocTest extends AbstractJavaTest { }; } - static - //#identify - public class Follower extends AbstractActor { + public + // #identify + static class Follower extends AbstractActor { final Integer identifyId = 1; - public Follower(){ + public Follower() { ActorSelection selection = getContext().actorSelection("/user/another"); selection.tell(new Identify(identifyId), getSelf()); } @@ -710,26 +743,31 @@ public class ActorDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .match(ActorIdentity.class, id -> id.getActorRef().isPresent(), id -> { - ActorRef ref = id.getActorRef().get(); - getContext().watch(ref); - getContext().become(active(ref)); - }) - .match(ActorIdentity.class, id -> !id.getActorRef().isPresent(), id -> { - getContext().stop(getSelf()); - }) - .build(); + .match( + ActorIdentity.class, + id -> id.getActorRef().isPresent(), + id -> { + ActorRef ref = id.getActorRef().get(); + getContext().watch(ref); + getContext().become(active(ref)); + }) + .match( + ActorIdentity.class, + id -> !id.getActorRef().isPresent(), + id -> { + getContext().stop(getSelf()); + }) + .build(); } final AbstractActor.Receive active(final ActorRef another) { return receiveBuilder() - .match(Terminated.class, t -> t.actor().equals(another), t -> - getContext().stop(getSelf()) - ) - .build(); + .match( + Terminated.class, t -> t.actor().equals(another), t -> getContext().stop(getSelf())) + .build(); } } - //#identify + // #identify @Test public void using_Identify() { @@ -753,27 +791,27 @@ public class ActorDocTest extends AbstractJavaTest { ActorRef actorB = system.actorOf(TestActors.echoActorProps()); ActorRef actorC = getRef(); - //#ask-pipe + // #ask-pipe final Duration t = Duration.ofSeconds(5); // using 1000ms timeout CompletableFuture future1 = - ask(actorA, "request", Duration.ofMillis(1000)).toCompletableFuture(); + ask(actorA, "request", Duration.ofMillis(1000)).toCompletableFuture(); // using timeout from above - CompletableFuture future2 = - ask(actorB, "another request", t).toCompletableFuture(); + CompletableFuture future2 = ask(actorB, "another request", t).toCompletableFuture(); CompletableFuture transformed = - CompletableFuture.allOf(future1, future2) - .thenApply(v -> { - String x = (String) future1.join(); - String s = (String) future2.join(); - return new Result(x, s); - }); + CompletableFuture.allOf(future1, future2) + .thenApply( + v -> { + String x = (String) future1.join(); + String s = (String) future2.join(); + return new Result(x, s); + }); pipe(transformed, system.dispatcher()).to(actorC); - //#ask-pipe + // #ask-pipe expectMsgEquals(new Result("request", "another request")); } @@ -786,12 +824,12 @@ public class ActorDocTest extends AbstractJavaTest { { ActorRef victim = system.actorOf(TestActors.echoActorProps()); watch(victim); - //#kill + // #kill victim.tell(akka.actor.Kill.getInstance(), ActorRef.noSender()); // expecting the actor to indeed terminate: expectTerminated(Duration.ofSeconds(3), victim); - //#kill + // #kill } }; } @@ -802,9 +840,9 @@ public class ActorDocTest extends AbstractJavaTest { { ActorRef victim = system.actorOf(TestActors.echoActorProps()); watch(victim); - //#poison-pill + // #poison-pill victim.tell(akka.actor.PoisonPill.getInstance(), ActorRef.noSender()); - //#poison-pill + // #poison-pill expectTerminated(Duration.ofSeconds(3), victim); } }; @@ -813,28 +851,28 @@ public class ActorDocTest extends AbstractJavaTest { @Test public void coordinatedShutdown() { final ActorRef someActor = system.actorOf(Props.create(FirstActor.class)); - //#coordinated-shutdown-addTask - CoordinatedShutdown.get(system).addTask( - CoordinatedShutdown.PhaseBeforeServiceUnbind(), "someTaskName", - () -> { - return akka.pattern.Patterns.ask(someActor, "stop", Duration.ofSeconds(5)) - .thenApply(reply -> Done.getInstance()); - }); - //#coordinated-shutdown-addTask + // #coordinated-shutdown-addTask + CoordinatedShutdown.get(system) + .addTask( + CoordinatedShutdown.PhaseBeforeServiceUnbind(), + "someTaskName", + () -> { + return akka.pattern.Patterns.ask(someActor, "stop", Duration.ofSeconds(5)) + .thenApply(reply -> Done.getInstance()); + }); + // #coordinated-shutdown-addTask - //#coordinated-shutdown-jvm-hook - CoordinatedShutdown.get(system).addJvmShutdownHook(() -> - System.out.println("custom JVM shutdown hook...") - ); - //#coordinated-shutdown-jvm-hook + // #coordinated-shutdown-jvm-hook + CoordinatedShutdown.get(system) + .addJvmShutdownHook(() -> System.out.println("custom JVM shutdown hook...")); + // #coordinated-shutdown-jvm-hook // don't run this if (false) { - //#coordinated-shutdown-run - CompletionStage done = CoordinatedShutdown.get(system).runAll( - CoordinatedShutdown.unknownReason()); - //#coordinated-shutdown-run + // #coordinated-shutdown-run + CompletionStage done = + CoordinatedShutdown.get(system).runAll(CoordinatedShutdown.unknownReason()); + // #coordinated-shutdown-run } } - } diff --git a/akka-docs/src/test/java/jdocs/actor/BlockingActor.java b/akka-docs/src/test/java/jdocs/actor/BlockingActor.java index 929902535e..7e4911e052 100644 --- a/akka-docs/src/test/java/jdocs/actor/BlockingActor.java +++ b/akka-docs/src/test/java/jdocs/actor/BlockingActor.java @@ -12,11 +12,13 @@ class BlockingActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(Integer.class, i -> { - Thread.sleep(5000); //block for 5 seconds, representing blocking I/O, etc - System.out.println("Blocking operation finished: " + i); - }) - .build(); + .match( + Integer.class, + i -> { + Thread.sleep(5000); // block for 5 seconds, representing blocking I/O, etc + System.out.println("Blocking operation finished: " + i); + }) + .build(); } } -// #blocking-in-actor \ No newline at end of file +// #blocking-in-actor diff --git a/akka-docs/src/test/java/jdocs/actor/BlockingDispatcherTest.java b/akka-docs/src/test/java/jdocs/actor/BlockingDispatcherTest.java index 6da37e617b..5a438188b3 100644 --- a/akka-docs/src/test/java/jdocs/actor/BlockingDispatcherTest.java +++ b/akka-docs/src/test/java/jdocs/actor/BlockingDispatcherTest.java @@ -25,7 +25,7 @@ public class BlockingDispatcherTest { Thread.sleep(5000 * 6); } catch (InterruptedException e) { - //swallow the exception + // swallow the exception } finally { system.terminate(); } diff --git a/akka-docs/src/test/java/jdocs/actor/BlockingFutureActor.java b/akka-docs/src/test/java/jdocs/actor/BlockingFutureActor.java index ddaf5ff83d..36ceb378c8 100644 --- a/akka-docs/src/test/java/jdocs/actor/BlockingFutureActor.java +++ b/akka-docs/src/test/java/jdocs/actor/BlockingFutureActor.java @@ -16,15 +16,20 @@ class BlockingFutureActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(Integer.class, i -> { - System.out.println("Calling blocking Future: " + i); - Future f = Futures.future(() -> { - Thread.sleep(5000); - System.out.println("Blocking future finished: " + i); - return i; - }, ec); - }) - .build(); + .match( + Integer.class, + i -> { + System.out.println("Calling blocking Future: " + i); + Future f = + Futures.future( + () -> { + Thread.sleep(5000); + System.out.println("Blocking future finished: " + i); + return i; + }, + ec); + }) + .build(); } } -// #blocking-in-future \ No newline at end of file +// #blocking-in-future diff --git a/akka-docs/src/test/java/jdocs/actor/ByteBufferSerializerDocTest.java b/akka-docs/src/test/java/jdocs/actor/ByteBufferSerializerDocTest.java index 4703b3f507..be1d5067b0 100644 --- a/akka-docs/src/test/java/jdocs/actor/ByteBufferSerializerDocTest.java +++ b/akka-docs/src/test/java/jdocs/actor/ByteBufferSerializerDocTest.java @@ -4,19 +4,18 @@ package jdocs.actor; -//#bytebufserializer-with-manifest +// #bytebufserializer-with-manifest import akka.serialization.ByteBufferSerializer; import akka.serialization.SerializerWithStringManifest; -//#bytebufserializer-with-manifest +// #bytebufserializer-with-manifest import java.nio.ByteBuffer; public class ByteBufferSerializerDocTest { - - static //#bytebufserializer-with-manifest + static // #bytebufserializer-with-manifest class ExampleByteBufSerializer extends SerializerWithStringManifest - implements ByteBufferSerializer { + implements ByteBufferSerializer { @Override public int identifier() { @@ -56,24 +55,21 @@ public class ByteBufferSerializerDocTest { return null; } } - //#bytebufserializer-with-manifest - + // #bytebufserializer-with-manifest + static class OnlyForDocInclude { static - //#ByteBufferSerializer-interface + // #ByteBufferSerializer-interface interface ByteBufferSerializer { - /** - * Serializes the given object into the `ByteBuffer`. - */ + /** Serializes the given object into the `ByteBuffer`. */ void toBinary(Object o, ByteBuffer buf); - + /** - * Produces an object from a `ByteBuffer`, with an optional type-hint; - * the class should be loaded using ActorSystem.dynamicAccess. + * Produces an object from a `ByteBuffer`, with an optional type-hint; the class should be + * loaded using ActorSystem.dynamicAccess. */ Object fromBinary(ByteBuffer buf, String manifest); } - //#ByteBufferSerializer-interface + // #ByteBufferSerializer-interface } - } diff --git a/akka-docs/src/test/java/jdocs/actor/DependencyInjectionDocTest.java b/akka-docs/src/test/java/jdocs/actor/DependencyInjectionDocTest.java index 5872cfacb5..c88c051ac5 100644 --- a/akka-docs/src/test/java/jdocs/actor/DependencyInjectionDocTest.java +++ b/akka-docs/src/test/java/jdocs/actor/DependencyInjectionDocTest.java @@ -15,31 +15,33 @@ import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; -//#import +// #import import akka.actor.Actor; import akka.actor.IndirectActorProducer; -//#import +// #import public class DependencyInjectionDocTest extends AbstractJavaTest { public static class TheActor extends AbstractActor { final String s; - + public TheActor(String s) { this.s = s; } - + @Override public Receive createReceive() { return receiveBuilder() - .match(String.class, msg -> { - getSender().tell(s, getSelf()); - }) - .build(); + .match( + String.class, + msg -> { + getSender().tell(s, getSelf()); + }) + .build(); } } - + static ActorSystem system = null; @BeforeClass @@ -52,47 +54,48 @@ public class DependencyInjectionDocTest extends AbstractJavaTest { TestKit.shutdownActorSystem(system); } - //this is just to make the test below a tiny fraction nicer + // this is just to make the test below a tiny fraction nicer private ActorSystem getContext() { return system; } - + static - //#creating-indirectly + // #creating-indirectly class DependencyInjector implements IndirectActorProducer { final Object applicationContext; final String beanName; - + public DependencyInjector(Object applicationContext, String beanName) { this.applicationContext = applicationContext; this.beanName = beanName; } - + @Override public Class actorClass() { return TheActor.class; } - + @Override public TheActor produce() { TheActor result; - //#obtain-fresh-Actor-instance-from-DI-framework + // #obtain-fresh-Actor-instance-from-DI-framework result = new TheActor((String) applicationContext); - //#obtain-fresh-Actor-instance-from-DI-framework + // #obtain-fresh-Actor-instance-from-DI-framework return result; } } - //#creating-indirectly - + // #creating-indirectly + @Test public void indirectActorOf() { final String applicationContext = "..."; - //#creating-indirectly - - final ActorRef myActor = getContext().actorOf( - Props.create(DependencyInjector.class, applicationContext, "TheActor"), - "TheActor"); - //#creating-indirectly + // #creating-indirectly + + final ActorRef myActor = + getContext() + .actorOf( + Props.create(DependencyInjector.class, applicationContext, "TheActor"), "TheActor"); + // #creating-indirectly new TestKit(system) { { myActor.tell("hello", getRef()); @@ -100,5 +103,4 @@ public class DependencyInjectionDocTest extends AbstractJavaTest { } }; } - } diff --git a/akka-docs/src/test/java/jdocs/actor/FaultHandlingDocSample.java b/akka-docs/src/test/java/jdocs/actor/FaultHandlingDocSample.java index b4c4b2dbf8..c16eff95d0 100644 --- a/akka-docs/src/test/java/jdocs/actor/FaultHandlingDocSample.java +++ b/akka-docs/src/test/java/jdocs/actor/FaultHandlingDocSample.java @@ -4,8 +4,8 @@ package jdocs.actor; -//#all -//#imports +// #all +// #imports import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -33,20 +33,19 @@ import static jdocs.actor.FaultHandlingDocSample.CounterServiceApi.*; import static jdocs.actor.FaultHandlingDocSample.CounterApi.*; import static jdocs.actor.FaultHandlingDocSample.StorageApi.*; -//#imports +// #imports public class FaultHandlingDocSample { - /** - * Runs the sample - */ + /** Runs the sample */ public static void main(String[] args) { - Config config = ConfigFactory.parseString( - "akka.loglevel = \"DEBUG\"\n" + - "akka.actor.debug {\n" + - " receive = on\n" + - " lifecycle = on\n" + - "}\n"); + Config config = + ConfigFactory.parseString( + "akka.loglevel = \"DEBUG\"\n" + + "akka.actor.debug {\n" + + " receive = on\n" + + " lifecycle = on\n" + + "}\n"); ActorSystem system = ActorSystem.create("FaultToleranceSample", config); ActorRef worker = system.actorOf(Props.create(Worker.class), "worker"); @@ -58,8 +57,7 @@ public class FaultHandlingDocSample { } /** - * Listens on progress from the worker and shuts down the system when enough - * work has been done. + * Listens on progress from the worker and shuts down the system when enough work has been done. */ public static class Listener extends AbstractLoggingActor { @@ -72,23 +70,30 @@ public class FaultHandlingDocSample { @Override public Receive createReceive() { - return LoggingReceive.create(receiveBuilder(). - match(Progress.class, progress -> { - log().info("Current progress: {} %", progress.percent); - if (progress.percent >= 100.0) { - log().info("That's all, shutting down"); - getContext().getSystem().terminate(); - } - }). - matchEquals(ReceiveTimeout.getInstance(), x -> { - // No progress within 15 seconds, ServiceUnavailable - log().error("Shutting down due to unavailable service"); - getContext().getSystem().terminate(); - }).build(), getContext()); + return LoggingReceive.create( + receiveBuilder() + .match( + Progress.class, + progress -> { + log().info("Current progress: {} %", progress.percent); + if (progress.percent >= 100.0) { + log().info("That's all, shutting down"); + getContext().getSystem().terminate(); + } + }) + .matchEquals( + ReceiveTimeout.getInstance(), + x -> { + // No progress within 15 seconds, ServiceUnavailable + log().error("Shutting down due to unavailable service"); + getContext().getSystem().terminate(); + }) + .build(), + getContext()); } } - //#messages + // #messages public interface WorkerApi { public static final Object Start = "Start"; public static final Object Do = "Do"; @@ -106,12 +111,11 @@ public class FaultHandlingDocSample { } } - //#messages + // #messages /** - * Worker performs some work when it receives the Start message. It will - * continuously notify the sender of the Start message of current Progress. - * The Worker supervise the CounterService. + * Worker performs some work when it receives the Start message. It will continuously notify the + * sender of the Start message of current Progress. The Worker supervise the CounterService. */ public static class Worker extends AbstractLoggingActor { final Timeout askTimeout = Timeout.create(Duration.ofSeconds(5)); @@ -119,15 +123,16 @@ public class FaultHandlingDocSample { // The sender of the initial Start message will continuously be notified // about progress ActorRef progressListener; - final ActorRef counterService = getContext().actorOf( - Props.create(CounterService.class), "counter"); + final ActorRef counterService = + getContext().actorOf(Props.create(CounterService.class), "counter"); final int totalCount = 51; // Stop the CounterService child if it throws ServiceUnavailable private static final SupervisorStrategy strategy = - new OneForOneStrategy(DeciderBuilder. - match(ServiceUnavailable.class, e -> stop()). - matchAny(o -> escalate()).build()); + new OneForOneStrategy( + DeciderBuilder.match(ServiceUnavailable.class, e -> stop()) + .matchAny(o -> escalate()) + .build()); @Override public SupervisorStrategy supervisorStrategy() { @@ -136,32 +141,50 @@ public class FaultHandlingDocSample { @Override public Receive createReceive() { - return LoggingReceive.create(receiveBuilder(). - matchEquals(Start, x -> progressListener == null, x -> { - progressListener = getSender(); - getContext().getSystem().scheduler().schedule( - Duration.ZERO, Duration.ofSeconds(1L), getSelf(), Do, - getContext().getDispatcher(), null - ); - }). - matchEquals(Do, x -> { - counterService.tell(new Increment(1), getSelf()); - counterService.tell(new Increment(1), getSelf()); - counterService.tell(new Increment(1), getSelf()); - // Send current progress to the initial sender - pipe(Patterns.ask(counterService, GetCurrentCount, askTimeout) - .mapTo(classTag(CurrentCount.class)) - .map(new Mapper() { - public Progress apply(CurrentCount c) { - return new Progress(100.0 * c.count / totalCount); - } - }, getContext().dispatcher()), getContext().dispatcher()) - .to(progressListener); - }).build(), getContext()); + return LoggingReceive.create( + receiveBuilder() + .matchEquals( + Start, + x -> progressListener == null, + x -> { + progressListener = getSender(); + getContext() + .getSystem() + .scheduler() + .schedule( + Duration.ZERO, + Duration.ofSeconds(1L), + getSelf(), + Do, + getContext().getDispatcher(), + null); + }) + .matchEquals( + Do, + x -> { + counterService.tell(new Increment(1), getSelf()); + counterService.tell(new Increment(1), getSelf()); + counterService.tell(new Increment(1), getSelf()); + // Send current progress to the initial sender + pipe( + Patterns.ask(counterService, GetCurrentCount, askTimeout) + .mapTo(classTag(CurrentCount.class)) + .map( + new Mapper() { + public Progress apply(CurrentCount c) { + return new Progress(100.0 * c.count / totalCount); + } + }, + getContext().dispatcher()), + getContext().dispatcher()) + .to(progressListener); + }) + .build(), + getContext()); } } - //#messages + // #messages public interface CounterServiceApi { public static final Object GetCurrentCount = "GetCurrentCount"; @@ -194,19 +217,18 @@ public class FaultHandlingDocSample { public static class ServiceUnavailable extends RuntimeException { private static final long serialVersionUID = 1L; + public ServiceUnavailable(String msg) { super(msg); } } - } - //#messages + // #messages /** - * Adds the value received in Increment message to a persistent counter. - * Replies with CurrentCount when it is asked for CurrentCount. CounterService - * supervise Storage and Counter. + * Adds the value received in Increment message to a persistent counter. Replies with CurrentCount + * when it is asked for CurrentCount. CounterService supervise Storage and Counter. */ public static class CounterService extends AbstractLoggingActor { @@ -232,9 +254,12 @@ public class FaultHandlingDocSample { // Restart the storage child when StorageException is thrown. // After 3 restarts within 5 seconds it will be stopped. private static final SupervisorStrategy strategy = - new OneForOneStrategy(3, Duration.ofSeconds(5), DeciderBuilder. - match(StorageException.class, e -> restart()). - matchAny(o -> escalate()).build()); + new OneForOneStrategy( + 3, + Duration.ofSeconds(5), + DeciderBuilder.match(StorageException.class, e -> restart()) + .matchAny(o -> escalate()) + .build()); @Override public SupervisorStrategy supervisorStrategy() { @@ -247,58 +272,75 @@ public class FaultHandlingDocSample { } /** - * The child storage is restarted in case of failure, but after 3 restarts, - * and still failing it will be stopped. Better to back-off than - * continuously failing. When it has been stopped we will schedule a - * Reconnect after a delay. Watch the child so we receive Terminated message + * The child storage is restarted in case of failure, but after 3 restarts, and still failing it + * will be stopped. Better to back-off than continuously failing. When it has been stopped we + * will schedule a Reconnect after a delay. Watch the child so we receive Terminated message * when it has been terminated. */ void initStorage() { - storage = getContext().watch(getContext().actorOf( - Props.create(Storage.class), "storage")); + storage = getContext().watch(getContext().actorOf(Props.create(Storage.class), "storage")); // Tell the counter, if any, to use the new storage - if (counter != null) - counter.tell(new UseStorage(storage), getSelf()); + if (counter != null) counter.tell(new UseStorage(storage), getSelf()); // We need the initial value to be able to operate storage.tell(new Get(key), getSelf()); } @Override public Receive createReceive() { - return LoggingReceive.create(receiveBuilder(). - match(Entry.class, entry -> entry.key.equals(key) && counter == null, entry -> { - // Reply from Storage of the initial value, now we can create the Counter - final long value = entry.value; - counter = getContext().actorOf(Props.create(Counter.class, key, value)); - // Tell the counter to use current storage - counter.tell(new UseStorage(storage), getSelf()); - // and send the buffered backlog to the counter - for (SenderMsgPair each : backlog) { - counter.tell(each.msg, each.sender); - } - backlog.clear(); - }). - match(Increment.class, increment -> { - forwardOrPlaceInBacklog(increment); - }). - matchEquals(GetCurrentCount, gcc -> { - forwardOrPlaceInBacklog(gcc); - }). - match(Terminated.class, o -> { - // After 3 restarts the storage child is stopped. - // We receive Terminated because we watch the child, see initStorage. - storage = null; - // Tell the counter that there is no storage for the moment - counter.tell(new UseStorage(null), getSelf()); - // Try to re-establish storage after while - getContext().getSystem().scheduler().scheduleOnce( - Duration.ofSeconds(10), getSelf(), Reconnect, - getContext().getDispatcher(), null); - }). - matchEquals(Reconnect, o -> { - // Re-establish storage after the scheduled delay - initStorage(); - }).build(), getContext()); + return LoggingReceive.create( + receiveBuilder() + .match( + Entry.class, + entry -> entry.key.equals(key) && counter == null, + entry -> { + // Reply from Storage of the initial value, now we can create the Counter + final long value = entry.value; + counter = getContext().actorOf(Props.create(Counter.class, key, value)); + // Tell the counter to use current storage + counter.tell(new UseStorage(storage), getSelf()); + // and send the buffered backlog to the counter + for (SenderMsgPair each : backlog) { + counter.tell(each.msg, each.sender); + } + backlog.clear(); + }) + .match( + Increment.class, + increment -> { + forwardOrPlaceInBacklog(increment); + }) + .matchEquals( + GetCurrentCount, + gcc -> { + forwardOrPlaceInBacklog(gcc); + }) + .match( + Terminated.class, + o -> { + // After 3 restarts the storage child is stopped. + // We receive Terminated because we watch the child, see initStorage. + storage = null; + // Tell the counter that there is no storage for the moment + counter.tell(new UseStorage(null), getSelf()); + // Try to re-establish storage after while + getContext() + .getSystem() + .scheduler() + .scheduleOnce( + Duration.ofSeconds(10), + getSelf(), + Reconnect, + getContext().getDispatcher(), + null); + }) + .matchEquals( + Reconnect, + o -> { + // Re-establish storage after the scheduled delay + initStorage(); + }) + .build(), + getContext()); } void forwardOrPlaceInBacklog(Object msg) { @@ -307,8 +349,7 @@ public class FaultHandlingDocSample { // to the counter when it is initialized. if (counter == null) { if (backlog.size() >= MAX_BACKLOG) - throw new ServiceUnavailable("CounterService not available," + - " lack of initial value"); + throw new ServiceUnavailable("CounterService not available," + " lack of initial value"); backlog.add(new SenderMsgPair(getSender(), msg)); } else { counter.forward(msg, getContext()); @@ -316,7 +357,7 @@ public class FaultHandlingDocSample { } } - //#messages + // #messages public interface CounterApi { public static class UseStorage { public final ActorRef storage; @@ -331,11 +372,11 @@ public class FaultHandlingDocSample { } } - //#messages + // #messages /** - * The in memory count variable that will send current value to the Storage, - * if there is any storage available at the moment. + * The in memory count variable that will send current value to the Storage, if there is any + * storage available at the moment. */ public static class Counter extends AbstractLoggingActor { final String key; @@ -349,18 +390,27 @@ public class FaultHandlingDocSample { @Override public Receive createReceive() { - return LoggingReceive.create(receiveBuilder(). - match(UseStorage.class, useStorage -> { - storage = useStorage.storage; - storeCount(); - }). - match(Increment.class, increment -> { - count += increment.n; - storeCount(); - }). - matchEquals(GetCurrentCount, gcc -> { - getSender().tell(new CurrentCount(key, count), getSelf()); - }).build(), getContext()); + return LoggingReceive.create( + receiveBuilder() + .match( + UseStorage.class, + useStorage -> { + storage = useStorage.storage; + storeCount(); + }) + .match( + Increment.class, + increment -> { + count += increment.n; + storeCount(); + }) + .matchEquals( + GetCurrentCount, + gcc -> { + getSender().tell(new CurrentCount(key, count), getSelf()); + }) + .build(), + getContext()); } void storeCount() { @@ -372,7 +422,7 @@ public class FaultHandlingDocSample { } } - //#messages + // #messages public interface StorageApi { public static class Store { @@ -415,18 +465,19 @@ public class FaultHandlingDocSample { public static class StorageException extends RuntimeException { private static final long serialVersionUID = 1L; + public StorageException(String msg) { super(msg); } } } - //#messages + // #messages /** - * Saves key/value pairs to persistent storage when receiving Store message. - * Replies with current value when receiving Get message. Will throw - * StorageException if the underlying data store is out of order. + * Saves key/value pairs to persistent storage when receiving Store message. Replies with current + * value when receiving Get message. Will throw StorageException if the underlying data store is + * out of order. */ public static class Storage extends AbstractLoggingActor { @@ -434,25 +485,33 @@ public class FaultHandlingDocSample { @Override public Receive createReceive() { - return LoggingReceive.create(receiveBuilder(). - match(Store.class, store -> { - db.save(store.entry.key, store.entry.value); - }). - match(Get.class, get -> { - Long value = db.load(get.key); - getSender().tell(new Entry(get.key, value == null ? - Long.valueOf(0L) : value), getSelf()); - }).build(), getContext()); + return LoggingReceive.create( + receiveBuilder() + .match( + Store.class, + store -> { + db.save(store.entry.key, store.entry.value); + }) + .match( + Get.class, + get -> { + Long value = db.load(get.key); + getSender() + .tell( + new Entry(get.key, value == null ? Long.valueOf(0L) : value), + getSelf()); + }) + .build(), + getContext()); } } - //#dummydb + // #dummydb public static class DummyDB { public static final DummyDB instance = new DummyDB(); private final Map db = new HashMap(); - private DummyDB() { - } + private DummyDB() {} public synchronized void save(String key, Long value) throws StorageException { if (11 <= value && value <= 14) @@ -464,6 +523,6 @@ public class FaultHandlingDocSample { return db.get(key); } } - //#dummydb + // #dummydb } -//#all +// #all diff --git a/akka-docs/src/test/java/jdocs/actor/FaultHandlingTest.java b/akka-docs/src/test/java/jdocs/actor/FaultHandlingTest.java index 79d55b753b..32ba85febf 100644 --- a/akka-docs/src/test/java/jdocs/actor/FaultHandlingTest.java +++ b/akka-docs/src/test/java/jdocs/actor/FaultHandlingTest.java @@ -6,7 +6,6 @@ package jdocs.actor; import akka.actor.*; - import akka.testkit.javadsl.TestKit; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; @@ -16,7 +15,7 @@ import java.time.Duration; import static akka.pattern.Patterns.ask; -//#testkit +// #testkit import akka.testkit.TestProbe; import akka.testkit.ErrorFilter; import akka.testkit.EventFilter; @@ -25,89 +24,97 @@ import static java.util.concurrent.TimeUnit.SECONDS; import static akka.japi.Util.immutableSeq; import scala.concurrent.Await; -//#testkit +// #testkit -//#supervisor +// #supervisor import akka.japi.pf.DeciderBuilder; import akka.actor.SupervisorStrategy; -//#supervisor +// #supervisor import org.junit.Test; import org.junit.BeforeClass; import org.junit.AfterClass; -//#testkit +// #testkit public class FaultHandlingTest extends AbstractJavaTest { -//#testkit + // #testkit - public static Config config = ConfigFactory.parseString( - "akka {\n" + - " loggers = [\"akka.testkit.TestEventListener\"]\n" + - " loglevel = \"WARNING\"\n" + - " stdout-loglevel = \"WARNING\"\n" + - "}\n"); + public static Config config = + ConfigFactory.parseString( + "akka {\n" + + " loggers = [\"akka.testkit.TestEventListener\"]\n" + + " loglevel = \"WARNING\"\n" + + " stdout-loglevel = \"WARNING\"\n" + + "}\n"); - static - //#supervisor - public class Supervisor extends AbstractActor { + public + // #supervisor + static class Supervisor extends AbstractActor { - //#strategy + // #strategy private static SupervisorStrategy strategy = - new OneForOneStrategy(10, Duration.ofMinutes(1), - DeciderBuilder - .match(ArithmeticException.class, e -> SupervisorStrategy.resume()) - .match(NullPointerException.class, e -> SupervisorStrategy.restart()) - .match(IllegalArgumentException.class, e -> SupervisorStrategy.stop()) - .matchAny(o -> SupervisorStrategy.escalate()) - .build()); + new OneForOneStrategy( + 10, + Duration.ofMinutes(1), + DeciderBuilder.match(ArithmeticException.class, e -> SupervisorStrategy.resume()) + .match(NullPointerException.class, e -> SupervisorStrategy.restart()) + .match(IllegalArgumentException.class, e -> SupervisorStrategy.stop()) + .matchAny(o -> SupervisorStrategy.escalate()) + .build()); @Override public SupervisorStrategy supervisorStrategy() { return strategy; } - //#strategy + // #strategy @Override public Receive createReceive() { return receiveBuilder() - .match(Props.class, props -> { - getSender().tell(getContext().actorOf(props), getSelf()); - }) - .build(); + .match( + Props.class, + props -> { + getSender().tell(getContext().actorOf(props), getSelf()); + }) + .build(); } } - //#supervisor + // #supervisor - static - //#supervisor2 - public class Supervisor2 extends AbstractActor { + public + // #supervisor2 + static class Supervisor2 extends AbstractActor { - //#strategy2 + // #strategy2 private static SupervisorStrategy strategy = - new OneForOneStrategy(10, Duration.ofMinutes(1), DeciderBuilder. - match(ArithmeticException.class, e -> SupervisorStrategy.resume()). - match(NullPointerException.class, e -> SupervisorStrategy.restart()). - match(IllegalArgumentException.class, e -> SupervisorStrategy.stop()). - matchAny(o -> SupervisorStrategy.escalate()) - .build()); + new OneForOneStrategy( + 10, + Duration.ofMinutes(1), + DeciderBuilder.match(ArithmeticException.class, e -> SupervisorStrategy.resume()) + .match(NullPointerException.class, e -> SupervisorStrategy.restart()) + .match(IllegalArgumentException.class, e -> SupervisorStrategy.stop()) + .matchAny(o -> SupervisorStrategy.escalate()) + .build()); @Override public SupervisorStrategy supervisorStrategy() { return strategy; } - //#strategy2 + // #strategy2 @Override public Receive createReceive() { return receiveBuilder() - .match(Props.class, props -> { - getSender().tell(getContext().actorOf(props), getSelf()); - }) - .build(); + .match( + Props.class, + props -> { + getSender().tell(getContext().actorOf(props), getSelf()); + }) + .build(); } @Override @@ -116,28 +123,33 @@ public class FaultHandlingTest extends AbstractJavaTest { } } - //#supervisor2 + // #supervisor2 - static - //#child - public class Child extends AbstractActor { + public + // #child + static class Child extends AbstractActor { int state = 0; @Override public Receive createReceive() { return receiveBuilder() - .match(Exception.class, exception -> { throw exception; }) - .match(Integer.class, i -> state = i) - .matchEquals("get", s -> getSender().tell(state, getSelf())) - .build(); + .match( + Exception.class, + exception -> { + throw exception; + }) + .match(Integer.class, i -> state = i) + .matchEquals("get", s -> getSender().tell(state, getSelf())) + .build(); } } - //#child + // #child - //#testkit + // #testkit static ActorSystem system; - scala.concurrent.duration.Duration timeout = scala.concurrent.duration.Duration.create(5, SECONDS); + scala.concurrent.duration.Duration timeout = + scala.concurrent.duration.Duration.create(5, SECONDS); @BeforeClass public static void start() { @@ -153,61 +165,58 @@ public class FaultHandlingTest extends AbstractJavaTest { @Test public void mustEmploySupervisorStrategy() throws Exception { // code here - //#testkit + // #testkit EventFilter ex1 = new ErrorFilter(ArithmeticException.class); EventFilter ex2 = new ErrorFilter(NullPointerException.class); EventFilter ex3 = new ErrorFilter(IllegalArgumentException.class); EventFilter ex4 = new ErrorFilter(Exception.class); - EventFilter[] ignoreExceptions = { ex1, ex2, ex3, ex4 }; + EventFilter[] ignoreExceptions = {ex1, ex2, ex3, ex4}; system.getEventStream().publish(new TestEvent.Mute(immutableSeq(ignoreExceptions))); - //#create + // #create Props superprops = Props.create(Supervisor.class); ActorRef supervisor = system.actorOf(superprops, "supervisor"); - ActorRef child = (ActorRef) Await.result(ask(supervisor, - Props.create(Child.class), 5000), timeout); - //#create + ActorRef child = + (ActorRef) Await.result(ask(supervisor, Props.create(Child.class), 5000), timeout); + // #create - //#resume + // #resume child.tell(42, ActorRef.noSender()); assert Await.result(ask(child, "get", 5000), timeout).equals(42); child.tell(new ArithmeticException(), ActorRef.noSender()); assert Await.result(ask(child, "get", 5000), timeout).equals(42); - //#resume + // #resume - //#restart + // #restart child.tell(new NullPointerException(), ActorRef.noSender()); assert Await.result(ask(child, "get", 5000), timeout).equals(0); - //#restart + // #restart - //#stop + // #stop final TestProbe probe = new TestProbe(system); probe.watch(child); child.tell(new IllegalArgumentException(), ActorRef.noSender()); probe.expectMsgClass(Terminated.class); - //#stop + // #stop - //#escalate-kill - child = (ActorRef) Await.result(ask(supervisor, - Props.create(Child.class), 5000), timeout); + // #escalate-kill + child = (ActorRef) Await.result(ask(supervisor, Props.create(Child.class), 5000), timeout); probe.watch(child); assert Await.result(ask(child, "get", 5000), timeout).equals(0); child.tell(new Exception(), ActorRef.noSender()); probe.expectMsgClass(Terminated.class); - //#escalate-kill + // #escalate-kill - //#escalate-restart + // #escalate-restart superprops = Props.create(Supervisor2.class); supervisor = system.actorOf(superprops); - child = (ActorRef) Await.result(ask(supervisor, - Props.create(Child.class), 5000), timeout); + child = (ActorRef) Await.result(ask(supervisor, Props.create(Child.class), 5000), timeout); child.tell(23, ActorRef.noSender()); assert Await.result(ask(child, "get", 5000), timeout).equals(23); child.tell(new Exception(), ActorRef.noSender()); assert Await.result(ask(child, "get", 5000), timeout).equals(0); - //#escalate-restart - //#testkit + // #escalate-restart + // #testkit } - } -//#testkit +// #testkit diff --git a/akka-docs/src/test/java/jdocs/actor/GraduallyBuiltActor.java b/akka-docs/src/test/java/jdocs/actor/GraduallyBuiltActor.java index 122e1a03e6..a9bfb11d64 100644 --- a/akka-docs/src/test/java/jdocs/actor/GraduallyBuiltActor.java +++ b/akka-docs/src/test/java/jdocs/actor/GraduallyBuiltActor.java @@ -4,36 +4,38 @@ package jdocs.actor; -//#imports +// #imports import akka.actor.AbstractActor; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.japi.pf.ReceiveBuilder; -//#imports +// #imports -//#actor +// #actor public class GraduallyBuiltActor extends AbstractActor { private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); @Override public Receive createReceive() { ReceiveBuilder builder = ReceiveBuilder.create(); - - builder.match(String.class, s -> { - log.info("Received String message: {}", s); - //#actor - //#reply - getSender().tell(s, getSelf()); - //#reply - //#actor - }); - + + builder.match( + String.class, + s -> { + log.info("Received String message: {}", s); + // #actor + // #reply + getSender().tell(s, getSelf()); + // #reply + // #actor + }); + // do some other stuff in between - + builder.matchAny(o -> log.info("received unknown message")); - + return builder.build(); } } -//#actor +// #actor diff --git a/akka-docs/src/test/java/jdocs/actor/ImmutableMessage.java b/akka-docs/src/test/java/jdocs/actor/ImmutableMessage.java index 680091b6e3..4f43b6ccfe 100644 --- a/akka-docs/src/test/java/jdocs/actor/ImmutableMessage.java +++ b/akka-docs/src/test/java/jdocs/actor/ImmutableMessage.java @@ -8,7 +8,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -//#immutable-message +// #immutable-message public class ImmutableMessage { private final int sequenceNumber; private final List values; @@ -26,4 +26,4 @@ public class ImmutableMessage { return values; } } -//#immutable-message +// #immutable-message diff --git a/akka-docs/src/test/java/jdocs/actor/InboxDocTest.java b/akka-docs/src/test/java/jdocs/actor/InboxDocTest.java index e3d1240909..9e78e1437a 100644 --- a/akka-docs/src/test/java/jdocs/actor/InboxDocTest.java +++ b/akka-docs/src/test/java/jdocs/actor/InboxDocTest.java @@ -23,7 +23,7 @@ public class InboxDocTest extends AbstractJavaTest { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("InboxDocTest", AkkaSpec.testConf()); + new AkkaJUnitActorSystemResource("InboxDocTest", AkkaSpec.testConf()); private final ActorSystem system = actorSystemResource.getSystem(); @@ -31,26 +31,26 @@ public class InboxDocTest extends AbstractJavaTest { public void demonstrateInbox() { final TestKit probe = new TestKit(system); final ActorRef target = probe.getRef(); - //#inbox + // #inbox final Inbox inbox = Inbox.create(system); inbox.send(target, "hello"); - //#inbox + // #inbox probe.expectMsgEquals("hello"); probe.send(probe.getLastSender(), "world"); - //#inbox + // #inbox try { assert inbox.receive(Duration.ofSeconds(1)).equals("world"); } catch (java.util.concurrent.TimeoutException e) { // timeout } - //#inbox + // #inbox } - + @Test public void demonstrateWatch() { final TestKit probe = new TestKit(system); final ActorRef target = probe.getRef(); - //#watch + // #watch final Inbox inbox = Inbox.create(system); inbox.watch(target); target.tell(PoisonPill.getInstance(), ActorRef.noSender()); @@ -59,7 +59,6 @@ public class InboxDocTest extends AbstractJavaTest { } catch (java.util.concurrent.TimeoutException e) { // timeout } - //#watch + // #watch } - } diff --git a/akka-docs/src/test/java/jdocs/actor/InitializationDocTest.java b/akka-docs/src/test/java/jdocs/actor/InitializationDocTest.java index 3f63a5f9f7..7d3ca546a3 100644 --- a/akka-docs/src/test/java/jdocs/actor/InitializationDocTest.java +++ b/akka-docs/src/test/java/jdocs/actor/InitializationDocTest.java @@ -31,15 +31,15 @@ public class InitializationDocTest extends AbstractJavaTest { public static void afterClass() { TestKit.shutdownActorSystem(system); } - - static public class PreStartInitExample extends AbstractActor { + + public static class PreStartInitExample extends AbstractActor { @Override public Receive createReceive() { return AbstractActor.emptyBehavior(); } - //#preStartInit + // #preStartInit @Override public void preStart() { // Initialize children here @@ -48,40 +48,44 @@ public class InitializationDocTest extends AbstractJavaTest { // Overriding postRestart to disable the call to preStart() // after restarts @Override - public void postRestart(Throwable reason) { - } + public void postRestart(Throwable reason) {} // The default implementation of preRestart() stops all the children // of the actor. To opt-out from stopping the children, we // have to override preRestart() @Override - public void preRestart(Throwable reason, Optional message) - throws Exception { + public void preRestart(Throwable reason, Optional message) throws Exception { // Keep the call to postStop(), but no stopping of children postStop(); } - //#preStartInit + // #preStartInit } public static class MessageInitExample extends AbstractActor { private String initializeMe = null; - //#messageInit + // #messageInit @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("init", m1 -> { - initializeMe = "Up and running"; - getContext().become(receiveBuilder() - .matchEquals("U OK?", m2 -> { - getSender().tell(initializeMe, getSelf()); - }) - .build()); - }) - .build(); + .matchEquals( + "init", + m1 -> { + initializeMe = "Up and running"; + getContext() + .become( + receiveBuilder() + .matchEquals( + "U OK?", + m2 -> { + getSender().tell(initializeMe, getSelf()); + }) + .build()); + }) + .build(); } - //#messageInit + // #messageInit } public class GenericMessage { @@ -96,11 +100,13 @@ public class InitializationDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .matchUnchecked(GenericMessage.class, (GenericMessage msg) -> { - GenericMessage message = msg; - getSender().tell(message.value.toUpperCase(), getSelf()); - }) - .build(); + .matchUnchecked( + GenericMessage.class, + (GenericMessage msg) -> { + GenericMessage message = msg; + getSender().tell(message.value.toUpperCase(), getSelf()); + }) + .build(); } } @@ -110,82 +116,102 @@ public class InitializationDocTest extends AbstractJavaTest { FI.TypedPredicate> typedPredicate = s -> !s.value.isEmpty(); return receiveBuilder() - .matchUnchecked(GenericMessage.class, typedPredicate, (GenericMessage msg) -> { - getSender().tell(msg.value.toUpperCase(), getSelf()); - }) - .build(); + .matchUnchecked( + GenericMessage.class, + typedPredicate, + (GenericMessage msg) -> { + getSender().tell(msg.value.toUpperCase(), getSelf()); + }) + .build(); } } static class GenericActorWithPredicateAlwaysResponse extends AbstractActor { - private boolean alwaysResponse() { - return true; - } - - @Override - public Receive createReceive() { - return receiveBuilder() - .matchUnchecked(GenericMessage.class, this::alwaysResponse, (GenericMessage msg) -> { - getSender().tell(msg.value.toUpperCase(), getSelf()); - }) - .build(); - } + private boolean alwaysResponse() { + return true; } + @Override + public Receive createReceive() { + return receiveBuilder() + .matchUnchecked( + GenericMessage.class, + this::alwaysResponse, + (GenericMessage msg) -> { + getSender().tell(msg.value.toUpperCase(), getSelf()); + }) + .build(); + } + } + @Test public void testIt() { - new TestKit(system) {{ - ActorRef testactor = system.actorOf(Props.create(MessageInitExample.class), "testactor"); - String msg = "U OK?"; + new TestKit(system) { + { + ActorRef testactor = system.actorOf(Props.create(MessageInitExample.class), "testactor"); + String msg = "U OK?"; - testactor.tell(msg, getRef()); - expectNoMessage(Duration.ofSeconds(1)); + testactor.tell(msg, getRef()); + expectNoMessage(Duration.ofSeconds(1)); - testactor.tell("init", getRef()); - testactor.tell(msg, getRef()); - expectMsgEquals("Up and running"); - }}; + testactor.tell("init", getRef()); + testactor.tell(msg, getRef()); + expectMsgEquals("Up and running"); + } + }; } @Test public void testGenericActor() { - new TestKit(system) {{ - ActorRef genericTestActor = system.actorOf(Props.create(GenericActor.class), "genericActor"); - GenericMessage genericMessage = new GenericMessage("a"); + new TestKit(system) { + { + ActorRef genericTestActor = + system.actorOf(Props.create(GenericActor.class), "genericActor"); + GenericMessage genericMessage = new GenericMessage("a"); - genericTestActor.tell(genericMessage, getRef()); - expectMsgEquals("A"); - }}; + genericTestActor.tell(genericMessage, getRef()); + expectMsgEquals("A"); + } + }; } @Test public void actorShouldNotRespondForEmptyMessage() { - new TestKit(system) {{ - ActorRef genericTestActor = system.actorOf(Props.create(GenericActorWithPredicate.class), "genericActorWithPredicate"); - GenericMessage emptyGenericMessage = new GenericMessage(""); - GenericMessage nonEmptyGenericMessage = new GenericMessage("a"); + new TestKit(system) { + { + ActorRef genericTestActor = + system.actorOf( + Props.create(GenericActorWithPredicate.class), "genericActorWithPredicate"); + GenericMessage emptyGenericMessage = new GenericMessage(""); + GenericMessage nonEmptyGenericMessage = new GenericMessage("a"); - genericTestActor.tell(emptyGenericMessage, getRef()); - expectNoMessage(); + genericTestActor.tell(emptyGenericMessage, getRef()); + expectNoMessage(); - genericTestActor.tell(nonEmptyGenericMessage, getRef()); - expectMsgEquals("A"); - }}; + genericTestActor.tell(nonEmptyGenericMessage, getRef()); + expectMsgEquals("A"); + } + }; } - @Test - public void actorShouldAlwaysRespondForEmptyMessage() { - new TestKit(system) {{ - ActorRef genericTestActor = system.actorOf(Props.create(GenericActorWithPredicateAlwaysResponse.class), "genericActorWithPredicateAlwaysResponse"); - GenericMessage emptyGenericMessage = new GenericMessage(""); - GenericMessage nonEmptyGenericMessage = new GenericMessage("a"); + @Test + public void actorShouldAlwaysRespondForEmptyMessage() { + new TestKit(system) { + { + ActorRef genericTestActor = + system.actorOf( + Props.create(GenericActorWithPredicateAlwaysResponse.class), + "genericActorWithPredicateAlwaysResponse"); + GenericMessage emptyGenericMessage = new GenericMessage(""); + GenericMessage nonEmptyGenericMessage = new GenericMessage("a"); - genericTestActor.tell(emptyGenericMessage, getRef()); - expectMsg(""); + genericTestActor.tell(emptyGenericMessage, getRef()); + expectMsg(""); - genericTestActor.tell(nonEmptyGenericMessage, getRef()); - expectMsgEquals("A"); - }}; - } + genericTestActor.tell(nonEmptyGenericMessage, getRef()); + expectMsgEquals("A"); + } + }; + } } diff --git a/akka-docs/src/test/java/jdocs/actor/Messages.java b/akka-docs/src/test/java/jdocs/actor/Messages.java index 6964deac75..dbf294223a 100644 --- a/akka-docs/src/test/java/jdocs/actor/Messages.java +++ b/akka-docs/src/test/java/jdocs/actor/Messages.java @@ -9,9 +9,9 @@ import java.util.Collections; import java.util.List; public class Messages { - static - //#immutable-message - public class ImmutableMessage { + public + // #immutable-message + static class ImmutableMessage { private final int sequenceNumber; private final List values; @@ -28,7 +28,7 @@ public class Messages { return values; } } - //#immutable-message + // #immutable-message public static class DoIt { private final ImmutableMessage msg; @@ -60,9 +60,7 @@ public class Messages { @Override public String toString() { - return "DoIt{" + - "msg=" + msg + - '}'; + return "DoIt{" + "msg=" + msg + '}'; } } @@ -96,9 +94,7 @@ public class Messages { @Override public String toString() { - return "Message{" + - "str='" + str + '\'' + - '}'; + return "Message{" + "str='" + str + '\'' + '}'; } } @@ -126,23 +122,16 @@ public class Messages { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; Result other = (Result) obj; if (s == null) { - if (other.s != null) - return false; - } else if (!s.equals(other.s)) - return false; + if (other.s != null) return false; + } else if (!s.equals(other.s)) return false; if (x == null) { - if (other.x != null) - return false; - } else if (!x.equals(other.x)) - return false; + if (other.x != null) return false; + } else if (!x.equals(other.x)) return false; return true; } } diff --git a/akka-docs/src/test/java/jdocs/actor/MyActor.java b/akka-docs/src/test/java/jdocs/actor/MyActor.java index f2491d83c3..54c986e504 100644 --- a/akka-docs/src/test/java/jdocs/actor/MyActor.java +++ b/akka-docs/src/test/java/jdocs/actor/MyActor.java @@ -4,30 +4,32 @@ package jdocs.actor; -//#imports +// #imports import akka.actor.AbstractActor; import akka.event.Logging; import akka.event.LoggingAdapter; -//#imports +// #imports -//#my-actor +// #my-actor public class MyActor extends AbstractActor { private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); @Override public Receive createReceive() { return receiveBuilder() - .match(String.class, s -> { - log.info("Received String message: {}", s); - //#my-actor - //#reply - getSender().tell(s, getSelf()); - //#reply - //#my-actor - }) - .matchAny(o -> log.info("received unknown message")) - .build(); + .match( + String.class, + s -> { + log.info("Received String message: {}", s); + // #my-actor + // #reply + getSender().tell(s, getSelf()); + // #reply + // #my-actor + }) + .matchAny(o -> log.info("received unknown message")) + .build(); } } -//#my-actor +// #my-actor diff --git a/akka-docs/src/test/java/jdocs/actor/MyBoundedActor.java b/akka-docs/src/test/java/jdocs/actor/MyBoundedActor.java index edd2ee55dd..88a0e4efa5 100644 --- a/akka-docs/src/test/java/jdocs/actor/MyBoundedActor.java +++ b/akka-docs/src/test/java/jdocs/actor/MyBoundedActor.java @@ -4,11 +4,10 @@ package jdocs.actor; -//#my-bounded-untyped-actor +// #my-bounded-untyped-actor import akka.dispatch.BoundedMessageQueueSemantics; import akka.dispatch.RequiresMessageQueue; public class MyBoundedActor extends MyActor - implements RequiresMessageQueue { -} -//#my-bounded-untyped-actor + implements RequiresMessageQueue {} +// #my-bounded-untyped-actor diff --git a/akka-docs/src/test/java/jdocs/actor/MyStoppingActor.java b/akka-docs/src/test/java/jdocs/actor/MyStoppingActor.java index 876ef7bc94..9826b4babf 100644 --- a/akka-docs/src/test/java/jdocs/actor/MyStoppingActor.java +++ b/akka-docs/src/test/java/jdocs/actor/MyStoppingActor.java @@ -4,7 +4,7 @@ package jdocs.actor; -//#my-stopping-actor +// #my-stopping-actor import akka.actor.ActorRef; import akka.actor.AbstractActor; @@ -17,14 +17,9 @@ public class MyStoppingActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("interrupt-child", m -> - getContext().stop(child) - ) - .matchEquals("done", m -> - getContext().stop(getSelf()) - ) - .build(); + .matchEquals("interrupt-child", m -> getContext().stop(child)) + .matchEquals("done", m -> getContext().stop(getSelf())) + .build(); } } -//#my-stopping-actor - +// #my-stopping-actor diff --git a/akka-docs/src/test/java/jdocs/actor/PrintActor.java b/akka-docs/src/test/java/jdocs/actor/PrintActor.java index b611e13502..a2e564a4c3 100644 --- a/akka-docs/src/test/java/jdocs/actor/PrintActor.java +++ b/akka-docs/src/test/java/jdocs/actor/PrintActor.java @@ -11,10 +11,12 @@ class PrintActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(Integer.class, i -> { - System.out.println("PrintActor: " + i); - }) - .build(); + .match( + Integer.class, + i -> { + System.out.println("PrintActor: " + i); + }) + .build(); } } // #print-actor diff --git a/akka-docs/src/test/java/jdocs/actor/SampleActor.java b/akka-docs/src/test/java/jdocs/actor/SampleActor.java index 0e6ea7acc6..d71aa3a099 100644 --- a/akka-docs/src/test/java/jdocs/actor/SampleActor.java +++ b/akka-docs/src/test/java/jdocs/actor/SampleActor.java @@ -4,32 +4,43 @@ package jdocs.actor; -//#sample-actor +// #sample-actor import akka.actor.AbstractActor; public class SampleActor extends AbstractActor { - private Receive guarded = receiveBuilder() - .match(String.class, s -> s.contains("guard"), s -> { - getSender().tell("contains(guard): " + s, getSelf()); - getContext().unbecome(); - }) - .build(); + private Receive guarded = + receiveBuilder() + .match( + String.class, + s -> s.contains("guard"), + s -> { + getSender().tell("contains(guard): " + s, getSelf()); + getContext().unbecome(); + }) + .build(); @Override public Receive createReceive() { return receiveBuilder() - .match(Double.class, d -> { - getSender().tell(d.isNaN() ? 0 : d, getSelf()); - }) - .match(Integer.class, i -> { - getSender().tell(i * 10, getSelf()); - }) - .match(String.class, s -> s.startsWith("guard"), s -> { - getSender().tell("startsWith(guard): " + s.toUpperCase(), getSelf()); - getContext().become(guarded, false); - }) - .build(); + .match( + Double.class, + d -> { + getSender().tell(d.isNaN() ? 0 : d, getSelf()); + }) + .match( + Integer.class, + i -> { + getSender().tell(i * 10, getSelf()); + }) + .match( + String.class, + s -> s.startsWith("guard"), + s -> { + getSender().tell("startsWith(guard): " + s.toUpperCase(), getSelf()); + getContext().become(guarded, false); + }) + .build(); } } -//#sample-actor +// #sample-actor diff --git a/akka-docs/src/test/java/jdocs/actor/SampleActorTest.java b/akka-docs/src/test/java/jdocs/actor/SampleActorTest.java index ed37e84141..151bb223d6 100644 --- a/akka-docs/src/test/java/jdocs/actor/SampleActorTest.java +++ b/akka-docs/src/test/java/jdocs/actor/SampleActorTest.java @@ -31,26 +31,27 @@ public class SampleActorTest extends AbstractJavaTest { } @Test - public void testSampleActor() - { - new TestKit(system) {{ - final ActorRef subject = system.actorOf(Props.create(SampleActor.class), "sample-actor"); - final ActorRef probeRef = getRef(); + public void testSampleActor() { + new TestKit(system) { + { + final ActorRef subject = system.actorOf(Props.create(SampleActor.class), "sample-actor"); + final ActorRef probeRef = getRef(); - subject.tell(47.11, probeRef); - subject.tell("and no guard in the beginning", probeRef); - subject.tell("guard is a good thing", probeRef); - subject.tell(47.11, probeRef); - subject.tell(4711, probeRef); - subject.tell("and no guard in the beginning", probeRef); - subject.tell(4711, probeRef); - subject.tell("and an unmatched message", probeRef); + subject.tell(47.11, probeRef); + subject.tell("and no guard in the beginning", probeRef); + subject.tell("guard is a good thing", probeRef); + subject.tell(47.11, probeRef); + subject.tell(4711, probeRef); + subject.tell("and no guard in the beginning", probeRef); + subject.tell(4711, probeRef); + subject.tell("and an unmatched message", probeRef); - expectMsgEquals(47.11); - assertTrue(expectMsgClass(String.class).startsWith("startsWith(guard):")); - assertTrue(expectMsgClass(String.class).startsWith("contains(guard):")); - expectMsgEquals(47110); - expectNoMessage(); - }}; + expectMsgEquals(47.11); + assertTrue(expectMsgClass(String.class).startsWith("startsWith(guard):")); + assertTrue(expectMsgClass(String.class).startsWith("contains(guard):")); + expectMsgEquals(47110); + expectNoMessage(); + } + }; } } diff --git a/akka-docs/src/test/java/jdocs/actor/SchedulerDocTest.java b/akka-docs/src/test/java/jdocs/actor/SchedulerDocTest.java index 4b7df9493a..e5cfda9520 100644 --- a/akka-docs/src/test/java/jdocs/actor/SchedulerDocTest.java +++ b/akka-docs/src/test/java/jdocs/actor/SchedulerDocTest.java @@ -4,15 +4,15 @@ package jdocs.actor; -//#imports1 +// #imports1 import akka.actor.Props; import jdocs.AbstractJavaTest; import java.time.Duration; -//#imports1 +// #imports1 -//#imports2 +// #imports2 import akka.actor.Cancellable; -//#imports2 +// #imports2 import akka.actor.AbstractActor; import akka.actor.ActorRef; @@ -22,57 +22,66 @@ import akka.testkit.AkkaJUnitActorSystemResource; import org.junit.*; public class SchedulerDocTest extends AbstractJavaTest { - + @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("SchedulerDocTest", - AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("SchedulerDocTest", AkkaSpec.testConf()); private final ActorSystem system = actorSystemResource.getSystem(); private ActorRef testActor = system.actorOf(Props.create(MyActor.class)); @Test public void scheduleOneOffTask() { - //#schedule-one-off-message - system.scheduler().scheduleOnce(Duration.ofMillis(50), - testActor, "foo", system.dispatcher(), null); - //#schedule-one-off-message + // #schedule-one-off-message + system + .scheduler() + .scheduleOnce(Duration.ofMillis(50), testActor, "foo", system.dispatcher(), null); + // #schedule-one-off-message - //#schedule-one-off-thunk - system.scheduler().scheduleOnce(Duration.ofMillis(50), - new Runnable() { - @Override - public void run() { - testActor.tell(System.currentTimeMillis(), ActorRef.noSender()); - } - }, system.dispatcher()); - //#schedule-one-off-thunk + // #schedule-one-off-thunk + system + .scheduler() + .scheduleOnce( + Duration.ofMillis(50), + new Runnable() { + @Override + public void run() { + testActor.tell(System.currentTimeMillis(), ActorRef.noSender()); + } + }, + system.dispatcher()); + // #schedule-one-off-thunk } @Test public void scheduleRecurringTask() { - //#schedule-recurring + // #schedule-recurring class Ticker extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("Tick", m -> { - // Do someting - }) - .build(); + .matchEquals( + "Tick", + m -> { + // Do someting + }) + .build(); } } - + ActorRef tickActor = system.actorOf(Props.create(Ticker.class, this)); - //This will schedule to send the Tick-message - //to the tickActor after 0ms repeating every 50ms - Cancellable cancellable = system.scheduler().schedule(Duration.ZERO, - Duration.ofMillis(50), tickActor, "Tick", - system.dispatcher(), null); + // This will schedule to send the Tick-message + // to the tickActor after 0ms repeating every 50ms + Cancellable cancellable = + system + .scheduler() + .schedule( + Duration.ZERO, Duration.ofMillis(50), tickActor, "Tick", system.dispatcher(), null); - //This cancels further Ticks to be sent + // This cancels further Ticks to be sent cancellable.cancel(); - //#schedule-recurring + // #schedule-recurring system.stop(tickActor); } } diff --git a/akka-docs/src/test/java/jdocs/actor/SeparateDispatcherFutureActor.java b/akka-docs/src/test/java/jdocs/actor/SeparateDispatcherFutureActor.java index 38da4166d9..325479d17c 100644 --- a/akka-docs/src/test/java/jdocs/actor/SeparateDispatcherFutureActor.java +++ b/akka-docs/src/test/java/jdocs/actor/SeparateDispatcherFutureActor.java @@ -16,15 +16,20 @@ class SeparateDispatcherFutureActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(Integer.class, i -> { - System.out.println("Calling blocking Future on separate dispatcher: " + i); - Future f = Futures.future(() -> { - Thread.sleep(5000); - System.out.println("Blocking future finished: " + i); - return i; - }, ec); - }) - .build(); + .match( + Integer.class, + i -> { + System.out.println("Calling blocking Future on separate dispatcher: " + i); + Future f = + Futures.future( + () -> { + Thread.sleep(5000); + System.out.println("Blocking future finished: " + i); + return i; + }, + ec); + }) + .build(); } } -// #separate-dispatcher \ No newline at end of file +// #separate-dispatcher diff --git a/akka-docs/src/test/java/jdocs/actor/SeparateDispatcherTest.java b/akka-docs/src/test/java/jdocs/actor/SeparateDispatcherTest.java index dde950492d..4e3fbcb024 100644 --- a/akka-docs/src/test/java/jdocs/actor/SeparateDispatcherTest.java +++ b/akka-docs/src/test/java/jdocs/actor/SeparateDispatcherTest.java @@ -12,16 +12,16 @@ import com.typesafe.config.ConfigFactory; class SeparateDispatcherTest { public static void main(String args[]) { - Config config = ConfigFactory.parseString( - "my-blocking-dispatcher {\n" + - " type = Dispatcher\n" + - " executor = \"thread-pool-executor\"\n" + - " thread-pool-executor {\n" + - " fixed-pool-size = 16\n" + - " }\n" + - " throughput = 1\n" + - "}\n" - ); + Config config = + ConfigFactory.parseString( + "my-blocking-dispatcher {\n" + + " type = Dispatcher\n" + + " executor = \"thread-pool-executor\"\n" + + " thread-pool-executor {\n" + + " fixed-pool-size = 16\n" + + " }\n" + + " throughput = 1\n" + + "}\n"); ActorSystem system = ActorSystem.create("BlockingDispatcherTest", config); @@ -38,7 +38,7 @@ class SeparateDispatcherTest { Thread.sleep(5000 * 6); } catch (InterruptedException e) { - //swallow the exception + // swallow the exception } finally { system.terminate(); } diff --git a/akka-docs/src/test/java/jdocs/actor/TimerDocTest.java b/akka-docs/src/test/java/jdocs/actor/TimerDocTest.java index aa383a503a..704f900d91 100644 --- a/akka-docs/src/test/java/jdocs/actor/TimerDocTest.java +++ b/akka-docs/src/test/java/jdocs/actor/TimerDocTest.java @@ -4,23 +4,23 @@ package jdocs.actor; -//#timers +// #timers import java.time.Duration; import akka.actor.AbstractActorWithTimers; -//#timers +// #timers public class TimerDocTest { - static - //#timers - public class MyActor extends AbstractActorWithTimers { - + public + // #timers + static class MyActor extends AbstractActorWithTimers { + private static Object TICK_KEY = "TickKey"; - private static final class FirstTick { - } - private static final class Tick { - } + + private static final class FirstTick {} + + private static final class Tick {} public MyActor() { getTimers().startSingleTimer(TICK_KEY, new FirstTick(), Duration.ofMillis(500)); @@ -29,15 +29,19 @@ public class TimerDocTest { @Override public Receive createReceive() { return receiveBuilder() - .match(FirstTick.class, message -> { - // do something useful here - getTimers().startPeriodicTimer(TICK_KEY, new Tick(), Duration.ofSeconds(1)); - }) - .match(Tick.class, message -> { - // do something useful here - }) - .build(); + .match( + FirstTick.class, + message -> { + // do something useful here + getTimers().startPeriodicTimer(TICK_KEY, new Tick(), Duration.ofSeconds(1)); + }) + .match( + Tick.class, + message -> { + // do something useful here + }) + .build(); } } - //#timers + // #timers } diff --git a/akka-docs/src/test/java/jdocs/actor/TypedActorDocTest.java b/akka-docs/src/test/java/jdocs/actor/TypedActorDocTest.java index 3a2f553866..750c984036 100644 --- a/akka-docs/src/test/java/jdocs/actor/TypedActorDocTest.java +++ b/akka-docs/src/test/java/jdocs/actor/TypedActorDocTest.java @@ -4,7 +4,7 @@ package jdocs.actor; -//#imports +// #imports import akka.actor.TypedActor; import akka.actor.*; import akka.japi.*; @@ -20,184 +20,187 @@ import java.util.List; import java.util.ArrayList; import java.util.Random; import akka.routing.RoundRobinGroup; -//#imports +// #imports import org.junit.Test; import static org.junit.Assert.assertEquals; public class TypedActorDocTest extends AbstractJavaTest { - Object someReference = null; - ActorSystem system = null; + Object someReference = null; + ActorSystem system = null; - static - //#typed-actor-iface - public interface Squarer { - //#typed-actor-iface-methods - void squareDontCare(int i); //fire-forget + public + // #typed-actor-iface + static interface Squarer { + // #typed-actor-iface-methods + void squareDontCare(int i); // fire-forget - Future square(int i); //non-blocking send-request-reply + Future square(int i); // non-blocking send-request-reply - Option squareNowPlease(int i);//blocking send-request-reply + Option squareNowPlease(int i); // blocking send-request-reply - int squareNow(int i); //blocking send-request-reply - //#typed-actor-iface-methods + int squareNow(int i); // blocking send-request-reply + // #typed-actor-iface-methods + } + // #typed-actor-iface + + static + // #typed-actor-impl + class SquarerImpl implements Squarer { + private String name; + + public SquarerImpl() { + this.name = "default"; } - //#typed-actor-iface - static - //#typed-actor-impl - class SquarerImpl implements Squarer { - private String name; - - public SquarerImpl() { - this.name = "default"; - } - - public SquarerImpl(String name) { - this.name = name; - } - - //#typed-actor-impl-methods - - public void squareDontCare(int i) { - int sq = i * i; //Nobody cares :( - } - - public Future square(int i) { - return Futures.successful(i * i); - } - - public Option squareNowPlease(int i) { - return Option.some(i * i); - } - - public int squareNow(int i) { - return i * i; - } - //#typed-actor-impl-methods + public SquarerImpl(String name) { + this.name = name; } - //#typed-actor-impl - @Test public void mustGetTheTypedActorExtension() { + // #typed-actor-impl-methods + + public void squareDontCare(int i) { + int sq = i * i; // Nobody cares :( + } + + public Future square(int i) { + return Futures.successful(i * i); + } + + public Option squareNowPlease(int i) { + return Option.some(i * i); + } + + public int squareNow(int i) { + return i * i; + } + // #typed-actor-impl-methods + } + // #typed-actor-impl + + @Test + public void mustGetTheTypedActorExtension() { try { - //#typed-actor-extension-tools + // #typed-actor-extension-tools - //Returns the Typed Actor Extension + // Returns the Typed Actor Extension TypedActorExtension extension = - TypedActor.get(system); //system is an instance of ActorSystem + TypedActor.get(system); // system is an instance of ActorSystem - //Returns whether the reference is a Typed Actor Proxy or not + // Returns whether the reference is a Typed Actor Proxy or not TypedActor.get(system).isTypedActor(someReference); - //Returns the backing Akka Actor behind an external Typed Actor Proxy + // Returns the backing Akka Actor behind an external Typed Actor Proxy TypedActor.get(system).getActorRefFor(someReference); - //Returns the current ActorContext, + // Returns the current ActorContext, // method only valid within methods of a TypedActor implementation ActorContext context = TypedActor.context(); - //Returns the external proxy of the current Typed Actor, + // Returns the external proxy of the current Typed Actor, // method only valid within methods of a TypedActor implementation Squarer sq = TypedActor.self(); - //Returns a contextual instance of the Typed Actor Extension - //this means that if you create other Typed Actors with this, - //they will become children to the current Typed Actor. + // Returns a contextual instance of the Typed Actor Extension + // this means that if you create other Typed Actors with this, + // they will become children to the current Typed Actor. TypedActor.get(TypedActor.context()); - //#typed-actor-extension-tools + // #typed-actor-extension-tools } catch (Exception e) { - //dun care - } - } - @Test public void createATypedActor() { - try { - //#typed-actor-create1 - Squarer mySquarer = - TypedActor.get(system).typedActorOf( - new TypedProps(Squarer.class, SquarerImpl.class)); - //#typed-actor-create1 - //#typed-actor-create2 - Squarer otherSquarer = - TypedActor.get(system).typedActorOf( - new TypedProps(Squarer.class, - new Creator() { - public SquarerImpl create() { return new SquarerImpl("foo"); } - }), - "name"); - //#typed-actor-create2 - - //#typed-actor-calls - //#typed-actor-call-oneway - mySquarer.squareDontCare(10); - //#typed-actor-call-oneway - - //#typed-actor-call-future - Future fSquare = mySquarer.square(10); //A Future[Int] - //#typed-actor-call-future - - //#typed-actor-call-option - Option oSquare = mySquarer.squareNowPlease(10); //Option[Int] - //#typed-actor-call-option - - //#typed-actor-call-strict - int iSquare = mySquarer.squareNow(10); //Int - //#typed-actor-call-strict - //#typed-actor-calls - - assertEquals(100, Await.result(fSquare, - Duration.create(3, TimeUnit.SECONDS)).intValue()); - - assertEquals(100, oSquare.get().intValue()); - - assertEquals(100, iSquare); - - //#typed-actor-stop - TypedActor.get(system).stop(mySquarer); - //#typed-actor-stop - - //#typed-actor-poisonpill - TypedActor.get(system).poisonPill(otherSquarer); - //#typed-actor-poisonpill - } catch(Exception e) { - //Ignore + // dun care } } - @Test public void createHierarchies() { + @Test + public void createATypedActor() { try { - //#typed-actor-hierarchy - Squarer childSquarer = - TypedActor.get(TypedActor.context()). - typedActorOf( - new TypedProps(Squarer.class, SquarerImpl.class) - ); - //Use "childSquarer" as a Squarer - //#typed-actor-hierarchy + // #typed-actor-create1 + Squarer mySquarer = + TypedActor.get(system) + .typedActorOf(new TypedProps(Squarer.class, SquarerImpl.class)); + // #typed-actor-create1 + // #typed-actor-create2 + Squarer otherSquarer = + TypedActor.get(system) + .typedActorOf( + new TypedProps( + Squarer.class, + new Creator() { + public SquarerImpl create() { + return new SquarerImpl("foo"); + } + }), + "name"); + // #typed-actor-create2 + + // #typed-actor-calls + // #typed-actor-call-oneway + mySquarer.squareDontCare(10); + // #typed-actor-call-oneway + + // #typed-actor-call-future + Future fSquare = mySquarer.square(10); // A Future[Int] + // #typed-actor-call-future + + // #typed-actor-call-option + Option oSquare = mySquarer.squareNowPlease(10); // Option[Int] + // #typed-actor-call-option + + // #typed-actor-call-strict + int iSquare = mySquarer.squareNow(10); // Int + // #typed-actor-call-strict + // #typed-actor-calls + + assertEquals(100, Await.result(fSquare, Duration.create(3, TimeUnit.SECONDS)).intValue()); + + assertEquals(100, oSquare.get().intValue()); + + assertEquals(100, iSquare); + + // #typed-actor-stop + TypedActor.get(system).stop(mySquarer); + // #typed-actor-stop + + // #typed-actor-poisonpill + TypedActor.get(system).poisonPill(otherSquarer); + // #typed-actor-poisonpill } catch (Exception e) { - //dun care + // Ignore } } - @Test public void proxyAnyActorRef() { + @Test + public void createHierarchies() { try { - final ActorRef actorRefToRemoteActor = system.deadLetters(); - //#typed-actor-remote - Squarer typedActor = - TypedActor.get(system). - typedActorOf( - new TypedProps(Squarer.class), - actorRefToRemoteActor - ); - //Use "typedActor" as a FooBar - //#typed-actor-remote + // #typed-actor-hierarchy + Squarer childSquarer = + TypedActor.get(TypedActor.context()) + .typedActorOf(new TypedProps(Squarer.class, SquarerImpl.class)); + // Use "childSquarer" as a Squarer + // #typed-actor-hierarchy } catch (Exception e) { - //dun care + // dun care } } - //#typed-router-types + @Test + public void proxyAnyActorRef() { + try { + final ActorRef actorRefToRemoteActor = system.deadLetters(); + // #typed-actor-remote + Squarer typedActor = + TypedActor.get(system) + .typedActorOf(new TypedProps(Squarer.class), actorRefToRemoteActor); + // Use "typedActor" as a FooBar + // #typed-actor-remote + } catch (Exception e) { + // dun care + } + } + + // #typed-router-types interface HasName { String name(); } @@ -205,22 +208,23 @@ public class TypedActorDocTest extends AbstractJavaTest { class Named implements HasName { private int id = new Random().nextInt(1024); - @Override public String name() { return "name-" + id; } + @Override + public String name() { + return "name-" + id; + } } - //#typed-router-types + // #typed-router-types - - @Test public void typedRouterPattern() { + @Test + public void typedRouterPattern() { try { - //#typed-router + // #typed-router // prepare routees TypedActorExtension typed = TypedActor.get(system); - Named named1 = - typed.typedActorOf(new TypedProps(Named.class)); + Named named1 = typed.typedActorOf(new TypedProps(Named.class)); - Named named2 = - typed.typedActorOf(new TypedProps(Named.class)); + Named named2 = typed.typedActorOf(new TypedProps(Named.class)); List routees = new ArrayList(); routees.add(named1); @@ -241,13 +245,13 @@ public class TypedActorDocTest extends AbstractJavaTest { System.out.println("actor was: " + typedRouter.name()); // name-243 System.out.println("actor was: " + typedRouter.name()); // name-614 - //#typed-router + // #typed-router typed.poisonPill(named1); typed.poisonPill(named2); typed.poisonPill(typedRouter); } catch (Exception e) { - //dun care + // dun care } } } diff --git a/akka-docs/src/test/java/jdocs/actor/fsm/Buncher.java b/akka-docs/src/test/java/jdocs/actor/fsm/Buncher.java index a4f2dfffe4..b491f4e082 100644 --- a/akka-docs/src/test/java/jdocs/actor/fsm/Buncher.java +++ b/akka-docs/src/test/java/jdocs/actor/fsm/Buncher.java @@ -4,7 +4,7 @@ package jdocs.actor.fsm; -//#simple-imports +// #simple-imports import akka.actor.AbstractFSM; import akka.actor.ActorRef; import akka.japi.pf.UnitMatch; @@ -12,7 +12,7 @@ import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.time.Duration; -//#simple-imports +// #simple-imports import static jdocs.actor.fsm.Buncher.Data; import static jdocs.actor.fsm.Buncher.State.*; @@ -20,75 +20,100 @@ import static jdocs.actor.fsm.Buncher.State; import static jdocs.actor.fsm.Buncher.Uninitialized.*; import static jdocs.actor.fsm.Events.*; -//#simple-fsm +// #simple-fsm public class Buncher extends AbstractFSM { { - //#fsm-body + // #fsm-body startWith(Idle, Uninitialized); - //#when-syntax - when(Idle, - matchEvent(SetTarget.class, Uninitialized.class, - (setTarget, uninitialized) -> - stay().using(new Todo(setTarget.getRef(), new LinkedList<>())))); - //#when-syntax + // #when-syntax + when( + Idle, + matchEvent( + SetTarget.class, + Uninitialized.class, + (setTarget, uninitialized) -> + stay().using(new Todo(setTarget.getRef(), new LinkedList<>())))); + // #when-syntax - //#transition-elided + // #transition-elided onTransition( - matchState(Active, Idle, () -> { - // reuse this matcher - final UnitMatch m = UnitMatch.create( - matchData(Todo.class, - todo -> todo.getTarget().tell(new Batch(todo.getQueue()), getSelf()))); - m.match(stateData()); - }). - state(Idle, Active, () -> {/* Do something here */})); - //#transition-elided + matchState( + Active, + Idle, + () -> { + // reuse this matcher + final UnitMatch m = + UnitMatch.create( + matchData( + Todo.class, + todo -> + todo.getTarget().tell(new Batch(todo.getQueue()), getSelf()))); + m.match(stateData()); + }) + .state( + Idle, + Active, + () -> { + /* Do something here */ + })); + // #transition-elided - when(Active, Duration.ofSeconds(1L), - matchEvent(Arrays.asList(Flush.class, StateTimeout()), Todo.class, - (event, todo) -> goTo(Idle).using(todo.copy(new LinkedList<>())))); + when( + Active, + Duration.ofSeconds(1L), + matchEvent( + Arrays.asList(Flush.class, StateTimeout()), + Todo.class, + (event, todo) -> goTo(Idle).using(todo.copy(new LinkedList<>())))); - //#unhandled-elided + // #unhandled-elided whenUnhandled( - matchEvent(Queue.class, Todo.class, - (queue, todo) -> goTo(Active).using(todo.addElement(queue.getObj()))). - anyEvent((event, state) -> { - log().warning("received unhandled request {} in state {}/{}", - event, stateName(), state); - return stay(); - })); - //#unhandled-elided + matchEvent( + Queue.class, + Todo.class, + (queue, todo) -> goTo(Active).using(todo.addElement(queue.getObj()))) + .anyEvent( + (event, state) -> { + log() + .warning( + "received unhandled request {} in state {}/{}", + event, + stateName(), + state); + return stay(); + })); + // #unhandled-elided initialize(); - //#fsm-body + // #fsm-body } - //#simple-fsm + // #simple-fsm static - //#simple-state + // #simple-state // states enum State { - Idle, Active + Idle, + Active } - //#simple-state + // #simple-state static - //#simple-state + // #simple-state // state data - interface Data { - } + interface Data {} - //#simple-state + // #simple-state static - //#simple-state + // #simple-state enum Uninitialized implements Data { Uninitialized } - //#simple-state + // #simple-state static - //#simple-state + // #simple-state final class Todo implements Data { private final ActorRef target; private final List queue; @@ -105,14 +130,11 @@ public class Buncher extends AbstractFSM { public List getQueue() { return queue; } - //#boilerplate + // #boilerplate @Override public String toString() { - return "Todo{" + - "target=" + target + - ", queue=" + queue + - '}'; + return "Todo{" + "target=" + target + ", queue=" + queue + '}'; } public Todo addElement(Object element) { @@ -128,9 +150,9 @@ public class Buncher extends AbstractFSM { public Todo copy(ActorRef target) { return new Todo(target, this.queue); } - //#boilerplate + // #boilerplate } - //#simple-state - //#simple-fsm + // #simple-state + // #simple-fsm } -//#simple-fsm +// #simple-fsm diff --git a/akka-docs/src/test/java/jdocs/actor/fsm/BuncherTest.java b/akka-docs/src/test/java/jdocs/actor/fsm/BuncherTest.java index 378c21319b..eaeec5b81f 100644 --- a/akka-docs/src/test/java/jdocs/actor/fsm/BuncherTest.java +++ b/akka-docs/src/test/java/jdocs/actor/fsm/BuncherTest.java @@ -19,7 +19,7 @@ import static jdocs.actor.fsm.Events.Queue; import static jdocs.actor.fsm.Events.SetTarget; import static jdocs.actor.fsm.Events.Flush.Flush; -//#test-code +// #test-code public class BuncherTest extends AbstractJavaTest { static ActorSystem system; @@ -37,42 +37,44 @@ public class BuncherTest extends AbstractJavaTest { @Test public void testBuncherActorBatchesCorrectly() { - new TestKit(system) {{ - final ActorRef buncher = - system.actorOf(Props.create(Buncher.class)); - final ActorRef probe = getRef(); + new TestKit(system) { + { + final ActorRef buncher = system.actorOf(Props.create(Buncher.class)); + final ActorRef probe = getRef(); - buncher.tell(new SetTarget(probe), probe); - buncher.tell(new Queue(42), probe); - buncher.tell(new Queue(43), probe); - LinkedList list1 = new LinkedList<>(); - list1.add(42); - list1.add(43); - expectMsgEquals(new Batch(list1)); - buncher.tell(new Queue(44), probe); - buncher.tell(Flush, probe); - buncher.tell(new Queue(45), probe); - LinkedList list2 = new LinkedList<>(); - list2.add(44); - expectMsgEquals(new Batch(list2)); - LinkedList list3 = new LinkedList<>(); - list3.add(45); - expectMsgEquals(new Batch(list3)); - system.stop(buncher); - }}; + buncher.tell(new SetTarget(probe), probe); + buncher.tell(new Queue(42), probe); + buncher.tell(new Queue(43), probe); + LinkedList list1 = new LinkedList<>(); + list1.add(42); + list1.add(43); + expectMsgEquals(new Batch(list1)); + buncher.tell(new Queue(44), probe); + buncher.tell(Flush, probe); + buncher.tell(new Queue(45), probe); + LinkedList list2 = new LinkedList<>(); + list2.add(44); + expectMsgEquals(new Batch(list2)); + LinkedList list3 = new LinkedList<>(); + list3.add(45); + expectMsgEquals(new Batch(list3)); + system.stop(buncher); + } + }; } @Test public void testBuncherActorDoesntBatchUninitialized() { - new TestKit(system) {{ - final ActorRef buncher = - system.actorOf(Props.create(Buncher.class)); - final ActorRef probe = getRef(); + new TestKit(system) { + { + final ActorRef buncher = system.actorOf(Props.create(Buncher.class)); + final ActorRef probe = getRef(); - buncher.tell(new Queue(42), probe); - expectNoMessage(); - system.stop(buncher); - }}; + buncher.tell(new Queue(42), probe); + expectNoMessage(); + system.stop(buncher); + } + }; } } -//#test-code +// #test-code diff --git a/akka-docs/src/test/java/jdocs/actor/fsm/Events.java b/akka-docs/src/test/java/jdocs/actor/fsm/Events.java index 3742bcdbb8..a2fbd484f3 100644 --- a/akka-docs/src/test/java/jdocs/actor/fsm/Events.java +++ b/akka-docs/src/test/java/jdocs/actor/fsm/Events.java @@ -9,9 +9,9 @@ import java.util.List; public class Events { - static - //#simple-events - public final class SetTarget { + public + // #simple-events + static final class SetTarget { private final ActorRef ref; public SetTarget(ActorRef ref) { @@ -21,21 +21,19 @@ public class Events { public ActorRef getRef() { return ref; } - //#boilerplate + // #boilerplate @Override public String toString() { - return "SetTarget{" + - "ref=" + ref + - '}'; + return "SetTarget{" + "ref=" + ref + '}'; } - //#boilerplate + // #boilerplate } - //#simple-events - static - //#simple-events - public final class Queue { + // #simple-events + public + // #simple-events + static final class Queue { private final Object obj; public Queue(Object obj) { @@ -45,21 +43,19 @@ public class Events { public Object getObj() { return obj; } - //#boilerplate + // #boilerplate @Override public String toString() { - return "Queue{" + - "obj=" + obj + - '}'; + return "Queue{" + "obj=" + obj + '}'; } - //#boilerplate + // #boilerplate } - //#simple-events - static - //#simple-events - public final class Batch { + // #simple-events + public + // #simple-events + static final class Batch { private final List list; public Batch(List list) { @@ -69,7 +65,7 @@ public class Events { public List getList() { return list; } - //#boilerplate + // #boilerplate @Override public boolean equals(Object o) { @@ -89,20 +85,25 @@ public class Events { @Override public String toString() { final StringBuilder builder = new StringBuilder(); - builder.append( "Batch{list="); - list.stream().forEachOrdered(e -> { builder.append(e); builder.append(","); }); + builder.append("Batch{list="); + list.stream() + .forEachOrdered( + e -> { + builder.append(e); + builder.append(","); + }); int len = builder.length(); builder.replace(len, len, "}"); return builder.toString(); } - //#boilerplate + // #boilerplate } - //#simple-events - static - //#simple-events - public enum Flush { + // #simple-events + public + // #simple-events + static enum Flush { Flush } - //#simple-events + // #simple-events } diff --git a/akka-docs/src/test/java/jdocs/actor/fsm/FSMDocTest.java b/akka-docs/src/test/java/jdocs/actor/fsm/FSMDocTest.java index c2e127619a..f9183bee81 100644 --- a/akka-docs/src/test/java/jdocs/actor/fsm/FSMDocTest.java +++ b/akka-docs/src/test/java/jdocs/actor/fsm/FSMDocTest.java @@ -54,126 +54,166 @@ public class FSMDocTest extends AbstractJavaTest { public static class DummyFSM extends AbstractFSM { Integer newData = 42; - //#alt-transition-syntax + // #alt-transition-syntax public void handler(StateType from, StateType to) { // handle transition here } - //#alt-transition-syntax + // #alt-transition-syntax { - //#modifier-syntax - when(SomeState, matchAnyEvent((msg, data) -> { - return goTo(Processing).using(newData). - forMax(Duration.ofSeconds(5)).replying(WillDo); - })); - //#modifier-syntax + // #modifier-syntax + when( + SomeState, + matchAnyEvent( + (msg, data) -> { + return goTo(Processing) + .using(newData) + .forMax(Duration.ofSeconds(5)) + .replying(WillDo); + })); + // #modifier-syntax - //#NullFunction - when(SomeState, AbstractFSM.NullFunction()); - //#NullFunction + // #NullFunction + when(SomeState, AbstractFSM.NullFunction()); + // #NullFunction - //#transition-syntax - onTransition( - matchState(Idle, Active, () -> setTimer("timeout", - Tick, Duration.ofSeconds(1L), true)). - state(Active, null, () -> cancelTimer("timeout")). - state(null, Idle, (f, t) -> log().info("entering Idle from " + f))); - //#transition-syntax + // #transition-syntax + onTransition( + matchState(Idle, Active, () -> setTimer("timeout", Tick, Duration.ofSeconds(1L), true)) + .state(Active, null, () -> cancelTimer("timeout")) + .state(null, Idle, (f, t) -> log().info("entering Idle from " + f))); + // #transition-syntax - //#alt-transition-syntax - onTransition(this::handler); - //#alt-transition-syntax + // #alt-transition-syntax + onTransition(this::handler); + // #alt-transition-syntax - //#stop-syntax - when(Error, matchEventEquals("stop", (event, data) -> { - // do cleanup ... - return stop(); - })); - //#stop-syntax + // #stop-syntax + when( + Error, + matchEventEquals( + "stop", + (event, data) -> { + // do cleanup ... + return stop(); + })); + // #stop-syntax - //#termination-syntax - onTermination( - matchStop(Normal(), - (state, data) -> {/* Do something here */}). - stop(Shutdown(), - (state, data) -> {/* Do something here */}). - stop(Failure.class, - (reason, state, data) -> {/* Do something here */})); - //#termination-syntax + // #termination-syntax + onTermination( + matchStop( + Normal(), + (state, data) -> { + /* Do something here */ + }) + .stop( + Shutdown(), + (state, data) -> { + /* Do something here */ + }) + .stop( + Failure.class, + (reason, state, data) -> { + /* Do something here */ + })); + // #termination-syntax - //#unhandled-syntax - whenUnhandled( - matchEvent(X.class, (x, data) -> { - log().info("Received unhandled event: " + x); - return stay(); - }). - anyEvent((event, data) -> { - log().warning("Received unknown event: " + event); - return goTo(Error); - })); - } - //#unhandled-syntax + // #unhandled-syntax + whenUnhandled( + matchEvent( + X.class, + (x, data) -> { + log().info("Received unhandled event: " + x); + return stay(); + }) + .anyEvent( + (event, data) -> { + log().warning("Received unknown event: " + event); + return goTo(Error); + })); } + // #unhandled-syntax + } - static - //#logging-fsm - public class MyFSM extends AbstractLoggingFSM { - //#body-elided - //#logging-fsm + public + // #logging-fsm + static class MyFSM extends AbstractLoggingFSM { + // #body-elided + // #logging-fsm ActorRef target = null; - //#logging-fsm + // #logging-fsm @Override - public int logDepth() { return 12; } + public int logDepth() { + return 12; + } + { onTermination( - matchStop(Failure.class, (reason, state, data) -> { - String lastEvents = getLog().mkString("\n\t"); - log().warning("Failure in state " + state + " with data " + data + "\n" + - "Events leading up to this point:\n\t" + lastEvents); - //#logging-fsm - target.tell(reason.cause(), getSelf()); - target.tell(state, getSelf()); - target.tell(data, getSelf()); - target.tell(lastEvents, getSelf()); - //#logging-fsm - }) - ); - //... - //#logging-fsm + matchStop( + Failure.class, + (reason, state, data) -> { + String lastEvents = getLog().mkString("\n\t"); + log() + .warning( + "Failure in state " + + state + + " with data " + + data + + "\n" + + "Events leading up to this point:\n\t" + + lastEvents); + // #logging-fsm + target.tell(reason.cause(), getSelf()); + target.tell(state, getSelf()); + target.tell(data, getSelf()); + target.tell(lastEvents, getSelf()); + // #logging-fsm + })); + // ... + // #logging-fsm startWith(SomeState, Data.Foo); - when(SomeState, matchEvent(ActorRef.class, Data.class, (ref, data) -> { - target = ref; - target.tell("going active", getSelf()); - return goTo(Active); - })); - when(Active, matchEventEquals("stop", (event, data) -> { - target.tell("stopping", getSelf()); - return stop(new Failure("This is not the error you're looking for")); - })); + when( + SomeState, + matchEvent( + ActorRef.class, + Data.class, + (ref, data) -> { + target = ref; + target.tell("going active", getSelf()); + return goTo(Active); + })); + when( + Active, + matchEventEquals( + "stop", + (event, data) -> { + target.tell("stopping", getSelf()); + return stop(new Failure("This is not the error you're looking for")); + })); initialize(); - //#logging-fsm + // #logging-fsm } - //#body-elided + // #body-elided } - //#logging-fsm + // #logging-fsm @Test - public void testLoggingFSM() - { - new TestKit(system) {{ - final ActorRef logger = - system.actorOf(Props.create(MyFSM.class)); - final ActorRef probe = getRef(); + public void testLoggingFSM() { + new TestKit(system) { + { + final ActorRef logger = system.actorOf(Props.create(MyFSM.class)); + final ActorRef probe = getRef(); - logger.tell(probe, probe); - expectMsgEquals("going active"); - logger.tell("stop", probe); - expectMsgEquals("stopping"); - expectMsgEquals("This is not the error you're looking for"); - expectMsgEquals(Active); - expectMsgEquals(Data.Foo); - String msg = expectMsgClass(String.class); - assertTrue(msg.startsWith("LogEntry(SomeState,Foo,Actor[akka://FSMDocTest/system/")); - }}; + logger.tell(probe, probe); + expectMsgEquals("going active"); + logger.tell("stop", probe); + expectMsgEquals("stopping"); + expectMsgEquals("This is not the error you're looking for"); + expectMsgEquals(Active); + expectMsgEquals(Data.Foo); + String msg = expectMsgClass(String.class); + assertTrue(msg.startsWith("LogEntry(SomeState,Foo,Actor[akka://FSMDocTest/system/")); + } + }; } } diff --git a/akka-docs/src/test/java/jdocs/actor/io/dns/DnsCompileOnlyDocTest.java b/akka-docs/src/test/java/jdocs/actor/io/dns/DnsCompileOnlyDocTest.java index ed05cad2ee..ef8548e251 100644 --- a/akka-docs/src/test/java/jdocs/actor/io/dns/DnsCompileOnlyDocTest.java +++ b/akka-docs/src/test/java/jdocs/actor/io/dns/DnsCompileOnlyDocTest.java @@ -16,41 +16,40 @@ import scala.Option; import java.time.Duration; import java.util.concurrent.CompletionStage; - public class DnsCompileOnlyDocTest { - public static void example() { - ActorSystem system = ActorSystem.create(); + public static void example() { + ActorSystem system = ActorSystem.create(); - ActorRef actorRef = null; - final Duration timeout = Duration.ofMillis(1000L); + ActorRef actorRef = null; + final Duration timeout = Duration.ofMillis(1000L); - //#resolve - Option initial = Dns.get(system).cache().resolve("google.com", system, actorRef); - Option cached = Dns.get(system).cache().cached("google.com"); - //#resolve - - { - //#actor-api-inet-address - final ActorRef dnsManager = Dns.get(system).manager(); - CompletionStage resolved = ask(dnsManager, new Dns.Resolve("google.com"), timeout); - //#actor-api-inet-address - - } - - { - //#actor-api-async - final ActorRef dnsManager = Dns.get(system).manager(); - CompletionStage resolved = ask(dnsManager, DnsProtocol.resolve("google.com"), timeout); - //#actor-api-async - } - - { - //#srv - final ActorRef dnsManager = Dns.get(system).manager(); - CompletionStage resolved = ask(dnsManager, DnsProtocol.resolve("google.com", DnsProtocol.srvRequestType()), timeout); - //#srv - } + // #resolve + Option initial = Dns.get(system).cache().resolve("google.com", system, actorRef); + Option cached = Dns.get(system).cache().cached("google.com"); + // #resolve + { + // #actor-api-inet-address + final ActorRef dnsManager = Dns.get(system).manager(); + CompletionStage resolved = ask(dnsManager, new Dns.Resolve("google.com"), timeout); + // #actor-api-inet-address } + + { + // #actor-api-async + final ActorRef dnsManager = Dns.get(system).manager(); + CompletionStage resolved = + ask(dnsManager, DnsProtocol.resolve("google.com"), timeout); + // #actor-api-async + } + + { + // #srv + final ActorRef dnsManager = Dns.get(system).manager(); + CompletionStage resolved = + ask(dnsManager, DnsProtocol.resolve("google.com", DnsProtocol.srvRequestType()), timeout); + // #srv + } + } } diff --git a/akka-docs/src/test/java/jdocs/agent/AgentDocTest.java b/akka-docs/src/test/java/jdocs/agent/AgentDocTest.java index 999551e6ba..4944f8ff23 100644 --- a/akka-docs/src/test/java/jdocs/agent/AgentDocTest.java +++ b/akka-docs/src/test/java/jdocs/agent/AgentDocTest.java @@ -11,19 +11,19 @@ import org.junit.Test; import scala.concurrent.Await; import scala.concurrent.duration.Duration; -//#import-agent - import scala.concurrent.ExecutionContext; - import akka.agent.Agent; - import akka.dispatch.ExecutionContexts; -//#import-agent +// #import-agent +import scala.concurrent.ExecutionContext; +import akka.agent.Agent; +import akka.dispatch.ExecutionContexts; +// #import-agent -//#import-function - import akka.dispatch.Mapper; -//#import-function +// #import-function +import akka.dispatch.Mapper; +// #import-function -//#import-future - import scala.concurrent.Future; -//#import-future +// #import-future +import scala.concurrent.Future; +// #import-future public class AgentDocTest extends jdocs.AbstractJavaTest { @@ -31,86 +31,90 @@ public class AgentDocTest extends jdocs.AbstractJavaTest { @Test public void createAndRead() throws Exception { - //#create + // #create ExecutionContext ec = ExecutionContexts.global(); Agent agent = Agent.create(5, ec); - //#create + // #create - //#read-get + // #read-get Integer result = agent.get(); - //#read-get + // #read-get - //#read-future + // #read-future Future future = agent.future(); - //#read-future + // #read-future assertEquals(result, new Integer(5)); - assertEquals(Await.result(future, Duration.create(5,"s")), new Integer(5)); + assertEquals(Await.result(future, Duration.create(5, "s")), new Integer(5)); } @Test public void sendAndSendOffAndReadAwait() throws Exception { Agent agent = Agent.create(5, ec); - //#send + // #send // send a value, enqueues this change // of the value of the Agent agent.send(7); // send a Mapper, enqueues this change // to the value of the Agent - agent.send(new Mapper() { - public Integer apply(Integer i) { - return i * 2; - } - }); - //#send + agent.send( + new Mapper() { + public Integer apply(Integer i) { + return i * 2; + } + }); + // #send - Mapper longRunningOrBlockingFunction = new Mapper() { - public Integer apply(Integer i) { - return i * 1; - } - }; + Mapper longRunningOrBlockingFunction = + new Mapper() { + public Integer apply(Integer i) { + return i * 1; + } + }; ExecutionContext theExecutionContextToExecuteItIn = ec; - //#send-off + // #send-off // sendOff a function - agent.sendOff(longRunningOrBlockingFunction, - theExecutionContextToExecuteItIn); - //#send-off + agent.sendOff(longRunningOrBlockingFunction, theExecutionContextToExecuteItIn); + // #send-off - assertEquals(Await.result(agent.future(), Duration.create(5,"s")), new Integer(14)); + assertEquals(Await.result(agent.future(), Duration.create(5, "s")), new Integer(14)); } - @Test - public void alterAndAlterOff() throws Exception { + @Test + public void alterAndAlterOff() throws Exception { Agent agent = Agent.create(5, ec); - //#alter + // #alter // alter a value Future f1 = agent.alter(7); // alter a function (Mapper) - Future f2 = agent.alter(new Mapper() { - public Integer apply(Integer i) { - return i * 2; - } - }); - //#alter + Future f2 = + agent.alter( + new Mapper() { + public Integer apply(Integer i) { + return i * 2; + } + }); + // #alter - Mapper longRunningOrBlockingFunction = new Mapper() { - public Integer apply(Integer i) { + Mapper longRunningOrBlockingFunction = + new Mapper() { + public Integer apply(Integer i) { return i * 1; - } - }; + } + }; ExecutionContext theExecutionContextToExecuteItIn = ec; - //#alter-off + // #alter-off // alterOff a function (Mapper) - Future f3 = agent.alterOff(longRunningOrBlockingFunction, - theExecutionContextToExecuteItIn); - //#alter-off + Future f3 = + agent.alterOff(longRunningOrBlockingFunction, theExecutionContextToExecuteItIn); + // #alter-off - assertEquals(Await.result(f3, Duration.create(5,"s")), new Integer(14)); - } + assertEquals(Await.result(f3, Duration.create(5, "s")), new Integer(14)); + } } diff --git a/akka-docs/src/test/java/jdocs/camel/ActivationTestBase.java b/akka-docs/src/test/java/jdocs/camel/ActivationTestBase.java index ac2cca5020..4ce572fc9b 100644 --- a/akka-docs/src/test/java/jdocs/camel/ActivationTestBase.java +++ b/akka-docs/src/test/java/jdocs/camel/ActivationTestBase.java @@ -3,20 +3,20 @@ */ package jdocs.camel; -//#CamelActivation - import akka.actor.ActorRef; - import akka.actor.ActorSystem; - import akka.actor.Props; - import akka.camel.Camel; - import akka.camel.CamelExtension; - import akka.camel.javaapi.UntypedConsumerActor; - import akka.testkit.javadsl.TestKit; - import akka.util.Timeout; - import jdocs.AbstractJavaTest; - import scala.concurrent.Future; - import scala.concurrent.duration.Duration; - import static java.util.concurrent.TimeUnit.SECONDS; -//#CamelActivation +// #CamelActivation +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import akka.camel.Camel; +import akka.camel.CamelExtension; +import akka.camel.javaapi.UntypedConsumerActor; +import akka.testkit.javadsl.TestKit; +import akka.util.Timeout; +import jdocs.AbstractJavaTest; +import scala.concurrent.Future; +import scala.concurrent.duration.Duration; +import static java.util.concurrent.TimeUnit.SECONDS; +// #CamelActivation import org.junit.Test; @@ -25,25 +25,25 @@ public class ActivationTestBase extends AbstractJavaTest { @SuppressWarnings("unused") @Test public void testActivation() { - //#CamelActivation + // #CamelActivation // .. ActorSystem system = ActorSystem.create("some-system"); Props props = Props.create(MyConsumer.class); - ActorRef producer = system.actorOf(props,"myproducer"); + ActorRef producer = system.actorOf(props, "myproducer"); Camel camel = CamelExtension.get(system); // get a future reference to the activation of the endpoint of the Consumer Actor Timeout timeout = new Timeout(Duration.create(10, SECONDS)); - Future activationFuture = camel.activationFutureFor(producer, - timeout, system.dispatcher()); - //#CamelActivation - //#CamelDeactivation + Future activationFuture = + camel.activationFutureFor(producer, timeout, system.dispatcher()); + // #CamelActivation + // #CamelDeactivation // .. system.stop(producer); // get a future reference to the deactivation of the endpoint of the Consumer Actor - Future deactivationFuture = camel.deactivationFutureFor(producer, - timeout, system.dispatcher()); - //#CamelDeactivation + Future deactivationFuture = + camel.deactivationFutureFor(producer, timeout, system.dispatcher()); + // #CamelDeactivation TestKit.shutdownActorSystem(system); } @@ -52,7 +52,6 @@ public class ActivationTestBase extends AbstractJavaTest { return "direct:test"; } - public void onReceive(Object message) { - } + public void onReceive(Object message) {} } } diff --git a/akka-docs/src/test/java/jdocs/camel/CamelExtensionTest.java b/akka-docs/src/test/java/jdocs/camel/CamelExtensionTest.java index fdf1f640e9..041fe3909c 100644 --- a/akka-docs/src/test/java/jdocs/camel/CamelExtensionTest.java +++ b/akka-docs/src/test/java/jdocs/camel/CamelExtensionTest.java @@ -16,23 +16,23 @@ import org.junit.Test; public class CamelExtensionTest extends AbstractJavaTest { @Test public void getCamelExtension() { - //#CamelExtension + // #CamelExtension ActorSystem system = ActorSystem.create("some-system"); Camel camel = CamelExtension.get(system); CamelContext camelContext = camel.context(); ProducerTemplate producerTemplate = camel.template(); - //#CamelExtension + // #CamelExtension TestKit.shutdownActorSystem(system); } + public void addActiveMQComponent() { - //#CamelExtensionAddComponent + // #CamelExtensionAddComponent ActorSystem system = ActorSystem.create("some-system"); Camel camel = CamelExtension.get(system); CamelContext camelContext = camel.context(); // camelContext.addComponent("activemq", ActiveMQComponent.activeMQComponent( // "vm://localhost?broker.persistent=false")); - //#CamelExtensionAddComponent + // #CamelExtensionAddComponent TestKit.shutdownActorSystem(system); } - } diff --git a/akka-docs/src/test/java/jdocs/camel/Consumer1.java b/akka-docs/src/test/java/jdocs/camel/Consumer1.java index f9def24eae..418ed9bd35 100644 --- a/akka-docs/src/test/java/jdocs/camel/Consumer1.java +++ b/akka-docs/src/test/java/jdocs/camel/Consumer1.java @@ -3,7 +3,7 @@ */ package jdocs.camel; -//#Consumer1 +// #Consumer1 import akka.camel.CamelMessage; import akka.camel.javaapi.UntypedConsumerActor; import akka.event.Logging; @@ -21,8 +21,7 @@ public class Consumer1 extends UntypedConsumerActor { CamelMessage camelMessage = (CamelMessage) message; String body = camelMessage.getBodyAs(String.class, getCamelContext()); log.info("Received message: {}", body); - } else - unhandled(message); + } else unhandled(message); } } -//#Consumer1 +// #Consumer1 diff --git a/akka-docs/src/test/java/jdocs/camel/Consumer2.java b/akka-docs/src/test/java/jdocs/camel/Consumer2.java index cb46fc4262..bbace1c693 100644 --- a/akka-docs/src/test/java/jdocs/camel/Consumer2.java +++ b/akka-docs/src/test/java/jdocs/camel/Consumer2.java @@ -3,7 +3,7 @@ */ package jdocs.camel; -//#Consumer2 +// #Consumer2 import akka.camel.CamelMessage; import akka.camel.javaapi.UntypedConsumerActor; @@ -16,9 +16,8 @@ public class Consumer2 extends UntypedConsumerActor { if (message instanceof CamelMessage) { CamelMessage camelMessage = (CamelMessage) message; String body = camelMessage.getBodyAs(String.class, getCamelContext()); - getSender().tell(String.format("Received message: %s",body), getSelf()); - } else - unhandled(message); + getSender().tell(String.format("Received message: %s", body), getSelf()); + } else unhandled(message); } } -//#Consumer2 +// #Consumer2 diff --git a/akka-docs/src/test/java/jdocs/camel/Consumer3.java b/akka-docs/src/test/java/jdocs/camel/Consumer3.java index 4c712f08a3..d1f78dfe01 100644 --- a/akka-docs/src/test/java/jdocs/camel/Consumer3.java +++ b/akka-docs/src/test/java/jdocs/camel/Consumer3.java @@ -3,13 +3,13 @@ */ package jdocs.camel; -//#Consumer3 +// #Consumer3 import akka.actor.Status; import akka.camel.Ack; import akka.camel.CamelMessage; import akka.camel.javaapi.UntypedConsumerActor; -public class Consumer3 extends UntypedConsumerActor{ +public class Consumer3 extends UntypedConsumerActor { @Override public boolean autoAck() { @@ -28,8 +28,7 @@ public class Consumer3 extends UntypedConsumerActor{ Exception someException = new Exception("e1"); // on failure getSender().tell(new Status.Failure(someException), getSelf()); - } else - unhandled(message); + } else unhandled(message); } } -//#Consumer3 +// #Consumer3 diff --git a/akka-docs/src/test/java/jdocs/camel/Consumer4.java b/akka-docs/src/test/java/jdocs/camel/Consumer4.java index 132afa57cd..54fd1f159e 100644 --- a/akka-docs/src/test/java/jdocs/camel/Consumer4.java +++ b/akka-docs/src/test/java/jdocs/camel/Consumer4.java @@ -3,7 +3,7 @@ */ package jdocs.camel; -//#Consumer4 +// #Consumer4 import akka.camel.CamelMessage; import akka.camel.javaapi.UntypedConsumerActor; import scala.concurrent.duration.Duration; @@ -12,8 +12,7 @@ import scala.concurrent.duration.FiniteDuration; import java.util.concurrent.TimeUnit; public class Consumer4 extends UntypedConsumerActor { - private final static FiniteDuration timeout = - Duration.create(500, TimeUnit.MILLISECONDS); + private static final FiniteDuration timeout = Duration.create(500, TimeUnit.MILLISECONDS); @Override public FiniteDuration replyTimeout() { @@ -28,9 +27,8 @@ public class Consumer4 extends UntypedConsumerActor { if (message instanceof CamelMessage) { CamelMessage camelMessage = (CamelMessage) message; String body = camelMessage.getBodyAs(String.class, getCamelContext()); - getSender().tell(String.format("Hello %s",body), getSelf()); - } else - unhandled(message); + getSender().tell(String.format("Hello %s", body), getSelf()); + } else unhandled(message); } } -//#Consumer4 \ No newline at end of file +// #Consumer4 diff --git a/akka-docs/src/test/java/jdocs/camel/CustomRouteBuilder.java b/akka-docs/src/test/java/jdocs/camel/CustomRouteBuilder.java index 4f1acdb708..bebeb449a6 100644 --- a/akka-docs/src/test/java/jdocs/camel/CustomRouteBuilder.java +++ b/akka-docs/src/test/java/jdocs/camel/CustomRouteBuilder.java @@ -3,12 +3,12 @@ */ package jdocs.camel; -//#CustomRoute +// #CustomRoute import akka.actor.ActorRef; import akka.camel.internal.component.CamelPath; import org.apache.camel.builder.RouteBuilder; -public class CustomRouteBuilder extends RouteBuilder{ +public class CustomRouteBuilder extends RouteBuilder { private String uri; public CustomRouteBuilder(ActorRef responder) { @@ -19,4 +19,4 @@ public class CustomRouteBuilder extends RouteBuilder{ from("jetty:http://localhost:8877/camel/custom").to(uri); } } -//#CustomRoute +// #CustomRoute diff --git a/akka-docs/src/test/java/jdocs/camel/CustomRouteTestBase.java b/akka-docs/src/test/java/jdocs/camel/CustomRouteTestBase.java index 34678c141c..b05978f00e 100644 --- a/akka-docs/src/test/java/jdocs/camel/CustomRouteTestBase.java +++ b/akka-docs/src/test/java/jdocs/camel/CustomRouteTestBase.java @@ -12,14 +12,14 @@ import akka.camel.CamelExtension; import akka.testkit.javadsl.TestKit; public class CustomRouteTestBase { - public void customRoute() throws Exception{ - //#CustomRoute + public void customRoute() throws Exception { + // #CustomRoute ActorSystem system = ActorSystem.create("some-system"); try { Camel camel = CamelExtension.get(system); ActorRef responder = system.actorOf(Props.create(Responder.class), "TestResponder"); camel.context().addRoutes(new CustomRouteBuilder(responder)); - //#CustomRoute + // #CustomRoute } finally { TestKit.shutdownActorSystem(system); } diff --git a/akka-docs/src/test/java/jdocs/camel/ErrorThrowingConsumer.java b/akka-docs/src/test/java/jdocs/camel/ErrorThrowingConsumer.java index ce83812c75..f77a6cfb2f 100644 --- a/akka-docs/src/test/java/jdocs/camel/ErrorThrowingConsumer.java +++ b/akka-docs/src/test/java/jdocs/camel/ErrorThrowingConsumer.java @@ -3,7 +3,7 @@ */ package jdocs.camel; -//#ErrorThrowingConsumer +// #ErrorThrowingConsumer import akka.actor.Status; import akka.camel.CamelMessage; import akka.camel.javaapi.UntypedConsumerActor; @@ -13,20 +13,22 @@ import org.apache.camel.model.ProcessorDefinition; import org.apache.camel.model.RouteDefinition; import scala.Option; -public class ErrorThrowingConsumer extends UntypedConsumerActor{ +public class ErrorThrowingConsumer extends UntypedConsumerActor { private String uri; private static Mapper> mapper = - new Mapper>() { - public ProcessorDefinition apply(RouteDefinition rd) { - // Catch any exception and handle it by returning the exception message - // as response - return rd.onException(Exception.class).handled(true). - transform(Builder.exceptionMessage()).end(); - } - }; + new Mapper>() { + public ProcessorDefinition apply(RouteDefinition rd) { + // Catch any exception and handle it by returning the exception message + // as response + return rd.onException(Exception.class) + .handled(true) + .transform(Builder.exceptionMessage()) + .end(); + } + }; - public ErrorThrowingConsumer(String uri){ + public ErrorThrowingConsumer(String uri) { this.uri = uri; } @@ -34,18 +36,16 @@ public class ErrorThrowingConsumer extends UntypedConsumerActor{ return uri; } - public void onReceive(Object message) throws Exception{ + public void onReceive(Object message) throws Exception { if (message instanceof CamelMessage) { CamelMessage camelMessage = (CamelMessage) message; String body = camelMessage.getBodyAs(String.class, getCamelContext()); - throw new Exception(String.format("error: %s",body)); - } else - unhandled(message); + throw new Exception(String.format("error: %s", body)); + } else unhandled(message); } @Override - public Mapper> getRouteDefinitionHandler() { + public Mapper> getRouteDefinitionHandler() { return mapper; } @@ -54,4 +54,4 @@ public class ErrorThrowingConsumer extends UntypedConsumerActor{ getSender().tell(new Status.Failure(reason), getSelf()); } } -//#ErrorThrowingConsumer \ No newline at end of file +// #ErrorThrowingConsumer diff --git a/akka-docs/src/test/java/jdocs/camel/FirstProducer.java b/akka-docs/src/test/java/jdocs/camel/FirstProducer.java index cc28a537ab..d2e24184f2 100644 --- a/akka-docs/src/test/java/jdocs/camel/FirstProducer.java +++ b/akka-docs/src/test/java/jdocs/camel/FirstProducer.java @@ -4,11 +4,12 @@ package jdocs.camel; -//#Producer1 +// #Producer1 import akka.camel.javaapi.UntypedProducerActor; + public class FirstProducer extends UntypedProducerActor { public String getEndpointUri() { return "http://localhost:8080/news"; } } -//#Producer1 \ No newline at end of file +// #Producer1 diff --git a/akka-docs/src/test/java/jdocs/camel/Forwarder.java b/akka-docs/src/test/java/jdocs/camel/Forwarder.java index efb566e62e..854e6d357c 100644 --- a/akka-docs/src/test/java/jdocs/camel/Forwarder.java +++ b/akka-docs/src/test/java/jdocs/camel/Forwarder.java @@ -3,7 +3,7 @@ */ package jdocs.camel; -//#RouteResponse +// #RouteResponse import akka.actor.ActorRef; import akka.camel.javaapi.UntypedProducerActor; @@ -25,4 +25,4 @@ public class Forwarder extends UntypedProducerActor { target.forward(message, getContext()); } } -//#RouteResponse +// #RouteResponse diff --git a/akka-docs/src/test/java/jdocs/camel/MyActor.java b/akka-docs/src/test/java/jdocs/camel/MyActor.java index a615df6892..419dfc2f5e 100644 --- a/akka-docs/src/test/java/jdocs/camel/MyActor.java +++ b/akka-docs/src/test/java/jdocs/camel/MyActor.java @@ -3,7 +3,7 @@ */ package jdocs.camel; -//#ProducerTemplate +// #ProducerTemplate import akka.actor.UntypedAbstractActor; import akka.camel.Camel; import akka.camel.CamelExtension; @@ -16,4 +16,4 @@ public class MyActor extends UntypedAbstractActor { template.sendBody("direct:news", message); } } -//#ProducerTemplate \ No newline at end of file +// #ProducerTemplate diff --git a/akka-docs/src/test/java/jdocs/camel/MyEndpoint.java b/akka-docs/src/test/java/jdocs/camel/MyEndpoint.java index 165cd908bf..7db8164306 100644 --- a/akka-docs/src/test/java/jdocs/camel/MyEndpoint.java +++ b/akka-docs/src/test/java/jdocs/camel/MyEndpoint.java @@ -4,11 +4,11 @@ package jdocs.camel; -//#Consumer-mina +// #Consumer-mina import akka.camel.CamelMessage; import akka.camel.javaapi.UntypedConsumerActor; -public class MyEndpoint extends UntypedConsumerActor{ +public class MyEndpoint extends UntypedConsumerActor { private String uri; public String getEndpointUri() { @@ -18,8 +18,7 @@ public class MyEndpoint extends UntypedConsumerActor{ public void onReceive(Object message) throws Exception { if (message instanceof CamelMessage) { /* ... */ - } else - unhandled(message); + } else unhandled(message); } // Extra constructor to change the default uri, @@ -32,4 +31,4 @@ public class MyEndpoint extends UntypedConsumerActor{ this.uri = "mina2:tcp://localhost:6200?textline=true"; } } -//#Consumer-mina \ No newline at end of file +// #Consumer-mina diff --git a/akka-docs/src/test/java/jdocs/camel/OnRouteResponseTestBase.java b/akka-docs/src/test/java/jdocs/camel/OnRouteResponseTestBase.java index bca0ca12ff..2f589adad4 100644 --- a/akka-docs/src/test/java/jdocs/camel/OnRouteResponseTestBase.java +++ b/akka-docs/src/test/java/jdocs/camel/OnRouteResponseTestBase.java @@ -9,17 +9,17 @@ import akka.testkit.javadsl.TestKit; public class OnRouteResponseTestBase { - public void onRouteResponse(){ - //#RouteResponse + public void onRouteResponse() { + // #RouteResponse ActorSystem system = ActorSystem.create("some-system"); Props receiverProps = Props.create(ResponseReceiver.class); - final ActorRef receiver = system.actorOf(receiverProps,"responseReceiver"); - ActorRef forwardResponse = system.actorOf(Props.create( - Forwarder.class, "http://localhost:8080/news/akka", receiver)); + final ActorRef receiver = system.actorOf(receiverProps, "responseReceiver"); + ActorRef forwardResponse = + system.actorOf(Props.create(Forwarder.class, "http://localhost:8080/news/akka", receiver)); // the Forwarder sends out a request to the web page and forwards the response to // the ResponseReceiver forwardResponse.tell("some request", ActorRef.noSender()); - //#RouteResponse + // #RouteResponse system.stop(receiver); system.stop(forwardResponse); TestKit.shutdownActorSystem(system); diff --git a/akka-docs/src/test/java/jdocs/camel/OnewaySender.java b/akka-docs/src/test/java/jdocs/camel/OnewaySender.java index 53557d94ea..15ac577eba 100644 --- a/akka-docs/src/test/java/jdocs/camel/OnewaySender.java +++ b/akka-docs/src/test/java/jdocs/camel/OnewaySender.java @@ -3,15 +3,16 @@ */ package jdocs.camel; -//#Oneway +// #Oneway import akka.camel.javaapi.UntypedProducerActor; -public class OnewaySender extends UntypedProducerActor{ +public class OnewaySender extends UntypedProducerActor { private String uri; public OnewaySender(String uri) { this.uri = uri; } + public String getEndpointUri() { return uri; } @@ -21,4 +22,4 @@ public class OnewaySender extends UntypedProducerActor{ return true; } } -//#Oneway +// #Oneway diff --git a/akka-docs/src/test/java/jdocs/camel/Orders.java b/akka-docs/src/test/java/jdocs/camel/Orders.java index d931e11be5..219b102b50 100644 --- a/akka-docs/src/test/java/jdocs/camel/Orders.java +++ b/akka-docs/src/test/java/jdocs/camel/Orders.java @@ -3,7 +3,7 @@ */ package jdocs.camel; -//#Producer +// #Producer import akka.camel.javaapi.UntypedProducerActor; public class Orders extends UntypedProducerActor { @@ -11,4 +11,4 @@ public class Orders extends UntypedProducerActor { return "jms:queue:Orders"; } } -//#Producer \ No newline at end of file +// #Producer diff --git a/akka-docs/src/test/java/jdocs/camel/Producer1.java b/akka-docs/src/test/java/jdocs/camel/Producer1.java index ae81e40ea8..3e2788620d 100644 --- a/akka-docs/src/test/java/jdocs/camel/Producer1.java +++ b/akka-docs/src/test/java/jdocs/camel/Producer1.java @@ -3,7 +3,7 @@ */ package jdocs.camel; -//#Producer1 +// #Producer1 import akka.camel.javaapi.UntypedProducerActor; public class Producer1 extends UntypedProducerActor { @@ -11,4 +11,4 @@ public class Producer1 extends UntypedProducerActor { return "http://localhost:8080/news"; } } -//#Producer1 \ No newline at end of file +// #Producer1 diff --git a/akka-docs/src/test/java/jdocs/camel/ProducerTestBase.java b/akka-docs/src/test/java/jdocs/camel/ProducerTestBase.java index 94feb351c9..beacde3d13 100644 --- a/akka-docs/src/test/java/jdocs/camel/ProducerTestBase.java +++ b/akka-docs/src/test/java/jdocs/camel/ProducerTestBase.java @@ -18,39 +18,39 @@ import akka.camel.CamelMessage; public class ProducerTestBase { public void tellJmsProducer() { - //#TellProducer + // #TellProducer ActorSystem system = ActorSystem.create("some-system"); Props props = Props.create(Orders.class); ActorRef producer = system.actorOf(props, "jmsproducer"); - producer.tell("", - ActorRef.noSender()); - //#TellProducer + producer.tell("", ActorRef.noSender()); + // #TellProducer TestKit.shutdownActorSystem(system); } @SuppressWarnings("unused") public void askProducer() { - //#AskProducer + // #AskProducer ActorSystem system = ActorSystem.create("some-system"); Props props = Props.create(FirstProducer.class); - ActorRef producer = system.actorOf(props,"myproducer"); - CompletionStage future = Patterns.ask(producer, "some request", - Duration.ofMillis(1000L)); - //#AskProducer + ActorRef producer = system.actorOf(props, "myproducer"); + CompletionStage future = + Patterns.ask(producer, "some request", Duration.ofMillis(1000L)); + // #AskProducer system.stop(producer); TestKit.shutdownActorSystem(system); } - public void correlate(){ - //#Correlate + public void correlate() { + // #Correlate ActorSystem system = ActorSystem.create("some-system"); Props props = Props.create(Orders.class); - ActorRef producer = system.actorOf(props,"jmsproducer"); - Map headers = new HashMap(); - headers.put(CamelMessage.MessageExchangeId(),"123"); - producer.tell(new CamelMessage("",headers), ActorRef.noSender()); - //#Correlate + ActorRef producer = system.actorOf(props, "jmsproducer"); + Map headers = new HashMap(); + headers.put(CamelMessage.MessageExchangeId(), "123"); + producer.tell( + new CamelMessage("", headers), + ActorRef.noSender()); + // #Correlate system.stop(producer); TestKit.shutdownActorSystem(system); } diff --git a/akka-docs/src/test/java/jdocs/camel/RequestBodyActor.java b/akka-docs/src/test/java/jdocs/camel/RequestBodyActor.java index e51970183d..817f7b8928 100644 --- a/akka-docs/src/test/java/jdocs/camel/RequestBodyActor.java +++ b/akka-docs/src/test/java/jdocs/camel/RequestBodyActor.java @@ -3,7 +3,7 @@ */ package jdocs.camel; -//#RequestProducerTemplate +// #RequestProducerTemplate import akka.actor.AbstractActor; import akka.camel.Camel; import akka.camel.CamelExtension; @@ -13,12 +13,13 @@ public class RequestBodyActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .matchAny(message -> { - Camel camel = CamelExtension.get(getContext().getSystem()); - ProducerTemplate template = camel.template(); - getSender().tell(template.requestBody("direct:news", message), getSelf()); - }) - .build(); + .matchAny( + message -> { + Camel camel = CamelExtension.get(getContext().getSystem()); + ProducerTemplate template = camel.template(); + getSender().tell(template.requestBody("direct:news", message), getSelf()); + }) + .build(); } } -//#RequestProducerTemplate \ No newline at end of file +// #RequestProducerTemplate diff --git a/akka-docs/src/test/java/jdocs/camel/Responder.java b/akka-docs/src/test/java/jdocs/camel/Responder.java index a5182e1001..4e79a12e1e 100644 --- a/akka-docs/src/test/java/jdocs/camel/Responder.java +++ b/akka-docs/src/test/java/jdocs/camel/Responder.java @@ -3,28 +3,28 @@ */ package jdocs.camel; -//#CustomRoute +// #CustomRoute import akka.actor.UntypedAbstractActor; import akka.camel.CamelMessage; import akka.dispatch.Mapper; -public class Responder extends UntypedAbstractActor{ +public class Responder extends UntypedAbstractActor { public void onReceive(Object message) { if (message instanceof CamelMessage) { CamelMessage camelMessage = (CamelMessage) message; getSender().tell(createResponse(camelMessage), getSelf()); - } else - unhandled(message); + } else unhandled(message); } private CamelMessage createResponse(CamelMessage msg) { - return msg.mapBody(new Mapper() { - @Override - public String apply(String body) { - return String.format("received %s", body); - } - }); + return msg.mapBody( + new Mapper() { + @Override + public String apply(String body) { + return String.format("received %s", body); + } + }); } } -//#CustomRoute \ No newline at end of file +// #CustomRoute diff --git a/akka-docs/src/test/java/jdocs/camel/ResponseReceiver.java b/akka-docs/src/test/java/jdocs/camel/ResponseReceiver.java index 156e5dc9a6..efdd75860c 100644 --- a/akka-docs/src/test/java/jdocs/camel/ResponseReceiver.java +++ b/akka-docs/src/test/java/jdocs/camel/ResponseReceiver.java @@ -3,15 +3,15 @@ */ package jdocs.camel; -//#RouteResponse +// #RouteResponse import akka.actor.UntypedAbstractActor; import akka.camel.CamelMessage; -public class ResponseReceiver extends UntypedAbstractActor{ +public class ResponseReceiver extends UntypedAbstractActor { public void onReceive(Object message) { - if(message instanceof CamelMessage) { - // do something with the forwarded response - } + if (message instanceof CamelMessage) { + // do something with the forwarded response + } } } -//#RouteResponse +// #RouteResponse diff --git a/akka-docs/src/test/java/jdocs/camel/Transformer.java b/akka-docs/src/test/java/jdocs/camel/Transformer.java index 14dd62fb04..a18cf7781b 100644 --- a/akka-docs/src/test/java/jdocs/camel/Transformer.java +++ b/akka-docs/src/test/java/jdocs/camel/Transformer.java @@ -3,12 +3,12 @@ */ package jdocs.camel; -//#TransformOutgoingMessage +// #TransformOutgoingMessage import akka.camel.CamelMessage; import akka.camel.javaapi.UntypedProducerActor; import akka.dispatch.Mapper; -public class Transformer extends UntypedProducerActor{ +public class Transformer extends UntypedProducerActor { private String uri; public Transformer(String uri) { @@ -20,17 +20,18 @@ public class Transformer extends UntypedProducerActor{ } private CamelMessage upperCase(CamelMessage msg) { - return msg.mapBody(new Mapper() { - @Override - public String apply(String body) { - return body.toUpperCase(); - } - }); + return msg.mapBody( + new Mapper() { + @Override + public String apply(String body) { + return body.toUpperCase(); + } + }); } @Override public Object onTransformOutgoingMessage(Object message) { - if(message instanceof CamelMessage) { + if (message instanceof CamelMessage) { CamelMessage camelMessage = (CamelMessage) message; return upperCase(camelMessage); } else { @@ -38,4 +39,4 @@ public class Transformer extends UntypedProducerActor{ } } } -//#TransformOutgoingMessage +// #TransformOutgoingMessage diff --git a/akka-docs/src/test/java/jdocs/circuitbreaker/DangerousJavaActor.java b/akka-docs/src/test/java/jdocs/circuitbreaker/DangerousJavaActor.java index a8740d4a81..5d62379ed6 100644 --- a/akka-docs/src/test/java/jdocs/circuitbreaker/DangerousJavaActor.java +++ b/akka-docs/src/test/java/jdocs/circuitbreaker/DangerousJavaActor.java @@ -4,7 +4,7 @@ package jdocs.circuitbreaker; -//#imports1 +// #imports1 import akka.actor.AbstractActor; import akka.event.LoggingAdapter; @@ -16,45 +16,55 @@ import static akka.pattern.Patterns.pipe; import java.util.concurrent.CompletableFuture; -//#imports1 +// #imports1 -//#circuit-breaker-initialization +// #circuit-breaker-initialization public class DangerousJavaActor extends AbstractActor { private final CircuitBreaker breaker; private final LoggingAdapter log = Logging.getLogger(getContext().system(), this); public DangerousJavaActor() { - this.breaker = new CircuitBreaker( - getContext().getDispatcher(), getContext().getSystem().getScheduler(), - 5, Duration.ofSeconds(10), Duration.ofMinutes(1)) - .addOnOpenListener(this::notifyMeOnOpen); + this.breaker = + new CircuitBreaker( + getContext().getDispatcher(), + getContext().getSystem().getScheduler(), + 5, + Duration.ofSeconds(10), + Duration.ofMinutes(1)) + .addOnOpenListener(this::notifyMeOnOpen); } public void notifyMeOnOpen() { log.warning("My CircuitBreaker is now open, and will not close for one minute"); } -//#circuit-breaker-initialization + // #circuit-breaker-initialization - //#circuit-breaker-usage + // #circuit-breaker-usage public String dangerousCall() { return "This really isn't that dangerous of a call after all"; } @Override public Receive createReceive() { - return receiveBuilder(). - match(String.class, "is my middle name"::equals, m -> pipe( - breaker.callWithCircuitBreakerCS(() -> - CompletableFuture.supplyAsync(this::dangerousCall) - ), getContext().getDispatcher() - ).to(sender())) - .match(String.class, "block for me"::equals, m -> { - sender().tell(breaker - .callWithSyncCircuitBreaker(this::dangerousCall), self()); - }) - .build(); + return receiveBuilder() + .match( + String.class, + "is my middle name"::equals, + m -> + pipe( + breaker.callWithCircuitBreakerCS( + () -> CompletableFuture.supplyAsync(this::dangerousCall)), + getContext().getDispatcher()) + .to(sender())) + .match( + String.class, + "block for me"::equals, + m -> { + sender().tell(breaker.callWithSyncCircuitBreaker(this::dangerousCall), self()); + }) + .build(); } -//#circuit-breaker-usage + // #circuit-breaker-usage } diff --git a/akka-docs/src/test/java/jdocs/circuitbreaker/EvenNoFailureJavaExample.java b/akka-docs/src/test/java/jdocs/circuitbreaker/EvenNoFailureJavaExample.java index 2c6912777f..6cbcdd06a7 100644 --- a/akka-docs/src/test/java/jdocs/circuitbreaker/EvenNoFailureJavaExample.java +++ b/akka-docs/src/test/java/jdocs/circuitbreaker/EvenNoFailureJavaExample.java @@ -12,26 +12,30 @@ import java.util.Optional; import java.util.function.BiFunction; public class EvenNoFailureJavaExample extends AbstractActor { - //#even-no-as-failure - private final CircuitBreaker breaker; + // #even-no-as-failure + private final CircuitBreaker breaker; - public EvenNoFailureJavaExample() { - this.breaker = new CircuitBreaker( - getContext().getDispatcher(), getContext().getSystem().getScheduler(), - 5, Duration.ofSeconds(10), Duration.ofMinutes(1)); - } + public EvenNoFailureJavaExample() { + this.breaker = + new CircuitBreaker( + getContext().getDispatcher(), + getContext().getSystem().getScheduler(), + 5, + Duration.ofSeconds(10), + Duration.ofMinutes(1)); + } - public int luckyNumber() { - BiFunction, Optional, Boolean> evenNoAsFailure = - (result, err) -> (result.isPresent() && result.get() % 2 == 0); + public int luckyNumber() { + BiFunction, Optional, Boolean> evenNoAsFailure = + (result, err) -> (result.isPresent() && result.get() % 2 == 0); - // this will return 8888 and increase failure count at the same time - return this.breaker.callWithSyncCircuitBreaker(() -> 8888, evenNoAsFailure); - } + // this will return 8888 and increase failure count at the same time + return this.breaker.callWithSyncCircuitBreaker(() -> 8888, evenNoAsFailure); + } - //#even-no-as-failure - @Override - public Receive createReceive() { - return null; - } + // #even-no-as-failure + @Override + public Receive createReceive() { + return null; + } } diff --git a/akka-docs/src/test/java/jdocs/circuitbreaker/TellPatternJavaActor.java b/akka-docs/src/test/java/jdocs/circuitbreaker/TellPatternJavaActor.java index 2f51fb39c0..3b88d3f8ae 100644 --- a/akka-docs/src/test/java/jdocs/circuitbreaker/TellPatternJavaActor.java +++ b/akka-docs/src/test/java/jdocs/circuitbreaker/TellPatternJavaActor.java @@ -14,40 +14,39 @@ import java.time.Duration; public class TellPatternJavaActor extends AbstractActor { - private final ActorRef target; + private final ActorRef target; private final CircuitBreaker breaker; private final LoggingAdapter log = Logging.getLogger(getContext().system(), this); public TellPatternJavaActor(ActorRef targetActor) { - this.target = targetActor; - this.breaker = new CircuitBreaker( - getContext().getDispatcher(), getContext().getSystem().getScheduler(), - 5, Duration.ofSeconds(10), Duration.ofMinutes(1)) - .addOnOpenListener(this::notifyMeOnOpen); + this.target = targetActor; + this.breaker = + new CircuitBreaker( + getContext().getDispatcher(), + getContext().getSystem().getScheduler(), + 5, + Duration.ofSeconds(10), + Duration.ofMinutes(1)) + .addOnOpenListener(this::notifyMeOnOpen); } public void notifyMeOnOpen() { log.warning("My CircuitBreaker is now open, and will not close for one minute"); } - //#circuit-breaker-tell-pattern + // #circuit-breaker-tell-pattern @Override public Receive createReceive() { return receiveBuilder() - .match(String.class, payload -> "call".equals(payload) && breaker.isClosed(), payload -> - target.tell("message", self()) - ) - .matchEquals("response", payload -> - breaker.succeed() - ) - .match(Throwable.class, t -> - breaker.fail() - ) - .match(ReceiveTimeout.class, t -> - breaker.fail() - ) - .build(); + .match( + String.class, + payload -> "call".equals(payload) && breaker.isClosed(), + payload -> target.tell("message", self())) + .matchEquals("response", payload -> breaker.succeed()) + .match(Throwable.class, t -> breaker.fail()) + .match(ReceiveTimeout.class, t -> breaker.fail()) + .build(); } - //#circuit-breaker-tell-pattern + // #circuit-breaker-tell-pattern } diff --git a/akka-docs/src/test/java/jdocs/cluster/ClusterDocTest.java b/akka-docs/src/test/java/jdocs/cluster/ClusterDocTest.java index 00c0b27ecf..4b3ba49019 100644 --- a/akka-docs/src/test/java/jdocs/cluster/ClusterDocTest.java +++ b/akka-docs/src/test/java/jdocs/cluster/ClusterDocTest.java @@ -15,23 +15,24 @@ import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -//#join-seed-nodes-imports +// #join-seed-nodes-imports import akka.actor.Address; import akka.cluster.Cluster; -//#join-seed-nodes-imports +// #join-seed-nodes-imports import akka.actor.ActorSystem; import akka.cluster.Member; - public class ClusterDocTest extends AbstractJavaTest { - + static ActorSystem system; - + @BeforeClass public static void setup() { - system = ActorSystem.create("ClusterDocTest", - ConfigFactory.parseString(scala.docs.cluster.ClusterDocSpec.config())); + system = + ActorSystem.create( + "ClusterDocTest", + ConfigFactory.parseString(scala.docs.cluster.ClusterDocSpec.config())); } @AfterClass @@ -42,17 +43,17 @@ public class ClusterDocTest extends AbstractJavaTest { @Test public void demonstrateLeave() { - //#leave + // #leave final Cluster cluster = Cluster.get(system); cluster.leave(cluster.selfAddress()); - //#leave + // #leave } - - // compile only + + // compile only @SuppressWarnings("unused") public void demonstrateDataCenter() { - //#dcAccess + // #dcAccess final Cluster cluster = Cluster.get(system); // this node's data center String dc = cluster.selfDataCenter(); @@ -61,16 +62,17 @@ public class ClusterDocTest extends AbstractJavaTest { // a specific member's data center Member aMember = cluster.state().getMembers().iterator().next(); String aDc = aMember.dataCenter(); - //#dcAccess + // #dcAccess } // compile only @SuppressWarnings("unused") public void demonstrateJoinSeedNodes() { - //#join-seed-nodes + // #join-seed-nodes final Cluster cluster = Cluster.get(system); - List
list = new LinkedList<>(); //replace this with your method to dynamically get seed nodes + List
list = + new LinkedList<>(); // replace this with your method to dynamically get seed nodes cluster.joinSeedNodes(list); - //#join-seed-nodes + // #join-seed-nodes } } diff --git a/akka-docs/src/test/java/jdocs/cluster/FactorialBackend.java b/akka-docs/src/test/java/jdocs/cluster/FactorialBackend.java index 130b9db3e0..7fcc3dffd5 100644 --- a/akka-docs/src/test/java/jdocs/cluster/FactorialBackend.java +++ b/akka-docs/src/test/java/jdocs/cluster/FactorialBackend.java @@ -10,22 +10,22 @@ import java.util.concurrent.CompletableFuture; import akka.actor.AbstractActor; import static akka.pattern.Patterns.pipe; -//#backend +// #backend public class FactorialBackend extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(Integer.class, n -> { + .match( + Integer.class, + n -> { + CompletableFuture result = + CompletableFuture.supplyAsync(() -> factorial(n)) + .thenApply((factorial) -> new FactorialResult(n, factorial)); - CompletableFuture result = - CompletableFuture.supplyAsync(() -> factorial(n)) - .thenApply((factorial) -> new FactorialResult(n, factorial)); - - pipe(result, getContext().dispatcher()).to(getSender()); - - }) - .build(); + pipe(result, getContext().dispatcher()).to(getSender()); + }) + .build(); } BigInteger factorial(int n) { @@ -36,5 +36,4 @@ public class FactorialBackend extends AbstractActor { return acc; } } -//#backend - +// #backend diff --git a/akka-docs/src/test/java/jdocs/cluster/FactorialFrontend.java b/akka-docs/src/test/java/jdocs/cluster/FactorialFrontend.java index f4871de6b6..513002d3c9 100644 --- a/akka-docs/src/test/java/jdocs/cluster/FactorialFrontend.java +++ b/akka-docs/src/test/java/jdocs/cluster/FactorialFrontend.java @@ -26,15 +26,15 @@ import akka.event.Logging; import akka.event.LoggingAdapter; import akka.routing.FromConfig; -//#frontend +// #frontend public class FactorialFrontend extends AbstractActor { final int upToN; final boolean repeat; LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); - ActorRef backend = getContext().actorOf(FromConfig.getInstance().props(), - "factorialBackendRouter"); + ActorRef backend = + getContext().actorOf(FromConfig.getInstance().props(), "factorialBackendRouter"); public FactorialFrontend(int upToN, boolean repeat) { this.upToN = upToN; @@ -50,20 +50,22 @@ public class FactorialFrontend extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(FactorialResult.class, result -> { - if (result.n == upToN) { - log.debug("{}! = {}", result.n, result.factorial); - if (repeat) - sendJobs(); - else - getContext().stop(getSelf()); - } - }) - .match(ReceiveTimeout.class, x -> { - log.info("Timeout"); - sendJobs(); - }) - .build(); + .match( + FactorialResult.class, + result -> { + if (result.n == upToN) { + log.debug("{}! = {}", result.n, result.factorial); + if (repeat) sendJobs(); + else getContext().stop(getSelf()); + } + }) + .match( + ReceiveTimeout.class, + x -> { + log.info("Timeout"); + sendJobs(); + }) + .build(); } void sendJobs() { @@ -72,38 +74,46 @@ public class FactorialFrontend extends AbstractActor { backend.tell(n, getSelf()); } } - } -//#frontend +// #frontend -//not used, only for documentation +// not used, only for documentation abstract class FactorialFrontend2 extends AbstractActor { - //#router-lookup-in-code + // #router-lookup-in-code int totalInstances = 100; Iterable routeesPaths = Arrays.asList("/user/factorialBackend", ""); boolean allowLocalRoutees = true; Set useRoles = new HashSet<>(Arrays.asList("backend")); - ActorRef backend = getContext().actorOf( - new ClusterRouterGroup(new AdaptiveLoadBalancingGroup( - HeapMetricsSelector.getInstance(), Collections. emptyList()), - new ClusterRouterGroupSettings(totalInstances, routeesPaths, - allowLocalRoutees, useRoles)).props(), "factorialBackendRouter2"); + ActorRef backend = + getContext() + .actorOf( + new ClusterRouterGroup( + new AdaptiveLoadBalancingGroup( + HeapMetricsSelector.getInstance(), Collections.emptyList()), + new ClusterRouterGroupSettings( + totalInstances, routeesPaths, allowLocalRoutees, useRoles)) + .props(), + "factorialBackendRouter2"); - //#router-lookup-in-code + // #router-lookup-in-code } -//not used, only for documentation +// not used, only for documentation abstract class FactorialFrontend3 extends AbstractActor { - //#router-deploy-in-code + // #router-deploy-in-code int totalInstances = 100; int maxInstancesPerNode = 3; boolean allowLocalRoutees = false; Set useRoles = new HashSet<>(Arrays.asList("backend")); - ActorRef backend = getContext().actorOf( - new ClusterRouterPool(new AdaptiveLoadBalancingPool( - SystemLoadAverageMetricsSelector.getInstance(), 0), - new ClusterRouterPoolSettings(totalInstances, maxInstancesPerNode, - allowLocalRoutees, useRoles)).props(Props - .create(FactorialBackend.class)), "factorialBackendRouter3"); - //#router-deploy-in-code + ActorRef backend = + getContext() + .actorOf( + new ClusterRouterPool( + new AdaptiveLoadBalancingPool( + SystemLoadAverageMetricsSelector.getInstance(), 0), + new ClusterRouterPoolSettings( + totalInstances, maxInstancesPerNode, allowLocalRoutees, useRoles)) + .props(Props.create(FactorialBackend.class)), + "factorialBackendRouter3"); + // #router-deploy-in-code } diff --git a/akka-docs/src/test/java/jdocs/cluster/FactorialFrontendMain.java b/akka-docs/src/test/java/jdocs/cluster/FactorialFrontendMain.java index 54971a07dd..bf90e5e8ca 100644 --- a/akka-docs/src/test/java/jdocs/cluster/FactorialFrontendMain.java +++ b/akka-docs/src/test/java/jdocs/cluster/FactorialFrontendMain.java @@ -19,56 +19,60 @@ public class FactorialFrontendMain { public static void main(String[] args) { final int upToN = 200; - final Config config = ConfigFactory.parseString( - "akka.cluster.roles = [frontend]").withFallback( - ConfigFactory.load("factorial")); + final Config config = + ConfigFactory.parseString("akka.cluster.roles = [frontend]") + .withFallback(ConfigFactory.load("factorial")); final ActorSystem system = ActorSystem.create("ClusterSystem", config); - system.log().info( - "Factorials will start when 2 backend members in the cluster."); - //#registerOnUp - Cluster.get(system).registerOnMemberUp(new Runnable() { - @Override - public void run() { - system.actorOf(Props.create(FactorialFrontend.class, upToN, true), - "factorialFrontend"); - } - }); - //#registerOnUp + system.log().info("Factorials will start when 2 backend members in the cluster."); + // #registerOnUp + Cluster.get(system) + .registerOnMemberUp( + new Runnable() { + @Override + public void run() { + system.actorOf( + Props.create(FactorialFrontend.class, upToN, true), "factorialFrontend"); + } + }); + // #registerOnUp - //#registerOnRemoved - Cluster.get(system).registerOnMemberRemoved(new Runnable() { - @Override - public void run() { - // exit JVM when ActorSystem has been terminated - final Runnable exit = new Runnable() { - @Override public void run() { - System.exit(0); - } - }; - system.registerOnTermination(exit); + // #registerOnRemoved + Cluster.get(system) + .registerOnMemberRemoved( + new Runnable() { + @Override + public void run() { + // exit JVM when ActorSystem has been terminated + final Runnable exit = + new Runnable() { + @Override + public void run() { + System.exit(0); + } + }; + system.registerOnTermination(exit); - // shut down ActorSystem - system.terminate(); + // shut down ActorSystem + system.terminate(); - // In case ActorSystem shutdown takes longer than 10 seconds, - // exit the JVM forcefully anyway. - // We must spawn a separate thread to not block current thread, - // since that would have blocked the shutdown of the ActorSystem. - new Thread() { - @Override public void run(){ - try { - system.getWhenTerminated().toCompletableFuture().get(10, TimeUnit.SECONDS); - } catch (Exception e) { - System.exit(-1); - } - - } - }.start(); - } - }); - //#registerOnRemoved + // In case ActorSystem shutdown takes longer than 10 seconds, + // exit the JVM forcefully anyway. + // We must spawn a separate thread to not block current thread, + // since that would have blocked the shutdown of the ActorSystem. + new Thread() { + @Override + public void run() { + try { + system.getWhenTerminated().toCompletableFuture().get(10, TimeUnit.SECONDS); + } catch (Exception e) { + System.exit(-1); + } + } + }.start(); + } + }); + // #registerOnRemoved } - } diff --git a/akka-docs/src/test/java/jdocs/cluster/FactorialResult.java b/akka-docs/src/test/java/jdocs/cluster/FactorialResult.java index cad4c40ae0..e2f03f7743 100644 --- a/akka-docs/src/test/java/jdocs/cluster/FactorialResult.java +++ b/akka-docs/src/test/java/jdocs/cluster/FactorialResult.java @@ -8,12 +8,12 @@ import java.math.BigInteger; import java.io.Serializable; public class FactorialResult implements Serializable { - private static final long serialVersionUID = 1L; - public final int n; - public final BigInteger factorial; + private static final long serialVersionUID = 1L; + public final int n; + public final BigInteger factorial; - FactorialResult(int n, BigInteger factorial) { - this.n = n; - this.factorial = factorial; - } + FactorialResult(int n, BigInteger factorial) { + this.n = n; + this.factorial = factorial; + } } diff --git a/akka-docs/src/test/java/jdocs/cluster/MetricsListener.java b/akka-docs/src/test/java/jdocs/cluster/MetricsListener.java index 571134e0e4..10cd907321 100644 --- a/akka-docs/src/test/java/jdocs/cluster/MetricsListener.java +++ b/akka-docs/src/test/java/jdocs/cluster/MetricsListener.java @@ -4,7 +4,7 @@ package jdocs.cluster; -//#metrics-listener +// #metrics-listener import akka.actor.AbstractActor; import akka.cluster.Cluster; import akka.cluster.ClusterEvent.CurrentClusterState; @@ -21,37 +21,40 @@ public class MetricsListener extends AbstractActor { LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); Cluster cluster = Cluster.get(getContext().getSystem()); - + ClusterMetricsExtension extension = ClusterMetricsExtension.get(getContext().getSystem()); - // Subscribe unto ClusterMetricsEvent events. @Override public void preStart() { - extension.subscribe(getSelf()); + extension.subscribe(getSelf()); } // Unsubscribe from ClusterMetricsEvent events. @Override public void postStop() { - extension.unsubscribe(getSelf()); + extension.unsubscribe(getSelf()); } @Override public Receive createReceive() { return receiveBuilder() - .match(ClusterMetricsChanged.class, clusterMetrics -> { - for (NodeMetrics nodeMetrics : clusterMetrics.getNodeMetrics()) { - if (nodeMetrics.address().equals(cluster.selfAddress())) { - logHeap(nodeMetrics); - logCpu(nodeMetrics); - } - } - }) - .match(CurrentClusterState.class, message -> { - // Ignore. - }) - .build(); + .match( + ClusterMetricsChanged.class, + clusterMetrics -> { + for (NodeMetrics nodeMetrics : clusterMetrics.getNodeMetrics()) { + if (nodeMetrics.address().equals(cluster.selfAddress())) { + logHeap(nodeMetrics); + logCpu(nodeMetrics); + } + } + }) + .match( + CurrentClusterState.class, + message -> { + // Ignore. + }) + .build(); } void logHeap(NodeMetrics nodeMetrics) { @@ -64,10 +67,8 @@ public class MetricsListener extends AbstractActor { void logCpu(NodeMetrics nodeMetrics) { Cpu cpu = StandardMetrics.extractCpu(nodeMetrics); if (cpu != null && cpu.systemLoadAverage().isDefined()) { - log.info("Load: {} ({} processors)", cpu.systemLoadAverage().get(), - cpu.processors()); + log.info("Load: {} ({} processors)", cpu.systemLoadAverage().get(), cpu.processors()); } } - } -//#metrics-listener \ No newline at end of file +// #metrics-listener diff --git a/akka-docs/src/test/java/jdocs/cluster/SimpleClusterListener.java b/akka-docs/src/test/java/jdocs/cluster/SimpleClusterListener.java index 0155e92d8e..a54c52a978 100644 --- a/akka-docs/src/test/java/jdocs/cluster/SimpleClusterListener.java +++ b/akka-docs/src/test/java/jdocs/cluster/SimpleClusterListener.java @@ -18,16 +18,16 @@ public class SimpleClusterListener extends AbstractActor { LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); Cluster cluster = Cluster.get(getContext().getSystem()); - //subscribe to cluster changes + // subscribe to cluster changes @Override public void preStart() { - //#subscribe - cluster.subscribe(getSelf(), ClusterEvent.initialStateAsEvents(), - MemberEvent.class, UnreachableMember.class); - //#subscribe + // #subscribe + cluster.subscribe( + getSelf(), ClusterEvent.initialStateAsEvents(), MemberEvent.class, UnreachableMember.class); + // #subscribe } - //re-subscribe when restart + // re-subscribe when restart @Override public void postStop() { cluster.unsubscribe(getSelf()); @@ -36,18 +36,26 @@ public class SimpleClusterListener extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(MemberUp.class, mUp -> { - log.info("Member is Up: {}", mUp.member()); - }) - .match(UnreachableMember.class, mUnreachable -> { - log.info("Member detected as unreachable: {}", mUnreachable.member()); - }) - .match(MemberRemoved.class, mRemoved -> { - log.info("Member is Removed: {}", mRemoved.member()); - }) - .match(MemberEvent.class, message -> { - // ignore - }) - .build(); + .match( + MemberUp.class, + mUp -> { + log.info("Member is Up: {}", mUp.member()); + }) + .match( + UnreachableMember.class, + mUnreachable -> { + log.info("Member detected as unreachable: {}", mUnreachable.member()); + }) + .match( + MemberRemoved.class, + mRemoved -> { + log.info("Member is Removed: {}", mRemoved.member()); + }) + .match( + MemberEvent.class, + message -> { + // ignore + }) + .build(); } } diff --git a/akka-docs/src/test/java/jdocs/cluster/SimpleClusterListener2.java b/akka-docs/src/test/java/jdocs/cluster/SimpleClusterListener2.java index ec8eb6fa8c..6f6fd0e074 100644 --- a/akka-docs/src/test/java/jdocs/cluster/SimpleClusterListener2.java +++ b/akka-docs/src/test/java/jdocs/cluster/SimpleClusterListener2.java @@ -16,29 +16,28 @@ import akka.event.LoggingAdapter; public class SimpleClusterListener2 extends AbstractActor { LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); - //#join + // #join Cluster cluster = Cluster.get(getContext().getSystem()); - //#join + // #join - //subscribe to cluster changes + // subscribe to cluster changes @Override public void preStart() { - //#join + // #join cluster.join(cluster.selfAddress()); - //#join + // #join - //#subscribe + // #subscribe cluster.subscribe(getSelf(), MemberEvent.class, UnreachableMember.class); - //#subscribe + // #subscribe - //#register-on-memberup + // #register-on-memberup cluster.registerOnMemberUp( - () -> cluster.subscribe(getSelf(), MemberEvent.class, UnreachableMember.class) - ); - //#register-on-memberup + () -> cluster.subscribe(getSelf(), MemberEvent.class, UnreachableMember.class)); + // #register-on-memberup } - //re-subscribe when restart + // re-subscribe when restart @Override public void postStop() { cluster.unsubscribe(getSelf()); @@ -47,21 +46,31 @@ public class SimpleClusterListener2 extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(CurrentClusterState.class, state -> { - log.info("Current members: {}", state.members()); - }) - .match(MemberUp.class, mUp -> { - log.info("Member is Up: {}", mUp.member()); - }) - .match(UnreachableMember.class, mUnreachable -> { - log.info("Member detected as unreachable: {}", mUnreachable.member()); - }) - .match(MemberRemoved.class, mRemoved -> { - log.info("Member is Removed: {}", mRemoved.member()); - }) - .match(MemberEvent.class, event -> { - // ignore - }) - .build(); + .match( + CurrentClusterState.class, + state -> { + log.info("Current members: {}", state.members()); + }) + .match( + MemberUp.class, + mUp -> { + log.info("Member is Up: {}", mUp.member()); + }) + .match( + UnreachableMember.class, + mUnreachable -> { + log.info("Member detected as unreachable: {}", mUnreachable.member()); + }) + .match( + MemberRemoved.class, + mRemoved -> { + log.info("Member is Removed: {}", mRemoved.member()); + }) + .match( + MemberEvent.class, + event -> { + // ignore + }) + .build(); } } diff --git a/akka-docs/src/test/java/jdocs/cluster/StatsAggregator.java b/akka-docs/src/test/java/jdocs/cluster/StatsAggregator.java index 6ee8a60f4a..b4344cc494 100644 --- a/akka-docs/src/test/java/jdocs/cluster/StatsAggregator.java +++ b/akka-docs/src/test/java/jdocs/cluster/StatsAggregator.java @@ -14,7 +14,7 @@ import akka.actor.ActorRef; import akka.actor.ReceiveTimeout; import akka.actor.AbstractActor; -//#aggregator +// #aggregator public class StatsAggregator extends AbstractActor { final int expectedResults; @@ -34,25 +34,27 @@ public class StatsAggregator extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(Integer.class, wordCount -> { - results.add(wordCount); - if (results.size() == expectedResults) { - int sum = 0; - for (int c : results) { - sum += c; - } - double meanWordLength = ((double) sum) / results.size(); - replyTo.tell(new StatsResult(meanWordLength), getSelf()); - getContext().stop(getSelf()); - } - }) - .match(ReceiveTimeout.class, x -> { - replyTo.tell(new JobFailed("Service unavailable, try again later"), - getSelf()); - getContext().stop(getSelf()); - }) - .build(); + .match( + Integer.class, + wordCount -> { + results.add(wordCount); + if (results.size() == expectedResults) { + int sum = 0; + for (int c : results) { + sum += c; + } + double meanWordLength = ((double) sum) / results.size(); + replyTo.tell(new StatsResult(meanWordLength), getSelf()); + getContext().stop(getSelf()); + } + }) + .match( + ReceiveTimeout.class, + x -> { + replyTo.tell(new JobFailed("Service unavailable, try again later"), getSelf()); + getContext().stop(getSelf()); + }) + .build(); } - } -//#aggregator +// #aggregator diff --git a/akka-docs/src/test/java/jdocs/cluster/StatsMessages.java b/akka-docs/src/test/java/jdocs/cluster/StatsMessages.java index 703ddab0db..3c4e2c63b7 100644 --- a/akka-docs/src/test/java/jdocs/cluster/StatsMessages.java +++ b/akka-docs/src/test/java/jdocs/cluster/StatsMessages.java @@ -6,7 +6,7 @@ package jdocs.cluster; import java.io.Serializable; -//#messages +// #messages public interface StatsMessages { public static class StatsJob implements Serializable { @@ -54,6 +54,5 @@ public interface StatsMessages { return "JobFailed(" + reason + ")"; } } - } -//#messages \ No newline at end of file +// #messages diff --git a/akka-docs/src/test/java/jdocs/cluster/StatsSampleClient.java b/akka-docs/src/test/java/jdocs/cluster/StatsSampleClient.java index b31f8f3d42..cd70fcc256 100644 --- a/akka-docs/src/test/java/jdocs/cluster/StatsSampleClient.java +++ b/akka-docs/src/test/java/jdocs/cluster/StatsSampleClient.java @@ -39,20 +39,20 @@ public class StatsSampleClient extends AbstractActor { public StatsSampleClient(String servicePath) { this.servicePath = servicePath; Duration interval = Duration.ofMillis(2); - tickTask = getContext() - .getSystem() - .scheduler() - .schedule(interval, interval, getSelf(), "tick", - getContext().getDispatcher(), null); + tickTask = + getContext() + .getSystem() + .scheduler() + .schedule(interval, interval, getSelf(), "tick", getContext().getDispatcher(), null); } - //subscribe to cluster changes, MemberEvent + // subscribe to cluster changes, MemberEvent @Override public void preStart() { cluster.subscribe(getSelf(), MemberEvent.class, ReachabilityEvent.class); } - //re-subscribe when restart + // re-subscribe when restart @Override public void postStop() { cluster.unsubscribe(getSelf()); @@ -62,41 +62,49 @@ public class StatsSampleClient extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("tick", x -> !nodes.isEmpty(), x -> { - // just pick any one - List
nodesList = new ArrayList
(nodes); - Address address = nodesList.get(ThreadLocalRandom.current().nextInt( - nodesList.size())); - ActorSelection service = getContext().actorSelection(address + servicePath); - service.tell(new StatsJob("this is the text that will be analyzed"), - getSelf()); - }) - .match(StatsResult.class, System.out::println) - .match(JobFailed.class, System.out::println) - .match(CurrentClusterState.class, state -> { - nodes.clear(); - for (Member member : state.getMembers()) { - if (member.hasRole("compute") && member.status().equals(MemberStatus.up())) { - nodes.add(member.address()); - } - } - }) - .match(MemberUp.class, mUp -> { - if (mUp.member().hasRole("compute")) - nodes.add(mUp.member().address()); - }) - .match(MemberEvent.class, event -> { - nodes.remove(event.member().address()); - }) - .match(UnreachableMember.class, unreachable -> { - nodes.remove(unreachable.member().address()); - }) - .match(ReachableMember.class, reachable -> { - if (reachable.member().hasRole("compute")) - nodes.add(reachable.member().address()); - - }) - .build(); + .matchEquals( + "tick", + x -> !nodes.isEmpty(), + x -> { + // just pick any one + List
nodesList = new ArrayList
(nodes); + Address address = + nodesList.get(ThreadLocalRandom.current().nextInt(nodesList.size())); + ActorSelection service = getContext().actorSelection(address + servicePath); + service.tell(new StatsJob("this is the text that will be analyzed"), getSelf()); + }) + .match(StatsResult.class, System.out::println) + .match(JobFailed.class, System.out::println) + .match( + CurrentClusterState.class, + state -> { + nodes.clear(); + for (Member member : state.getMembers()) { + if (member.hasRole("compute") && member.status().equals(MemberStatus.up())) { + nodes.add(member.address()); + } + } + }) + .match( + MemberUp.class, + mUp -> { + if (mUp.member().hasRole("compute")) nodes.add(mUp.member().address()); + }) + .match( + MemberEvent.class, + event -> { + nodes.remove(event.member().address()); + }) + .match( + UnreachableMember.class, + unreachable -> { + nodes.remove(unreachable.member().address()); + }) + .match( + ReachableMember.class, + reachable -> { + if (reachable.member().hasRole("compute")) nodes.add(reachable.member().address()); + }) + .build(); } - } diff --git a/akka-docs/src/test/java/jdocs/cluster/StatsSampleOneMasterClientMain.java b/akka-docs/src/test/java/jdocs/cluster/StatsSampleOneMasterClientMain.java index 83146c957f..0b0f8f27a8 100644 --- a/akka-docs/src/test/java/jdocs/cluster/StatsSampleOneMasterClientMain.java +++ b/akka-docs/src/test/java/jdocs/cluster/StatsSampleOneMasterClientMain.java @@ -13,11 +13,7 @@ public class StatsSampleOneMasterClientMain { public static void main(String[] args) { // note that client is not a compute node, role not defined - ActorSystem system = ActorSystem.create("ClusterSystem", - ConfigFactory.load("stats2")); - system.actorOf(Props.create(StatsSampleClient.class, "/user/statsServiceProxy"), - "client"); - + ActorSystem system = ActorSystem.create("ClusterSystem", ConfigFactory.load("stats2")); + system.actorOf(Props.create(StatsSampleClient.class, "/user/statsServiceProxy"), "client"); } - } diff --git a/akka-docs/src/test/java/jdocs/cluster/StatsSampleOneMasterMain.java b/akka-docs/src/test/java/jdocs/cluster/StatsSampleOneMasterMain.java index 7f34e6c5c9..e64cac22db 100644 --- a/akka-docs/src/test/java/jdocs/cluster/StatsSampleOneMasterMain.java +++ b/akka-docs/src/test/java/jdocs/cluster/StatsSampleOneMasterMain.java @@ -19,7 +19,7 @@ public class StatsSampleOneMasterMain { public static void main(String[] args) { if (args.length == 0) { - startup(new String[] { "2551", "2552", "0" }); + startup(new String[] {"2551", "2552", "0"}); StatsSampleOneMasterClientMain.main(new String[0]); } else { startup(args); @@ -29,29 +29,28 @@ public class StatsSampleOneMasterMain { public static void startup(String[] ports) { for (String port : ports) { // Override the configuration of the port - Config config = ConfigFactory - .parseString("akka.remote.netty.tcp.port=" + port) - .withFallback( - ConfigFactory.parseString("akka.cluster.roles = [compute]")) - .withFallback(ConfigFactory.load("stats2")); + Config config = + ConfigFactory.parseString("akka.remote.netty.tcp.port=" + port) + .withFallback(ConfigFactory.parseString("akka.cluster.roles = [compute]")) + .withFallback(ConfigFactory.load("stats2")); ActorSystem system = ActorSystem.create("ClusterSystem", config); - //#create-singleton-manager - ClusterSingletonManagerSettings settings = ClusterSingletonManagerSettings.create(system) - .withRole("compute"); - system.actorOf(ClusterSingletonManager.props( - Props.create(StatsService.class), PoisonPill.getInstance(), settings), + // #create-singleton-manager + ClusterSingletonManagerSettings settings = + ClusterSingletonManagerSettings.create(system).withRole("compute"); + system.actorOf( + ClusterSingletonManager.props( + Props.create(StatsService.class), PoisonPill.getInstance(), settings), "statsService"); - //#create-singleton-manager + // #create-singleton-manager - //#singleton-proxy + // #singleton-proxy ClusterSingletonProxySettings proxySettings = ClusterSingletonProxySettings.create(system).withRole("compute"); - system.actorOf(ClusterSingletonProxy.props("/user/statsService", - proxySettings), "statsServiceProxy"); - //#singleton-proxy + system.actorOf( + ClusterSingletonProxy.props("/user/statsService", proxySettings), "statsServiceProxy"); + // #singleton-proxy } - } } diff --git a/akka-docs/src/test/java/jdocs/cluster/StatsService.java b/akka-docs/src/test/java/jdocs/cluster/StatsService.java index ea9b508a9d..99ad26c4b0 100644 --- a/akka-docs/src/test/java/jdocs/cluster/StatsService.java +++ b/akka-docs/src/test/java/jdocs/cluster/StatsService.java @@ -22,66 +22,74 @@ import java.util.Collections; import java.util.HashSet; import java.util.Set; -//#service +// #service public class StatsService extends AbstractActor { // This router is used both with lookup and deploy of routees. If you // have a router with only lookup of routees you can use Props.empty() // instead of Props.create(StatsWorker.class). - ActorRef workerRouter = getContext().actorOf( - FromConfig.getInstance().props(Props.create(StatsWorker.class)), - "workerRouter"); + ActorRef workerRouter = + getContext() + .actorOf(FromConfig.getInstance().props(Props.create(StatsWorker.class)), "workerRouter"); @Override public Receive createReceive() { return receiveBuilder() - .match(StatsJob.class, job -> !job.getText().isEmpty(), job -> { - String[] words = job.getText().split(" "); - ActorRef replyTo = getSender(); + .match( + StatsJob.class, + job -> !job.getText().isEmpty(), + job -> { + String[] words = job.getText().split(" "); + ActorRef replyTo = getSender(); - // create actor that collects replies from workers - ActorRef aggregator = getContext().actorOf( - Props.create(StatsAggregator.class, words.length, replyTo)); + // create actor that collects replies from workers + ActorRef aggregator = + getContext().actorOf(Props.create(StatsAggregator.class, words.length, replyTo)); - // send each word to a worker - for (String word : words) { - workerRouter.tell(new ConsistentHashableEnvelope(word, word), - aggregator); - } - - }) - .build(); + // send each word to a worker + for (String word : words) { + workerRouter.tell(new ConsistentHashableEnvelope(word, word), aggregator); + } + }) + .build(); } } -//#service +// #service -//not used, only for documentation +// not used, only for documentation abstract class StatsService2 extends AbstractActor { - //#router-lookup-in-code + // #router-lookup-in-code int totalInstances = 100; - Iterable routeesPaths = Collections - .singletonList("/user/statsWorker"); + Iterable routeesPaths = Collections.singletonList("/user/statsWorker"); boolean allowLocalRoutees = true; Set useRoles = new HashSet<>(Arrays.asList("compute")); - ActorRef workerRouter = getContext().actorOf( - new ClusterRouterGroup(new ConsistentHashingGroup(routeesPaths), - new ClusterRouterGroupSettings(totalInstances, routeesPaths, - allowLocalRoutees, useRoles)).props(), "workerRouter2"); - //#router-lookup-in-code + ActorRef workerRouter = + getContext() + .actorOf( + new ClusterRouterGroup( + new ConsistentHashingGroup(routeesPaths), + new ClusterRouterGroupSettings( + totalInstances, routeesPaths, allowLocalRoutees, useRoles)) + .props(), + "workerRouter2"); + // #router-lookup-in-code } -//not used, only for documentation +// not used, only for documentation abstract class StatsService3 extends AbstractActor { - //#router-deploy-in-code + // #router-deploy-in-code int totalInstances = 100; int maxInstancesPerNode = 3; boolean allowLocalRoutees = false; Set useRoles = new HashSet<>(Arrays.asList("compute")); - ActorRef workerRouter = getContext().actorOf( - new ClusterRouterPool(new ConsistentHashingPool(0), - new ClusterRouterPoolSettings(totalInstances, maxInstancesPerNode, - allowLocalRoutees, useRoles)).props(Props - .create(StatsWorker.class)), "workerRouter3"); - //#router-deploy-in-code + ActorRef workerRouter = + getContext() + .actorOf( + new ClusterRouterPool( + new ConsistentHashingPool(0), + new ClusterRouterPoolSettings( + totalInstances, maxInstancesPerNode, allowLocalRoutees, useRoles)) + .props(Props.create(StatsWorker.class)), + "workerRouter3"); + // #router-deploy-in-code } - diff --git a/akka-docs/src/test/java/jdocs/cluster/StatsWorker.java b/akka-docs/src/test/java/jdocs/cluster/StatsWorker.java index 0bba07935f..7c252d1388 100644 --- a/akka-docs/src/test/java/jdocs/cluster/StatsWorker.java +++ b/akka-docs/src/test/java/jdocs/cluster/StatsWorker.java @@ -9,7 +9,7 @@ import java.util.Map; import akka.actor.AbstractActor; -//#worker +// #worker public class StatsWorker extends AbstractActor { Map cache = new HashMap(); @@ -17,15 +17,17 @@ public class StatsWorker extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(String.class, word -> { - Integer length = cache.get(word); - if (length == null) { - length = word.length(); - cache.put(word, length); - } - getSender().tell(length, getSelf()); - }) - .build(); + .match( + String.class, + word -> { + Integer length = cache.get(word); + if (length == null) { + length = word.length(); + cache.put(word, length); + } + getSender().tell(length, getSelf()); + }) + .build(); } } -//#worker \ No newline at end of file +// #worker diff --git a/akka-docs/src/test/java/jdocs/cluster/TransformationBackend.java b/akka-docs/src/test/java/jdocs/cluster/TransformationBackend.java index d4dc6a389b..7b751393ac 100644 --- a/akka-docs/src/test/java/jdocs/cluster/TransformationBackend.java +++ b/akka-docs/src/test/java/jdocs/cluster/TransformationBackend.java @@ -14,18 +14,18 @@ import akka.cluster.ClusterEvent.MemberUp; import akka.cluster.Member; import akka.cluster.MemberStatus; -//#backend +// #backend public class TransformationBackend extends AbstractActor { Cluster cluster = Cluster.get(getContext().getSystem()); - //subscribe to cluster changes, MemberUp + // subscribe to cluster changes, MemberUp @Override public void preStart() { cluster.subscribe(getSelf(), MemberUp.class); } - //re-subscribe when restart + // re-subscribe when restart @Override public void postStop() { cluster.unsubscribe(getSelf()); @@ -34,27 +34,33 @@ public class TransformationBackend extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(TransformationJob.class, job -> { - getSender().tell(new TransformationResult(job.getText().toUpperCase()), - getSelf()); - }) - .match(CurrentClusterState.class, state -> { - for (Member member : state.getMembers()) { - if (member.status().equals(MemberStatus.up())) { - register(member); - } - } - }) - .match(MemberUp.class, mUp -> { - register(mUp.member()); - }) - .build(); + .match( + TransformationJob.class, + job -> { + getSender().tell(new TransformationResult(job.getText().toUpperCase()), getSelf()); + }) + .match( + CurrentClusterState.class, + state -> { + for (Member member : state.getMembers()) { + if (member.status().equals(MemberStatus.up())) { + register(member); + } + } + }) + .match( + MemberUp.class, + mUp -> { + register(mUp.member()); + }) + .build(); } void register(Member member) { if (member.hasRole("frontend")) - getContext().actorSelection(member.address() + "/user/frontend").tell( - BACKEND_REGISTRATION, getSelf()); + getContext() + .actorSelection(member.address() + "/user/frontend") + .tell(BACKEND_REGISTRATION, getSelf()); } } -//#backend +// #backend diff --git a/akka-docs/src/test/java/jdocs/cluster/TransformationFrontend.java b/akka-docs/src/test/java/jdocs/cluster/TransformationFrontend.java index 61ca7fa54c..b55dda26ee 100644 --- a/akka-docs/src/test/java/jdocs/cluster/TransformationFrontend.java +++ b/akka-docs/src/test/java/jdocs/cluster/TransformationFrontend.java @@ -15,7 +15,7 @@ import akka.actor.ActorRef; import akka.actor.Terminated; import akka.actor.AbstractActor; -//#frontend +// #frontend public class TransformationFrontend extends AbstractActor { List backends = new ArrayList(); @@ -24,25 +24,31 @@ public class TransformationFrontend extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(TransformationJob.class, job -> backends.isEmpty(), job -> { - getSender().tell( - new JobFailed("Service unavailable, try again later", job), - getSender()); - }) - .match(TransformationJob.class, job -> { - jobCounter++; - backends.get(jobCounter % backends.size()) - .forward(job, getContext()); - }) - .matchEquals(BACKEND_REGISTRATION, x -> { - getContext().watch(getSender()); - backends.add(getSender()); - }) - .match(Terminated.class, terminated -> { - backends.remove(terminated.getActor()); - }) - .build(); + .match( + TransformationJob.class, + job -> backends.isEmpty(), + job -> { + getSender() + .tell(new JobFailed("Service unavailable, try again later", job), getSender()); + }) + .match( + TransformationJob.class, + job -> { + jobCounter++; + backends.get(jobCounter % backends.size()).forward(job, getContext()); + }) + .matchEquals( + BACKEND_REGISTRATION, + x -> { + getContext().watch(getSender()); + backends.add(getSender()); + }) + .match( + Terminated.class, + terminated -> { + backends.remove(terminated.getActor()); + }) + .build(); } - } -//#frontend +// #frontend diff --git a/akka-docs/src/test/java/jdocs/cluster/TransformationMessages.java b/akka-docs/src/test/java/jdocs/cluster/TransformationMessages.java index 69dd2cd60b..096e44f619 100644 --- a/akka-docs/src/test/java/jdocs/cluster/TransformationMessages.java +++ b/akka-docs/src/test/java/jdocs/cluster/TransformationMessages.java @@ -6,7 +6,7 @@ package jdocs.cluster; import java.io.Serializable; -//#messages +// #messages public interface TransformationMessages { public static class TransformationJob implements Serializable { @@ -62,6 +62,5 @@ public interface TransformationMessages { } public static final String BACKEND_REGISTRATION = "BackendRegistration"; - } -//#messages \ No newline at end of file +// #messages diff --git a/akka-docs/src/test/java/jdocs/cluster/singleton/ClusterSingletonSupervision.java b/akka-docs/src/test/java/jdocs/cluster/singleton/ClusterSingletonSupervision.java index 4257dbd9e4..a467e88a0e 100644 --- a/akka-docs/src/test/java/jdocs/cluster/singleton/ClusterSingletonSupervision.java +++ b/akka-docs/src/test/java/jdocs/cluster/singleton/ClusterSingletonSupervision.java @@ -9,23 +9,26 @@ import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.SupervisorStrategy; -//#singleton-supervisor-actor-usage-imports +// #singleton-supervisor-actor-usage-imports import akka.actor.PoisonPill; import akka.actor.Props; import akka.cluster.singleton.ClusterSingletonManager; import akka.cluster.singleton.ClusterSingletonManagerSettings; -//#singleton-supervisor-actor-usage-imports +// #singleton-supervisor-actor-usage-imports abstract class ClusterSingletonSupervision extends AbstractActor { public ActorRef createSingleton(String name, Props props, SupervisorStrategy supervisorStrategy) { - //#singleton-supervisor-actor-usage - return getContext().system().actorOf( - ClusterSingletonManager.props( - Props.create(SupervisorActor.class, () -> new SupervisorActor(props, supervisorStrategy)), - PoisonPill.getInstance(), - ClusterSingletonManagerSettings.create(getContext().system())), - name = name); - //#singleton-supervisor-actor-usage + // #singleton-supervisor-actor-usage + return getContext() + .system() + .actorOf( + ClusterSingletonManager.props( + Props.create( + SupervisorActor.class, () -> new SupervisorActor(props, supervisorStrategy)), + PoisonPill.getInstance(), + ClusterSingletonManagerSettings.create(getContext().system())), + name = name); + // #singleton-supervisor-actor-usage } -} \ No newline at end of file +} diff --git a/akka-docs/src/test/java/jdocs/cluster/singleton/SupervisorActor.java b/akka-docs/src/test/java/jdocs/cluster/singleton/SupervisorActor.java index 4ab21166d6..647761c735 100644 --- a/akka-docs/src/test/java/jdocs/cluster/singleton/SupervisorActor.java +++ b/akka-docs/src/test/java/jdocs/cluster/singleton/SupervisorActor.java @@ -4,7 +4,7 @@ package jdocs.cluster.singleton; -//#singleton-supervisor-actor +// #singleton-supervisor-actor import akka.actor.AbstractActor; import akka.actor.AbstractActor.Receive; import akka.actor.ActorRef; @@ -15,6 +15,7 @@ public class SupervisorActor extends AbstractActor { final Props childProps; final SupervisorStrategy supervisorStrategy; final ActorRef child; + SupervisorActor(Props childProps, SupervisorStrategy supervisorStrategy) { this.childProps = childProps; this.supervisorStrategy = supervisorStrategy; @@ -28,9 +29,7 @@ public class SupervisorActor extends AbstractActor { @Override public Receive createReceive() { - return receiveBuilder() - .matchAny(msg -> child.forward(msg, getContext())) - .build(); + return receiveBuilder().matchAny(msg -> child.forward(msg, getContext())).build(); } } -//#singleton-supervisor-actor \ No newline at end of file +// #singleton-supervisor-actor diff --git a/akka-docs/src/test/java/jdocs/config/ConfigDoc.java b/akka-docs/src/test/java/jdocs/config/ConfigDoc.java index 9e64a6368c..3b8702fa15 100644 --- a/akka-docs/src/test/java/jdocs/config/ConfigDoc.java +++ b/akka-docs/src/test/java/jdocs/config/ConfigDoc.java @@ -9,26 +9,20 @@ import com.typesafe.config.*; public class ConfigDoc { public ActorSystem createConfiguredSystem() { - //#java-custom-config + // #java-custom-config // make a Config with just your special setting - Config myConfig = - ConfigFactory.parseString("something=somethingElse"); + Config myConfig = ConfigFactory.parseString("something=somethingElse"); // load the normal config stack (system props, // then application.conf, then reference.conf) - Config regularConfig = - ConfigFactory.load(); + Config regularConfig = ConfigFactory.load(); // override regular stack with myConfig - Config combined = - myConfig.withFallback(regularConfig); + Config combined = myConfig.withFallback(regularConfig); // put the result in between the overrides // (system props) and defaults again - Config complete = - ConfigFactory.load(combined); + Config complete = ConfigFactory.load(combined); // create ActorSystem - ActorSystem system = - ActorSystem.create("myname", complete); - //#java-custom-config + ActorSystem system = ActorSystem.create("myname", complete); + // #java-custom-config return system; } } - diff --git a/akka-docs/src/test/java/jdocs/ddata/DataBot.java b/akka-docs/src/test/java/jdocs/ddata/DataBot.java index 9c1d03f34f..6f7a145a68 100644 --- a/akka-docs/src/test/java/jdocs/ddata/DataBot.java +++ b/akka-docs/src/test/java/jdocs/ddata/DataBot.java @@ -4,7 +4,7 @@ package jdocs.ddata; -//#data-bot +// #data-bot import java.time.Duration; import java.util.concurrent.ThreadLocalRandom; @@ -30,13 +30,20 @@ public class DataBot extends AbstractActor { private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); - private final ActorRef replicator = - DistributedData.get(getContext().getSystem()).replicator(); + private final ActorRef replicator = DistributedData.get(getContext().getSystem()).replicator(); private final Cluster node = Cluster.get(getContext().getSystem()); - private final Cancellable tickTask = getContext().getSystem().scheduler().schedule( - Duration.ofSeconds(5), Duration.ofSeconds(5), getSelf(), TICK, - getContext().getDispatcher(), getSelf()); + private final Cancellable tickTask = + getContext() + .getSystem() + .scheduler() + .schedule( + Duration.ofSeconds(5), + Duration.ofSeconds(5), + getSelf(), + TICK, + getContext().getDispatcher(), + getSelf()); private final Key> dataKey = ORSetKey.create("key"); @@ -44,37 +51,33 @@ public class DataBot extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(String.class, a -> a.equals(TICK), a -> receiveTick()) - .match(Changed.class, c -> c.key().equals(dataKey), c -> receiveChanged((Changed>) c)) - .match(UpdateResponse.class, r -> receiveUpdateResponse()) - .build(); + .match(String.class, a -> a.equals(TICK), a -> receiveTick()) + .match( + Changed.class, + c -> c.key().equals(dataKey), + c -> receiveChanged((Changed>) c)) + .match(UpdateResponse.class, r -> receiveUpdateResponse()) + .build(); } - private void receiveTick() { String s = String.valueOf((char) ThreadLocalRandom.current().nextInt(97, 123)); if (ThreadLocalRandom.current().nextBoolean()) { // add log.info("Adding: {}", s); - Update> update = new Update<>( - dataKey, - ORSet.create(), - Replicator.writeLocal(), - curr -> curr.add(node, s)); - replicator.tell(update, getSelf()); + Update> update = + new Update<>(dataKey, ORSet.create(), Replicator.writeLocal(), curr -> curr.add(node, s)); + replicator.tell(update, getSelf()); } else { // remove log.info("Removing: {}", s); - Update> update = new Update<>( - dataKey, - ORSet.create(), - Replicator.writeLocal(), - curr -> curr.remove(node, s)); + Update> update = + new Update<>( + dataKey, ORSet.create(), Replicator.writeLocal(), curr -> curr.remove(node, s)); replicator.tell(update, getSelf()); } } - private void receiveChanged(Changed> c) { ORSet data = c.dataValue(); log.info("Current elements: {}", data.getElements()); @@ -84,7 +87,6 @@ public class DataBot extends AbstractActor { // ignore } - @Override public void preStart() { Subscribe> subscribe = new Subscribe<>(dataKey, getSelf()); @@ -92,9 +94,8 @@ public class DataBot extends AbstractActor { } @Override - public void postStop(){ + public void postStop() { tickTask.cancel(); } - } -//#data-bot +// #data-bot diff --git a/akka-docs/src/test/java/jdocs/ddata/DistributedDataDocTest.java b/akka-docs/src/test/java/jdocs/ddata/DistributedDataDocTest.java index 58b9a50bac..bf0527b2f3 100644 --- a/akka-docs/src/test/java/jdocs/ddata/DistributedDataDocTest.java +++ b/akka-docs/src/test/java/jdocs/ddata/DistributedDataDocTest.java @@ -31,14 +31,14 @@ import static akka.cluster.ddata.Replicator.*; @SuppressWarnings({"unchecked", "unused"}) public class DistributedDataDocTest extends AbstractJavaTest { - + static ActorSystem system; - @BeforeClass public static void setup() { - system = ActorSystem.create("DistributedDataDocTest", - ConfigFactory.parseString(DistributedDataDocSpec.config())); + system = + ActorSystem.create( + "DistributedDataDocTest", ConfigFactory.parseString(DistributedDataDocSpec.config())); } @AfterClass @@ -48,11 +48,11 @@ public class DistributedDataDocTest extends AbstractJavaTest { } static - //#update + // #update class DemonstrateUpdate extends AbstractActor { - final SelfUniqueAddress node = DistributedData.get(getContext().getSystem()).selfUniqueAddress(); - final ActorRef replicator = - DistributedData.get(getContext().getSystem()).replicator(); + final SelfUniqueAddress node = + DistributedData.get(getContext().getSystem()).selfUniqueAddress(); + final ActorRef replicator = DistributedData.get(getContext().getSystem()).replicator(); final Key counter1Key = PNCounterKey.create("counter1"); final Key> set1Key = GSetKey.create("set1"); @@ -62,260 +62,310 @@ public class DistributedDataDocTest extends AbstractJavaTest { @Override public Receive createReceive() { ReceiveBuilder b = receiveBuilder(); - - b.matchEquals("demonstrate update", msg -> { - replicator.tell(new Replicator.Update(counter1Key, PNCounter.create(), - Replicator.writeLocal(), curr -> curr.increment(node, 1)), getSelf()); - final WriteConsistency writeTo3 = new WriteTo(3, Duration.ofSeconds(1)); - replicator.tell(new Replicator.Update>(set1Key, GSet.create(), - writeTo3, curr -> curr.add("hello")), getSelf()); + b.matchEquals( + "demonstrate update", + msg -> { + replicator.tell( + new Replicator.Update( + counter1Key, + PNCounter.create(), + Replicator.writeLocal(), + curr -> curr.increment(node, 1)), + getSelf()); - final WriteConsistency writeMajority = - new WriteMajority(Duration.ofSeconds(5)); - replicator.tell(new Replicator.Update>(set2Key, ORSet.create(), - writeMajority, curr -> curr.add(node, "hello")), getSelf()); + final WriteConsistency writeTo3 = new WriteTo(3, Duration.ofSeconds(1)); + replicator.tell( + new Replicator.Update>( + set1Key, GSet.create(), writeTo3, curr -> curr.add("hello")), + getSelf()); - final WriteConsistency writeAll = new WriteAll(Duration.ofSeconds(5)); - replicator.tell(new Replicator.Update(activeFlagKey, Flag.create(), - writeAll, curr -> curr.switchOn()), getSelf()); - }); - //#update - - //#update-response1 - b.match(UpdateSuccess.class, a -> a.key().equals(counter1Key), a -> { - // ok - }); - //#update-response1 - - //#update-response2 - b.match(UpdateSuccess.class, a -> a.key().equals(set1Key), a -> { - // ok - }) - .match(UpdateTimeout.class, a -> a.key().equals(set1Key), a -> { - // write to 3 nodes failed within 1.second - }); - //#update-response2 - - //#update + final WriteConsistency writeMajority = new WriteMajority(Duration.ofSeconds(5)); + replicator.tell( + new Replicator.Update>( + set2Key, ORSet.create(), writeMajority, curr -> curr.add(node, "hello")), + getSelf()); + + final WriteConsistency writeAll = new WriteAll(Duration.ofSeconds(5)); + replicator.tell( + new Replicator.Update( + activeFlagKey, Flag.create(), writeAll, curr -> curr.switchOn()), + getSelf()); + }); + // #update + + // #update-response1 + b.match( + UpdateSuccess.class, + a -> a.key().equals(counter1Key), + a -> { + // ok + }); + // #update-response1 + + // #update-response2 + b.match( + UpdateSuccess.class, + a -> a.key().equals(set1Key), + a -> { + // ok + }) + .match( + UpdateTimeout.class, + a -> a.key().equals(set1Key), + a -> { + // write to 3 nodes failed within 1.second + }); + // #update-response2 + + // #update return b.build(); } } - //#update + // #update static - //#update-request-context + // #update-request-context class DemonstrateUpdateWithRequestContext extends AbstractActor { final Cluster node = Cluster.get(getContext().getSystem()); - final ActorRef replicator = - DistributedData.get(getContext().getSystem()).replicator(); + final ActorRef replicator = DistributedData.get(getContext().getSystem()).replicator(); final WriteConsistency writeTwo = new WriteTo(2, Duration.ofSeconds(3)); final Key counter1Key = PNCounterKey.create("counter1"); - + @Override public Receive createReceive() { return receiveBuilder() - .match(String.class, a -> a.equals("increment"), a -> { - // incoming command to increase the counter - Optional reqContext = Optional.of(getSender()); - Replicator.Update upd = new Replicator.Update(counter1Key, - PNCounter.create(), writeTwo, reqContext, curr -> curr.increment(node, 1)); - replicator.tell(upd, getSelf()); - }) - - .match(UpdateSuccess.class, a -> a.key().equals(counter1Key), a -> { - ActorRef replyTo = (ActorRef) a.getRequest().get(); - replyTo.tell("ack", getSelf()); - }) - - .match(UpdateTimeout.class, a -> a.key().equals(counter1Key), a -> { - ActorRef replyTo = (ActorRef) a.getRequest().get(); - replyTo.tell("nack", getSelf()); - }) - - .build(); - } + .match( + String.class, + a -> a.equals("increment"), + a -> { + // incoming command to increase the counter + Optional reqContext = Optional.of(getSender()); + Replicator.Update upd = + new Replicator.Update( + counter1Key, + PNCounter.create(), + writeTwo, + reqContext, + curr -> curr.increment(node, 1)); + replicator.tell(upd, getSelf()); + }) + .match( + UpdateSuccess.class, + a -> a.key().equals(counter1Key), + a -> { + ActorRef replyTo = (ActorRef) a.getRequest().get(); + replyTo.tell("ack", getSelf()); + }) + .match( + UpdateTimeout.class, + a -> a.key().equals(counter1Key), + a -> { + ActorRef replyTo = (ActorRef) a.getRequest().get(); + replyTo.tell("nack", getSelf()); + }) + .build(); + } } - //#update-request-context + // #update-request-context static - //#get + // #get class DemonstrateGet extends AbstractActor { - final ActorRef replicator = - DistributedData.get(getContext().getSystem()).replicator(); - - final Key counter1Key = PNCounterKey.create("counter1"); - final Key> set1Key = GSetKey.create("set1"); - final Key> set2Key = ORSetKey.create("set2"); - final Key activeFlagKey = FlagKey.create("active"); - - @Override - public Receive createReceive() { - ReceiveBuilder b = receiveBuilder(); - - b.matchEquals("demonstrate get", msg -> { + final ActorRef replicator = DistributedData.get(getContext().getSystem()).replicator(); - replicator.tell(new Replicator.Get(counter1Key, - Replicator.readLocal()), getSelf()); - - final ReadConsistency readFrom3 = new ReadFrom(3, Duration.ofSeconds(1)); - replicator.tell(new Replicator.Get>(set1Key, - readFrom3), getSelf()); - - final ReadConsistency readMajority = new ReadMajority(Duration.ofSeconds(5)); - replicator.tell(new Replicator.Get>(set2Key, - readMajority), getSelf()); - - final ReadConsistency readAll = new ReadAll(Duration.ofSeconds(5)); - replicator.tell(new Replicator.Get(activeFlagKey, - readAll), getSelf()); - - }); - //#get + final Key counter1Key = PNCounterKey.create("counter1"); + final Key> set1Key = GSetKey.create("set1"); + final Key> set2Key = ORSetKey.create("set2"); + final Key activeFlagKey = FlagKey.create("active"); - //#get-response1 - b.match(GetSuccess.class, a -> a.key().equals(counter1Key), a -> { - GetSuccess g = a; - BigInteger value = g.dataValue().getValue(); - }). - match(NotFound.class, a -> a.key().equals(counter1Key), a -> { - // key counter1 does not exist - }); - //#get-response1 + @Override + public Receive createReceive() { + ReceiveBuilder b = receiveBuilder(); - //#get-response2 - b.match(GetSuccess.class, a -> a.key().equals(set1Key), a -> { - GetSuccess> g = a; - Set value = g.dataValue().getElements(); - }). - match(GetFailure.class, a -> a.key().equals(set1Key), a -> { - // read from 3 nodes failed within 1.second - }). - match(NotFound.class, a -> a.key().equals(set1Key), a -> { - // key set1 does not exist - }); - //#get-response2 + b.matchEquals( + "demonstrate get", + msg -> { + replicator.tell( + new Replicator.Get(counter1Key, Replicator.readLocal()), getSelf()); - //#get + final ReadConsistency readFrom3 = new ReadFrom(3, Duration.ofSeconds(1)); + replicator.tell(new Replicator.Get>(set1Key, readFrom3), getSelf()); + + final ReadConsistency readMajority = new ReadMajority(Duration.ofSeconds(5)); + replicator.tell(new Replicator.Get>(set2Key, readMajority), getSelf()); + + final ReadConsistency readAll = new ReadAll(Duration.ofSeconds(5)); + replicator.tell(new Replicator.Get(activeFlagKey, readAll), getSelf()); + }); + // #get + + // #get-response1 + b.match( + GetSuccess.class, + a -> a.key().equals(counter1Key), + a -> { + GetSuccess g = a; + BigInteger value = g.dataValue().getValue(); + }) + .match( + NotFound.class, + a -> a.key().equals(counter1Key), + a -> { + // key counter1 does not exist + }); + // #get-response1 + + // #get-response2 + b.match( + GetSuccess.class, + a -> a.key().equals(set1Key), + a -> { + GetSuccess> g = a; + Set value = g.dataValue().getElements(); + }) + .match( + GetFailure.class, + a -> a.key().equals(set1Key), + a -> { + // read from 3 nodes failed within 1.second + }) + .match( + NotFound.class, + a -> a.key().equals(set1Key), + a -> { + // key set1 does not exist + }); + // #get-response2 + + // #get return b.build(); } } - //#get + // #get static - //#get-request-context + // #get-request-context class DemonstrateGetWithRequestContext extends AbstractActor { - final ActorRef replicator = - DistributedData.get(getContext().getSystem()).replicator(); - - final ReadConsistency readTwo = new ReadFrom(2, Duration.ofSeconds(3)); - final Key counter1Key = PNCounterKey.create("counter1"); - - @Override - public Receive createReceive() { - return receiveBuilder() - .match(String.class, a -> a.equals("get-count"), a -> { - // incoming request to retrieve current value of the counter - Optional reqContext = Optional.of(getSender()); - replicator.tell(new Replicator.Get(counter1Key, - readTwo), getSelf()); - }) + final ActorRef replicator = DistributedData.get(getContext().getSystem()).replicator(); - .match(GetSuccess.class, a -> a.key().equals(counter1Key), a -> { - ActorRef replyTo = (ActorRef) a.getRequest().get(); - GetSuccess g = a; - long value = g.dataValue().getValue().longValue(); - replyTo.tell(value, getSelf()); - }) - - .match(GetFailure.class, a -> a.key().equals(counter1Key), a -> { - ActorRef replyTo = (ActorRef) a.getRequest().get(); - replyTo.tell(-1L, getSelf()); - }) - - .match(NotFound.class, a -> a.key().equals(counter1Key), a -> { - ActorRef replyTo = (ActorRef) a.getRequest().get(); - replyTo.tell(0L, getSelf()); - }) - - .build(); - } - } - //#get-request-context - - static -//#subscribe - class DemonstrateSubscribe extends AbstractActor { - final ActorRef replicator = - DistributedData.get(getContext().getSystem()).replicator(); + final ReadConsistency readTwo = new ReadFrom(2, Duration.ofSeconds(3)); final Key counter1Key = PNCounterKey.create("counter1"); - - BigInteger currentValue = BigInteger.valueOf(0); - + @Override public Receive createReceive() { return receiveBuilder() - .match(Changed.class, a -> a.key().equals(counter1Key), a -> { - Changed g = a; - currentValue = g.dataValue().getValue(); - }) - .match(String.class, a -> a.equals("get-count"), a -> { - // incoming request to retrieve current value of the counter - getSender().tell(currentValue, getSender()); - }) - .build(); + .match( + String.class, + a -> a.equals("get-count"), + a -> { + // incoming request to retrieve current value of the counter + Optional reqContext = Optional.of(getSender()); + replicator.tell(new Replicator.Get(counter1Key, readTwo), getSelf()); + }) + .match( + GetSuccess.class, + a -> a.key().equals(counter1Key), + a -> { + ActorRef replyTo = (ActorRef) a.getRequest().get(); + GetSuccess g = a; + long value = g.dataValue().getValue().longValue(); + replyTo.tell(value, getSelf()); + }) + .match( + GetFailure.class, + a -> a.key().equals(counter1Key), + a -> { + ActorRef replyTo = (ActorRef) a.getRequest().get(); + replyTo.tell(-1L, getSelf()); + }) + .match( + NotFound.class, + a -> a.key().equals(counter1Key), + a -> { + ActorRef replyTo = (ActorRef) a.getRequest().get(); + replyTo.tell(0L, getSelf()); + }) + .build(); } - + } + // #get-request-context + + static + // #subscribe + class DemonstrateSubscribe extends AbstractActor { + final ActorRef replicator = DistributedData.get(getContext().getSystem()).replicator(); + final Key counter1Key = PNCounterKey.create("counter1"); + + BigInteger currentValue = BigInteger.valueOf(0); + + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + Changed.class, + a -> a.key().equals(counter1Key), + a -> { + Changed g = a; + currentValue = g.dataValue().getValue(); + }) + .match( + String.class, + a -> a.equals("get-count"), + a -> { + // incoming request to retrieve current value of the counter + getSender().tell(currentValue, getSender()); + }) + .build(); + } + @Override public void preStart() { // subscribe to changes of the Counter1Key value replicator.tell(new Subscribe(counter1Key, getSelf()), ActorRef.noSender()); } - } - //#subscribe + // #subscribe static - //#delete + // #delete class DemonstrateDelete extends AbstractActor { - final ActorRef replicator = - DistributedData.get(getContext().getSystem()).replicator(); - + final ActorRef replicator = DistributedData.get(getContext().getSystem()).replicator(); + final Key counter1Key = PNCounterKey.create("counter1"); final Key> set2Key = ORSetKey.create("set2"); - + @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("demonstrate delete", msg -> { + .matchEquals( + "demonstrate delete", + msg -> { + replicator.tell( + new Delete(counter1Key, Replicator.writeLocal()), getSelf()); - replicator.tell(new Delete(counter1Key, - Replicator.writeLocal()), getSelf()); - - final WriteConsistency writeMajority = - new WriteMajority(Duration.ofSeconds(5)); - replicator.tell(new Delete(counter1Key, - writeMajority), getSelf()); - }) - .build(); + final WriteConsistency writeMajority = new WriteMajority(Duration.ofSeconds(5)); + replicator.tell(new Delete(counter1Key, writeMajority), getSelf()); + }) + .build(); } } - //#delete + // #delete public void demonstratePNCounter() { - //#pncounter + // #pncounter final SelfUniqueAddress node = DistributedData.get(system).selfUniqueAddress(); final PNCounter c0 = PNCounter.create(); final PNCounter c1 = c0.increment(node, 1); final PNCounter c2 = c1.increment(node, 7); final PNCounter c3 = c2.decrement(node, 2); System.out.println(c3.value()); // 6 - //#pncounter + // #pncounter } public void demonstratePNCounterMap() { - //#pncountermap + // #pncountermap final SelfUniqueAddress node = DistributedData.get(system).selfUniqueAddress(); final PNCounterMap m0 = PNCounterMap.create(); final PNCounterMap m1 = m0.increment(node, "a", 7); @@ -323,64 +373,62 @@ public class DistributedDataDocTest extends AbstractJavaTest { final PNCounterMap m3 = m2.increment(node, "b", 1); System.out.println(m3.get("a")); // 5 System.out.println(m3.getEntries()); - //#pncountermap + // #pncountermap } public void demonstrateGSet() { - //#gset + // #gset final GSet s0 = GSet.create(); final GSet s1 = s0.add("a"); final GSet s2 = s1.add("b").add("c"); - if (s2.contains("a")) - System.out.println(s2.getElements()); // a, b, c - //#gset + if (s2.contains("a")) System.out.println(s2.getElements()); // a, b, c + // #gset } public void demonstrateORSet() { - //#orset + // #orset final Cluster node = Cluster.get(system); final ORSet s0 = ORSet.create(); final ORSet s1 = s0.add(node, "a"); final ORSet s2 = s1.add(node, "b"); final ORSet s3 = s2.remove(node, "a"); System.out.println(s3.getElements()); // b - //#orset + // #orset } public void demonstrateORMultiMap() { - //#ormultimap + // #ormultimap final SelfUniqueAddress node = DistributedData.get(system).selfUniqueAddress(); final ORMultiMap m0 = ORMultiMap.create(); - final ORMultiMap m1 = m0.put(node, "a", - new HashSet<>(Arrays.asList(1, 2, 3))); + final ORMultiMap m1 = m0.put(node, "a", new HashSet<>(Arrays.asList(1, 2, 3))); final ORMultiMap m2 = m1.addBinding(node, "a", 4); final ORMultiMap m3 = m2.removeBinding(node, "a", 2); final ORMultiMap m4 = m3.addBinding(node, "b", 1); System.out.println(m4.getEntries()); - //#ormultimap + // #ormultimap } public void demonstrateFlag() { - //#flag + // #flag final Flag f0 = Flag.create(); final Flag f1 = f0.switchOn(); System.out.println(f1.enabled()); - //#flag + // #flag } @Test public void demonstrateLWWRegister() { - //#lwwregister + // #lwwregister final SelfUniqueAddress node = DistributedData.get(system).selfUniqueAddress(); final LWWRegister r1 = LWWRegister.create(node, "Hello"); final LWWRegister r2 = r1.withValue(node, "Hi"); System.out.println(r1.value() + " by " + r1.updatedBy() + " at " + r1.timestamp()); - //#lwwregister + // #lwwregister assertEquals("Hi", r2.value()); } - + static - //#lwwregister-custom-clock + // #lwwregister-custom-clock class Record { public final int version; public final String name; @@ -392,19 +440,20 @@ public class DistributedDataDocTest extends AbstractJavaTest { this.address = address; } } - - //#lwwregister-custom-clock - + + // #lwwregister-custom-clock + public void demonstrateLWWRegisterWithCustomClock() { - //#lwwregister-custom-clock + // #lwwregister-custom-clock final SelfUniqueAddress node = DistributedData.get(system).selfUniqueAddress(); - final LWWRegister.Clock recordClock = new LWWRegister.Clock() { - @Override - public long apply(long currentTimestamp, Record value) { - return value.version; - } - }; + final LWWRegister.Clock recordClock = + new LWWRegister.Clock() { + @Override + public long apply(long currentTimestamp, Record value) { + return value.version; + } + }; final Record record1 = new Record(1, "Alice", "Union Square"); final LWWRegister r1 = LWWRegister.create(node, record1); @@ -414,9 +463,8 @@ public class DistributedDataDocTest extends AbstractJavaTest { final LWWRegister r3 = r1.merge(r2); System.out.println(r3.value()); - //#lwwregister-custom-clock + // #lwwregister-custom-clock assertEquals("Madison Square", r3.value().address); } - } diff --git a/akka-docs/src/test/java/jdocs/ddata/ShoppingCart.java b/akka-docs/src/test/java/jdocs/ddata/ShoppingCart.java index 9a2055d6a1..156fedd680 100644 --- a/akka-docs/src/test/java/jdocs/ddata/ShoppingCart.java +++ b/akka-docs/src/test/java/jdocs/ddata/ShoppingCart.java @@ -30,12 +30,10 @@ import akka.cluster.ddata.Replicator.WriteMajority; @SuppressWarnings("unchecked") public class ShoppingCart extends AbstractActor { - //#read-write-majority - private final WriteConsistency writeMajority = - new WriteMajority(Duration.ofSeconds(3)); - private final static ReadConsistency readMajority = - new ReadMajority(Duration.ofSeconds(3)); - //#read-write-majority + // #read-write-majority + private final WriteConsistency writeMajority = new WriteMajority(Duration.ofSeconds(3)); + private static final ReadConsistency readMajority = new ReadMajority(Duration.ofSeconds(3)); + // #read-write-majority public static final String GET_CART = "getCart"; @@ -87,33 +85,30 @@ public class ShoppingCart extends AbstractActor { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; LineItem other = (LineItem) obj; if (productId == null) { - if (other.productId != null) - return false; - } else if (!productId.equals(other.productId)) - return false; - if (quantity != other.quantity) - return false; + if (other.productId != null) return false; + } else if (!productId.equals(other.productId)) return false; + if (quantity != other.quantity) return false; if (title == null) { - if (other.title != null) - return false; - } else if (!title.equals(other.title)) - return false; + if (other.title != null) return false; + } else if (!title.equals(other.title)) return false; return true; } @Override public String toString() { - return "LineItem [productId=" + productId + ", title=" + title + ", quantity=" + quantity + "]"; + return "LineItem [productId=" + + productId + + ", title=" + + title + + ", quantity=" + + quantity + + "]"; } - } public static Props props(String userId) { @@ -121,10 +116,12 @@ public class ShoppingCart extends AbstractActor { } private final ActorRef replicator = DistributedData.get(getContext().getSystem()).replicator(); - private final SelfUniqueAddress node = DistributedData.get(getContext().getSystem()).selfUniqueAddress(); + private final SelfUniqueAddress node = + DistributedData.get(getContext().getSystem()).selfUniqueAddress(); @SuppressWarnings("unused") private final String userId; + private final Key> dataKey; public ShoppingCart(String userId) { @@ -134,34 +131,37 @@ public class ShoppingCart extends AbstractActor { @Override public Receive createReceive() { - return matchGetCart() - .orElse(matchAddItem()) - .orElse(matchRemoveItem()) - .orElse(matchOther()); + return matchGetCart().orElse(matchAddItem()).orElse(matchRemoveItem()).orElse(matchOther()); } - //#get-cart + // #get-cart private Receive matchGetCart() { return receiveBuilder() - .matchEquals(GET_CART, s -> receiveGetCart()) - .match(GetSuccess.class, this::isResponseToGetCart, - g -> receiveGetSuccess((GetSuccess>) g)) - .match(NotFound.class, this::isResponseToGetCart, - n -> receiveNotFound((NotFound>) n)) - .match(GetFailure.class, this::isResponseToGetCart, - f -> receiveGetFailure((GetFailure>) f)) - .build(); + .matchEquals(GET_CART, s -> receiveGetCart()) + .match( + GetSuccess.class, + this::isResponseToGetCart, + g -> receiveGetSuccess((GetSuccess>) g)) + .match( + NotFound.class, + this::isResponseToGetCart, + n -> receiveNotFound((NotFound>) n)) + .match( + GetFailure.class, + this::isResponseToGetCart, + f -> receiveGetFailure((GetFailure>) f)) + .build(); } private void receiveGetCart() { Optional ctx = Optional.of(getSender()); - replicator.tell(new Replicator.Get>(dataKey, readMajority, ctx), - getSelf()); + replicator.tell( + new Replicator.Get>(dataKey, readMajority, ctx), getSelf()); } private boolean isResponseToGetCart(GetResponse response) { - return response.key().equals(dataKey) && - (response.getRequest().orElse(null) instanceof ActorRef); + return response.key().equals(dataKey) + && (response.getRequest().orElse(null) instanceof ActorRef); } private void receiveGetSuccess(GetSuccess> g) { @@ -178,25 +178,24 @@ public class ShoppingCart extends AbstractActor { private void receiveGetFailure(GetFailure> f) { // ReadMajority failure, try again with local read Optional ctx = Optional.of(getSender()); - replicator.tell(new Replicator.Get>(dataKey, Replicator.readLocal(), - ctx), getSelf()); + replicator.tell( + new Replicator.Get>(dataKey, Replicator.readLocal(), ctx), + getSelf()); } - //#get-cart + // #get-cart - //#add-item + // #add-item private Receive matchAddItem() { - return receiveBuilder() - .match(AddItem.class, this::receiveAddItem) - .build(); + return receiveBuilder().match(AddItem.class, this::receiveAddItem).build(); } private void receiveAddItem(AddItem add) { - Update> update = new Update<>(dataKey, LWWMap.create(), writeMajority, - cart -> updateCart(cart, add.item)); + Update> update = + new Update<>(dataKey, LWWMap.create(), writeMajority, cart -> updateCart(cart, add.item)); replicator.tell(update, getSelf()); } - //#add-item + // #add-item private LWWMap updateCart(LWWMap data, LineItem item) { if (data.contains(item.productId)) { @@ -211,22 +210,31 @@ public class ShoppingCart extends AbstractActor { private Receive matchRemoveItem() { return receiveBuilder() - .match(RemoveItem.class, this::receiveRemoveItem) - .match(GetSuccess.class, this::isResponseToRemoveItem, - g -> receiveRemoveItemGetSuccess((GetSuccess>) g)) - .match(GetFailure.class, this::isResponseToRemoveItem, - f -> receiveRemoveItemGetFailure((GetFailure>) f)) - .match(NotFound.class, this::isResponseToRemoveItem, n -> {/* nothing to remove */}) - .build(); + .match(RemoveItem.class, this::receiveRemoveItem) + .match( + GetSuccess.class, + this::isResponseToRemoveItem, + g -> receiveRemoveItemGetSuccess((GetSuccess>) g)) + .match( + GetFailure.class, + this::isResponseToRemoveItem, + f -> receiveRemoveItemGetFailure((GetFailure>) f)) + .match( + NotFound.class, + this::isResponseToRemoveItem, + n -> { + /* nothing to remove */ + }) + .build(); } - //#remove-item + // #remove-item private void receiveRemoveItem(RemoveItem rm) { // Try to fetch latest from a majority of nodes first, since ORMap // remove must have seen the item to be able to remove it. Optional ctx = Optional.of(rm); - replicator.tell(new Replicator.Get>(dataKey, readMajority, ctx), - getSelf()); + replicator.tell( + new Replicator.Get>(dataKey, readMajority, ctx), getSelf()); } private void receiveRemoveItemGetSuccess(GetSuccess> g) { @@ -234,7 +242,6 @@ public class ShoppingCart extends AbstractActor { removeItem(rm.productId); } - private void receiveRemoveItemGetFailure(GetFailure> f) { // ReadMajority failed, fall back to best effort local value RemoveItem rm = (RemoveItem) f.getRequest().get(); @@ -242,29 +249,34 @@ public class ShoppingCart extends AbstractActor { } private void removeItem(String productId) { - Update> update = new Update<>(dataKey, LWWMap.create(), writeMajority, - cart -> cart.remove(node, productId)); + Update> update = + new Update<>(dataKey, LWWMap.create(), writeMajority, cart -> cart.remove(node, productId)); replicator.tell(update, getSelf()); } private boolean isResponseToRemoveItem(GetResponse response) { - return response.key().equals(dataKey) && - (response.getRequest().orElse(null) instanceof RemoveItem); + return response.key().equals(dataKey) + && (response.getRequest().orElse(null) instanceof RemoveItem); } - //#remove-item + // #remove-item private Receive matchOther() { return receiveBuilder() - .match(UpdateSuccess.class, u -> { - // ok - }) - .match(UpdateTimeout.class, t -> { - // will eventually be replicated - }) - .match(UpdateFailure.class, f -> { - throw new IllegalStateException("Unexpected failure: " + f); - }) - .build(); + .match( + UpdateSuccess.class, + u -> { + // ok + }) + .match( + UpdateTimeout.class, + t -> { + // will eventually be replicated + }) + .match( + UpdateFailure.class, + f -> { + throw new IllegalStateException("Unexpected failure: " + f); + }) + .build(); } - -} \ No newline at end of file +} diff --git a/akka-docs/src/test/java/jdocs/ddata/TwoPhaseSet.java b/akka-docs/src/test/java/jdocs/ddata/TwoPhaseSet.java index 2ce83b8fb3..0e2fa0cb9e 100644 --- a/akka-docs/src/test/java/jdocs/ddata/TwoPhaseSet.java +++ b/akka-docs/src/test/java/jdocs/ddata/TwoPhaseSet.java @@ -11,17 +11,17 @@ import java.util.Set; import akka.cluster.ddata.AbstractReplicatedData; import akka.cluster.ddata.GSet; -//#twophaseset +// #twophaseset public class TwoPhaseSet extends AbstractReplicatedData { - + public final GSet adds; public final GSet removals; - + public TwoPhaseSet(GSet adds, GSet removals) { this.adds = adds; this.removals = removals; } - + public static TwoPhaseSet create() { return new TwoPhaseSet(GSet.create(), GSet.create()); } @@ -29,7 +29,7 @@ public class TwoPhaseSet extends AbstractReplicatedData { public TwoPhaseSet add(String element) { return new TwoPhaseSet(adds.add(element), removals); } - + public TwoPhaseSet remove(String element) { return new TwoPhaseSet(adds, removals.add(element)); } @@ -42,8 +42,7 @@ public class TwoPhaseSet extends AbstractReplicatedData { @Override public TwoPhaseSet mergeData(TwoPhaseSet that) { - return new TwoPhaseSet(this.adds.merge(that.adds), - this.removals.merge(that.removals)); + return new TwoPhaseSet(this.adds.merge(that.adds), this.removals.merge(that.removals)); } } -//#twophaseset +// #twophaseset diff --git a/akka-docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializer.java b/akka-docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializer.java index 447a8dc9ef..a0239382ca 100644 --- a/akka-docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializer.java +++ b/akka-docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializer.java @@ -4,7 +4,7 @@ package jdocs.ddata.protobuf; -//#serializer +// #serializer import jdocs.ddata.TwoPhaseSet; import docs.ddata.protobuf.msg.TwoPhaseSetMessages; import docs.ddata.protobuf.msg.TwoPhaseSetMessages.TwoPhaseSet.Builder; @@ -16,13 +16,13 @@ import akka.cluster.ddata.GSet; import akka.cluster.ddata.protobuf.AbstractSerializationSupport; public class TwoPhaseSetSerializer extends AbstractSerializationSupport { - + private final ExtendedActorSystem system; public TwoPhaseSetSerializer(ExtendedActorSystem system) { this.system = system; } - + @Override public ExtendedActorSystem system() { return this.system; @@ -33,7 +33,7 @@ public class TwoPhaseSetSerializer extends AbstractSerializationSupport { return false; } - @Override + @Override public int identifier() { return 99998; } @@ -43,8 +43,7 @@ public class TwoPhaseSetSerializer extends AbstractSerializationSupport { if (obj instanceof TwoPhaseSet) { return twoPhaseSetToProto((TwoPhaseSet) obj).toByteArray(); } else { - throw new IllegalArgumentException( - "Can't serialize object of type " + obj.getClass()); + throw new IllegalArgumentException("Can't serialize object of type " + obj.getClass()); } } @@ -69,9 +68,8 @@ public class TwoPhaseSetSerializer extends AbstractSerializationSupport { } protected TwoPhaseSet twoPhaseSetFromBinary(byte[] bytes) { - try { - TwoPhaseSetMessages.TwoPhaseSet msg = - TwoPhaseSetMessages.TwoPhaseSet.parseFrom(bytes); + try { + TwoPhaseSetMessages.TwoPhaseSet msg = TwoPhaseSetMessages.TwoPhaseSet.parseFrom(bytes); GSet adds = GSet.create(); for (String elem : msg.getAddsList()) { adds = adds.add(elem); @@ -88,6 +86,4 @@ public class TwoPhaseSetSerializer extends AbstractSerializationSupport { } } } -//#serializer - - +// #serializer diff --git a/akka-docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializer2.java b/akka-docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializer2.java index 3fb84778fc..bbfa65be78 100644 --- a/akka-docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializer2.java +++ b/akka-docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializer2.java @@ -4,7 +4,7 @@ package jdocs.ddata.protobuf; -//#serializer +// #serializer import jdocs.ddata.TwoPhaseSet; import docs.ddata.protobuf.msg.TwoPhaseSetMessages; import docs.ddata.protobuf.msg.TwoPhaseSetMessages.TwoPhaseSet2.Builder; @@ -15,7 +15,7 @@ import akka.cluster.ddata.protobuf.AbstractSerializationSupport; import akka.cluster.ddata.protobuf.ReplicatedDataSerializer; public class TwoPhaseSetSerializer2 extends AbstractSerializationSupport { - + private final ExtendedActorSystem system; private final ReplicatedDataSerializer replicatedDataSerializer; @@ -23,7 +23,7 @@ public class TwoPhaseSetSerializer2 extends AbstractSerializationSupport { this.system = system; this.replicatedDataSerializer = new ReplicatedDataSerializer(system); } - + @Override public ExtendedActorSystem system() { return this.system; @@ -34,7 +34,7 @@ public class TwoPhaseSetSerializer2 extends AbstractSerializationSupport { return false; } - @Override + @Override public int identifier() { return 99998; } @@ -44,8 +44,7 @@ public class TwoPhaseSetSerializer2 extends AbstractSerializationSupport { if (obj instanceof TwoPhaseSet) { return twoPhaseSetToProto((TwoPhaseSet) obj).toByteArray(); } else { - throw new IllegalArgumentException( - "Can't serialize object of type " + obj.getClass()); + throw new IllegalArgumentException("Can't serialize object of type " + obj.getClass()); } } @@ -65,24 +64,20 @@ public class TwoPhaseSetSerializer2 extends AbstractSerializationSupport { @SuppressWarnings("unchecked") protected TwoPhaseSet twoPhaseSetFromBinary(byte[] bytes) { - try { - TwoPhaseSetMessages.TwoPhaseSet2 msg = - TwoPhaseSetMessages.TwoPhaseSet2.parseFrom(bytes); - + try { + TwoPhaseSetMessages.TwoPhaseSet2 msg = TwoPhaseSetMessages.TwoPhaseSet2.parseFrom(bytes); + GSet adds = GSet.create(); - if (msg.hasAdds()) - adds = (GSet) otherMessageFromBinary(msg.getAdds().toByteArray()); - + if (msg.hasAdds()) adds = (GSet) otherMessageFromBinary(msg.getAdds().toByteArray()); + GSet removals = GSet.create(); if (msg.hasRemovals()) adds = (GSet) otherMessageFromBinary(msg.getRemovals().toByteArray()); - + return new TwoPhaseSet(adds, removals); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } -//#serializer - - +// #serializer diff --git a/akka-docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializerWithCompression.java b/akka-docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializerWithCompression.java index 8d308bbb54..ea0a031593 100644 --- a/akka-docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializerWithCompression.java +++ b/akka-docs/src/test/java/jdocs/ddata/protobuf/TwoPhaseSetSerializerWithCompression.java @@ -12,15 +12,14 @@ public class TwoPhaseSetSerializerWithCompression extends TwoPhaseSetSerializer public TwoPhaseSetSerializerWithCompression(ExtendedActorSystem system) { super(system); } - - //#compression + + // #compression @Override public byte[] toBinary(Object obj) { if (obj instanceof TwoPhaseSet) { return compress(twoPhaseSetToProto((TwoPhaseSet) obj)); } else { - throw new IllegalArgumentException( - "Can't serialize object of type " + obj.getClass()); + throw new IllegalArgumentException("Can't serialize object of type " + obj.getClass()); } } @@ -28,6 +27,5 @@ public class TwoPhaseSetSerializerWithCompression extends TwoPhaseSetSerializer public Object fromBinaryJava(byte[] bytes, Class manifest) { return twoPhaseSetFromBinary(decompress(bytes)); } - //#compression + // #compression } - diff --git a/akka-docs/src/test/java/jdocs/dispatcher/DispatcherDocTest.java b/akka-docs/src/test/java/jdocs/dispatcher/DispatcherDocTest.java index 818136999f..fcd30ba6d8 100644 --- a/akka-docs/src/test/java/jdocs/dispatcher/DispatcherDocTest.java +++ b/akka-docs/src/test/java/jdocs/dispatcher/DispatcherDocTest.java @@ -17,137 +17,143 @@ import org.junit.ClassRule; import org.junit.Test; import scala.concurrent.ExecutionContext; -//#imports +// #imports import akka.actor.*; -//#imports -//#imports-prio +// #imports +// #imports-prio import akka.event.Logging; import akka.event.LoggingAdapter; -//#imports-prio +// #imports-prio -//#imports-prio-mailbox +// #imports-prio-mailbox import akka.dispatch.PriorityGenerator; import akka.dispatch.UnboundedStablePriorityMailbox; import akka.testkit.AkkaJUnitActorSystemResource; import com.typesafe.config.Config; -//#imports-prio-mailbox +// #imports-prio-mailbox -//#imports-required-mailbox +// #imports-required-mailbox -//#imports-required-mailbox +// #imports-required-mailbox public class DispatcherDocTest extends AbstractJavaTest { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("DispatcherDocTest", ConfigFactory.parseString( - DispatcherDocSpec.javaConfig()).withFallback(ConfigFactory.parseString( - DispatcherDocSpec.config())).withFallback(AkkaSpec.testConf())); + new AkkaJUnitActorSystemResource( + "DispatcherDocTest", + ConfigFactory.parseString(DispatcherDocSpec.javaConfig()) + .withFallback(ConfigFactory.parseString(DispatcherDocSpec.config())) + .withFallback(AkkaSpec.testConf())); private final ActorSystem system = actorSystemResource.getSystem(); @SuppressWarnings("unused") @Test public void defineDispatcherInConfig() { - //#defining-dispatcher-in-config - ActorRef myActor = - system.actorOf(Props.create(MyActor.class), - "myactor"); - //#defining-dispatcher-in-config + // #defining-dispatcher-in-config + ActorRef myActor = system.actorOf(Props.create(MyActor.class), "myactor"); + // #defining-dispatcher-in-config } @SuppressWarnings("unused") @Test public void defineDispatcherInCode() { - //#defining-dispatcher-in-code + // #defining-dispatcher-in-code ActorRef myActor = - system.actorOf(Props.create(MyActor.class).withDispatcher("my-dispatcher"), - "myactor3"); - //#defining-dispatcher-in-code + system.actorOf(Props.create(MyActor.class).withDispatcher("my-dispatcher"), "myactor3"); + // #defining-dispatcher-in-code } @SuppressWarnings("unused") @Test public void defineFixedPoolSizeDispatcher() { - //#defining-fixed-pool-size-dispatcher - ActorRef myActor = system.actorOf(Props.create(MyActor.class) - .withDispatcher("blocking-io-dispatcher")); - //#defining-fixed-pool-size-dispatcher + // #defining-fixed-pool-size-dispatcher + ActorRef myActor = + system.actorOf(Props.create(MyActor.class).withDispatcher("blocking-io-dispatcher")); + // #defining-fixed-pool-size-dispatcher } @SuppressWarnings("unused") @Test public void definePinnedDispatcher() { - //#defining-pinned-dispatcher - ActorRef myActor = system.actorOf(Props.create(MyActor.class) - .withDispatcher("my-pinned-dispatcher")); - //#defining-pinned-dispatcher + // #defining-pinned-dispatcher + ActorRef myActor = + system.actorOf(Props.create(MyActor.class).withDispatcher("my-pinned-dispatcher")); + // #defining-pinned-dispatcher } @SuppressWarnings("unused") public void compileLookup() { - //#lookup + // #lookup // this is scala.concurrent.ExecutionContext // for use with Futures, Scheduler, etc. final ExecutionContext ex = system.dispatchers().lookup("my-dispatcher"); - //#lookup + // #lookup } @SuppressWarnings("unused") @Test public void defineMailboxInConfig() { - //#defining-mailbox-in-config - ActorRef myActor = - system.actorOf(Props.create(MyActor.class), - "priomailboxactor"); - //#defining-mailbox-in-config + // #defining-mailbox-in-config + ActorRef myActor = system.actorOf(Props.create(MyActor.class), "priomailboxactor"); + // #defining-mailbox-in-config } @SuppressWarnings("unused") @Test public void defineMailboxInCode() { - //#defining-mailbox-in-code - ActorRef myActor = - system.actorOf(Props.create(MyActor.class) - .withMailbox("prio-mailbox")); - //#defining-mailbox-in-code + // #defining-mailbox-in-code + ActorRef myActor = system.actorOf(Props.create(MyActor.class).withMailbox("prio-mailbox")); + // #defining-mailbox-in-code } @SuppressWarnings("unused") @Test public void usingARequiredMailbox() { - ActorRef myActor = - system.actorOf(Props.create(MyBoundedActor.class)); + ActorRef myActor = system.actorOf(Props.create(MyBoundedActor.class)); } @Test public void priorityDispatcher() throws Exception { TestKit probe = new TestKit(system); - //#prio-dispatcher + // #prio-dispatcher class Demo extends AbstractActor { LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); + { - for (Object msg : new Object[] { "lowpriority", "lowpriority", - "highpriority", "pigdog", "pigdog2", "pigdog3", "highpriority", - PoisonPill.getInstance() }) { - getSelf().tell(msg, getSelf()); + for (Object msg : + new Object[] { + "lowpriority", + "lowpriority", + "highpriority", + "pigdog", + "pigdog2", + "pigdog3", + "highpriority", + PoisonPill.getInstance() + }) { + getSelf().tell(msg, getSelf()); } } @Override public Receive createReceive() { - return receiveBuilder().matchAny(message -> { - log.info(message.toString()); - }).build(); + return receiveBuilder() + .matchAny( + message -> { + log.info(message.toString()); + }) + .build(); } } // We create a new Actor that just prints out what it processes - ActorRef myActor = system.actorOf(Props.create(Demo.class, this) - .withDispatcher("prio-dispatcher")); + ActorRef myActor = + system.actorOf(Props.create(Demo.class, this).withDispatcher("prio-dispatcher")); /* Logs: @@ -159,7 +165,7 @@ public class DispatcherDocTest extends AbstractJavaTest { 'lowpriority 'lowpriority */ - //#prio-dispatcher + // #prio-dispatcher probe.watch(myActor); probe.expectMsgClass(Terminated.class); @@ -168,28 +174,32 @@ public class DispatcherDocTest extends AbstractJavaTest { @Test public void controlAwareDispatcher() throws Exception { TestKit probe = new TestKit(system); - //#control-aware-dispatcher + // #control-aware-dispatcher class Demo extends AbstractActor { LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); + { - for (Object msg : new Object[] { "foo", "bar", new MyControlMessage(), - PoisonPill.getInstance() }) { - getSelf().tell(msg, getSelf()); + for (Object msg : + new Object[] {"foo", "bar", new MyControlMessage(), PoisonPill.getInstance()}) { + getSelf().tell(msg, getSelf()); } } @Override public Receive createReceive() { - return receiveBuilder().matchAny(message -> { - log.info(message.toString()); - }).build(); + return receiveBuilder() + .matchAny( + message -> { + log.info(message.toString()); + }) + .build(); } } // We create a new Actor that just prints out what it processes - ActorRef myActor = system.actorOf(Props.create(Demo.class, this) - .withDispatcher("control-aware-dispatcher")); + ActorRef myActor = + system.actorOf(Props.create(Demo.class, this).withDispatcher("control-aware-dispatcher")); /* Logs: @@ -197,63 +207,62 @@ public class DispatcherDocTest extends AbstractJavaTest { 'foo 'bar */ - //#control-aware-dispatcher + // #control-aware-dispatcher probe.watch(myActor); probe.expectMsgClass(Terminated.class); } - static - //#prio-mailbox - public class MyPrioMailbox extends UnboundedStablePriorityMailbox { + public + // #prio-mailbox + static class MyPrioMailbox extends UnboundedStablePriorityMailbox { // needed for reflective instantiation public MyPrioMailbox(ActorSystem.Settings settings, Config config) { // Create a new PriorityGenerator, lower prio means more important - super(new PriorityGenerator() { - @Override - public int gen(Object message) { - if (message.equals("highpriority")) - return 0; // 'highpriority messages should be treated first if possible - else if (message.equals("lowpriority")) - return 2; // 'lowpriority messages should be treated last if possible - else if (message.equals(PoisonPill.getInstance())) - return 3; // PoisonPill when no other left - else - return 1; // By default they go between high and low prio - } - }); + super( + new PriorityGenerator() { + @Override + public int gen(Object message) { + if (message.equals("highpriority")) + return 0; // 'highpriority messages should be treated first if possible + else if (message.equals("lowpriority")) + return 2; // 'lowpriority messages should be treated last if possible + else if (message.equals(PoisonPill.getInstance())) + return 3; // PoisonPill when no other left + else return 1; // By default they go between high and low prio + } + }); } } - //#prio-mailbox + // #prio-mailbox - static - //#control-aware-mailbox-messages - public class MyControlMessage implements ControlMessage {} - //#control-aware-mailbox-messages + public + // #control-aware-mailbox-messages + static class MyControlMessage implements ControlMessage {} + // #control-aware-mailbox-messages @Test public void requiredMailboxDispatcher() throws Exception { - ActorRef myActor = system.actorOf(Props.create(MyActor.class) - .withDispatcher("custom-dispatcher")); + ActorRef myActor = + system.actorOf(Props.create(MyActor.class).withDispatcher("custom-dispatcher")); } - static - //#require-mailbox-on-actor - public class MySpecialActor extends AbstractActor implements - RequiresMessageQueue { - //#require-mailbox-on-actor + public + // #require-mailbox-on-actor + static class MySpecialActor extends AbstractActor + implements RequiresMessageQueue { + // #require-mailbox-on-actor @Override public Receive createReceive() { return AbstractActor.emptyBehavior(); } - //#require-mailbox-on-actor + // #require-mailbox-on-actor // ... } - //#require-mailbox-on-actor + // #require-mailbox-on-actor @Test public void requiredMailboxActor() throws Exception { ActorRef myActor = system.actorOf(Props.create(MySpecialActor.class)); } - } diff --git a/akka-docs/src/test/java/jdocs/dispatcher/MyUnboundedMailbox.java b/akka-docs/src/test/java/jdocs/dispatcher/MyUnboundedMailbox.java index 21e02dd36d..9c46c1bb58 100644 --- a/akka-docs/src/test/java/jdocs/dispatcher/MyUnboundedMailbox.java +++ b/akka-docs/src/test/java/jdocs/dispatcher/MyUnboundedMailbox.java @@ -4,7 +4,7 @@ package jdocs.dispatcher; -//#mailbox-implementation-example +// #mailbox-implementation-example import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.dispatch.Envelope; @@ -16,24 +16,32 @@ import java.util.concurrent.ConcurrentLinkedQueue; import java.util.Queue; import scala.Option; -public class MyUnboundedMailbox implements MailboxType, - ProducesMessageQueue { +public class MyUnboundedMailbox + implements MailboxType, ProducesMessageQueue { // This is the MessageQueue implementation - public static class MyMessageQueue implements MessageQueue, - MyUnboundedMessageQueueSemantics { - private final Queue queue = - new ConcurrentLinkedQueue(); + public static class MyMessageQueue implements MessageQueue, MyUnboundedMessageQueueSemantics { + private final Queue queue = new ConcurrentLinkedQueue(); // these must be implemented; queue used as example public void enqueue(ActorRef receiver, Envelope handle) { queue.offer(handle); } - public Envelope dequeue() { return queue.poll(); } - public int numberOfMessages() { return queue.size(); } - public boolean hasMessages() { return !queue.isEmpty(); } + + public Envelope dequeue() { + return queue.poll(); + } + + public int numberOfMessages() { + return queue.size(); + } + + public boolean hasMessages() { + return !queue.isEmpty(); + } + public void cleanUp(ActorRef owner, MessageQueue deadLetters) { - for (Envelope handle: queue) { + for (Envelope handle : queue) { deadLetters.enqueue(owner, handle); } } @@ -49,4 +57,4 @@ public class MyUnboundedMailbox implements MailboxType, return new MyMessageQueue(); } } -//#mailbox-implementation-example +// #mailbox-implementation-example diff --git a/akka-docs/src/test/java/jdocs/dispatcher/MyUnboundedMessageQueueSemantics.java b/akka-docs/src/test/java/jdocs/dispatcher/MyUnboundedMessageQueueSemantics.java index 4ca291dcc8..0c222fa247 100644 --- a/akka-docs/src/test/java/jdocs/dispatcher/MyUnboundedMessageQueueSemantics.java +++ b/akka-docs/src/test/java/jdocs/dispatcher/MyUnboundedMessageQueueSemantics.java @@ -4,8 +4,7 @@ package jdocs.dispatcher; -//#mailbox-marker-interface +// #mailbox-marker-interface // Marker interface used for mailbox requirements mapping -public interface MyUnboundedMessageQueueSemantics { -} -//#mailbox-marker-interface +public interface MyUnboundedMessageQueueSemantics {} +// #mailbox-marker-interface diff --git a/akka-docs/src/test/java/jdocs/duration/Java.java b/akka-docs/src/test/java/jdocs/duration/Java.java index 531ea1f600..7d33fbf34a 100644 --- a/akka-docs/src/test/java/jdocs/duration/Java.java +++ b/akka-docs/src/test/java/jdocs/duration/Java.java @@ -4,24 +4,24 @@ package jdocs.duration; -//#import +// #import import scala.concurrent.duration.Duration; import scala.concurrent.duration.Deadline; -//#import +// #import class Java { public void demo() { - //#dsl + // #dsl final Duration fivesec = Duration.create(5, "seconds"); final Duration threemillis = Duration.create("3 millis"); final Duration diff = fivesec.minus(threemillis); assert diff.lt(fivesec); assert Duration.Zero().lt(Duration.Inf()); - //#dsl - //#deadline + // #dsl + // #deadline final Deadline deadline = Duration.create(10, "seconds").fromNow(); final Duration rest = deadline.timeLeft(); - //#deadline + // #deadline rest.toString(); } } diff --git a/akka-docs/src/test/java/jdocs/event/EventBusDocTest.java b/akka-docs/src/test/java/jdocs/event/EventBusDocTest.java index bcb668771a..95feb93720 100644 --- a/akka-docs/src/test/java/jdocs/event/EventBusDocTest.java +++ b/akka-docs/src/test/java/jdocs/event/EventBusDocTest.java @@ -18,79 +18,79 @@ import akka.actor.ActorRef; import akka.testkit.AkkaJUnitActorSystemResource; import akka.util.Subclassification; -//#lookup-bus +// #lookup-bus import akka.event.japi.LookupEventBus; -//#lookup-bus +// #lookup-bus -//#subchannel-bus +// #subchannel-bus import akka.event.japi.SubchannelEventBus; -//#subchannel-bus +// #subchannel-bus -//#scanning-bus +// #scanning-bus import akka.event.japi.ScanningEventBus; -//#scanning-bus +// #scanning-bus -//#actor-bus +// #actor-bus import akka.event.japi.ManagedActorEventBus; -//#actor-bus +// #actor-bus public class EventBusDocTest extends AbstractJavaTest { - + public static class Event {} + public static class Subscriber {} + public static class Classifier {} - - static public interface EventBusApi extends EventBus { + + public static interface EventBusApi extends EventBus { @Override - //#event-bus-api + // #event-bus-api /** * Attempts to register the subscriber to the specified Classifier - * @return true if successful and false if not (because it was already - * subscribed to that Classifier, or otherwise) + * + * @return true if successful and false if not (because it was already subscribed to that + * Classifier, or otherwise) */ public boolean subscribe(Subscriber subscriber, Classifier to); - - //#event-bus-api + + // #event-bus-api @Override - //#event-bus-api + // #event-bus-api /** * Attempts to deregister the subscriber from the specified Classifier - * @return true if successful and false if not (because it wasn't subscribed - * to that Classifier, or otherwise) + * + * @return true if successful and false if not (because it wasn't subscribed to that Classifier, + * or otherwise) */ public boolean unsubscribe(Subscriber subscriber, Classifier from); - //#event-bus-api - - @Override - //#event-bus-api - /** - * Attempts to deregister the subscriber from all Classifiers it may be subscribed to - */ - public void unsubscribe(Subscriber subscriber); - - //#event-bus-api + // #event-bus-api @Override - //#event-bus-api - /** - * Publishes the specified Event to this bus - */ + // #event-bus-api + /** Attempts to deregister the subscriber from all Classifiers it may be subscribed to */ + public void unsubscribe(Subscriber subscriber); + + // #event-bus-api + + @Override + // #event-bus-api + /** Publishes the specified Event to this bus */ public void publish(Event event); - - //#event-bus-api - + + // #event-bus-api + } - static - //#lookup-bus - public class MsgEnvelope { + public + // #lookup-bus + static class MsgEnvelope { public final String topic; public final Object payload; @@ -99,121 +99,131 @@ public class EventBusDocTest extends AbstractJavaTest { this.payload = payload; } } - - //#lookup-bus - static - //#lookup-bus + + // #lookup-bus + public + // #lookup-bus /** - * Publishes the payload of the MsgEnvelope when the topic of the - * MsgEnvelope equals the String specified when subscribing. + * Publishes the payload of the MsgEnvelope when the topic of the MsgEnvelope equals the String + * specified when subscribing. */ - public class LookupBusImpl extends LookupEventBus { + static class LookupBusImpl extends LookupEventBus { // is used for extracting the classifier from the incoming events - @Override public String classify(MsgEnvelope event) { + @Override + public String classify(MsgEnvelope event) { return event.topic; } // will be invoked for each event for all subscribers which registered themselves // for the event’s classifier - @Override public void publish(MsgEnvelope event, ActorRef subscriber) { + @Override + public void publish(MsgEnvelope event, ActorRef subscriber) { subscriber.tell(event.payload, ActorRef.noSender()); } // must define a full order over the subscribers, expressed as expected from // `java.lang.Comparable.compare` - @Override public int compareSubscribers(ActorRef a, ActorRef b) { + @Override + public int compareSubscribers(ActorRef a, ActorRef b) { return a.compareTo(b); } // determines the initial size of the index data structure // used internally (i.e. the expected number of different classifiers) - @Override public int mapSize() { + @Override + public int mapSize() { return 128; } - } - //#lookup-bus - - static - //#subchannel-bus - public class StartsWithSubclassification implements Subclassification { - @Override public boolean isEqual(String x, String y) { + // #lookup-bus + + public + // #subchannel-bus + static class StartsWithSubclassification implements Subclassification { + @Override + public boolean isEqual(String x, String y) { return x.equals(y); } - @Override public boolean isSubclass(String x, String y) { + @Override + public boolean isSubclass(String x, String y) { return x.startsWith(y); } } - - //#subchannel-bus - - static - //#subchannel-bus + + // #subchannel-bus + + public + // #subchannel-bus /** - * Publishes the payload of the MsgEnvelope when the topic of the - * MsgEnvelope starts with the String specified when subscribing. + * Publishes the payload of the MsgEnvelope when the topic of the MsgEnvelope starts with the + * String specified when subscribing. */ - public class SubchannelBusImpl extends SubchannelEventBus { + static class SubchannelBusImpl extends SubchannelEventBus { // Subclassification is an object providing `isEqual` and `isSubclass` // to be consumed by the other methods of this classifier - @Override public Subclassification subclassification() { + @Override + public Subclassification subclassification() { return new StartsWithSubclassification(); } - + // is used for extracting the classifier from the incoming events - @Override public String classify(MsgEnvelope event) { + @Override + public String classify(MsgEnvelope event) { return event.topic; } // will be invoked for each event for all subscribers which registered themselves // for the event’s classifier - @Override public void publish(MsgEnvelope event, ActorRef subscriber) { + @Override + public void publish(MsgEnvelope event, ActorRef subscriber) { subscriber.tell(event.payload, ActorRef.noSender()); } - } - //#subchannel-bus - - static - //#scanning-bus + // #subchannel-bus + + public + // #scanning-bus /** - * Publishes String messages with length less than or equal to the length - * specified when subscribing. + * Publishes String messages with length less than or equal to the length specified when + * subscribing. */ - public class ScanningBusImpl extends ScanningEventBus { + static class ScanningBusImpl extends ScanningEventBus { // is needed for determining matching classifiers and storing them in an // ordered collection - @Override public int compareClassifiers(Integer a, Integer b) { + @Override + public int compareClassifiers(Integer a, Integer b) { return a.compareTo(b); } - // is needed for storing subscribers in an ordered collection - @Override public int compareSubscribers(ActorRef a, ActorRef b) { + // is needed for storing subscribers in an ordered collection + @Override + public int compareSubscribers(ActorRef a, ActorRef b) { return a.compareTo(b); } // determines whether a given classifier shall match a given event; it is invoked // for each subscription for all received events, hence the name of the classifier - @Override public boolean matches(Integer classifier, String event) { + @Override + public boolean matches(Integer classifier, String event) { return event.length() <= classifier; } // will be invoked for each event for all subscribers which registered themselves // for the event’s classifier - @Override public void publish(String event, ActorRef subscriber) { + @Override + public void publish(String event, ActorRef subscriber) { subscriber.tell(event, ActorRef.noSender()); } - } - //#scanning-bus - - static - //#actor-bus - public class Notification { + // #scanning-bus + + public + // #actor-bus + static class Notification { public final ActorRef ref; public final int id; @@ -222,12 +232,12 @@ public class EventBusDocTest extends AbstractJavaTest { this.id = id; } } - - //#actor-bus - - static - //#actor-bus - public class ActorBusImpl extends ManagedActorEventBus { + + // #actor-bus + + public + // #actor-bus + static class ActorBusImpl extends ManagedActorEventBus { // the ActorSystem will be used for book-keeping operations, such as subscribers terminating public ActorBusImpl(ActorSystem system) { @@ -235,91 +245,97 @@ public class EventBusDocTest extends AbstractJavaTest { } // is used for extracting the classifier from the incoming events - @Override public ActorRef classify(Notification event) { + @Override + public ActorRef classify(Notification event) { return event.ref; } - + // determines the initial size of the index data structure // used internally (i.e. the expected number of different classifiers) - @Override public int mapSize() { + @Override + public int mapSize() { return 128; } - } - //#actor-bus - + // #actor-bus + @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("EventBusDocTest"); + new AkkaJUnitActorSystemResource("EventBusDocTest"); private final ActorSystem system = actorSystemResource.getSystem(); - + @Test public void demonstrateLookupClassification() { - new TestKit(system) {{ - //#lookup-bus-test - LookupBusImpl lookupBus = new LookupBusImpl(); - lookupBus.subscribe(getTestActor(), "greetings"); - lookupBus.publish(new MsgEnvelope("time", System.currentTimeMillis())); - lookupBus.publish(new MsgEnvelope("greetings", "hello")); - expectMsgEquals("hello"); - //#lookup-bus-test - }}; - } - - @Test - public void demonstrateSubchannelClassification() { - new TestKit(system) {{ - //#subchannel-bus-test - SubchannelBusImpl subchannelBus = new SubchannelBusImpl(); - subchannelBus.subscribe(getTestActor(), "abc"); - subchannelBus.publish(new MsgEnvelope("xyzabc", "x")); - subchannelBus.publish(new MsgEnvelope("bcdef", "b")); - subchannelBus.publish(new MsgEnvelope("abc", "c")); - expectMsgEquals("c"); - subchannelBus.publish(new MsgEnvelope("abcdef", "d")); - expectMsgEquals("d"); - //#subchannel-bus-test - }}; - } - - @Test - public void demonstrateScanningClassification() { - new TestKit(system) {{ - //#scanning-bus-test - ScanningBusImpl scanningBus = new ScanningBusImpl(); - scanningBus.subscribe(getTestActor(), 3); - scanningBus.publish("xyzabc"); - scanningBus.publish("ab"); - expectMsgEquals("ab"); - scanningBus.publish("abc"); - expectMsgEquals("abc"); - //#scanning-bus-test - }}; - } - - @Test - public void demonstrateManagedActorClassification() { - //#actor-bus-test - ActorRef observer1 = new TestKit(system).getRef(); - ActorRef observer2 = new TestKit(system).getRef(); - TestKit probe1 = new TestKit(system); - TestKit probe2 = new TestKit(system); - ActorRef subscriber1 = probe1.getRef(); - ActorRef subscriber2 = probe2.getRef(); - ActorBusImpl actorBus = new ActorBusImpl(system); - actorBus.subscribe(subscriber1, observer1); - actorBus.subscribe(subscriber2, observer1); - actorBus.subscribe(subscriber2, observer2); - Notification n1 = new Notification(observer1, 100); - actorBus.publish(n1); - probe1.expectMsgEquals(n1); - probe2.expectMsgEquals(n1); - Notification n2 = new Notification(observer2, 101); - actorBus.publish(n2); - probe2.expectMsgEquals(n2); - probe1.expectNoMessage(Duration.ofMillis(500)); - //#actor-bus-test + new TestKit(system) { + { + // #lookup-bus-test + LookupBusImpl lookupBus = new LookupBusImpl(); + lookupBus.subscribe(getTestActor(), "greetings"); + lookupBus.publish(new MsgEnvelope("time", System.currentTimeMillis())); + lookupBus.publish(new MsgEnvelope("greetings", "hello")); + expectMsgEquals("hello"); + // #lookup-bus-test + } + }; } + @Test + public void demonstrateSubchannelClassification() { + new TestKit(system) { + { + // #subchannel-bus-test + SubchannelBusImpl subchannelBus = new SubchannelBusImpl(); + subchannelBus.subscribe(getTestActor(), "abc"); + subchannelBus.publish(new MsgEnvelope("xyzabc", "x")); + subchannelBus.publish(new MsgEnvelope("bcdef", "b")); + subchannelBus.publish(new MsgEnvelope("abc", "c")); + expectMsgEquals("c"); + subchannelBus.publish(new MsgEnvelope("abcdef", "d")); + expectMsgEquals("d"); + // #subchannel-bus-test + } + }; + } + + @Test + public void demonstrateScanningClassification() { + new TestKit(system) { + { + // #scanning-bus-test + ScanningBusImpl scanningBus = new ScanningBusImpl(); + scanningBus.subscribe(getTestActor(), 3); + scanningBus.publish("xyzabc"); + scanningBus.publish("ab"); + expectMsgEquals("ab"); + scanningBus.publish("abc"); + expectMsgEquals("abc"); + // #scanning-bus-test + } + }; + } + + @Test + public void demonstrateManagedActorClassification() { + // #actor-bus-test + ActorRef observer1 = new TestKit(system).getRef(); + ActorRef observer2 = new TestKit(system).getRef(); + TestKit probe1 = new TestKit(system); + TestKit probe2 = new TestKit(system); + ActorRef subscriber1 = probe1.getRef(); + ActorRef subscriber2 = probe2.getRef(); + ActorBusImpl actorBus = new ActorBusImpl(system); + actorBus.subscribe(subscriber1, observer1); + actorBus.subscribe(subscriber2, observer1); + actorBus.subscribe(subscriber2, observer2); + Notification n1 = new Notification(observer1, 100); + actorBus.publish(n1); + probe1.expectMsgEquals(n1); + probe2.expectMsgEquals(n1); + Notification n2 = new Notification(observer2, 101); + actorBus.publish(n2); + probe2.expectMsgEquals(n2); + probe1.expectNoMessage(Duration.ofMillis(500)); + // #actor-bus-test + } } diff --git a/akka-docs/src/test/java/jdocs/event/LoggingDocTest.java b/akka-docs/src/test/java/jdocs/event/LoggingDocTest.java index 716fdb3c33..da94c24c2e 100644 --- a/akka-docs/src/test/java/jdocs/event/LoggingDocTest.java +++ b/akka-docs/src/test/java/jdocs/event/LoggingDocTest.java @@ -4,37 +4,37 @@ package jdocs.event; -//#imports +// #imports import akka.actor.*; import akka.event.Logging; import akka.event.LoggingAdapter; -//#imports +// #imports -//#imports-listener +// #imports-listener import akka.event.Logging.InitializeLogger; import akka.event.Logging.Error; import akka.event.Logging.Warning; import akka.event.Logging.Info; import akka.event.Logging.Debug; -//#imports-listener +// #imports-listener import jdocs.AbstractJavaTest; import akka.testkit.javadsl.TestKit; import org.junit.Test; import java.util.Optional; -//#imports-mdc +// #imports-mdc import akka.event.DiagnosticLoggingAdapter; import java.util.HashMap; import java.util.Map; -//#imports-mdc +// #imports-mdc -//#imports-deadletter +// #imports-deadletter import akka.actor.ActorRef; import akka.actor.ActorSystem; -//#imports-deadletter +// #imports-deadletter public class LoggingDocTest extends AbstractJavaTest { @@ -56,25 +56,28 @@ public class LoggingDocTest extends AbstractJavaTest { @Test public void subscribeToDeadLetters() { - //#deadletters + // #deadletters final ActorSystem system = ActorSystem.create("DeadLetters"); final ActorRef actor = system.actorOf(Props.create(DeadLetterActor.class)); system.getEventStream().subscribe(actor, DeadLetter.class); - //#deadletters + // #deadletters TestKit.shutdownActorSystem(system); } - //#superclass-subscription-eventstream - interface AllKindsOfMusic { } + // #superclass-subscription-eventstream + interface AllKindsOfMusic {} class Jazz implements AllKindsOfMusic { - final public String artist; + public final String artist; + public Jazz(String artist) { this.artist = artist; } } + class Electronic implements AllKindsOfMusic { - final public String artist; + public final String artist; + public Electronic(String artist) { this.artist = artist; } @@ -82,23 +85,23 @@ public class LoggingDocTest extends AbstractJavaTest { static class Listener extends AbstractActor { @Override - public Receive createReceive() { - return receiveBuilder() - .match(Jazz.class, msg -> - System.out.printf("%s is listening to: %s%n", getSelf().path().name(), msg) - ) - .match(Electronic.class, msg -> - System.out.printf("%s is listening to: %s%n", getSelf().path().name(), msg) - ) + public Receive createReceive() { + return receiveBuilder() + .match( + Jazz.class, + msg -> System.out.printf("%s is listening to: %s%n", getSelf().path().name(), msg)) + .match( + Electronic.class, + msg -> System.out.printf("%s is listening to: %s%n", getSelf().path().name(), msg)) .build(); - } + } } - //#superclass-subscription-eventstream + // #superclass-subscription-eventstream @Test public void subscribeBySubclassification() { final ActorSystem system = ActorSystem.create("DeadLetters"); - //#superclass-subscription-eventstream + // #superclass-subscription-eventstream final ActorRef actor = system.actorOf(Props.create(DeadLetterActor.class)); system.getEventStream().subscribe(actor, DeadLetter.class); @@ -113,7 +116,7 @@ public class LoggingDocTest extends AbstractJavaTest { // jazzListener and musicListener will be notified about Jazz: system.getEventStream().publish(new Jazz("Sonny Rollins")); - //#superclass-subscription-eventstream + // #superclass-subscription-eventstream TestKit.shutdownActorSystem(system); } @@ -122,20 +125,21 @@ public class LoggingDocTest extends AbstractJavaTest { final ActorSystem system = ActorSystem.create("SuppressedDeadLetters"); final ActorRef actor = system.actorOf(Props.create(DeadLetterActor.class)); - //#suppressed-deadletters + // #suppressed-deadletters system.getEventStream().subscribe(actor, SuppressedDeadLetter.class); - //#suppressed-deadletters + // #suppressed-deadletters TestKit.shutdownActorSystem(system); } + @Test public void subscribeToAllDeadLetters() { final ActorSystem system = ActorSystem.create("AllDeadLetters"); final ActorRef actor = system.actorOf(Props.create(DeadLetterActor.class)); - //#all-deadletters + // #all-deadletters system.getEventStream().subscribe(actor, AllDeadLetters.class); - //#all-deadletters + // #all-deadletters TestKit.shutdownActorSystem(system); } @@ -143,14 +147,14 @@ public class LoggingDocTest extends AbstractJavaTest { @Test public void demonstrateMultipleArgs() { final ActorSystem system = ActorSystem.create("multiArg"); - //#array - final Object[] args = new Object[] { "The", "brown", "fox", "jumps", 42 }; + // #array + final Object[] args = new Object[] {"The", "brown", "fox", "jumps", 42}; system.log().debug("five parameters: {}, {}, {}, {}, {}", args); - //#array + // #array TestKit.shutdownActorSystem(system); } - //#my-actor + // #my-actor class MyActor extends AbstractActor { LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); @@ -161,86 +165,98 @@ public class LoggingDocTest extends AbstractJavaTest { @Override public void preRestart(Throwable reason, Optional message) { - log.error(reason, "Restarting due to [{}] when processing [{}]", - reason.getMessage(), message.isPresent() ? message.get() : ""); + log.error( + reason, + "Restarting due to [{}] when processing [{}]", + reason.getMessage(), + message.isPresent() ? message.get() : ""); } @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("test", msg -> - log.info("Received test") - ) - .matchAny(msg -> - log.warning("Received unknown message: {}", msg) - ) - .build(); + .matchEquals("test", msg -> log.info("Received test")) + .matchAny(msg -> log.warning("Received unknown message: {}", msg)) + .build(); } } - //#my-actor + // #my-actor - //#mdc-actor + // #mdc-actor class MdcActor extends AbstractActor { - final DiagnosticLoggingAdapter log = Logging.getLogger(this); + final DiagnosticLoggingAdapter log = Logging.getLogger(this); - @Override - public Receive createReceive() { - return receiveBuilder() - .matchAny(msg -> { - Map mdc; - mdc = new HashMap(); - mdc.put("requestId", 1234); - mdc.put("visitorId", 5678); - log.setMDC(mdc); + @Override + public Receive createReceive() { + return receiveBuilder() + .matchAny( + msg -> { + Map mdc; + mdc = new HashMap(); + mdc.put("requestId", 1234); + mdc.put("visitorId", 5678); + log.setMDC(mdc); - log.info("Starting new request"); + log.info("Starting new request"); - log.clearMDC(); - }) + log.clearMDC(); + }) .build(); - } + } } - //#mdc-actor + // #mdc-actor - //#my-event-listener + // #my-event-listener class MyEventListener extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(InitializeLogger.class, msg -> { - getSender().tell(Logging.loggerInitialized(), getSelf()); - }) - .match(Error.class, msg -> { - // ... - }) - .match(Warning.class, msg -> { - // ... - }) - .match(Info.class, msg -> { - // ... - }) - .match(Debug.class, msg -> { - // ... - }) - .build(); + .match( + InitializeLogger.class, + msg -> { + getSender().tell(Logging.loggerInitialized(), getSelf()); + }) + .match( + Error.class, + msg -> { + // ... + }) + .match( + Warning.class, + msg -> { + // ... + }) + .match( + Info.class, + msg -> { + // ... + }) + .match( + Debug.class, + msg -> { + // ... + }) + .build(); } } - //#my-event-listener + // #my-event-listener - static - //#deadletter-actor - public class DeadLetterActor extends AbstractActor { + public + // #deadletter-actor + static class DeadLetterActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(DeadLetter.class, msg -> { - System.out.println(msg); - }) - .build(); + .match( + DeadLetter.class, + msg -> { + System.out.println(msg); + }) + .build(); } } - //#deadletter-actor + // #deadletter-actor } diff --git a/akka-docs/src/test/java/jdocs/extension/ExtensionDocTest.java b/akka-docs/src/test/java/jdocs/extension/ExtensionDocTest.java index 1cb48aa3cb..925ec7f64d 100644 --- a/akka-docs/src/test/java/jdocs/extension/ExtensionDocTest.java +++ b/akka-docs/src/test/java/jdocs/extension/ExtensionDocTest.java @@ -4,87 +4,87 @@ package jdocs.extension; -//#imports +// #imports import akka.actor.*; import java.util.concurrent.atomic.AtomicLong; -//#imports +// #imports import jdocs.AbstractJavaTest; import org.junit.Test; public class ExtensionDocTest extends AbstractJavaTest { - static - //#extension - public class CountExtensionImpl implements Extension { - //Since this Extension is a shared instance + public + // #extension + static class CountExtensionImpl implements Extension { + // Since this Extension is a shared instance // per ActorSystem we need to be threadsafe private final AtomicLong counter = new AtomicLong(0); - //This is the operation this Extension provides + // This is the operation this Extension provides public long increment() { return counter.incrementAndGet(); } } - //#extension + // #extension - static - //#extensionid - public class CountExtension extends AbstractExtensionId - implements ExtensionIdProvider { - //This will be the identifier of our CountExtension - public final static CountExtension CountExtensionProvider = new CountExtension(); + public + // #extensionid + static class CountExtension extends AbstractExtensionId + implements ExtensionIdProvider { + // This will be the identifier of our CountExtension + public static final CountExtension CountExtensionProvider = new CountExtension(); private CountExtension() {} - //The lookup method is required by ExtensionIdProvider, + // The lookup method is required by ExtensionIdProvider, // so we return ourselves here, this allows us // to configure our extension to be loaded when // the ActorSystem starts up public CountExtension lookup() { - return CountExtension.CountExtensionProvider; //The public static final + return CountExtension.CountExtensionProvider; // The public static final } - //This method will be called by Akka + // This method will be called by Akka // to instantiate our Extension public CountExtensionImpl createExtension(ExtendedActorSystem system) { return new CountExtensionImpl(); } } - //#extensionid + // #extensionid - static - //#extension-usage-actor - public class MyActor extends AbstractActor { + public + // #extension-usage-actor + static class MyActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .matchAny(msg -> { - // typically you would use static import of the - // CountExtension.CountExtensionProvider field - CountExtension.CountExtensionProvider.get(getContext().getSystem()).increment(); - }) - .build(); + .matchAny( + msg -> { + // typically you would use static import of the + // CountExtension.CountExtensionProvider field + CountExtension.CountExtensionProvider.get(getContext().getSystem()).increment(); + }) + .build(); } } - //#extension-usage-actor + // #extension-usage-actor @Test public void demonstrateHowToCreateAndUseAnAkkaExtensionInJava() { final ActorSystem system = null; try { - //#extension-usage + // #extension-usage // typically you would use static import of the // CountExtension.CountExtensionProvider field CountExtension.CountExtensionProvider.get(system).increment(); - //#extension-usage + // #extension-usage } catch (Exception e) { - //do nothing + // do nothing } } - } diff --git a/akka-docs/src/test/java/jdocs/extension/SettingsExtensionDocTest.java b/akka-docs/src/test/java/jdocs/extension/SettingsExtensionDocTest.java index 94b0926c83..d5ca07551f 100644 --- a/akka-docs/src/test/java/jdocs/extension/SettingsExtensionDocTest.java +++ b/akka-docs/src/test/java/jdocs/extension/SettingsExtensionDocTest.java @@ -4,7 +4,7 @@ package jdocs.extension; -//#imports +// #imports import akka.actor.Extension; import akka.actor.AbstractExtensionId; import akka.actor.ExtensionIdProvider; @@ -14,7 +14,7 @@ import com.typesafe.config.Config; import java.util.concurrent.TimeUnit; import java.time.Duration; -//#imports +// #imports import jdocs.AbstractJavaTest; import akka.actor.AbstractActor; @@ -22,9 +22,9 @@ import org.junit.Test; public class SettingsExtensionDocTest extends AbstractJavaTest { - static - //#extension - public class SettingsImpl implements Extension { + public + // #extension + static class SettingsImpl implements Extension { public final String DB_URI; public final Duration CIRCUIT_BREAKER_TIMEOUT; @@ -32,18 +32,17 @@ public class SettingsExtensionDocTest extends AbstractJavaTest { public SettingsImpl(Config config) { DB_URI = config.getString("myapp.db.uri"); CIRCUIT_BREAKER_TIMEOUT = - Duration.ofMillis(config.getDuration("myapp.circuit-breaker.timeout", TimeUnit.MILLISECONDS)); + Duration.ofMillis( + config.getDuration("myapp.circuit-breaker.timeout", TimeUnit.MILLISECONDS)); } - } - //#extension + // #extension - static - //#extensionid - public class Settings extends AbstractExtensionId - implements ExtensionIdProvider { - public final static Settings SettingsProvider = new Settings(); + public + // #extensionid + static class Settings extends AbstractExtensionId implements ExtensionIdProvider { + public static final Settings SettingsProvider = new Settings(); private Settings() {} @@ -56,18 +55,16 @@ public class SettingsExtensionDocTest extends AbstractJavaTest { } } - //#extensionid + // #extensionid - static - //#extension-usage-actor - public class MyActor extends AbstractActor { + public + // #extension-usage-actor + static class MyActor extends AbstractActor { // typically you would use static import of the Settings.SettingsProvider field - final SettingsImpl settings = - Settings.SettingsProvider.get(getContext().getSystem()); - Connection connection = - connect(settings.DB_URI, settings.CIRCUIT_BREAKER_TIMEOUT); + final SettingsImpl settings = Settings.SettingsProvider.get(getContext().getSystem()); + Connection connection = connect(settings.DB_URI, settings.CIRCUIT_BREAKER_TIMEOUT); - //#extension-usage-actor + // #extension-usage-actor public Connection connect(String dbUri, Duration circuitBreakerTimeout) { return new Connection(); @@ -77,24 +74,22 @@ public class SettingsExtensionDocTest extends AbstractJavaTest { public Receive createReceive() { return AbstractActor.emptyBehavior(); } - //#extension-usage-actor + // #extension-usage-actor } - //#extension-usage-actor + // #extension-usage-actor - public static class Connection { - } + public static class Connection {} @Test public void demonstrateHowToCreateAndUseAnAkkaExtensionInJava() { final ActorSystem system = null; try { - //#extension-usage + // #extension-usage // typically you would use static import of the Settings.SettingsProvider field String dbUri = Settings.SettingsProvider.get(system).DB_URI; - //#extension-usage + // #extension-usage } catch (Exception e) { - //do nothing + // do nothing } } - } diff --git a/akka-docs/src/test/java/jdocs/future/ActorWithFuture.java b/akka-docs/src/test/java/jdocs/future/ActorWithFuture.java index ae32e73e11..494902efd5 100644 --- a/akka-docs/src/test/java/jdocs/future/ActorWithFuture.java +++ b/akka-docs/src/test/java/jdocs/future/ActorWithFuture.java @@ -4,12 +4,12 @@ package jdocs.future; -//#context-dispatcher +// #context-dispatcher import akka.actor.AbstractActor; import akka.dispatch.Futures; public class ActorWithFuture extends AbstractActor { - ActorWithFuture(){ + ActorWithFuture() { Futures.future(() -> "hello", getContext().dispatcher()); } diff --git a/akka-docs/src/test/java/jdocs/future/FutureDocTest.java b/akka-docs/src/test/java/jdocs/future/FutureDocTest.java index 933e652c08..3f40f61ff3 100644 --- a/akka-docs/src/test/java/jdocs/future/FutureDocTest.java +++ b/akka-docs/src/test/java/jdocs/future/FutureDocTest.java @@ -4,7 +4,7 @@ package jdocs.future; -//#imports1 +// #imports1 import akka.dispatch.*; import jdocs.AbstractJavaTest; import scala.concurrent.ExecutionContext; @@ -13,10 +13,9 @@ import scala.concurrent.Await; import scala.concurrent.Promise; import akka.util.Timeout; +// #imports1 -//#imports1 - -//#imports2 +// #imports2 import java.time.Duration; import java.util.concurrent.*; @@ -27,54 +26,47 @@ import akka.japi.Function; import static akka.dispatch.Futures.future; import static java.util.concurrent.TimeUnit.SECONDS; -//#imports2 +// #imports2 -//#imports3 +// #imports3 import static akka.dispatch.Futures.sequence; +// #imports3 -//#imports3 - -//#imports4 +// #imports4 import static akka.dispatch.Futures.traverse; +// #imports4 -//#imports4 - -//#imports5 +// #imports5 import akka.japi.Function2; import static akka.dispatch.Futures.fold; +// #imports5 -//#imports5 - -//#imports6 +// #imports6 import static akka.dispatch.Futures.reduce; +// #imports6 -//#imports6 - -//#imports7 +// #imports7 import static akka.pattern.Patterns.after; - import java.util.Arrays; -//#imports7 +// #imports7 - -//#imports8 +// #imports8 import static akka.pattern.Patterns.retry; -//#imports8 +// #imports8 -//#imports-ask +// #imports-ask import static akka.pattern.Patterns.ask; -//#imports-ask -//#imports-pipe +// #imports-ask +// #imports-pipe import static akka.pattern.Patterns.pipe; -//#imports-pipe - +// #imports-pipe import java.util.ArrayList; import java.util.List; @@ -101,30 +93,32 @@ public class FutureDocTest extends AbstractJavaTest { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("FutureDocTest", AkkaSpec.testConf()); + new AkkaJUnitActorSystemResource("FutureDocTest", AkkaSpec.testConf()); private final ActorSystem system = actorSystemResource.getSystem(); - public final static class PrintResult extends OnSuccess { - @Override public final void onSuccess(T t) { + public static final class PrintResult extends OnSuccess { + @Override + public final void onSuccess(T t) { // print t } } - public final static class Demo { - //#print-result - public final static class PrintResult extends OnSuccess { - @Override public final void onSuccess(T t) { + public static final class Demo { + // #print-result + public static final class PrintResult extends OnSuccess { + @Override + public final void onSuccess(T t) { System.out.println(t); } } - //#print-result + // #print-result } - //#pipe-to-usage + // #pipe-to-usage public class ActorUsingPipeTo extends AbstractActor { ActorRef target; - Duration timeout; + Duration timeout; ActorUsingPipeTo(ActorRef target) { this.target = target; @@ -134,55 +128,58 @@ public class FutureDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .match(String.class, msg -> { - CompletableFuture fut = - ask(target, "some message", timeout).toCompletableFuture(); + .match( + String.class, + msg -> { + CompletableFuture fut = + ask(target, "some message", timeout).toCompletableFuture(); - // the pipe pattern - pipe(fut, getContext().dispatcher()).to(getSender()); - }) - .build(); + // the pipe pattern + pipe(fut, getContext().dispatcher()).to(getSender()); + }) + .build(); } } - //#pipe-to-usage + // #pipe-to-usage - //#pipe-to-returned-data - public class UserData { + // #pipe-to-returned-data + public class UserData { final String data; - UserData(String data){ + UserData(String data) { this.data = data; } } public class UserActivity { final String activity; - UserActivity(String activity){ + + UserActivity(String activity) { this.activity = activity; } } - //#pipe-to-returned-data + // #pipe-to-returned-data - //#pipe-to-user-data-actor + // #pipe-to-user-data-actor public class UserDataActor extends AbstractActor { UserData internalData; - UserDataActor(){ + UserDataActor() { this.internalData = new UserData("initial data"); } @Override public Receive createReceive() { return receiveBuilder() - .match(GetFromUserDataActor.class, msg -> sender().tell(internalData, self())) - .build(); + .match(GetFromUserDataActor.class, msg -> sender().tell(internalData, self())) + .build(); } } public class GetFromUserDataActor {} - //#pipe-to-user-data-actor + // #pipe-to-user-data-actor - //#pipe-to-user-activity-actor + // #pipe-to-user-activity-actor interface UserActivityRepository { CompletableFuture> queryHistoricalActivities(String userId); } @@ -199,20 +196,22 @@ public class FutureDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .match(GetFromUserActivityActor.class, msg -> { - CompletableFuture> fut = - repository.queryHistoricalActivities(userId); + .match( + GetFromUserActivityActor.class, + msg -> { + CompletableFuture> fut = + repository.queryHistoricalActivities(userId); - pipe(fut, getContext().dispatcher()).to(sender()); - }) - .build(); + pipe(fut, getContext().dispatcher()).to(sender()); + }) + .build(); } } public class GetFromUserActivityActor {} - //#pipe-to-user-activity-actor + // #pipe-to-user-activity-actor - //#pipe-to-proxy-actor + // #pipe-to-proxy-actor public class UserProxyActor extends AbstractActor { ActorRef userActor; ActorRef userActivityActor; @@ -226,66 +225,76 @@ public class FutureDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .match(GetUserData.class, msg -> { - CompletableFuture fut = - ask(userActor, new GetUserData(), timeout).toCompletableFuture(); + .match( + GetUserData.class, + msg -> { + CompletableFuture fut = + ask(userActor, new GetUserData(), timeout).toCompletableFuture(); - pipe(fut, getContext().dispatcher()); - }) - .match(GetUserActivities.class, msg -> { - CompletableFuture fut = - ask(userActivityActor, new GetFromUserActivityActor(), timeout).toCompletableFuture(); + pipe(fut, getContext().dispatcher()); + }) + .match( + GetUserActivities.class, + msg -> { + CompletableFuture fut = + ask(userActivityActor, new GetFromUserActivityActor(), timeout) + .toCompletableFuture(); - pipe(fut, getContext().dispatcher()).to(sender()); - }) - .build(); + pipe(fut, getContext().dispatcher()).to(sender()); + }) + .build(); } } - //#pipe-to-proxy-actor + // #pipe-to-proxy-actor - //#pipe-to-proxy-messages + // #pipe-to-proxy-messages public class GetUserData {} + public class GetUserActivities {} - //#pipe-to-proxy-messages + // #pipe-to-proxy-messages - @SuppressWarnings("unchecked") @Test public void useCustomExecutionContext() throws Exception { + @SuppressWarnings("unchecked") + @Test + public void useCustomExecutionContext() throws Exception { ExecutorService yourExecutorServiceGoesHere = Executors.newSingleThreadExecutor(); - //#diy-execution-context - ExecutionContext ec = - ExecutionContexts.fromExecutorService(yourExecutorServiceGoesHere); + // #diy-execution-context + ExecutionContext ec = ExecutionContexts.fromExecutorService(yourExecutorServiceGoesHere); - //Use ec with your Futures + // Use ec with your Futures Future f1 = Futures.successful("foo"); // Then you shut down the ExecutorService at the end of your application. yourExecutorServiceGoesHere.shutdown(); - //#diy-execution-context + // #diy-execution-context } @Test public void useBlockingFromActor() throws Exception { ActorRef actor = system.actorOf(Props.create(MyActor.class)); String msg = "hello"; - //#ask-blocking + // #ask-blocking Timeout timeout = Timeout.create(Duration.ofSeconds(5)); Future future = Patterns.ask(actor, msg, timeout); String result = (String) Await.result(future, timeout.duration()); - //#ask-blocking + // #ask-blocking assertEquals("HELLO", result); } @Test public void useFutureEval() throws Exception { - //#future-eval - Future f = future(new Callable() { - public String call() { - return "Hello" + "World"; - } - }, system.dispatcher()); + // #future-eval + Future f = + future( + new Callable() { + public String call() { + return "Hello" + "World"; + } + }, + system.dispatcher()); f.onComplete(new PrintResult>(), system.dispatcher()); - //#future-eval + // #future-eval Timeout timeout = Timeout.create(Duration.ofSeconds(5)); String result = (String) Await.result(f, timeout.duration()); assertEquals("HelloWorld", result); @@ -293,23 +302,29 @@ public class FutureDocTest extends AbstractJavaTest { @Test public void useMap() throws Exception { - //#map + // #map final ExecutionContext ec = system.dispatcher(); - Future f1 = future(new Callable() { - public String call() { - return "Hello" + "World"; - } - }, ec); + Future f1 = + future( + new Callable() { + public String call() { + return "Hello" + "World"; + } + }, + ec); - Future f2 = f1.map(new Mapper() { - public Integer apply(String s) { - return s.length(); - } - }, ec); + Future f2 = + f1.map( + new Mapper() { + public Integer apply(String s) { + return s.length(); + } + }, + ec); f2.onComplete(new PrintResult>(), system.dispatcher()); - //#map + // #map Timeout timeout = Timeout.create(Duration.ofSeconds(5)); int result = Await.result(f2, timeout.duration()); assertEquals(10, result); @@ -317,27 +332,35 @@ public class FutureDocTest extends AbstractJavaTest { @Test public void useFlatMap() throws Exception { - //#flat-map + // #flat-map final ExecutionContext ec = system.dispatcher(); - Future f1 = future(new Callable() { - public String call() { - return "Hello" + "World"; - } - }, ec); + Future f1 = + future( + new Callable() { + public String call() { + return "Hello" + "World"; + } + }, + ec); - Future f2 = f1.flatMap(new Mapper>() { - public Future apply(final String s) { - return future(new Callable() { - public Integer call() { - return s.length(); - } - }, ec); - } - }, ec); + Future f2 = + f1.flatMap( + new Mapper>() { + public Future apply(final String s) { + return future( + new Callable() { + public Integer call() { + return s.length(); + } + }, + ec); + } + }, + ec); f2.onComplete(new PrintResult>(), system.dispatcher()); - //#flat-map + // #flat-map Timeout timeout = Timeout.create(Duration.ofSeconds(5)); int result = Await.result(f2, timeout.duration()); assertEquals(10, result); @@ -349,27 +372,28 @@ public class FutureDocTest extends AbstractJavaTest { source.add(Futures.successful(1)); source.add(Futures.successful(2)); - //#sequence + // #sequence final ExecutionContext ec = system.dispatcher(); - //Some source generating a sequence of Future:s + // Some source generating a sequence of Future:s Iterable> listOfFutureInts = source; // now we have a Future[Iterable[Integer]] Future> futureListOfInts = sequence(listOfFutureInts, ec); // Find the sum of the odd numbers - Future futureSum = futureListOfInts.map( - new Mapper, Long>() { - public Long apply(Iterable ints) { - long sum = 0; - for (Integer i : ints) - sum += i; - return sum; - } - }, ec); + Future futureSum = + futureListOfInts.map( + new Mapper, Long>() { + public Long apply(Iterable ints) { + long sum = 0; + for (Integer i : ints) sum += i; + return sum; + } + }, + ec); futureSum.onComplete(new PrintResult>(), system.dispatcher()); - //#sequence + // #sequence Timeout timeout = Timeout.create(Duration.ofSeconds(5)); long result = Await.result(futureSum, timeout.duration()); assertEquals(3L, result); @@ -377,25 +401,30 @@ public class FutureDocTest extends AbstractJavaTest { @Test public void useTraverse() throws Exception { - //#traverse + // #traverse final ExecutionContext ec = system.dispatcher(); - //Just a sequence of Strings + // Just a sequence of Strings Iterable listStrings = Arrays.asList("a", "b", "c"); - Future> futureResult = traverse(listStrings, - new Function>() { - public Future apply(final String r) { - return future(new Callable() { - public String call() { - return r.toUpperCase(); - } - }, ec); - } - }, ec); + Future> futureResult = + traverse( + listStrings, + new Function>() { + public Future apply(final String r) { + return future( + new Callable() { + public String call() { + return r.toUpperCase(); + } + }, + ec); + } + }, + ec); - //Returns the sequence of strings as upper case + // Returns the sequence of strings as upper case futureResult.onComplete(new PrintResult>>(), system.dispatcher()); - //#traverse + // #traverse Timeout timeout = Timeout.create(Duration.ofSeconds(5)); Iterable result = Await.result(futureResult, timeout.duration()); assertEquals(Arrays.asList("A", "B", "C"), result); @@ -406,23 +435,27 @@ public class FutureDocTest extends AbstractJavaTest { List> source = new ArrayList>(); source.add(Futures.successful("a")); source.add(Futures.successful("b")); - //#fold + // #fold final ExecutionContext ec = system.dispatcher(); - //A sequence of Futures, in this case Strings + // A sequence of Futures, in this case Strings Iterable> futures = source; - //Start value is the empty string - Future resultFuture = fold("", futures, - new Function2() { - public String apply(String r, String t) { - return r + t; //Just concatenate - } - }, ec); + // Start value is the empty string + Future resultFuture = + fold( + "", + futures, + new Function2() { + public String apply(String r, String t) { + return r + t; // Just concatenate + } + }, + ec); resultFuture.onComplete(new PrintResult>(), system.dispatcher()); - //#fold + // #fold Timeout timeout = Timeout.create(Duration.ofSeconds(5)); String result = Await.result(resultFuture, timeout.duration()); assertEquals("ab", result); @@ -433,21 +466,24 @@ public class FutureDocTest extends AbstractJavaTest { List> source = new ArrayList>(); source.add(Futures.successful("a")); source.add(Futures.successful("b")); - //#reduce + // #reduce final ExecutionContext ec = system.dispatcher(); - //A sequence of Futures, in this case Strings + // A sequence of Futures, in this case Strings Iterable> futures = source; - Future resultFuture = reduce(futures, - new Function2() { - public Object apply(Object r, String t) { - return r + t; //Just concatenate - } - }, ec); + Future resultFuture = + reduce( + futures, + new Function2() { + public Object apply(Object r, String t) { + return r + t; // Just concatenate + } + }, + ec); resultFuture.onComplete(new PrintResult>(), system.dispatcher()); - //#reduce + // #reduce Timeout timeout = Timeout.create(Duration.ofSeconds(5)); Object result = Await.result(resultFuture, timeout.duration()); @@ -457,23 +493,21 @@ public class FutureDocTest extends AbstractJavaTest { @Test public void useSuccessfulAndFailedAndPromise() throws Exception { final ExecutionContext ec = system.dispatcher(); - //#successful + // #successful Future future = Futures.successful("Yay!"); - //#successful - //#failed - Future otherFuture = Futures.failed( - new IllegalArgumentException("Bang!")); - //#failed - //#promise + // #successful + // #failed + Future otherFuture = Futures.failed(new IllegalArgumentException("Bang!")); + // #failed + // #promise Promise promise = Futures.promise(); Future theFuture = promise.future(); promise.success("hello"); - //#promise + // #promise Timeout timeout = Timeout.create(Duration.ofSeconds(5)); Object result = Await.result(future, timeout.duration()); assertEquals("Yay!", result); - Throwable result2 = Await.result(otherFuture.failed(), - timeout.duration()); + Throwable result2 = Await.result(otherFuture.failed(), timeout.duration()); assertEquals("Bang!", result2.getMessage()); String out = Await.result(theFuture, timeout.duration()); assertEquals("hello", out); @@ -481,73 +515,83 @@ public class FutureDocTest extends AbstractJavaTest { @Test public void useFilter() throws Exception { - //#filter + // #filter final ExecutionContext ec = system.dispatcher(); Future future1 = Futures.successful(4); - Future successfulFilter = future1.filter(Filter.filterOf( - new Function() { - public Boolean apply(Integer i) { - return i % 2 == 0; - } - }), ec); + Future successfulFilter = + future1.filter( + Filter.filterOf( + new Function() { + public Boolean apply(Integer i) { + return i % 2 == 0; + } + }), + ec); - Future failedFilter = future1.filter(Filter.filterOf( - new Function() { - public Boolean apply(Integer i) { - return i % 2 != 0; - } - }), ec); - //When filter fails, the returned Future will be failed with a scala.MatchError - //#filter + Future failedFilter = + future1.filter( + Filter.filterOf( + new Function() { + public Boolean apply(Integer i) { + return i % 2 != 0; + } + }), + ec); + // When filter fails, the returned Future will be failed with a scala.MatchError + // #filter } - public void sendToTheInternetz(String s) { + public void sendToTheInternetz(String s) {} - } - - public void sendToIssueTracker(Throwable t) { - - } + public void sendToIssueTracker(Throwable t) {} @Test public void useAndThen() { - //#and-then + // #and-then final ExecutionContext ec = system.dispatcher(); - Future future1 = Futures.successful("value").andThen( - new OnComplete() { - public void onComplete(Throwable failure, String result) { - if (failure != null) - sendToIssueTracker(failure); - } - }, ec).andThen(new OnComplete() { - public void onComplete(Throwable failure, String result) { - if (result != null) - sendToTheInternetz(result); - } - }, ec); - //#and-then + Future future1 = + Futures.successful("value") + .andThen( + new OnComplete() { + public void onComplete(Throwable failure, String result) { + if (failure != null) sendToIssueTracker(failure); + } + }, + ec) + .andThen( + new OnComplete() { + public void onComplete(Throwable failure, String result) { + if (result != null) sendToTheInternetz(result); + } + }, + ec); + // #and-then } @Test public void useRecover() throws Exception { - //#recover + // #recover final ExecutionContext ec = system.dispatcher(); - Future future = future(new Callable() { - public Integer call() { - return 1 / 0; - } - }, ec).recover(new Recover() { - public Integer recover(Throwable problem) throws Throwable { - if (problem instanceof ArithmeticException) - return 0; - else - throw problem; - } - }, ec); + Future future = + future( + new Callable() { + public Integer call() { + return 1 / 0; + } + }, + ec) + .recover( + new Recover() { + public Integer recover(Throwable problem) throws Throwable { + if (problem instanceof ArithmeticException) return 0; + else throw problem; + } + }, + ec); future.onComplete(new PrintResult>(), system.dispatcher()); - //#recover + // #recover Timeout timeout = Timeout.create(Duration.ofSeconds(5)); int result = Await.result(future, timeout.duration()); assertEquals(result, 0); @@ -555,30 +599,37 @@ public class FutureDocTest extends AbstractJavaTest { @Test public void useTryRecover() throws Exception { - //#try-recover + // #try-recover final ExecutionContext ec = system.dispatcher(); - Future future = future(new Callable() { - public Integer call() { - return 1 / 0; - } - }, ec).recoverWith(new Recover>() { - public Future recover(Throwable problem) throws Throwable { - if (problem instanceof ArithmeticException) { - return future(new Callable() { - public Integer call() { - return 0; - } - }, ec); - } else - throw problem; - } - }, ec); + Future future = + future( + new Callable() { + public Integer call() { + return 1 / 0; + } + }, + ec) + .recoverWith( + new Recover>() { + public Future recover(Throwable problem) throws Throwable { + if (problem instanceof ArithmeticException) { + return future( + new Callable() { + public Integer call() { + return 0; + } + }, + ec); + } else throw problem; + } + }, + ec); future.onComplete(new PrintResult>(), system.dispatcher()); - //#try-recover + // #try-recover Timeout timeout = Timeout.create(Duration.ofSeconds(5)); - int result = Await.result(future, timeout.duration()); + int result = Await.result(future, timeout.duration()); assertEquals(result, 0); } @@ -587,77 +638,84 @@ public class FutureDocTest extends AbstractJavaTest { { Future future = Futures.successful("foo"); - //#onComplete + // #onComplete final ExecutionContext ec = system.dispatcher(); - future.onComplete(new OnComplete() { - public void onComplete(Throwable failure, String result) { - if (failure != null) { - //We got a failure, handle it here - } else { - // We got a result, do something with it - } - } - }, ec); - //#onComplete + future.onComplete( + new OnComplete() { + public void onComplete(Throwable failure, String result) { + if (failure != null) { + // We got a failure, handle it here + } else { + // We got a result, do something with it + } + } + }, + ec); + // #onComplete } } @Test public void useOrAndZip() throws Exception { { - //#zip + // #zip final ExecutionContext ec = system.dispatcher(); Future future1 = Futures.successful("foo"); Future future2 = Futures.successful("bar"); - Future future3 = future1.zip(future2).map( - new Mapper, String>() { - public String apply(scala.Tuple2 zipped) { - return zipped._1() + " " + zipped._2(); - } - }, ec); + Future future3 = + future1 + .zip(future2) + .map( + new Mapper, String>() { + public String apply(scala.Tuple2 zipped) { + return zipped._1() + " " + zipped._2(); + } + }, + ec); future3.onComplete(new PrintResult>(), system.dispatcher()); - //#zip + // #zip Timeout timeout = Timeout.create(Duration.ofSeconds(5)); String result = Await.result(future3, timeout.duration()); assertEquals("foo bar", result); } { - //#fallback-to + // #fallback-to Future future1 = Futures.failed(new IllegalStateException("OHNOES1")); Future future2 = Futures.failed(new IllegalStateException("OHNOES2")); Future future3 = Futures.successful("bar"); // Will have "bar" in this case Future future4 = future1.fallbackTo(future2).fallbackTo(future3); future4.onComplete(new PrintResult>(), system.dispatcher()); - //#fallback-to + // #fallback-to Timeout timeout = Timeout.create(Duration.ofSeconds(5)); String result = Await.result(future4, timeout.duration()); assertEquals("bar", result); } - } @Test(expected = IllegalStateException.class) @SuppressWarnings("unchecked") public void useAfter() throws Exception { - //#after + // #after final ExecutionContext ec = system.dispatcher(); Future failExc = Futures.failed(new IllegalStateException("OHNOES1")); Timeout delay = Timeout.create(Duration.ofMillis(200)); - Future delayed = Patterns.after(delay.duration(), - system.scheduler(), ec, failExc); - Future future = future(new Callable() { - public String call() throws InterruptedException { - Thread.sleep(1000); - return "foo"; - } - }, ec); - Future result = Futures.firstCompletedOf( - Arrays.>asList(future, delayed), ec); - //#after + Future delayed = Patterns.after(delay.duration(), system.scheduler(), ec, failExc); + Future future = + future( + new Callable() { + public String call() throws InterruptedException { + Thread.sleep(1000); + return "foo"; + } + }, + ec); + Future result = + Futures.firstCompletedOf(Arrays.>asList(future, delayed), ec); + // #after Timeout timeout = Timeout.create(Duration.ofSeconds(2)); Await.result(result, timeout.duration()); } @@ -665,43 +723,56 @@ public class FutureDocTest extends AbstractJavaTest { @Test public void useRetry() throws Exception { - //#retry + // #retry final ExecutionContext ec = system.dispatcher(); Callable> attempt = () -> CompletableFuture.completedFuture("test"); - CompletionStage retriedFuture = retry(attempt, 3, java.time.Duration.ofMillis(200), system.scheduler(), ec); - //#retry + CompletionStage retriedFuture = + retry(attempt, 3, java.time.Duration.ofMillis(200), system.scheduler(), ec); + // #retry retriedFuture.toCompletableFuture().get(2, SECONDS); } @Test public void thenApplyCompletionThread() throws Exception { - //#apply-completion-thread + // #apply-completion-thread final ExecutionContext ec = system.dispatcher(); final CountDownLatch countDownLatch = new CountDownLatch(1); - Future scalaFuture = Futures.future(() -> { - assertThat(Thread.currentThread().getName(), containsString("akka.actor.default-dispatcher")); - countDownLatch.await(); // do not complete yet - return "hello"; - }, ec); + Future scalaFuture = + Futures.future( + () -> { + assertThat( + Thread.currentThread().getName(), + containsString("akka.actor.default-dispatcher")); + countDownLatch.await(); // do not complete yet + return "hello"; + }, + ec); - CompletionStage fromScalaFuture = FutureConverters.toJava(scalaFuture) - .thenApply(s -> { // 1 - assertThat(Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); - return s; - }) - .thenApply(s -> { // 2 - assertThat(Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); - return s; - }) - .thenApply(s -> { // 3 - assertThat(Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); - return s; - }); + CompletionStage fromScalaFuture = + FutureConverters.toJava(scalaFuture) + .thenApply( + s -> { // 1 + assertThat( + Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); + return s; + }) + .thenApply( + s -> { // 2 + assertThat( + Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); + return s; + }) + .thenApply( + s -> { // 3 + assertThat( + Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); + return s; + }); countDownLatch.countDown(); // complete scalaFuture - //#apply-completion-thread + // #apply-completion-thread fromScalaFuture.toCompletableFuture().get(2, SECONDS); } @@ -710,31 +781,42 @@ public class FutureDocTest extends AbstractJavaTest { public void thenApplyMainThread() throws Exception { final ExecutionContext ec = system.dispatcher(); - //#apply-main-thread - Future scalaFuture = Futures.future(() -> { - assertThat(Thread.currentThread().getName(), containsString("akka.actor.default-dispatcher")); - return "hello"; - }, ec); + // #apply-main-thread + Future scalaFuture = + Futures.future( + () -> { + assertThat( + Thread.currentThread().getName(), + containsString("akka.actor.default-dispatcher")); + return "hello"; + }, + ec); - CompletionStage completedStage = FutureConverters.toJava(scalaFuture) - .thenApply(s -> { // 1 - assertThat(Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); - return s; - }); + CompletionStage completedStage = + FutureConverters.toJava(scalaFuture) + .thenApply( + s -> { // 1 + assertThat( + Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); + return s; + }); completedStage.toCompletableFuture().get(2, SECONDS); // complete current CompletionStage final String currentThread = Thread.currentThread().getName(); - CompletionStage stage2 = completedStage - .thenApply(s -> { // 2 - assertThat(Thread.currentThread().getName(), is(currentThread)); - return s; - }) - .thenApply(s -> { // 3 - assertThat(Thread.currentThread().getName(), is(currentThread)); - return s; - }); - //#apply-main-thread + CompletionStage stage2 = + completedStage + .thenApply( + s -> { // 2 + assertThat(Thread.currentThread().getName(), is(currentThread)); + return s; + }) + .thenApply( + s -> { // 3 + assertThat(Thread.currentThread().getName(), is(currentThread)); + return s; + }); + // #apply-main-thread stage2.toCompletableFuture().get(2, SECONDS); } @@ -743,26 +825,38 @@ public class FutureDocTest extends AbstractJavaTest { public void thenApplyAsyncDefault() throws Exception { final ExecutionContext ec = system.dispatcher(); - Future scalaFuture = Futures.future(() -> { - assertThat(Thread.currentThread().getName(), containsString("akka.actor.default-dispatcher")); - return "hello"; - }, ec); + Future scalaFuture = + Futures.future( + () -> { + assertThat( + Thread.currentThread().getName(), + containsString("akka.actor.default-dispatcher")); + return "hello"; + }, + ec); - //#apply-async-default - CompletionStage fromScalaFuture = FutureConverters.toJava(scalaFuture) - .thenApplyAsync(s -> { // 1 - assertThat(Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); - return s; - }) - .thenApplyAsync(s -> { // 2 - assertThat(Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); - return s; - }) - .thenApplyAsync(s -> { // 3 - assertThat(Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); - return s; - }); - //#apply-async-default + // #apply-async-default + CompletionStage fromScalaFuture = + FutureConverters.toJava(scalaFuture) + .thenApplyAsync( + s -> { // 1 + assertThat( + Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); + return s; + }) + .thenApplyAsync( + s -> { // 2 + assertThat( + Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); + return s; + }) + .thenApplyAsync( + s -> { // 3 + assertThat( + Thread.currentThread().getName(), containsString("ForkJoinPool.commonPool")); + return s; + }); + // #apply-async-default fromScalaFuture.toCompletableFuture().get(2, SECONDS); } @@ -771,49 +865,72 @@ public class FutureDocTest extends AbstractJavaTest { public void thenApplyAsyncExecutor() throws Exception { final ExecutionContext ec = system.dispatcher(); - Future scalaFuture = Futures.future(() -> { - assertThat(Thread.currentThread().getName(), containsString("akka.actor.default-dispatcher")); - return "hello"; - }, ec); + Future scalaFuture = + Futures.future( + () -> { + assertThat( + Thread.currentThread().getName(), + containsString("akka.actor.default-dispatcher")); + return "hello"; + }, + ec); - //#apply-async-executor + // #apply-async-executor final Executor ex = system.dispatcher(); - CompletionStage fromScalaFuture = FutureConverters.toJava(scalaFuture) - .thenApplyAsync(s -> { - assertThat(Thread.currentThread().getName(), containsString("akka.actor.default-dispatcher")); - return s; - }, ex) - .thenApplyAsync(s -> { - assertThat(Thread.currentThread().getName(), containsString("akka.actor.default-dispatcher")); - return s; - }, ex) - .thenApplyAsync(s -> { - assertThat(Thread.currentThread().getName(), containsString("akka.actor.default-dispatcher")); - return s; - }, ex); - //#apply-async-executor + CompletionStage fromScalaFuture = + FutureConverters.toJava(scalaFuture) + .thenApplyAsync( + s -> { + assertThat( + Thread.currentThread().getName(), + containsString("akka.actor.default-dispatcher")); + return s; + }, + ex) + .thenApplyAsync( + s -> { + assertThat( + Thread.currentThread().getName(), + containsString("akka.actor.default-dispatcher")); + return s; + }, + ex) + .thenApplyAsync( + s -> { + assertThat( + Thread.currentThread().getName(), + containsString("akka.actor.default-dispatcher")); + return s; + }, + ex); + // #apply-async-executor fromScalaFuture.toCompletableFuture().get(2, SECONDS); } - - public static class MyActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(String.class, msg -> { - getSender().tell(msg.toUpperCase(), getSelf()); - }) - .match(Integer.class, i -> { - if (i < 0) { - getSender().tell(new Failure(new ArithmeticException("Negative values not supported")), getSelf()); - } else { - getSender().tell(i, getSelf()); - } - }) - .build(); + .match( + String.class, + msg -> { + getSender().tell(msg.toUpperCase(), getSelf()); + }) + .match( + Integer.class, + i -> { + if (i < 0) { + getSender() + .tell( + new Failure(new ArithmeticException("Negative values not supported")), + getSelf()); + } else { + getSender().tell(i, getSelf()); + } + }) + .build(); } } } diff --git a/akka-docs/src/test/java/jdocs/io/IODocTest.java b/akka-docs/src/test/java/jdocs/io/IODocTest.java index 95ad183c45..c95c67899e 100644 --- a/akka-docs/src/test/java/jdocs/io/IODocTest.java +++ b/akka-docs/src/test/java/jdocs/io/IODocTest.java @@ -6,7 +6,7 @@ package jdocs.io; import akka.actor.ActorSystem; import akka.actor.AbstractActor; -//#imports +// #imports import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; @@ -17,68 +17,78 @@ import akka.io.TcpMessage; import akka.io.TcpSO; import akka.util.ByteString; import java.time.Duration; -//#imports +// #imports public class IODocTest { - static public class Demo extends AbstractActor { + public static class Demo extends AbstractActor { ActorRef connectionActor = null; ActorRef listener = getSelf(); @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("connect", msg -> { - //#manager - final ActorRef tcp = Tcp.get(system).manager(); - //#manager - //#connect - final InetSocketAddress remoteAddr = new InetSocketAddress("127.0.0.1", - 12345); - tcp.tell(TcpMessage.connect(remoteAddr), getSelf()); - //#connect - //#connect-with-options - final InetSocketAddress localAddr = new InetSocketAddress("127.0.0.1", - 1234); - final List options = new ArrayList(); - options.add(TcpSO.keepAlive(true)); - Duration timeout = null; - tcp.tell(TcpMessage.connect(remoteAddr, localAddr, options, timeout, false), getSelf()); - //#connect-with-options - }) - //#connected - .match(Tcp.Connected.class, conn -> { - connectionActor = getSender(); - connectionActor.tell(TcpMessage.register(listener), getSelf()); - }) - //#connected - //#received - .match(Tcp.Received.class, recv -> { - final ByteString data = recv.data(); - // and do something with the received data ... - }) - .match(Tcp.CommandFailed.class, failed -> { - final Tcp.Command command = failed.cmd(); - // react to failed connect, bind, write, etc. - }) - .match(Tcp.ConnectionClosed.class, closed -> { - if (closed.isAborted()) { - // handle close reasons like this - } - }) - //#received - .matchEquals("bind", msg -> { - final ActorRef handler = getSelf(); - //#bind - final ActorRef tcp = Tcp.get(system).manager(); - final InetSocketAddress localAddr = new InetSocketAddress("127.0.0.1", - 1234); - final List options = new ArrayList(); - options.add(TcpSO.reuseAddress(true)); - tcp.tell(TcpMessage.bind(handler, localAddr, 10, options, false), getSelf()); - //#bind - }) - .build(); + .matchEquals( + "connect", + msg -> { + // #manager + final ActorRef tcp = Tcp.get(system).manager(); + // #manager + // #connect + final InetSocketAddress remoteAddr = new InetSocketAddress("127.0.0.1", 12345); + tcp.tell(TcpMessage.connect(remoteAddr), getSelf()); + // #connect + // #connect-with-options + final InetSocketAddress localAddr = new InetSocketAddress("127.0.0.1", 1234); + final List options = new ArrayList(); + options.add(TcpSO.keepAlive(true)); + Duration timeout = null; + tcp.tell( + TcpMessage.connect(remoteAddr, localAddr, options, timeout, false), getSelf()); + // #connect-with-options + }) + // #connected + .match( + Tcp.Connected.class, + conn -> { + connectionActor = getSender(); + connectionActor.tell(TcpMessage.register(listener), getSelf()); + }) + // #connected + // #received + .match( + Tcp.Received.class, + recv -> { + final ByteString data = recv.data(); + // and do something with the received data ... + }) + .match( + Tcp.CommandFailed.class, + failed -> { + final Tcp.Command command = failed.cmd(); + // react to failed connect, bind, write, etc. + }) + .match( + Tcp.ConnectionClosed.class, + closed -> { + if (closed.isAborted()) { + // handle close reasons like this + } + }) + // #received + .matchEquals( + "bind", + msg -> { + final ActorRef handler = getSelf(); + // #bind + final ActorRef tcp = Tcp.get(system).manager(); + final InetSocketAddress localAddr = new InetSocketAddress("127.0.0.1", 1234); + final List options = new ArrayList(); + options.add(TcpSO.reuseAddress(true)); + tcp.tell(TcpMessage.bind(handler, localAddr, 10, options, false), getSelf()); + // #bind + }) + .build(); } } diff --git a/akka-docs/src/test/java/jdocs/io/JavaReadBackPressure.java b/akka-docs/src/test/java/jdocs/io/JavaReadBackPressure.java index d54f8e2ca6..5d22a793e7 100644 --- a/akka-docs/src/test/java/jdocs/io/JavaReadBackPressure.java +++ b/akka-docs/src/test/java/jdocs/io/JavaReadBackPressure.java @@ -17,87 +17,90 @@ import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; -/** - * Copyright (C) 2009-2018 Lightbend Inc. - */ +/** Copyright (C) 2009-2018 Lightbend Inc. */ public class JavaReadBackPressure { - static public class Listener extends AbstractActor { - ActorRef tcp; - ActorRef listener; + public static class Listener extends AbstractActor { + ActorRef tcp; + ActorRef listener; - @Override - //#pull-accepting - public Receive createReceive() { - return receiveBuilder() - .match(Tcp.Bound.class, x -> { - listener = getSender(); - // Accept connections one by one - listener.tell(TcpMessage.resumeAccepting(1), getSelf()); - }) - .match(Tcp.Connected.class, x -> { - ActorRef handler = getContext().actorOf(Props.create(PullEcho.class, getSender())); - getSender().tell(TcpMessage.register(handler), getSelf()); - // Resume accepting connections - listener.tell(TcpMessage.resumeAccepting(1), getSelf()); - }) - .build(); - } - //#pull-accepting + @Override + // #pull-accepting + public Receive createReceive() { + return receiveBuilder() + .match( + Tcp.Bound.class, + x -> { + listener = getSender(); + // Accept connections one by one + listener.tell(TcpMessage.resumeAccepting(1), getSelf()); + }) + .match( + Tcp.Connected.class, + x -> { + ActorRef handler = getContext().actorOf(Props.create(PullEcho.class, getSender())); + getSender().tell(TcpMessage.register(handler), getSelf()); + // Resume accepting connections + listener.tell(TcpMessage.resumeAccepting(1), getSelf()); + }) + .build(); + } + // #pull-accepting - @Override - public void preStart() throws Exception { - //#pull-mode-bind - tcp = Tcp.get(getContext().getSystem()).manager(); - final List options = new ArrayList(); - tcp.tell( - TcpMessage.bind(getSelf(), new InetSocketAddress("localhost", 0), 100, options, true), - getSelf() - ); - //#pull-mode-bind - } - - private void demonstrateConnect() { - //#pull-mode-connect - final List options = new ArrayList(); - Duration timeout = null; - tcp.tell( - TcpMessage.connect(new InetSocketAddress("localhost", 3000), null, options, timeout, true), - getSelf() - ); - //#pull-mode-connect - } + @Override + public void preStart() throws Exception { + // #pull-mode-bind + tcp = Tcp.get(getContext().getSystem()).manager(); + final List options = new ArrayList(); + tcp.tell( + TcpMessage.bind(getSelf(), new InetSocketAddress("localhost", 0), 100, options, true), + getSelf()); + // #pull-mode-bind } - static public class Ack implements Tcp.Event { + private void demonstrateConnect() { + // #pull-mode-connect + final List options = new ArrayList(); + Duration timeout = null; + tcp.tell( + TcpMessage.connect( + new InetSocketAddress("localhost", 3000), null, options, timeout, true), + getSelf()); + // #pull-mode-connect + } + } + + public static class Ack implements Tcp.Event {} + + public static class PullEcho extends AbstractActor { + final ActorRef connection; + + public PullEcho(ActorRef connection) { + this.connection = connection; } - static public class PullEcho extends AbstractActor { - final ActorRef connection; - - public PullEcho(ActorRef connection) { - this.connection = connection; - } - - //#pull-reading-echo - @Override - public void preStart() throws Exception { - connection.tell(TcpMessage.resumeReading(), getSelf()); - } - - @Override - public Receive createReceive() { - return receiveBuilder() - .match(Tcp.Received.class, message -> { - ByteString data = message.data(); - connection.tell(TcpMessage.write(data, new Ack()), getSelf()); - }) - .match(Ack.class, message -> { - connection.tell(TcpMessage.resumeReading(), getSelf()); - }) - .build(); - } - //#pull-reading-echo + // #pull-reading-echo + @Override + public void preStart() throws Exception { + connection.tell(TcpMessage.resumeReading(), getSelf()); } + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + Tcp.Received.class, + message -> { + ByteString data = message.data(); + connection.tell(TcpMessage.write(data, new Ack()), getSelf()); + }) + .match( + Ack.class, + message -> { + connection.tell(TcpMessage.resumeReading(), getSelf()); + }) + .build(); + } + // #pull-reading-echo + } } diff --git a/akka-docs/src/test/java/jdocs/io/JavaUdpMulticast.java b/akka-docs/src/test/java/jdocs/io/JavaUdpMulticast.java index 6670ea10bc..e2407aad6a 100644 --- a/akka-docs/src/test/java/jdocs/io/JavaUdpMulticast.java +++ b/akka-docs/src/test/java/jdocs/io/JavaUdpMulticast.java @@ -4,7 +4,7 @@ package jdocs.io; -//#imports +// #imports import akka.actor.ActorRef; import akka.actor.AbstractActor; import akka.event.Logging; @@ -22,107 +22,114 @@ import java.net.DatagramSocket; import java.nio.channels.DatagramChannel; import java.util.ArrayList; import java.util.List; -//#imports +// #imports public class JavaUdpMulticast { - //#inet6-protocol-family - public static class Inet6ProtocolFamily extends Inet.DatagramChannelCreator { - @Override - public DatagramChannel create() throws Exception { - return DatagramChannel.open(StandardProtocolFamily.INET6); - } + // #inet6-protocol-family + public static class Inet6ProtocolFamily extends Inet.DatagramChannelCreator { + @Override + public DatagramChannel create() throws Exception { + return DatagramChannel.open(StandardProtocolFamily.INET6); } - //#inet6-protocol-family + } + // #inet6-protocol-family - //#multicast-group - public static class MulticastGroup extends Inet.AbstractSocketOptionV2 { - private String address; - private String interf; + // #multicast-group + public static class MulticastGroup extends Inet.AbstractSocketOptionV2 { + private String address; + private String interf; - public MulticastGroup(String address, String interf) { - this.address = address; - this.interf = interf; - } - - @Override - public void afterBind(DatagramSocket s) { - try { - InetAddress group = InetAddress.getByName(address); - NetworkInterface networkInterface = NetworkInterface.getByName(interf); - s.getChannel().join(group, networkInterface); - } catch (Exception ex) { - System.out.println("Unable to join multicast group."); - } - } - } - //#multicast-group - - public static class Listener extends AbstractActor { - LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); - - ActorRef sink; - - public Listener(String iface, String group, Integer port, ActorRef sink) { - this.sink = sink; - - //#bind - List options = new ArrayList<>(); - options.add(new Inet6ProtocolFamily()); - options.add(new MulticastGroup(group, iface)); - - final ActorRef mgr = Udp.get(getContext().getSystem()).getManager(); - // listen for datagrams on this address - InetSocketAddress endpoint = new InetSocketAddress(port); - mgr.tell(UdpMessage.bind(getSelf(), endpoint, options), getSelf()); - //#bind - } - - @Override - public Receive createReceive() { - return receiveBuilder() - .match(Udp.Bound.class, bound -> { - log.info("Bound to {}", bound.localAddress()); - sink.tell(bound, getSelf()); - }) - .match(Udp.Received.class, received -> { - final String txt = received.data().decodeString("utf-8"); - log.info("Received '{}' from {}", txt, received.sender()); - sink.tell(txt, getSelf()); - }) - .build(); - } + public MulticastGroup(String address, String interf) { + this.address = address; + this.interf = interf; } - public static class Sender extends AbstractActor { - LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); - - String iface; - String group; - Integer port; - String message; - - public Sender(String iface, String group, Integer port, String msg) { - this.iface = iface; - this.group = group; - this.port = port; - this.message = msg; - - List options = new ArrayList<>(); - options.add(new Inet6ProtocolFamily()); - - final ActorRef mgr = Udp.get(getContext().getSystem()).getManager(); - mgr.tell(UdpMessage.simpleSender(options), getSelf()); - } - - @Override - public Receive createReceive() { - return receiveBuilder() - .match(Udp.SimpleSenderReady.class, x -> { - InetSocketAddress remote = new InetSocketAddress(group + "%" + iface, port); - log.info("Sending message to " + remote); - getSender().tell(UdpMessage.send(ByteString.fromString(message), remote), getSelf()); - }) - .build(); - } + @Override + public void afterBind(DatagramSocket s) { + try { + InetAddress group = InetAddress.getByName(address); + NetworkInterface networkInterface = NetworkInterface.getByName(interf); + s.getChannel().join(group, networkInterface); + } catch (Exception ex) { + System.out.println("Unable to join multicast group."); + } } + } + // #multicast-group + + public static class Listener extends AbstractActor { + LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); + + ActorRef sink; + + public Listener(String iface, String group, Integer port, ActorRef sink) { + this.sink = sink; + + // #bind + List options = new ArrayList<>(); + options.add(new Inet6ProtocolFamily()); + options.add(new MulticastGroup(group, iface)); + + final ActorRef mgr = Udp.get(getContext().getSystem()).getManager(); + // listen for datagrams on this address + InetSocketAddress endpoint = new InetSocketAddress(port); + mgr.tell(UdpMessage.bind(getSelf(), endpoint, options), getSelf()); + // #bind + } + + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + Udp.Bound.class, + bound -> { + log.info("Bound to {}", bound.localAddress()); + sink.tell(bound, getSelf()); + }) + .match( + Udp.Received.class, + received -> { + final String txt = received.data().decodeString("utf-8"); + log.info("Received '{}' from {}", txt, received.sender()); + sink.tell(txt, getSelf()); + }) + .build(); + } + } + + public static class Sender extends AbstractActor { + LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); + + String iface; + String group; + Integer port; + String message; + + public Sender(String iface, String group, Integer port, String msg) { + this.iface = iface; + this.group = group; + this.port = port; + this.message = msg; + + List options = new ArrayList<>(); + options.add(new Inet6ProtocolFamily()); + + final ActorRef mgr = Udp.get(getContext().getSystem()).getManager(); + mgr.tell(UdpMessage.simpleSender(options), getSelf()); + } + + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + Udp.SimpleSenderReady.class, + x -> { + InetSocketAddress remote = new InetSocketAddress(group + "%" + iface, port); + log.info("Sending message to " + remote); + getSender() + .tell(UdpMessage.send(ByteString.fromString(message), remote), getSelf()); + }) + .build(); + } + } } diff --git a/akka-docs/src/test/java/jdocs/io/JavaUdpMulticastTest.java b/akka-docs/src/test/java/jdocs/io/JavaUdpMulticastTest.java index 1ed9da5075..7aa68683f1 100644 --- a/akka-docs/src/test/java/jdocs/io/JavaUdpMulticastTest.java +++ b/akka-docs/src/test/java/jdocs/io/JavaUdpMulticastTest.java @@ -21,80 +21,96 @@ import java.net.InetAddress; import java.net.NetworkInterface; import java.util.*; - public class JavaUdpMulticastTest extends AbstractJavaTest { - static ActorSystem system; + static ActorSystem system; - @BeforeClass - public static void setup() { - system = ActorSystem.create("JavaUdpMulticastTest"); - } + @BeforeClass + public static void setup() { + system = ActorSystem.create("JavaUdpMulticastTest"); + } - @Test - public void testUdpMulticast() throws Exception { - new TestKit(system) {{ - List ipv6Ifaces = new ArrayList<>(); - for (Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) { - NetworkInterface interf = interfaces.nextElement(); - if (interf.isUp() && interf.supportsMulticast()) { - for (Enumeration addresses = interf.getInetAddresses(); addresses.hasMoreElements(); ) { - InetAddress address = addresses.nextElement(); - if (address instanceof Inet6Address) { - ipv6Ifaces.add(interf); - } - } - } + @Test + public void testUdpMulticast() throws Exception { + new TestKit(system) { + { + List ipv6Ifaces = new ArrayList<>(); + for (Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + interfaces.hasMoreElements(); ) { + NetworkInterface interf = interfaces.nextElement(); + if (interf.isUp() && interf.supportsMulticast()) { + for (Enumeration addresses = interf.getInetAddresses(); + addresses.hasMoreElements(); ) { + InetAddress address = addresses.nextElement(); + if (address instanceof Inet6Address) { + ipv6Ifaces.add(interf); + } } - if (ipv6Ifaces.isEmpty()) { - system.log().info("JavaUdpMulticastTest skipped since no ipv6 interface supporting multicast could be found"); - } else { - // lots of problems with choosing the wrong interface for this test depending - // 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 - for (Iterator interfaceIterator = ipv6Ifaces.iterator(); interfaceIterator.hasNext(); ) { - NetworkInterface ipv6Iface = interfaceIterator.next(); - // 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 - final String randomAddress = Long.toHexString(((long) Math.abs(new Random().nextInt())) | (1L << 31)).toUpperCase(); - final StringBuilder groupBuilder = new StringBuilder("FF02:"); - for (int i = 0; i < 2; i += 1) { - groupBuilder.append(":"); - groupBuilder.append(randomAddress.subSequence(i * 4, i * 4 + 4)); - } - final String group = groupBuilder.toString(); - final Integer port = SocketUtil.temporaryUdpIpv6Port(ipv6Iface); - final String msg = "ohi"; - final ActorRef sink = getRef(); - final String iface = ipv6Iface.getName(); - - final ActorRef listener = system.actorOf(Props.create(JavaUdpMulticast.Listener.class, iface, group, port, sink)); - - try { - expectMsgClass(Udp.Bound.class); - final ActorRef sender = system.actorOf(Props.create(JavaUdpMulticast.Sender.class, iface, group, port, msg)); - expectMsgEquals(msg); - // success with one interface is enough - break; - - } catch (AssertionError ex) { - if (!interfaceIterator.hasNext()) throw ex; - else { - system.log().info("Failed to run test on interface {}", ipv6Iface.getDisplayName()); - } - } finally { - // unbind - system.stop(listener); - } - } + } + } + if (ipv6Ifaces.isEmpty()) { + system + .log() + .info( + "JavaUdpMulticastTest skipped since no ipv6 interface supporting multicast could be found"); + } else { + // lots of problems with choosing the wrong interface for this test depending + // 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 + for (Iterator interfaceIterator = ipv6Ifaces.iterator(); + interfaceIterator.hasNext(); ) { + NetworkInterface ipv6Iface = interfaceIterator.next(); + // 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 + final String randomAddress = + Long.toHexString(((long) Math.abs(new Random().nextInt())) | (1L << 31)) + .toUpperCase(); + final StringBuilder groupBuilder = new StringBuilder("FF02:"); + for (int i = 0; i < 2; i += 1) { + groupBuilder.append(":"); + groupBuilder.append(randomAddress.subSequence(i * 4, i * 4 + 4)); } - }}; - } + final String group = groupBuilder.toString(); + final Integer port = SocketUtil.temporaryUdpIpv6Port(ipv6Iface); + final String msg = "ohi"; + final ActorRef sink = getRef(); + final String iface = ipv6Iface.getName(); - @AfterClass - public static void tearDown() { - TestKit.shutdownActorSystem(system); - system = null; - } + final ActorRef listener = + system.actorOf( + Props.create(JavaUdpMulticast.Listener.class, iface, group, port, sink)); + + try { + expectMsgClass(Udp.Bound.class); + final ActorRef sender = + system.actorOf( + Props.create(JavaUdpMulticast.Sender.class, iface, group, port, msg)); + expectMsgEquals(msg); + // success with one interface is enough + break; + + } catch (AssertionError ex) { + if (!interfaceIterator.hasNext()) throw ex; + else { + system.log().info("Failed to run test on interface {}", ipv6Iface.getDisplayName()); + } + } finally { + // unbind + system.stop(listener); + } + } + } + } + }; + } + + @AfterClass + public static void tearDown() { + TestKit.shutdownActorSystem(system); + system = null; + } } diff --git a/akka-docs/src/test/java/jdocs/io/UdpConnectedDocTest.java b/akka-docs/src/test/java/jdocs/io/UdpConnectedDocTest.java index d7a6babcea..d16eb059e0 100644 --- a/akka-docs/src/test/java/jdocs/io/UdpConnectedDocTest.java +++ b/akka-docs/src/test/java/jdocs/io/UdpConnectedDocTest.java @@ -9,7 +9,7 @@ import org.junit.Test; import akka.actor.ActorSystem; import akka.actor.AbstractActor; -//#imports +// #imports import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; @@ -19,11 +19,11 @@ import akka.io.UdpConnected; import akka.io.UdpConnectedMessage; import akka.io.UdpSO; import akka.util.ByteString; -//#imports +// #imports public class UdpConnectedDocTest { - static public class Demo extends AbstractActor { + public static class Demo extends AbstractActor { ActorRef connectionActor = null; ActorRef handler = getSelf(); ActorSystem system = getContext().getSystem(); @@ -31,55 +31,63 @@ public class UdpConnectedDocTest { @Override public Receive createReceive() { ReceiveBuilder builder = receiveBuilder(); - builder.matchEquals("connect", message -> { - //#manager - final ActorRef udp = UdpConnected.get(system).manager(); - //#manager - //#connect - final InetSocketAddress remoteAddr = - new InetSocketAddress("127.0.0.1", 12345); - udp.tell(UdpConnectedMessage.connect(handler, remoteAddr), getSelf()); - //#connect - //#connect-with-options - final InetSocketAddress localAddr = - new InetSocketAddress("127.0.0.1", 1234); - final List options = - new ArrayList(); - options.add(UdpSO.broadcast(true)); - udp.tell(UdpConnectedMessage.connect(handler, remoteAddr, localAddr, options), getSelf()); - //#connect-with-options - }); - //#connected - builder.match(UdpConnected.Connected.class, conn -> { - connectionActor = getSender(); // Save the worker ref for later use - }); - //#connected - //#received + builder.matchEquals( + "connect", + message -> { + // #manager + final ActorRef udp = UdpConnected.get(system).manager(); + // #manager + // #connect + final InetSocketAddress remoteAddr = new InetSocketAddress("127.0.0.1", 12345); + udp.tell(UdpConnectedMessage.connect(handler, remoteAddr), getSelf()); + // #connect + // #connect-with-options + final InetSocketAddress localAddr = new InetSocketAddress("127.0.0.1", 1234); + final List options = new ArrayList(); + options.add(UdpSO.broadcast(true)); + udp.tell( + UdpConnectedMessage.connect(handler, remoteAddr, localAddr, options), getSelf()); + // #connect-with-options + }); + // #connected + builder.match( + UdpConnected.Connected.class, + conn -> { + connectionActor = getSender(); // Save the worker ref for later use + }); + // #connected + // #received builder - .match(UdpConnected.Received.class, recv -> { - final ByteString data = recv.data(); - // and do something with the received data ... - }) - .match(UdpConnected.CommandFailed.class, failed -> { - final UdpConnected.Command command = failed.cmd(); - // react to failed connect, etc. - }) - .match(UdpConnected.Disconnected.class, x -> { - // do something on disconnect - }); - //#received - builder.matchEquals("send", x -> { - ByteString data = ByteString.empty(); - //#send - connectionActor.tell(UdpConnectedMessage.send(data), getSelf()); - //#send - }); + .match( + UdpConnected.Received.class, + recv -> { + final ByteString data = recv.data(); + // and do something with the received data ... + }) + .match( + UdpConnected.CommandFailed.class, + failed -> { + final UdpConnected.Command command = failed.cmd(); + // react to failed connect, etc. + }) + .match( + UdpConnected.Disconnected.class, + x -> { + // do something on disconnect + }); + // #received + builder.matchEquals( + "send", + x -> { + ByteString data = ByteString.empty(); + // #send + connectionActor.tell(UdpConnectedMessage.send(data), getSelf()); + // #send + }); return builder.build(); } } @Test - public void demonstrateConnect() { - } - + public void demonstrateConnect() {} } diff --git a/akka-docs/src/test/java/jdocs/io/UdpDocTest.java b/akka-docs/src/test/java/jdocs/io/UdpDocTest.java index 42f5f2a742..b3fddd7a14 100644 --- a/akka-docs/src/test/java/jdocs/io/UdpDocTest.java +++ b/akka-docs/src/test/java/jdocs/io/UdpDocTest.java @@ -4,7 +4,7 @@ package jdocs.io; -//#imports +// #imports import akka.actor.ActorRef; import akka.actor.PoisonPill; import akka.actor.AbstractActor; @@ -15,105 +15,116 @@ import akka.io.UdpMessage; import akka.util.ByteString; import java.net.InetSocketAddress; -//#imports +// #imports public class UdpDocTest { - //#sender + // #sender public static class SimpleSender extends AbstractActor { final InetSocketAddress remote; public SimpleSender(InetSocketAddress remote) { this.remote = remote; - + // request creation of a SimpleSender final ActorRef mgr = Udp.get(getContext().getSystem()).getManager(); mgr.tell(UdpMessage.simpleSender(), getSelf()); } - + @Override public Receive createReceive() { return receiveBuilder() - .match(Udp.SimpleSenderReady.class, message -> { - getContext().become(ready(getSender())); - //#sender - getSender().tell(UdpMessage.send(ByteString.fromString("hello"), remote), getSelf()); - //#sender - }) - .build(); + .match( + Udp.SimpleSenderReady.class, + message -> { + getContext().become(ready(getSender())); + // #sender + getSender() + .tell(UdpMessage.send(ByteString.fromString("hello"), remote), getSelf()); + // #sender + }) + .build(); } private Receive ready(final ActorRef send) { return receiveBuilder() - .match(String.class, message -> { - send.tell(UdpMessage.send(ByteString.fromString(message), remote), getSelf()); - //#sender - if (message.equals("world")) { - send.tell(PoisonPill.getInstance(), getSelf()); - } - //#sender - }) - .build(); + .match( + String.class, + message -> { + send.tell(UdpMessage.send(ByteString.fromString(message), remote), getSelf()); + // #sender + if (message.equals("world")) { + send.tell(PoisonPill.getInstance(), getSelf()); + } + // #sender + }) + .build(); } } - //#sender - - //#listener + // #sender + + // #listener public static class Listener extends AbstractActor { final ActorRef nextActor; public Listener(ActorRef nextActor) { this.nextActor = nextActor; - + // request creation of a bound listen socket final ActorRef mgr = Udp.get(getContext().getSystem()).getManager(); - mgr.tell( - UdpMessage.bind(getSelf(), new InetSocketAddress("localhost", 0)), - getSelf()); + mgr.tell(UdpMessage.bind(getSelf(), new InetSocketAddress("localhost", 0)), getSelf()); } @Override public Receive createReceive() { return receiveBuilder() - .match(Udp.Bound.class, bound -> { - //#listener - nextActor.tell(bound.localAddress(), getSender()); - //#listener - getContext().become(ready(getSender())); - }) - .build(); + .match( + Udp.Bound.class, + bound -> { + // #listener + nextActor.tell(bound.localAddress(), getSender()); + // #listener + getContext().become(ready(getSender())); + }) + .build(); } private Receive ready(final ActorRef socket) { return receiveBuilder() - .match(Udp.Received.class, r -> { - // echo server example: send back the data - socket.tell(UdpMessage.send(r.data(), r.sender()), getSelf()); - // or do some processing and forward it on - final Object processed = // parse data etc., e.g. using PipelineStage - // #listener - r.data().utf8String(); - //#listener - nextActor.tell(processed, getSelf()); - }) - .matchEquals(UdpMessage.unbind(), message -> { - socket.tell(message, getSelf()); - }) - .match(Udp.Unbound.class, message -> { - getContext().stop(getSelf()); - }) - .build(); + .match( + Udp.Received.class, + r -> { + // echo server example: send back the data + socket.tell(UdpMessage.send(r.data(), r.sender()), getSelf()); + // or do some processing and forward it on + final Object processed = // parse data etc., e.g. using PipelineStage + // #listener + r.data().utf8String(); + // #listener + nextActor.tell(processed, getSelf()); + }) + .matchEquals( + UdpMessage.unbind(), + message -> { + socket.tell(message, getSelf()); + }) + .match( + Udp.Unbound.class, + message -> { + getContext().stop(getSelf()); + }) + .build(); } } - //#listener - - //#connected - public static class Connected extends AbstractActor { + // #listener + + // #connected + public static class Connected extends AbstractActor { final InetSocketAddress remote; public Connected(InetSocketAddress remote) { this.remote = remote; - + // create a restricted a.k.a. “connected” socket final ActorRef mgr = UdpConnected.get(getContext().getSystem()).getManager(); mgr.tell(UdpConnectedMessage.connect(getSelf(), remote), getSelf()); @@ -122,43 +133,49 @@ public class UdpDocTest { @Override public Receive createReceive() { return receiveBuilder() - .match(UdpConnected.Connected.class, message -> { - getContext().become(ready(getSender())); - //#connected - getSender() - .tell(UdpConnectedMessage.send(ByteString.fromString("hello")), - getSelf()); - //#connected - }) - .build(); + .match( + UdpConnected.Connected.class, + message -> { + getContext().become(ready(getSender())); + // #connected + getSender() + .tell(UdpConnectedMessage.send(ByteString.fromString("hello")), getSelf()); + // #connected + }) + .build(); } private Receive ready(final ActorRef connection) { return receiveBuilder() - .match(UdpConnected.Received.class, r -> { - // process data, send it on, etc. - // #connected - if (r.data().utf8String().equals("hello")) { - connection.tell( - UdpConnectedMessage.send(ByteString.fromString("world")), - getSelf()); - } - // #connected - }) - .match(String.class, str -> { - connection - .tell(UdpConnectedMessage.send(ByteString.fromString(str)), - getSelf()); - }) - .matchEquals(UdpConnectedMessage.disconnect(), message -> { - connection.tell(message, getSelf()); - }) - .match(UdpConnected.Disconnected.class, x -> { - getContext().stop(getSelf()); - }) - .build(); + .match( + UdpConnected.Received.class, + r -> { + // process data, send it on, etc. + // #connected + if (r.data().utf8String().equals("hello")) { + connection.tell( + UdpConnectedMessage.send(ByteString.fromString("world")), getSelf()); + } + // #connected + }) + .match( + String.class, + str -> { + connection.tell(UdpConnectedMessage.send(ByteString.fromString(str)), getSelf()); + }) + .matchEquals( + UdpConnectedMessage.disconnect(), + message -> { + connection.tell(message, getSelf()); + }) + .match( + UdpConnected.Disconnected.class, + x -> { + getContext().stop(getSelf()); + }) + .build(); } } - //#connected + // #connected } diff --git a/akka-docs/src/test/java/jdocs/io/japi/EchoHandler.java b/akka-docs/src/test/java/jdocs/io/japi/EchoHandler.java index 7501029c08..1120a0678c 100644 --- a/akka-docs/src/test/java/jdocs/io/japi/EchoHandler.java +++ b/akka-docs/src/test/java/jdocs/io/japi/EchoHandler.java @@ -21,11 +21,10 @@ import akka.io.Tcp.WritingResumed; import akka.io.TcpMessage; import akka.util.ByteString; -//#echo-handler +// #echo-handler public class EchoHandler extends AbstractActor { - final LoggingAdapter log = Logging - .getLogger(getContext().getSystem(), getSelf()); + final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), getSelf()); final ActorRef connection; final InetSocketAddress remote; @@ -33,16 +32,17 @@ public class EchoHandler extends AbstractActor { public static final long MAX_STORED = 100000000; public static final long HIGH_WATERMARK = MAX_STORED * 5 / 10; public static final long LOW_WATERMARK = MAX_STORED * 2 / 10; - + private long transferred; private int storageOffset = 0; private long stored = 0; private Queue storage = new LinkedList(); private boolean suspended = false; - + private static class Ack implements Event { public final int ack; + public Ack(int ack) { this.ack = ack; } @@ -51,7 +51,7 @@ public class EchoHandler extends AbstractActor { public EchoHandler(ActorRef connection, InetSocketAddress remote) { this.connection = connection; this.remote = remote; - + writing = writing(); // sign death pact: this actor stops when the connection is closed @@ -60,137 +60,150 @@ public class EchoHandler extends AbstractActor { // start out in optimistic write-through mode getContext().become(writing); } - + @Override - public Receive createReceive() { - return writing; - } - - private final Receive writing; - - private Receive writing() { - return receiveBuilder() - .match(Received.class, msg -> { - final ByteString data = msg.data(); - connection.tell(TcpMessage.write(data, new Ack(currentOffset())), getSelf()); - buffer(data); - - }) - .match(Integer.class, msg -> { - acknowledge(msg); - }) - .match(CommandFailed.class, msg -> { - final Write w = (Write) msg.cmd(); - connection.tell(TcpMessage.resumeWriting(), getSelf()); - getContext().become(buffering((Ack) w.ack())); - }) - .match(ConnectionClosed.class, msg -> { - if (msg.isPeerClosed()) { - if (storage.isEmpty()) { - getContext().stop(getSelf()); - } else { - getContext().become(closing()); - } - } - }) - .build(); + public Receive createReceive() { + return writing; } - //#buffering - - final static class BufferingState { + private final Receive writing; + + private Receive writing() { + return receiveBuilder() + .match( + Received.class, + msg -> { + final ByteString data = msg.data(); + connection.tell(TcpMessage.write(data, new Ack(currentOffset())), getSelf()); + buffer(data); + }) + .match( + Integer.class, + msg -> { + acknowledge(msg); + }) + .match( + CommandFailed.class, + msg -> { + final Write w = (Write) msg.cmd(); + connection.tell(TcpMessage.resumeWriting(), getSelf()); + getContext().become(buffering((Ack) w.ack())); + }) + .match( + ConnectionClosed.class, + msg -> { + if (msg.isPeerClosed()) { + if (storage.isEmpty()) { + getContext().stop(getSelf()); + } else { + getContext().become(closing()); + } + } + }) + .build(); + } + + // #buffering + + static final class BufferingState { int toAck = 10; boolean peerClosed = false; } - + protected Receive buffering(final Ack nack) { final BufferingState state = new BufferingState(); - + return receiveBuilder() - .match(Received.class, msg -> { - buffer(msg.data()); - - }) - .match(WritingResumed.class, msg -> { - writeFirst(); - - }) - .match(ConnectionClosed.class, msg -> { - if (msg.isPeerClosed()) - state.peerClosed = true; - else - getContext().stop(getSelf()); - - }) - .match(Integer.class, ack -> { - acknowledge(ack); - - if (ack >= nack.ack) { - // otherwise it was the ack of the last successful write - - if (storage.isEmpty()) { - if (state.peerClosed) - getContext().stop(getSelf()); - else - getContext().become(writing); - - } else { - if (state.toAck > 0) { - // stay in ACK-based mode for a short while + .match( + Received.class, + msg -> { + buffer(msg.data()); + }) + .match( + WritingResumed.class, + msg -> { writeFirst(); - --state.toAck; - } else { - // then return to NACK-based again - writeAll(); - if (state.peerClosed) - getContext().become(closing()); - else - getContext().become(writing); - } - } - } - }) - .build(); - } - //#buffering + }) + .match( + ConnectionClosed.class, + msg -> { + if (msg.isPeerClosed()) state.peerClosed = true; + else getContext().stop(getSelf()); + }) + .match( + Integer.class, + ack -> { + acknowledge(ack); - //#closing + if (ack >= nack.ack) { + // otherwise it was the ack of the last successful write + + if (storage.isEmpty()) { + if (state.peerClosed) getContext().stop(getSelf()); + else getContext().become(writing); + + } else { + if (state.toAck > 0) { + // stay in ACK-based mode for a short while + writeFirst(); + --state.toAck; + } else { + // then return to NACK-based again + writeAll(); + if (state.peerClosed) getContext().become(closing()); + else getContext().become(writing); + } + } + } + }) + .build(); + } + // #buffering + + // #closing protected Receive closing() { return receiveBuilder() - .match(CommandFailed.class, msg -> { - // the command can only have been a Write - connection.tell(TcpMessage.resumeWriting(), getSelf()); - getContext().become(closeResend(), false); - }) - .match(Integer.class, msg -> { - acknowledge(msg); - if (storage.isEmpty()) - getContext().stop(getSelf()); - }) - .build(); + .match( + CommandFailed.class, + msg -> { + // the command can only have been a Write + connection.tell(TcpMessage.resumeWriting(), getSelf()); + getContext().become(closeResend(), false); + }) + .match( + Integer.class, + msg -> { + acknowledge(msg); + if (storage.isEmpty()) getContext().stop(getSelf()); + }) + .build(); } protected Receive closeResend() { return receiveBuilder() - .match(WritingResumed.class, msg -> { - writeAll(); - getContext().unbecome(); - }) - .match(Integer.class, msg -> { - acknowledge(msg); - }) - .build(); + .match( + WritingResumed.class, + msg -> { + writeAll(); + getContext().unbecome(); + }) + .match( + Integer.class, + msg -> { + acknowledge(msg); + }) + .build(); } - //#closing + // #closing - //#storage-omitted + // #storage-omitted @Override public void postStop() { log.info("transferred {} bytes from/to [{}]", transferred, remote); } - //#helpers + // #helpers protected void buffer(ByteString data) { storage.add(data); stored += data.size(); @@ -221,7 +234,7 @@ public class EchoHandler extends AbstractActor { suspended = false; } } - //#helpers + // #helpers protected int currentOffset() { return storageOffset + storage.size(); @@ -238,6 +251,6 @@ public class EchoHandler extends AbstractActor { connection.tell(TcpMessage.write(storage.peek(), new Ack(storageOffset)), getSelf()); } - //#storage-omitted + // #storage-omitted } -//#echo-handler +// #echo-handler diff --git a/akka-docs/src/test/java/jdocs/io/japi/EchoManager.java b/akka-docs/src/test/java/jdocs/io/japi/EchoManager.java index 9e7467f96e..26a542d419 100644 --- a/akka-docs/src/test/java/jdocs/io/japi/EchoManager.java +++ b/akka-docs/src/test/java/jdocs/io/japi/EchoManager.java @@ -20,8 +20,7 @@ import akka.io.TcpMessage; public class EchoManager extends AbstractActor { - final LoggingAdapter log = Logging - .getLogger(getContext().getSystem(), getSelf()); + final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), getSelf()); final Class handlerClass; @@ -36,12 +35,11 @@ public class EchoManager extends AbstractActor { @Override public void preStart() throws Exception { - //#manager + // #manager final ActorRef tcpManager = Tcp.get(getContext().getSystem()).manager(); - //#manager + // #manager tcpManager.tell( - TcpMessage.bind(getSelf(), new InetSocketAddress("localhost", 0), 100), - getSelf()); + TcpMessage.bind(getSelf(), new InetSocketAddress("localhost", 0), 100), getSelf()); } @Override @@ -53,29 +51,37 @@ public class EchoManager extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(Bound.class, msg -> { - log.info("listening on [{}]", msg.localAddress()); - }) - .match(Tcp.CommandFailed.class, failed -> { - if (failed.cmd() instanceof Bind) { - log.warning("cannot bind to [{}]", ((Bind) failed.cmd()).localAddress()); - getContext().stop(getSelf()); - } else { - log.warning("unknown command failed [{}]", failed.cmd()); - } - }) - .match(Connected.class, conn -> { - log.info("received connection from [{}]", conn.remoteAddress()); - final ActorRef connection = getSender(); - final ActorRef handler = getContext().actorOf( - Props.create(handlerClass, connection, conn.remoteAddress())); - //#echo-manager - connection.tell(TcpMessage.register(handler, - true, // <-- keepOpenOnPeerClosed flag - true), getSelf()); - //#echo-manager - }) - .build(); + .match( + Bound.class, + msg -> { + log.info("listening on [{}]", msg.localAddress()); + }) + .match( + Tcp.CommandFailed.class, + failed -> { + if (failed.cmd() instanceof Bind) { + log.warning("cannot bind to [{}]", ((Bind) failed.cmd()).localAddress()); + getContext().stop(getSelf()); + } else { + log.warning("unknown command failed [{}]", failed.cmd()); + } + }) + .match( + Connected.class, + conn -> { + log.info("received connection from [{}]", conn.remoteAddress()); + final ActorRef connection = getSender(); + final ActorRef handler = + getContext() + .actorOf(Props.create(handlerClass, connection, conn.remoteAddress())); + // #echo-manager + connection.tell( + TcpMessage.register( + handler, true, // <-- keepOpenOnPeerClosed flag + true), + getSelf()); + // #echo-manager + }) + .build(); } - } diff --git a/akka-docs/src/test/java/jdocs/io/japi/EchoServer.java b/akka-docs/src/test/java/jdocs/io/japi/EchoServer.java index 461070a033..f7163c3391 100644 --- a/akka-docs/src/test/java/jdocs/io/japi/EchoServer.java +++ b/akka-docs/src/test/java/jdocs/io/japi/EchoServer.java @@ -22,8 +22,10 @@ public class EchoServer { try { final CountDownLatch latch = new CountDownLatch(1); final ActorRef watcher = system.actorOf(Props.create(Watcher.class, latch), "watcher"); - final ActorRef nackServer = system.actorOf(Props.create(EchoManager.class, EchoHandler.class), "nack"); - final ActorRef ackServer = system.actorOf(Props.create(EchoManager.class, SimpleEchoHandler.class), "ack"); + final ActorRef nackServer = + system.actorOf(Props.create(EchoManager.class, EchoHandler.class), "nack"); + final ActorRef ackServer = + system.actorOf(Props.create(EchoManager.class, SimpleEchoHandler.class), "ack"); watcher.tell(nackServer, ActorRef.noSender()); watcher.tell(ackServer, ActorRef.noSender()); latch.await(10, TimeUnit.MINUTES); @@ -31,5 +33,4 @@ public class EchoServer { system.terminate(); } } - } diff --git a/akka-docs/src/test/java/jdocs/io/japi/IODocTest.java b/akka-docs/src/test/java/jdocs/io/japi/IODocTest.java index c87c9d2adf..aa13d348ab 100644 --- a/akka-docs/src/test/java/jdocs/io/japi/IODocTest.java +++ b/akka-docs/src/test/java/jdocs/io/japi/IODocTest.java @@ -4,14 +4,13 @@ package jdocs.io.japi; - import akka.testkit.AkkaJUnitActorSystemResource; import jdocs.AbstractJavaTest; import akka.testkit.javadsl.TestKit; import org.junit.ClassRule; import org.junit.Test; -//#imports +// #imports import java.net.InetSocketAddress; import akka.actor.ActorRef; import akka.actor.ActorSystem; @@ -25,22 +24,22 @@ import akka.io.Tcp.ConnectionClosed; import akka.io.Tcp.Received; import akka.io.TcpMessage; import akka.util.ByteString; -//#imports +// #imports import akka.testkit.AkkaSpec; public class IODocTest extends AbstractJavaTest { - static - //#server - public class Server extends AbstractActor { - + public + // #server + static class Server extends AbstractActor { + final ActorRef manager; - + public Server(ActorRef manager) { this.manager = manager; } - + public static Props props(ActorRef manager) { return Props.create(Server.class, manager); } @@ -48,67 +47,73 @@ public class IODocTest extends AbstractJavaTest { @Override public void preStart() throws Exception { final ActorRef tcp = Tcp.get(getContext().getSystem()).manager(); - tcp.tell(TcpMessage.bind(getSelf(), - new InetSocketAddress("localhost", 0), 100), getSelf()); + tcp.tell(TcpMessage.bind(getSelf(), new InetSocketAddress("localhost", 0), 100), getSelf()); } @Override public Receive createReceive() { return receiveBuilder() - .match(Bound.class, msg -> { - manager.tell(msg, getSelf()); - - }) - .match(CommandFailed.class, msg -> { - getContext().stop(getSelf()); - - }) - .match(Connected.class, conn -> { - manager.tell(conn, getSelf()); - final ActorRef handler = getContext().actorOf( - Props.create(SimplisticHandler.class)); - getSender().tell(TcpMessage.register(handler), getSelf()); - }) - .build(); + .match( + Bound.class, + msg -> { + manager.tell(msg, getSelf()); + }) + .match( + CommandFailed.class, + msg -> { + getContext().stop(getSelf()); + }) + .match( + Connected.class, + conn -> { + manager.tell(conn, getSelf()); + final ActorRef handler = + getContext().actorOf(Props.create(SimplisticHandler.class)); + getSender().tell(TcpMessage.register(handler), getSelf()); + }) + .build(); } - } - //#server + // #server - static - //#simplistic-handler - public class SimplisticHandler extends AbstractActor { + public + // #simplistic-handler + static class SimplisticHandler extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(Received.class, msg -> { - final ByteString data = msg.data(); - System.out.println(data); - getSender().tell(TcpMessage.write(data), getSelf()); - }) - .match(ConnectionClosed.class, msg -> { - getContext().stop(getSelf()); - }) - .build(); + .match( + Received.class, + msg -> { + final ByteString data = msg.data(); + System.out.println(data); + getSender().tell(TcpMessage.write(data), getSelf()); + }) + .match( + ConnectionClosed.class, + msg -> { + getContext().stop(getSelf()); + }) + .build(); } } - //#simplistic-handler - - static - //#client - public class Client extends AbstractActor { - + // #simplistic-handler + + public + // #client + static class Client extends AbstractActor { + final InetSocketAddress remote; final ActorRef listener; - + public static Props props(InetSocketAddress remote, ActorRef listener) { - return Props.create(Client.class, remote, listener); + return Props.create(Client.class, remote, listener); } public Client(InetSocketAddress remote, ActorRef listener) { this.remote = remote; this.listener = listener; - + final ActorRef tcp = Tcp.get(getContext().getSystem()).manager(); tcp.tell(TcpMessage.connect(remote), getSelf()); } @@ -116,45 +121,57 @@ public class IODocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .match(CommandFailed.class, msg -> { - listener.tell("failed", getSelf()); - getContext().stop(getSelf()); - - }) - .match(Connected.class, msg -> { - listener.tell(msg, getSelf()); - getSender().tell(TcpMessage.register(getSelf()), getSelf()); - getContext().become(connected(getSender())); - }) - .build(); + .match( + CommandFailed.class, + msg -> { + listener.tell("failed", getSelf()); + getContext().stop(getSelf()); + }) + .match( + Connected.class, + msg -> { + listener.tell(msg, getSelf()); + getSender().tell(TcpMessage.register(getSelf()), getSelf()); + getContext().become(connected(getSender())); + }) + .build(); } private Receive connected(final ActorRef connection) { return receiveBuilder() - .match(ByteString.class, msg -> { - connection.tell(TcpMessage.write((ByteString) msg), getSelf()); - }) - .match(CommandFailed.class, msg -> { - // OS kernel socket buffer was full - }) - .match(Received.class, msg -> { - listener.tell(msg.data(), getSelf()); - }) - .matchEquals("close", msg -> { - connection.tell(TcpMessage.close(), getSelf()); - }) - .match(ConnectionClosed.class, msg -> { - getContext().stop(getSelf()); - }) - .build(); + .match( + ByteString.class, + msg -> { + connection.tell(TcpMessage.write((ByteString) msg), getSelf()); + }) + .match( + CommandFailed.class, + msg -> { + // OS kernel socket buffer was full + }) + .match( + Received.class, + msg -> { + listener.tell(msg.data(), getSelf()); + }) + .matchEquals( + "close", + msg -> { + connection.tell(TcpMessage.close(), getSelf()); + }) + .match( + ConnectionClosed.class, + msg -> { + getContext().stop(getSelf()); + }) + .build(); } - } - //#client + // #client @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("IODocTest", AkkaSpec.testConf()); + new AkkaJUnitActorSystemResource("IODocTest", AkkaSpec.testConf()); private final ActorSystem system = actorSystemResource.getSystem(); @@ -166,21 +183,20 @@ public class IODocTest extends AbstractJavaTest { final ActorRef server = system.actorOf(Server.props(getRef()), "server1"); final InetSocketAddress listen = expectMsgClass(Bound.class).localAddress(); final ActorRef client = system.actorOf(Client.props(listen, getRef()), "client1"); - + final Connected c1 = expectMsgClass(Connected.class); final Connected c2 = expectMsgClass(Connected.class); assert c1.localAddress().equals(c2.remoteAddress()); assert c2.localAddress().equals(c1.remoteAddress()); - + client.tell(ByteString.fromString("hello"), getRef()); final ByteString reply = expectMsgClass(ByteString.class); assert reply.utf8String().equals("hello"); - + watch(client); client.tell("close", getRef()); expectTerminated(client); } }; } - } diff --git a/akka-docs/src/test/java/jdocs/io/japi/Message.java b/akka-docs/src/test/java/jdocs/io/japi/Message.java index 4e544cc336..853d804f3f 100644 --- a/akka-docs/src/test/java/jdocs/io/japi/Message.java +++ b/akka-docs/src/test/java/jdocs/io/japi/Message.java @@ -4,10 +4,10 @@ package jdocs.io.japi; -//#message +// #message public class Message { - - static public class Person { + + public static class Person { private final String first; private final String last; @@ -23,7 +23,6 @@ public class Message { public String getLast() { return last; } - } private final Person[] persons; @@ -42,4 +41,4 @@ public class Message { return happinessCurve; } } -//#message +// #message diff --git a/akka-docs/src/test/java/jdocs/io/japi/SimpleEchoHandler.java b/akka-docs/src/test/java/jdocs/io/japi/SimpleEchoHandler.java index b5a0fa713d..0371e57c2f 100644 --- a/akka-docs/src/test/java/jdocs/io/japi/SimpleEchoHandler.java +++ b/akka-docs/src/test/java/jdocs/io/japi/SimpleEchoHandler.java @@ -18,11 +18,10 @@ import akka.io.Tcp.Received; import akka.io.TcpMessage; import akka.util.ByteString; -//#simple-echo-handler +// #simple-echo-handler public class SimpleEchoHandler extends AbstractActor { - - final LoggingAdapter log = Logging - .getLogger(getContext().getSystem(), getSelf()); + + final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), getSelf()); final ActorRef connection; final InetSocketAddress remote; @@ -42,42 +41,50 @@ public class SimpleEchoHandler extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(Received.class, msg -> { - final ByteString data = msg.data(); - buffer(data); - connection.tell(TcpMessage.write(data, ACK), getSelf()); - // now switch behavior to “waiting for acknowledgement” - getContext().become(buffering(), false); - - }) - .match(ConnectionClosed.class, msg -> { - getContext().stop(getSelf()); - }) - .build(); + .match( + Received.class, + msg -> { + final ByteString data = msg.data(); + buffer(data); + connection.tell(TcpMessage.write(data, ACK), getSelf()); + // now switch behavior to “waiting for acknowledgement” + getContext().become(buffering(), false); + }) + .match( + ConnectionClosed.class, + msg -> { + getContext().stop(getSelf()); + }) + .build(); } private final Receive buffering() { return receiveBuilder() - .match(Received.class, msg -> { - buffer(msg.data()); - - }) - .match(Event.class, msg -> msg == ACK, msg -> { - acknowledge(); - - }) - .match(ConnectionClosed.class, msg -> { - if (msg.isPeerClosed()) { - closing = true; - } else { - // could also be ErrorClosed, in which case we just give up - getContext().stop(getSelf()); - } - }) - .build(); + .match( + Received.class, + msg -> { + buffer(msg.data()); + }) + .match( + Event.class, + msg -> msg == ACK, + msg -> { + acknowledge(); + }) + .match( + ConnectionClosed.class, + msg -> { + if (msg.isPeerClosed()) { + closing = true; + } else { + // could also be ErrorClosed, in which case we just give up + getContext().stop(getSelf()); + } + }) + .build(); } - //#storage-omitted + // #storage-omitted public void postStop() { log.info("transferred {} bytes from/to [{}]", transferred, remote); } @@ -88,10 +95,10 @@ public class SimpleEchoHandler extends AbstractActor { private boolean suspended = false; private boolean closing = false; - + private final Event ACK = new Event() {}; - //#simple-helpers + // #simple-helpers protected void buffer(ByteString data) { storage.add(data); stored += data.size(); @@ -117,7 +124,7 @@ public class SimpleEchoHandler extends AbstractActor { connection.tell(TcpMessage.resumeReading(), getSelf()); suspended = false; } - + if (storage.isEmpty()) { if (closing) { getContext().stop(getSelf()); @@ -128,7 +135,7 @@ public class SimpleEchoHandler extends AbstractActor { connection.tell(TcpMessage.write(storage.peek(), ACK), getSelf()); } } - //#simple-helpers - //#storage-omitted + // #simple-helpers + // #storage-omitted } -//#simple-echo-handler +// #simple-echo-handler diff --git a/akka-docs/src/test/java/jdocs/io/japi/Watcher.java b/akka-docs/src/test/java/jdocs/io/japi/Watcher.java index 0d4bda82a0..cf9af39aa0 100644 --- a/akka-docs/src/test/java/jdocs/io/japi/Watcher.java +++ b/akka-docs/src/test/java/jdocs/io/japi/Watcher.java @@ -11,14 +11,15 @@ import akka.actor.Terminated; import akka.actor.AbstractActor; public class Watcher extends AbstractActor { - - static public class Watch { + + public static class Watch { final ActorRef target; + public Watch(ActorRef target) { this.target = target; } } - + final CountDownLatch latch; public Watcher(CountDownLatch latch) { @@ -28,14 +29,17 @@ public class Watcher extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(Watch.class, msg -> { - getContext().watch(msg.target); - }) - .match(Terminated.class, msg -> { - latch.countDown(); - if (latch.getCount() == 0) getContext().stop(getSelf()); - }) - .build(); + .match( + Watch.class, + msg -> { + getContext().watch(msg.target); + }) + .match( + Terminated.class, + msg -> { + latch.countDown(); + if (latch.getCount() == 0) getContext().stop(getSelf()); + }) + .build(); } - } diff --git a/akka-docs/src/test/java/jdocs/pattern/BackoffSupervisorDocTest.java b/akka-docs/src/test/java/jdocs/pattern/BackoffSupervisorDocTest.java index 19f7239963..e1b68b421b 100644 --- a/akka-docs/src/test/java/jdocs/pattern/BackoffSupervisorDocTest.java +++ b/akka-docs/src/test/java/jdocs/pattern/BackoffSupervisorDocTest.java @@ -8,41 +8,43 @@ import akka.actor.*; import akka.pattern.Backoff; import akka.pattern.BackoffSupervisor; import akka.testkit.TestActors.EchoActor; -//#backoff-imports +// #backoff-imports import java.time.Duration; -//#backoff-imports +// #backoff-imports public class BackoffSupervisorDocTest { - void exampleStop (ActorSystem system) { - //#backoff-stop + void exampleStop(ActorSystem system) { + // #backoff-stop final Props childProps = Props.create(EchoActor.class); - final Props supervisorProps = BackoffSupervisor.props( - Backoff.onStop( - childProps, - "myEcho", - Duration.ofSeconds(3), - Duration.ofSeconds(30), - 0.2)); // adds 20% "noise" to vary the intervals slightly + final Props supervisorProps = + BackoffSupervisor.props( + Backoff.onStop( + childProps, + "myEcho", + Duration.ofSeconds(3), + Duration.ofSeconds(30), + 0.2)); // adds 20% "noise" to vary the intervals slightly system.actorOf(supervisorProps, "echoSupervisor"); - //#backoff-stop + // #backoff-stop } - void exampleFailure (ActorSystem system) { - //#backoff-fail + void exampleFailure(ActorSystem system) { + // #backoff-fail final Props childProps = Props.create(EchoActor.class); - final Props supervisorProps = BackoffSupervisor.props( - Backoff.onFailure( - childProps, - "myEcho", - Duration.ofSeconds(3), - Duration.ofSeconds(30), - 0.2)); // adds 20% "noise" to vary the intervals slightly + final Props supervisorProps = + BackoffSupervisor.props( + Backoff.onFailure( + childProps, + "myEcho", + Duration.ofSeconds(3), + Duration.ofSeconds(30), + 0.2)); // adds 20% "noise" to vary the intervals slightly system.actorOf(supervisorProps, "echoSupervisor"); - //#backoff-fail + // #backoff-fail } } diff --git a/akka-docs/src/test/java/jdocs/pattern/SupervisedAsk.java b/akka-docs/src/test/java/jdocs/pattern/SupervisedAsk.java index 89f035f909..250298e17b 100644 --- a/akka-docs/src/test/java/jdocs/pattern/SupervisedAsk.java +++ b/akka-docs/src/test/java/jdocs/pattern/SupervisedAsk.java @@ -35,20 +35,20 @@ public class SupervisedAsk { } } - private static class AskTimeout { - } + private static class AskTimeout {} public static class AskSupervisorCreator extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(AskParam.class, message -> { - ActorRef supervisor = getContext().actorOf( - Props.create(AskSupervisor.class)); - supervisor.forward(message, getContext()); - }) - .build(); + .match( + AskParam.class, + message -> { + ActorRef supervisor = getContext().actorOf(Props.create(AskSupervisor.class)); + supervisor.forward(message, getContext()); + }) + .build(); } } @@ -60,49 +60,63 @@ public class SupervisedAsk { @Override public SupervisorStrategy supervisorStrategy() { - return new OneForOneStrategy(0, Duration.ZERO, cause -> { - caller.tell(new Status.Failure(cause), getSelf()); - return SupervisorStrategy.stop(); - }); + return new OneForOneStrategy( + 0, + Duration.ZERO, + cause -> { + caller.tell(new Status.Failure(cause), getSelf()); + return SupervisorStrategy.stop(); + }); } @Override public Receive createReceive() { return receiveBuilder() - .match(AskParam.class, message -> { - askParam = message; - caller = getSender(); - targetActor = getContext().actorOf(askParam.props); - getContext().watch(targetActor); - targetActor.forward(askParam.message, getContext()); - Scheduler scheduler = getContext().getSystem().scheduler(); - timeoutMessage = scheduler.scheduleOnce(askParam.timeout, - getSelf(), new AskTimeout(), getContext().getDispatcher(), null); - }) - .match(Terminated.class, message -> { - Throwable ex = new ActorKilledException("Target actor terminated."); - caller.tell(new Status.Failure(ex), getSelf()); - timeoutMessage.cancel(); - getContext().stop(getSelf()); - }) - .match(AskTimeout.class, message -> { - Throwable ex = new TimeoutException("Target actor timed out after " - + askParam.timeout.toString()); - caller.tell(new Status.Failure(ex), getSelf()); - getContext().stop(getSelf()); - }) - .build(); + .match( + AskParam.class, + message -> { + askParam = message; + caller = getSender(); + targetActor = getContext().actorOf(askParam.props); + getContext().watch(targetActor); + targetActor.forward(askParam.message, getContext()); + Scheduler scheduler = getContext().getSystem().scheduler(); + timeoutMessage = + scheduler.scheduleOnce( + askParam.timeout, + getSelf(), + new AskTimeout(), + getContext().getDispatcher(), + null); + }) + .match( + Terminated.class, + message -> { + Throwable ex = new ActorKilledException("Target actor terminated."); + caller.tell(new Status.Failure(ex), getSelf()); + timeoutMessage.cancel(); + getContext().stop(getSelf()); + }) + .match( + AskTimeout.class, + message -> { + Throwable ex = + new TimeoutException( + "Target actor timed out after " + askParam.timeout.toString()); + caller.tell(new Status.Failure(ex), getSelf()); + getContext().stop(getSelf()); + }) + .build(); } } - public static CompletionStage askOf(ActorRef supervisorCreator, Props props, - Object message, Duration timeout) { + public static CompletionStage askOf( + ActorRef supervisorCreator, Props props, Object message, Duration timeout) { AskParam param = new AskParam(props, message, timeout); return Patterns.ask(supervisorCreator, param, timeout); } - synchronized public static ActorRef createSupervisorCreator( - ActorRefFactory factory) { + public static synchronized ActorRef createSupervisorCreator(ActorRefFactory factory) { return factory.actorOf(Props.create(AskSupervisorCreator.class)); } } diff --git a/akka-docs/src/test/java/jdocs/pattern/SupervisedAskSpec.java b/akka-docs/src/test/java/jdocs/pattern/SupervisedAskSpec.java index 31ab5e95ba..d30083ceaa 100644 --- a/akka-docs/src/test/java/jdocs/pattern/SupervisedAskSpec.java +++ b/akka-docs/src/test/java/jdocs/pattern/SupervisedAskSpec.java @@ -17,15 +17,17 @@ import java.util.concurrent.TimeUnit; public class SupervisedAskSpec { - public Object execute(Class someActor, - Object message, Duration timeout, ActorRefFactory actorSystem) + public Object execute( + Class someActor, + Object message, + Duration timeout, + ActorRefFactory actorSystem) throws Exception { // example usage try { - ActorRef supervisorCreator = SupervisedAsk - .createSupervisorCreator(actorSystem); - CompletionStage finished = SupervisedAsk.askOf(supervisorCreator, - Props.create(someActor), message, timeout); + ActorRef supervisorCreator = SupervisedAsk.createSupervisorCreator(actorSystem); + CompletionStage finished = + SupervisedAsk.askOf(supervisorCreator, Props.create(someActor), message, timeout); return finished.toCompletableFuture().get(timeout.toMillis(), TimeUnit.MILLISECONDS); } catch (Exception e) { // exception propagated by supervision diff --git a/akka-docs/src/test/java/jdocs/persistence/LambdaPersistenceDocTest.java b/akka-docs/src/test/java/jdocs/persistence/LambdaPersistenceDocTest.java index 34823bb8a2..a2f01bf42e 100644 --- a/akka-docs/src/test/java/jdocs/persistence/LambdaPersistenceDocTest.java +++ b/akka-docs/src/test/java/jdocs/persistence/LambdaPersistenceDocTest.java @@ -18,625 +18,717 @@ public class LambdaPersistenceDocTest { public interface SomeOtherMessage {} public interface PersistentActorMethods { - //#persistence-id + // #persistence-id public String persistenceId(); - //#persistence-id - //#recovery-status + // #persistence-id + // #recovery-status public boolean recoveryRunning(); + public boolean recoveryFinished(); - //#recovery-status + // #recovery-status } - static Object o2 = new Object() { - abstract class MyPersistentActor1 extends AbstractPersistentActor { - //#recovery-disabled - @Override - public Recovery recovery() { - return Recovery.none(); - } - //#recovery-disabled + static Object o2 = + new Object() { + abstract class MyPersistentActor1 extends AbstractPersistentActor { + // #recovery-disabled + @Override + public Recovery recovery() { + return Recovery.none(); + } + // #recovery-disabled - //#recover-on-restart-disabled - @Override - public void preRestart(Throwable reason, Optional message) {} - //#recover-on-restart-disabled - } - - abstract class MyPersistentActor2 extends AbstractPersistentActor { - //#recovery-custom - @Override - public Recovery recovery() { - return Recovery.create(457L); - } - //#recovery-custom - } - - class MyPersistentActor4 extends AbstractPersistentActor implements PersistentActorMethods { - //#persistence-id-override - @Override - public String persistenceId() { - return "my-stable-persistence-id"; - } - - //#persistence-id-override - - @Override - public Receive createReceive() { - return receiveBuilder(). - match(String.class, cmd -> {/* ... */}).build(); - } - - @Override - public Receive createReceiveRecover() { - return receiveBuilder(). - match(String.class, evt -> {/* ... */}).build(); - } - - } - - //#recovery-completed - class MyPersistentActor5 extends AbstractPersistentActor { - - @Override public String persistenceId() { - return "my-stable-persistence-id"; - } - - @Override public Receive createReceiveRecover() { - return receiveBuilder(). - match(RecoveryCompleted.class, r -> { - // perform init after recovery, before any other messages - // ... - }). - match(String.class, this::handleEvent).build(); - } - - @Override public Receive createReceive() { - return receiveBuilder(). - match(String.class, s -> s.equals("cmd"), - s -> persist("evt", this::handleEvent)).build(); - } - - private void handleEvent(String event) { - // update state - // ... - } - - } - //#recovery-completed - - abstract class MyPersistentActor6 extends AbstractPersistentActor { - //#recovery-no-snap - @Override - public Recovery recovery() { - return Recovery.create(SnapshotSelectionCriteria.none()); - } - //#recovery-no-snap - } - - abstract class MyActor extends AbstractPersistentActor { - //#backoff - @Override - public void preStart() throws Exception { - final Props childProps = Props.create(MyPersistentActor1.class); - final Props props = BackoffSupervisor.props( - childProps, - "myActor", - Duration.ofSeconds(3), - Duration.ofSeconds(30), - 0.2); - getContext().actorOf(props, "mySupervisor"); - super.preStart(); - } - //#backoff - } - }; - - static Object atLeastOnceExample = new Object() { - //#at-least-once-example - - class Msg implements Serializable { - private static final long serialVersionUID = 1L; - public final long deliveryId; - public final String s; - - public Msg(long deliveryId, String s) { - this.deliveryId = deliveryId; - this.s = s; - } - } - - class Confirm implements Serializable { - private static final long serialVersionUID = 1L; - public final long deliveryId; - - public Confirm(long deliveryId) { - this.deliveryId = deliveryId; - } - } - - - class MsgSent implements Serializable { - private static final long serialVersionUID = 1L; - public final String s; - - public MsgSent(String s) { - this.s = s; - } - } - class MsgConfirmed implements Serializable { - private static final long serialVersionUID = 1L; - public final long deliveryId; - - public MsgConfirmed(long deliveryId) { - this.deliveryId = deliveryId; - } - } - - class MyPersistentActor extends AbstractPersistentActorWithAtLeastOnceDelivery { - private final ActorSelection destination; - - public MyPersistentActor(ActorSelection destination) { - this.destination = destination; + // #recover-on-restart-disabled + @Override + public void preRestart(Throwable reason, Optional message) {} + // #recover-on-restart-disabled } - @Override public String persistenceId() { - return "persistence-id"; + abstract class MyPersistentActor2 extends AbstractPersistentActor { + // #recovery-custom + @Override + public Recovery recovery() { + return Recovery.create(457L); + } + // #recovery-custom } - @Override - public Receive createReceive() { - return receiveBuilder(). - match(String.class, s -> { - persist(new MsgSent(s), evt -> updateState(evt)); - }). - match(Confirm.class, confirm -> { - persist(new MsgConfirmed(confirm.deliveryId), evt -> updateState(evt)); - }). - build(); - } + class MyPersistentActor4 extends AbstractPersistentActor implements PersistentActorMethods { + // #persistence-id-override + @Override + public String persistenceId() { + return "my-stable-persistence-id"; + } - @Override - public Receive createReceiveRecover() { - return receiveBuilder(). - match(Object.class, evt -> updateState(evt)).build(); - } + // #persistence-id-override - void updateState(Object event) { - if (event instanceof MsgSent) { - final MsgSent evt = (MsgSent) event; - deliver(destination, deliveryId -> new Msg(deliveryId, evt.s)); - } else if (event instanceof MsgConfirmed) { - final MsgConfirmed evt = (MsgConfirmed) event; - confirmDelivery(evt.deliveryId); + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + String.class, + cmd -> { + /* ... */ + }) + .build(); + } + + @Override + public Receive createReceiveRecover() { + return receiveBuilder() + .match( + String.class, + evt -> { + /* ... */ + }) + .build(); } } - } - class MyDestination extends AbstractActor { - @Override - public Receive createReceive() { - return receiveBuilder() - .match(Msg.class, msg -> { - // ... - getSender().tell(new Confirm(msg.deliveryId), getSelf()); - }) - .build(); + // #recovery-completed + class MyPersistentActor5 extends AbstractPersistentActor { + + @Override + public String persistenceId() { + return "my-stable-persistence-id"; + } + + @Override + public Receive createReceiveRecover() { + return receiveBuilder() + .match( + RecoveryCompleted.class, + r -> { + // perform init after recovery, before any other messages + // ... + }) + .match(String.class, this::handleEvent) + .build(); + } + + @Override + public Receive createReceive() { + return receiveBuilder() + .match(String.class, s -> s.equals("cmd"), s -> persist("evt", this::handleEvent)) + .build(); + } + + private void handleEvent(String event) { + // update state + // ... + } } - } - //#at-least-once-example - - }; - - static Object o4 = new Object() { - class MyPersistentActor extends AbstractPersistentActor { - - private void updateState(String evt){} - - //#save-snapshot - private Object state; - private int snapShotInterval = 1000; - - @Override public Receive createReceive() { - return receiveBuilder(). - match(SaveSnapshotSuccess.class, ss -> { - SnapshotMetadata metadata = ss.metadata(); - // ... - }). - match(SaveSnapshotFailure.class, sf -> { - SnapshotMetadata metadata = sf.metadata(); - // ... - }). - match(String.class, cmd -> { - persist( "evt-" + cmd, e -> { - updateState(e); - if (lastSequenceNr() % snapShotInterval == 0 && lastSequenceNr() != 0) - saveSnapshot(state); - }); - }).build(); - } - //#save-snapshot - - @Override public String persistenceId() { - return "persistence-id"; - } - - @Override public Receive createReceiveRecover() { - return receiveBuilder(). - match(RecoveryCompleted.class, r -> {/* ...*/}).build(); - } - - } - }; - - static Object o5 = new Object() { - - class MyPersistentActor extends AbstractPersistentActor { - - //#snapshot-criteria - @Override - public Recovery recovery() { - return Recovery.create( - SnapshotSelectionCriteria - .create(457L, System.currentTimeMillis())); - } - //#snapshot-criteria - - //#snapshot-offer - private Object state; - - @Override public Receive createReceiveRecover() { - return receiveBuilder(). - match(SnapshotOffer.class, s -> { - state = s.snapshot(); - // ... - }). - match(String.class, s -> {/* ...*/}).build(); - } - //#snapshot-offer - - @Override public String persistenceId() { - return "persistence-id"; - } - - @Override public Receive createReceive() { - return receiveBuilder(). - match(String.class, s -> {/* ...*/}).build(); - } - } - - - class MyActor extends AbstractActor { - private final ActorRef persistentActor = - getContext().actorOf(Props.create(MyPersistentActor.class)); - - @Override - public Receive createReceive() { - return receiveBuilder() - .match(Object.class, o -> {/* ... */}) - .build(); - } - } - }; - - static Object o9 = new Object() { - //#persist-async - class MyPersistentActor extends AbstractPersistentActor { - - @Override public String persistenceId() { - return "my-stable-persistence-id"; - } - - private void handleCommand(String c) { - getSender().tell(c, getSelf()); - - persistAsync(String.format("evt-%s-1", c), e -> { - getSender().tell(e, getSelf()); - }); - persistAsync(String.format("evt-%s-2", c), e -> { - getSender().tell(e, getSelf()); - }); - } - - @Override public Receive createReceiveRecover() { - return receiveBuilder(). - match(String.class, this::handleCommand).build(); - } - - @Override public Receive createReceive() { - return receiveBuilder(). - match(String.class, this::handleCommand).build(); - } - } - //#persist-async - - public void usage() { - final ActorSystem system = ActorSystem.create("example"); - //#persist-async-usage - final ActorRef persistentActor = system.actorOf(Props.create(MyPersistentActor.class)); - persistentActor.tell("a", null); - persistentActor.tell("b", null); - - // possible order of received messages: - // a - // b - // evt-a-1 - // evt-a-2 - // evt-b-1 - // evt-b-2 - //#persist-async-usage - } - }; - - - static Object o10 = new Object() { - //#defer - class MyPersistentActor extends AbstractPersistentActor { - - @Override public String persistenceId() { - return "my-stable-persistence-id"; - } - - private void handleCommand(String c) { - persistAsync(String.format("evt-%s-1", c), e -> { - getSender().tell(e, getSelf()); - }); - persistAsync(String.format("evt-%s-2", c), e -> { - getSender().tell(e, getSelf()); - }); - - deferAsync(String.format("evt-%s-3", c), e -> { - getSender().tell(e, getSelf()); - }); - } - - @Override public Receive createReceiveRecover() { - return receiveBuilder(). - match(String.class, this::handleCommand).build(); - } - - @Override public Receive createReceive() { - return receiveBuilder(). - match(String.class, this::handleCommand).build(); - } - } - //#defer - - public void usage() { - final ActorSystem system = ActorSystem.create("example"); - final ActorRef sender = null; // your imaginary sender here - //#defer-caller - final ActorRef persistentActor = system.actorOf(Props.create(MyPersistentActor.class)); - persistentActor.tell("a", sender); - persistentActor.tell("b", sender); - - // order of received messages: - // a - // b - // evt-a-1 - // evt-a-2 - // evt-a-3 - // evt-b-1 - // evt-b-2 - // evt-b-3 - //#defer-caller - } - }; - - static Object o100 = new Object() { - //#defer-with-persist - class MyPersistentActor extends AbstractPersistentActor { - - @Override public String persistenceId() { - return "my-stable-persistence-id"; - } - - private void handleCommand(String c) { - persist(String.format("evt-%s-1", c), e -> { - sender().tell(e, self()); - }); - persist(String.format("evt-%s-2", c), e -> { - sender().tell(e, self()); - }); - - defer(String.format("evt-%s-3", c), e -> { - sender().tell(e, self()); - }); - } - - @Override public Receive createReceiveRecover() { - return receiveBuilder(). - match(String.class, this::handleCommand).build(); - } - - @Override public Receive createReceive() { - return receiveBuilder(). - match(String.class, this::handleCommand).build(); - } - } - //#defer-with-persist - - }; - - static Object o11 = new Object() { - - class MyPersistentActor extends AbstractPersistentActor { - @Override - public String persistenceId() { - return "my-stable-persistence-id"; - } - - @Override public Receive createReceive() { - return receiveBuilder().matchAny(event -> {}).build(); - } - - //#nested-persist-persist - @Override public Receive createReceiveRecover() { - final Procedure replyToSender = event -> getSender().tell(event, getSelf()); - - return receiveBuilder() - .match(String.class, msg -> { - persist(String.format("%s-outer-1", msg), event -> { - getSender().tell(event, getSelf()); - persist(String.format("%s-inner-1", event), replyToSender); - }); - - persist(String.format("%s-outer-2", msg), event -> { - getSender().tell(event, getSelf()); - persist(String.format("%s-inner-2", event), replyToSender); - }); - }) - .build(); - } - //#nested-persist-persist - - void usage(ActorRef persistentActor) { - //#nested-persist-persist-caller - persistentActor.tell("a", ActorRef.noSender()); - persistentActor.tell("b", ActorRef.noSender()); - - // order of received messages: - // a - // a-outer-1 - // a-outer-2 - // a-inner-1 - // a-inner-2 - // and only then process "b" - // b - // b-outer-1 - // b-outer-2 - // b-inner-1 - // b-inner-2 - - //#nested-persist-persist-caller - } - } - - - class MyPersistAsyncActor extends AbstractPersistentActor { - @Override - public String persistenceId() { - return "my-stable-persistence-id"; - } - - @Override - public Receive createReceiveRecover() { - return receiveBuilder().matchAny(event -> {}).build(); - } - - //#nested-persistAsync-persistAsync - @Override - public Receive createReceive() { - final Procedure replyToSender = event -> getSender().tell(event, getSelf()); - - return receiveBuilder() - .match(String.class, msg -> { - persistAsync(String.format("%s-outer-1", msg ), event -> { - getSender().tell(event, getSelf()); - persistAsync(String.format("%s-inner-1", event), replyToSender); - }); - - persistAsync(String.format("%s-outer-2", msg ), event -> { - getSender().tell(event, getSelf()); - persistAsync(String.format("%s-inner-1", event), replyToSender); - }); - }) - .build(); - } - //#nested-persistAsync-persistAsync - - void usage(ActorRef persistentActor) { - //#nested-persistAsync-persistAsync-caller - persistentActor.tell("a", getSelf()); - persistentActor.tell("b", getSelf()); - - // order of received messages: - // a - // b - // a-outer-1 - // a-outer-2 - // b-outer-1 - // b-outer-2 - // a-inner-1 - // a-inner-2 - // b-inner-1 - // b-inner-2 - - // which can be seen as the following causal relationship: - // a -> a-outer-1 -> a-outer-2 -> a-inner-1 -> a-inner-2 - // b -> b-outer-1 -> b-outer-2 -> b-inner-1 -> b-inner-2 - - //#nested-persistAsync-persistAsync-caller - } - } - }; - - static Object o14 = new Object() { - //#safe-shutdown - final class Shutdown { - } - - class MyPersistentActor extends AbstractPersistentActor { - @Override - public String persistenceId() { - return "some-persistence-id"; - } - - @Override - public Receive createReceive() { - return receiveBuilder() - .match(Shutdown.class, shutdown -> { - getContext().stop(getSelf()); - }) - .match(String.class, msg -> { - System.out.println(msg); - persist("handle-" + msg, e -> System.out.println(e)); - }) - .build(); - } - - @Override - public Receive createReceiveRecover() { - return receiveBuilder().matchAny(any -> {}).build(); - } - - } - //#safe-shutdown - - - public void usage() { - final ActorSystem system = ActorSystem.create("example"); - final ActorRef persistentActor = system.actorOf(Props.create(MyPersistentActor.class)); - //#safe-shutdown-example-bad - // UN-SAFE, due to PersistentActor's command stashing: - persistentActor.tell("a", ActorRef.noSender()); - persistentActor.tell("b", ActorRef.noSender()); - persistentActor.tell(PoisonPill.getInstance(), ActorRef.noSender()); - // order of received messages: - // a - // # b arrives at mailbox, stashing; internal-stash = [b] - // # PoisonPill arrives at mailbox, stashing; internal-stash = [b, Shutdown] - // PoisonPill is an AutoReceivedMessage, is handled automatically - // !! stop !! - // Actor is stopped without handling `b` nor the `a` handler! - //#safe-shutdown-example-bad - - //#safe-shutdown-example-good - // SAFE: - persistentActor.tell("a", ActorRef.noSender()); - persistentActor.tell("b", ActorRef.noSender()); - persistentActor.tell(new Shutdown(), ActorRef.noSender()); - // order of received messages: - // a - // # b arrives at mailbox, stashing; internal-stash = [b] - // # Shutdown arrives at mailbox, stashing; internal-stash = [b, Shutdown] - // handle-a - // # unstashing; internal-stash = [Shutdown] - // b - // handle-b - // # unstashing; internal-stash = [] - // Shutdown - // -- stop -- - //#safe-shutdown-example-good - } - }; + // #recovery-completed + + abstract class MyPersistentActor6 extends AbstractPersistentActor { + // #recovery-no-snap + @Override + public Recovery recovery() { + return Recovery.create(SnapshotSelectionCriteria.none()); + } + // #recovery-no-snap + } + + abstract class MyActor extends AbstractPersistentActor { + // #backoff + @Override + public void preStart() throws Exception { + final Props childProps = Props.create(MyPersistentActor1.class); + final Props props = + BackoffSupervisor.props( + childProps, "myActor", Duration.ofSeconds(3), Duration.ofSeconds(30), 0.2); + getContext().actorOf(props, "mySupervisor"); + super.preStart(); + } + // #backoff + } + }; + + static Object atLeastOnceExample = + new Object() { + // #at-least-once-example + + class Msg implements Serializable { + private static final long serialVersionUID = 1L; + public final long deliveryId; + public final String s; + + public Msg(long deliveryId, String s) { + this.deliveryId = deliveryId; + this.s = s; + } + } + + class Confirm implements Serializable { + private static final long serialVersionUID = 1L; + public final long deliveryId; + + public Confirm(long deliveryId) { + this.deliveryId = deliveryId; + } + } + + class MsgSent implements Serializable { + private static final long serialVersionUID = 1L; + public final String s; + + public MsgSent(String s) { + this.s = s; + } + } + + class MsgConfirmed implements Serializable { + private static final long serialVersionUID = 1L; + public final long deliveryId; + + public MsgConfirmed(long deliveryId) { + this.deliveryId = deliveryId; + } + } + + class MyPersistentActor extends AbstractPersistentActorWithAtLeastOnceDelivery { + private final ActorSelection destination; + + public MyPersistentActor(ActorSelection destination) { + this.destination = destination; + } + + @Override + public String persistenceId() { + return "persistence-id"; + } + + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + String.class, + s -> { + persist(new MsgSent(s), evt -> updateState(evt)); + }) + .match( + Confirm.class, + confirm -> { + persist(new MsgConfirmed(confirm.deliveryId), evt -> updateState(evt)); + }) + .build(); + } + + @Override + public Receive createReceiveRecover() { + return receiveBuilder().match(Object.class, evt -> updateState(evt)).build(); + } + + void updateState(Object event) { + if (event instanceof MsgSent) { + final MsgSent evt = (MsgSent) event; + deliver(destination, deliveryId -> new Msg(deliveryId, evt.s)); + } else if (event instanceof MsgConfirmed) { + final MsgConfirmed evt = (MsgConfirmed) event; + confirmDelivery(evt.deliveryId); + } + } + } + + class MyDestination extends AbstractActor { + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + Msg.class, + msg -> { + // ... + getSender().tell(new Confirm(msg.deliveryId), getSelf()); + }) + .build(); + } + } + // #at-least-once-example + + }; + + static Object o4 = + new Object() { + class MyPersistentActor extends AbstractPersistentActor { + + private void updateState(String evt) {} + + // #save-snapshot + private Object state; + private int snapShotInterval = 1000; + + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + SaveSnapshotSuccess.class, + ss -> { + SnapshotMetadata metadata = ss.metadata(); + // ... + }) + .match( + SaveSnapshotFailure.class, + sf -> { + SnapshotMetadata metadata = sf.metadata(); + // ... + }) + .match( + String.class, + cmd -> { + persist( + "evt-" + cmd, + e -> { + updateState(e); + if (lastSequenceNr() % snapShotInterval == 0 && lastSequenceNr() != 0) + saveSnapshot(state); + }); + }) + .build(); + } + // #save-snapshot + + @Override + public String persistenceId() { + return "persistence-id"; + } + + @Override + public Receive createReceiveRecover() { + return receiveBuilder() + .match( + RecoveryCompleted.class, + r -> { + /* ...*/ + }) + .build(); + } + } + }; + + static Object o5 = + new Object() { + + class MyPersistentActor extends AbstractPersistentActor { + + // #snapshot-criteria + @Override + public Recovery recovery() { + return Recovery.create( + SnapshotSelectionCriteria.create(457L, System.currentTimeMillis())); + } + // #snapshot-criteria + + // #snapshot-offer + private Object state; + + @Override + public Receive createReceiveRecover() { + return receiveBuilder() + .match( + SnapshotOffer.class, + s -> { + state = s.snapshot(); + // ... + }) + .match( + String.class, + s -> { + /* ...*/ + }) + .build(); + } + // #snapshot-offer + + @Override + public String persistenceId() { + return "persistence-id"; + } + + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + String.class, + s -> { + /* ...*/ + }) + .build(); + } + } + + class MyActor extends AbstractActor { + private final ActorRef persistentActor = + getContext().actorOf(Props.create(MyPersistentActor.class)); + + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + Object.class, + o -> { + /* ... */ + }) + .build(); + } + } + }; + + static Object o9 = + new Object() { + // #persist-async + class MyPersistentActor extends AbstractPersistentActor { + + @Override + public String persistenceId() { + return "my-stable-persistence-id"; + } + + private void handleCommand(String c) { + getSender().tell(c, getSelf()); + + persistAsync( + String.format("evt-%s-1", c), + e -> { + getSender().tell(e, getSelf()); + }); + persistAsync( + String.format("evt-%s-2", c), + e -> { + getSender().tell(e, getSelf()); + }); + } + + @Override + public Receive createReceiveRecover() { + return receiveBuilder().match(String.class, this::handleCommand).build(); + } + + @Override + public Receive createReceive() { + return receiveBuilder().match(String.class, this::handleCommand).build(); + } + } + // #persist-async + + public void usage() { + final ActorSystem system = ActorSystem.create("example"); + // #persist-async-usage + final ActorRef persistentActor = system.actorOf(Props.create(MyPersistentActor.class)); + persistentActor.tell("a", null); + persistentActor.tell("b", null); + + // possible order of received messages: + // a + // b + // evt-a-1 + // evt-a-2 + // evt-b-1 + // evt-b-2 + // #persist-async-usage + } + }; + + static Object o10 = + new Object() { + // #defer + class MyPersistentActor extends AbstractPersistentActor { + + @Override + public String persistenceId() { + return "my-stable-persistence-id"; + } + + private void handleCommand(String c) { + persistAsync( + String.format("evt-%s-1", c), + e -> { + getSender().tell(e, getSelf()); + }); + persistAsync( + String.format("evt-%s-2", c), + e -> { + getSender().tell(e, getSelf()); + }); + + deferAsync( + String.format("evt-%s-3", c), + e -> { + getSender().tell(e, getSelf()); + }); + } + + @Override + public Receive createReceiveRecover() { + return receiveBuilder().match(String.class, this::handleCommand).build(); + } + + @Override + public Receive createReceive() { + return receiveBuilder().match(String.class, this::handleCommand).build(); + } + } + // #defer + + public void usage() { + final ActorSystem system = ActorSystem.create("example"); + final ActorRef sender = null; // your imaginary sender here + // #defer-caller + final ActorRef persistentActor = system.actorOf(Props.create(MyPersistentActor.class)); + persistentActor.tell("a", sender); + persistentActor.tell("b", sender); + + // order of received messages: + // a + // b + // evt-a-1 + // evt-a-2 + // evt-a-3 + // evt-b-1 + // evt-b-2 + // evt-b-3 + // #defer-caller + } + }; + + static Object o100 = + new Object() { + // #defer-with-persist + class MyPersistentActor extends AbstractPersistentActor { + + @Override + public String persistenceId() { + return "my-stable-persistence-id"; + } + + private void handleCommand(String c) { + persist( + String.format("evt-%s-1", c), + e -> { + sender().tell(e, self()); + }); + persist( + String.format("evt-%s-2", c), + e -> { + sender().tell(e, self()); + }); + + defer( + String.format("evt-%s-3", c), + e -> { + sender().tell(e, self()); + }); + } + + @Override + public Receive createReceiveRecover() { + return receiveBuilder().match(String.class, this::handleCommand).build(); + } + + @Override + public Receive createReceive() { + return receiveBuilder().match(String.class, this::handleCommand).build(); + } + } + // #defer-with-persist + + }; + + static Object o11 = + new Object() { + + class MyPersistentActor extends AbstractPersistentActor { + @Override + public String persistenceId() { + return "my-stable-persistence-id"; + } + + @Override + public Receive createReceive() { + return receiveBuilder().matchAny(event -> {}).build(); + } + + // #nested-persist-persist + @Override + public Receive createReceiveRecover() { + final Procedure replyToSender = event -> getSender().tell(event, getSelf()); + + return receiveBuilder() + .match( + String.class, + msg -> { + persist( + String.format("%s-outer-1", msg), + event -> { + getSender().tell(event, getSelf()); + persist(String.format("%s-inner-1", event), replyToSender); + }); + + persist( + String.format("%s-outer-2", msg), + event -> { + getSender().tell(event, getSelf()); + persist(String.format("%s-inner-2", event), replyToSender); + }); + }) + .build(); + } + // #nested-persist-persist + + void usage(ActorRef persistentActor) { + // #nested-persist-persist-caller + persistentActor.tell("a", ActorRef.noSender()); + persistentActor.tell("b", ActorRef.noSender()); + + // order of received messages: + // a + // a-outer-1 + // a-outer-2 + // a-inner-1 + // a-inner-2 + // and only then process "b" + // b + // b-outer-1 + // b-outer-2 + // b-inner-1 + // b-inner-2 + + // #nested-persist-persist-caller + } + } + + class MyPersistAsyncActor extends AbstractPersistentActor { + @Override + public String persistenceId() { + return "my-stable-persistence-id"; + } + + @Override + public Receive createReceiveRecover() { + return receiveBuilder().matchAny(event -> {}).build(); + } + + // #nested-persistAsync-persistAsync + @Override + public Receive createReceive() { + final Procedure replyToSender = event -> getSender().tell(event, getSelf()); + + return receiveBuilder() + .match( + String.class, + msg -> { + persistAsync( + String.format("%s-outer-1", msg), + event -> { + getSender().tell(event, getSelf()); + persistAsync(String.format("%s-inner-1", event), replyToSender); + }); + + persistAsync( + String.format("%s-outer-2", msg), + event -> { + getSender().tell(event, getSelf()); + persistAsync(String.format("%s-inner-1", event), replyToSender); + }); + }) + .build(); + } + // #nested-persistAsync-persistAsync + + void usage(ActorRef persistentActor) { + // #nested-persistAsync-persistAsync-caller + persistentActor.tell("a", getSelf()); + persistentActor.tell("b", getSelf()); + + // order of received messages: + // a + // b + // a-outer-1 + // a-outer-2 + // b-outer-1 + // b-outer-2 + // a-inner-1 + // a-inner-2 + // b-inner-1 + // b-inner-2 + + // which can be seen as the following causal relationship: + // a -> a-outer-1 -> a-outer-2 -> a-inner-1 -> a-inner-2 + // b -> b-outer-1 -> b-outer-2 -> b-inner-1 -> b-inner-2 + + // #nested-persistAsync-persistAsync-caller + } + } + }; + + static Object o14 = + new Object() { + // #safe-shutdown + final class Shutdown {} + + class MyPersistentActor extends AbstractPersistentActor { + @Override + public String persistenceId() { + return "some-persistence-id"; + } + + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + Shutdown.class, + shutdown -> { + getContext().stop(getSelf()); + }) + .match( + String.class, + msg -> { + System.out.println(msg); + persist("handle-" + msg, e -> System.out.println(e)); + }) + .build(); + } + + @Override + public Receive createReceiveRecover() { + return receiveBuilder().matchAny(any -> {}).build(); + } + } + // #safe-shutdown + + public void usage() { + final ActorSystem system = ActorSystem.create("example"); + final ActorRef persistentActor = system.actorOf(Props.create(MyPersistentActor.class)); + // #safe-shutdown-example-bad + // UN-SAFE, due to PersistentActor's command stashing: + persistentActor.tell("a", ActorRef.noSender()); + persistentActor.tell("b", ActorRef.noSender()); + persistentActor.tell(PoisonPill.getInstance(), ActorRef.noSender()); + // order of received messages: + // a + // # b arrives at mailbox, stashing; internal-stash = [b] + // # PoisonPill arrives at mailbox, stashing; internal-stash = [b, Shutdown] + // PoisonPill is an AutoReceivedMessage, is handled automatically + // !! stop !! + // Actor is stopped without handling `b` nor the `a` handler! + // #safe-shutdown-example-bad + + // #safe-shutdown-example-good + // SAFE: + persistentActor.tell("a", ActorRef.noSender()); + persistentActor.tell("b", ActorRef.noSender()); + persistentActor.tell(new Shutdown(), ActorRef.noSender()); + // order of received messages: + // a + // # b arrives at mailbox, stashing; internal-stash = [b] + // # Shutdown arrives at mailbox, stashing; internal-stash = [b, Shutdown] + // handle-a + // # unstashing; internal-stash = [Shutdown] + // b + // handle-b + // # unstashing; internal-stash = [] + // Shutdown + // -- stop -- + // #safe-shutdown-example-good + } + }; } diff --git a/akka-docs/src/test/java/jdocs/persistence/LambdaPersistencePluginDocTest.java b/akka-docs/src/test/java/jdocs/persistence/LambdaPersistencePluginDocTest.java index 4d6f64563c..83d6ce3fcb 100644 --- a/akka-docs/src/test/java/jdocs/persistence/LambdaPersistencePluginDocTest.java +++ b/akka-docs/src/test/java/jdocs/persistence/LambdaPersistencePluginDocTest.java @@ -4,12 +4,12 @@ package jdocs.persistence; -//#plugin-imports +// #plugin-imports import akka.dispatch.Futures; import akka.persistence.*; import akka.persistence.journal.japi.*; import akka.persistence.snapshot.japi.*; -//#plugin-imports +// #plugin-imports import akka.actor.*; import akka.persistence.journal.leveldb.SharedLeveldbJournal; @@ -28,47 +28,49 @@ import java.util.Optional; import akka.persistence.japi.journal.JavaJournalSpec; import akka.persistence.japi.snapshot.JavaSnapshotStoreSpec; - public class LambdaPersistencePluginDocTest { + static Object o1 = + new Object() { + final ActorSystem system = null; + // #shared-store-creation + final ActorRef store = system.actorOf(Props.create(SharedLeveldbStore.class), "store"); + // #shared-store-creation - static Object o1 = new Object() { - final ActorSystem system = null; - //#shared-store-creation - final ActorRef store = system.actorOf(Props.create(SharedLeveldbStore.class), "store"); - //#shared-store-creation + // #shared-store-usage + class SharedStorageUsage extends AbstractActor { + @Override + public void preStart() throws Exception { + String path = "akka.tcp://example@127.0.0.1:2552/user/store"; + ActorSelection selection = getContext().actorSelection(path); + selection.tell(new Identify(1), getSelf()); + } - //#shared-store-usage - class SharedStorageUsage extends AbstractActor { - @Override - public void preStart() throws Exception { - String path = "akka.tcp://example@127.0.0.1:2552/user/store"; - ActorSelection selection = getContext().actorSelection(path); - selection.tell(new Identify(1), getSelf()); - } - - @Override - public Receive createReceive() { - return receiveBuilder() - .match(ActorIdentity.class, ai -> { - if (ai.correlationId().equals(1)) { - Optional store = ai.getActorRef(); - if (store.isPresent()) { - SharedLeveldbJournal.setStore(store.get(), getContext().getSystem()); - } else { - throw new RuntimeException("Couldn't identify store"); - } - } - }) - .build(); - } - } - //#shared-store-usage - }; + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + ActorIdentity.class, + ai -> { + if (ai.correlationId().equals(1)) { + Optional store = ai.getActorRef(); + if (store.isPresent()) { + SharedLeveldbJournal.setStore(store.get(), getContext().getSystem()); + } else { + throw new RuntimeException("Couldn't identify store"); + } + } + }) + .build(); + } + } + // #shared-store-usage + }; class MySnapshotStore extends SnapshotStore { @Override - public Future> doLoadAsync(String persistenceId, SnapshotSelectionCriteria criteria) { + public Future> doLoadAsync( + String persistenceId, SnapshotSelectionCriteria criteria) { return null; } @@ -89,7 +91,7 @@ public class LambdaPersistencePluginDocTest { } class MyAsyncJournal extends AsyncWriteJournal { - //#sync-journal-plugin-api + // #sync-journal-plugin-api @Override public Future>> doAsyncWriteMessages( Iterable messages) { @@ -102,7 +104,7 @@ public class LambdaPersistencePluginDocTest { return Futures.failed(e); } } - //#sync-journal-plugin-api + // #sync-journal-plugin-api @Override public Future doAsyncDeleteMessagesTo(String persistenceId, long toSequenceNr) { @@ -110,10 +112,12 @@ public class LambdaPersistencePluginDocTest { } @Override - public Future doAsyncReplayMessages(String persistenceId, long fromSequenceNr, - long toSequenceNr, - long max, - Consumer replayCallback) { + public Future doAsyncReplayMessages( + String persistenceId, + long fromSequenceNr, + long toSequenceNr, + long max, + Consumer replayCallback) { return null; } @@ -122,79 +126,83 @@ public class LambdaPersistencePluginDocTest { return null; } } - - static Object o2 = new Object() { - //#journal-tck-java - class MyJournalSpecTest extends JavaJournalSpec { - public MyJournalSpecTest() { - super(ConfigFactory.parseString( - "persistence.journal.plugin = " + - "\"akka.persistence.journal.leveldb-shared\"")); - } + static Object o2 = + new Object() { + // #journal-tck-java + class MyJournalSpecTest extends JavaJournalSpec { - @Override - public CapabilityFlag supportsRejectingNonSerializableObjects() { - return CapabilityFlag.off(); - } - } - //#journal-tck-java - }; + public MyJournalSpecTest() { + super( + ConfigFactory.parseString( + "persistence.journal.plugin = " + + "\"akka.persistence.journal.leveldb-shared\"")); + } - static Object o3 = new Object() { - //#snapshot-store-tck-java - class MySnapshotStoreTest extends JavaSnapshotStoreSpec { - - public MySnapshotStoreTest() { - super(ConfigFactory.parseString( - "akka.persistence.snapshot-store.plugin = " + - "\"akka.persistence.snapshot-store.local\"")); - } - } - //#snapshot-store-tck-java - }; - - static Object o4 = new Object() { - //#journal-tck-before-after-java - class MyJournalSpecTest extends JavaJournalSpec { - - List storageLocations = new ArrayList(); - - public MyJournalSpecTest() { - super(ConfigFactory.parseString( - "persistence.journal.plugin = " + - "\"akka.persistence.journal.leveldb-shared\"")); - - Config config = system().settings().config(); - storageLocations.add(new File( - config.getString("akka.persistence.journal.leveldb.dir"))); - storageLocations.add(new File( - config.getString("akka.persistence.snapshot-store.local.dir"))); - } - - - @Override - public CapabilityFlag supportsRejectingNonSerializableObjects() { - return CapabilityFlag.on(); - } - - @Override - public void beforeAll() { - for (File storageLocation : storageLocations) { - FileUtils.deleteRecursively(storageLocation); + @Override + public CapabilityFlag supportsRejectingNonSerializableObjects() { + return CapabilityFlag.off(); + } } - super.beforeAll(); - } + // #journal-tck-java + }; - @Override - public void afterAll() { - super.afterAll(); - for (File storageLocation : storageLocations) { - FileUtils.deleteRecursively(storageLocation); + static Object o3 = + new Object() { + // #snapshot-store-tck-java + class MySnapshotStoreTest extends JavaSnapshotStoreSpec { + + public MySnapshotStoreTest() { + super( + ConfigFactory.parseString( + "akka.persistence.snapshot-store.plugin = " + + "\"akka.persistence.snapshot-store.local\"")); + } } - } - } - //#journal-tck-before-after-java - }; + // #snapshot-store-tck-java + }; + static Object o4 = + new Object() { + // #journal-tck-before-after-java + class MyJournalSpecTest extends JavaJournalSpec { + + List storageLocations = new ArrayList(); + + public MyJournalSpecTest() { + super( + ConfigFactory.parseString( + "persistence.journal.plugin = " + + "\"akka.persistence.journal.leveldb-shared\"")); + + Config config = system().settings().config(); + storageLocations.add( + new File(config.getString("akka.persistence.journal.leveldb.dir"))); + storageLocations.add( + new File(config.getString("akka.persistence.snapshot-store.local.dir"))); + } + + @Override + public CapabilityFlag supportsRejectingNonSerializableObjects() { + return CapabilityFlag.on(); + } + + @Override + public void beforeAll() { + for (File storageLocation : storageLocations) { + FileUtils.deleteRecursively(storageLocation); + } + super.beforeAll(); + } + + @Override + public void afterAll() { + super.afterAll(); + for (File storageLocation : storageLocations) { + FileUtils.deleteRecursively(storageLocation); + } + } + } + // #journal-tck-before-after-java + }; } diff --git a/akka-docs/src/test/java/jdocs/persistence/PersistenceEventAdapterDocTest.java b/akka-docs/src/test/java/jdocs/persistence/PersistenceEventAdapterDocTest.java index 30c96bca1c..43b5bac236 100644 --- a/akka-docs/src/test/java/jdocs/persistence/PersistenceEventAdapterDocTest.java +++ b/akka-docs/src/test/java/jdocs/persistence/PersistenceEventAdapterDocTest.java @@ -11,7 +11,7 @@ public class PersistenceEventAdapterDocTest { @SuppressWarnings("unused") static - //#identity-event-adapter + // #identity-event-adapter class MyEventAdapter implements EventAdapter { @Override public String manifest(Object event) { @@ -28,5 +28,5 @@ public class PersistenceEventAdapterDocTest { return EventSeq.single(event); // identity } } - //#identity-event-adapter + // #identity-event-adapter } diff --git a/akka-docs/src/test/java/jdocs/persistence/PersistenceMultiDocTest.java b/akka-docs/src/test/java/jdocs/persistence/PersistenceMultiDocTest.java index ea9aa09f13..711eedf022 100644 --- a/akka-docs/src/test/java/jdocs/persistence/PersistenceMultiDocTest.java +++ b/akka-docs/src/test/java/jdocs/persistence/PersistenceMultiDocTest.java @@ -12,77 +12,91 @@ import com.typesafe.config.ConfigFactory; public class PersistenceMultiDocTest { - //#default-plugins - abstract class AbstractPersistentActorWithDefaultPlugins extends AbstractPersistentActor { - @Override - public String persistenceId() { - return "123"; - } + // #default-plugins + abstract class AbstractPersistentActorWithDefaultPlugins extends AbstractPersistentActor { + @Override + public String persistenceId() { + return "123"; } - //#default-plugins + } + // #default-plugins - //#override-plugins - abstract class AbstractPersistentActorWithOverridePlugins extends AbstractPersistentActor { - @Override - public String persistenceId() { - return "123"; - } - - // Absolute path to the journal plugin configuration entry in the `reference.conf` - @Override - public String journalPluginId() { - return "akka.persistence.chronicle.journal"; - } - - // Absolute path to the snapshot store plugin configuration entry in the `reference.conf` - @Override - public String snapshotPluginId() { - return "akka.persistence.chronicle.snapshot-store"; - } + // #override-plugins + abstract class AbstractPersistentActorWithOverridePlugins extends AbstractPersistentActor { + @Override + public String persistenceId() { + return "123"; } - //#override-plugins - - //#runtime-config - abstract class AbstractPersistentActorWithRuntimePluginConfig extends AbstractPersistentActor implements RuntimePluginConfig { - // Variable that is retrieved at runtime, from an external service for instance. - String runtimeDistinction = "foo"; - - @Override - public String persistenceId() { - return "123"; - } - - // Absolute path to the journal plugin configuration entry in the `reference.conf` - @Override - public String journalPluginId() { - return "journal-plugin-" + runtimeDistinction; - } - - // Absolute path to the snapshot store plugin configuration entry in the `reference.conf` - @Override - public String snapshotPluginId() { - return "snapshot-store-plugin-" + runtimeDistinction; - } - - // Configuration which contains the journal plugin id defined above - @Override - public Config journalPluginConfig() { - return ConfigFactory.empty().withValue( - "journal-plugin-" + runtimeDistinction, - getContext().getSystem().settings().config().getValue("journal-plugin") // or a very different configuration coming from an external service. - ); - } - - // Configuration which contains the snapshot store plugin id defined above - @Override - public Config snapshotPluginConfig() { - return ConfigFactory.empty().withValue( - "snapshot-plugin-" + runtimeDistinction, - getContext().getSystem().settings().config().getValue("snapshot-store-plugin") // or a very different configuration coming from an external service. - ); - } + // Absolute path to the journal plugin configuration entry in the `reference.conf` + @Override + public String journalPluginId() { + return "akka.persistence.chronicle.journal"; } - //#runtime-config + + // Absolute path to the snapshot store plugin configuration entry in the `reference.conf` + @Override + public String snapshotPluginId() { + return "akka.persistence.chronicle.snapshot-store"; + } + } + // #override-plugins + + // #runtime-config + abstract class AbstractPersistentActorWithRuntimePluginConfig extends AbstractPersistentActor + implements RuntimePluginConfig { + // Variable that is retrieved at runtime, from an external service for instance. + String runtimeDistinction = "foo"; + + @Override + public String persistenceId() { + return "123"; + } + + // Absolute path to the journal plugin configuration entry in the `reference.conf` + @Override + public String journalPluginId() { + return "journal-plugin-" + runtimeDistinction; + } + + // Absolute path to the snapshot store plugin configuration entry in the `reference.conf` + @Override + public String snapshotPluginId() { + return "snapshot-store-plugin-" + runtimeDistinction; + } + + // Configuration which contains the journal plugin id defined above + @Override + public Config journalPluginConfig() { + return ConfigFactory.empty() + .withValue( + "journal-plugin-" + runtimeDistinction, + getContext() + .getSystem() + .settings() + .config() + .getValue( + "journal-plugin") // or a very different configuration coming from an external + // service. + ); + } + + // Configuration which contains the snapshot store plugin id defined above + @Override + public Config snapshotPluginConfig() { + return ConfigFactory.empty() + .withValue( + "snapshot-plugin-" + runtimeDistinction, + getContext() + .getSystem() + .settings() + .config() + .getValue( + "snapshot-store-plugin") // or a very different configuration coming from an + // external service. + ); + } + } + // #runtime-config } diff --git a/akka-docs/src/test/java/jdocs/persistence/PersistenceQueryDocTest.java b/akka-docs/src/test/java/jdocs/persistence/PersistenceQueryDocTest.java index 22ac8d1d58..de7ee04357 100644 --- a/akka-docs/src/test/java/jdocs/persistence/PersistenceQueryDocTest.java +++ b/akka-docs/src/test/java/jdocs/persistence/PersistenceQueryDocTest.java @@ -35,10 +35,10 @@ public class PersistenceQueryDocTest { final ActorSystem system = ActorSystem.create(); final ActorMaterializer mat = ActorMaterializer.create(system); - static - //#advanced-journal-query-types - public class RichEvent { - public final Settags; + public + // #advanced-journal-query-types + static class RichEvent { + public final Set tags; public final Object payload; public RichEvent(Set tags, Object payload) { @@ -46,12 +46,12 @@ public class PersistenceQueryDocTest { this.payload = payload; } } - //#advanced-journal-query-types + // #advanced-journal-query-types - static - //#advanced-journal-query-types + public + // #advanced-journal-query-types // a plugin can provide: - public final class QueryMetadata{ + static final class QueryMetadata { public final boolean deterministicOrder; public final boolean infinite; @@ -60,11 +60,11 @@ public class PersistenceQueryDocTest { this.infinite = infinite; } } - //#advanced-journal-query-types + // #advanced-journal-query-types - static - //#my-read-journal - public class MyReadJournalProvider implements ReadJournalProvider { + public + // #my-read-journal + static class MyReadJournalProvider implements ReadJournalProvider { private final MyJavadslReadJournal javadslReadJournal; public MyReadJournalProvider(ExtendedActorSystem system, Config config) { @@ -81,52 +81,54 @@ public class PersistenceQueryDocTest { return this.javadslReadJournal; } } - //#my-read-journal + // #my-read-journal - static - //#my-read-journal - public class MyJavadslReadJournal implements - akka.persistence.query.javadsl.ReadJournal, - akka.persistence.query.javadsl.EventsByTagQuery, - akka.persistence.query.javadsl.EventsByPersistenceIdQuery, - akka.persistence.query.javadsl.PersistenceIdsQuery, - akka.persistence.query.javadsl.CurrentPersistenceIdsQuery { + public + // #my-read-journal + static class MyJavadslReadJournal + implements akka.persistence.query.javadsl.ReadJournal, + akka.persistence.query.javadsl.EventsByTagQuery, + akka.persistence.query.javadsl.EventsByPersistenceIdQuery, + akka.persistence.query.javadsl.PersistenceIdsQuery, + akka.persistence.query.javadsl.CurrentPersistenceIdsQuery { private final FiniteDuration refreshInterval; public MyJavadslReadJournal(ExtendedActorSystem system, Config config) { refreshInterval = - FiniteDuration.create(config.getDuration("refresh-interval", - TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); + FiniteDuration.create( + config.getDuration("refresh-interval", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS); } /** * You can use `NoOffset` to retrieve all events with a given tag or retrieve a subset of all - * events by specifying a `Sequence` `offset`. The `offset` corresponds to an ordered sequence number for - * the specific tag. Note that the corresponding offset of each event is provided in the - * [[akka.persistence.query.EventEnvelope]], which makes it possible to resume the - * stream at a later point from a given offset. + * events by specifying a `Sequence` `offset`. The `offset` corresponds to an ordered sequence + * number for the specific tag. Note that the corresponding offset of each event is provided in + * the [[akka.persistence.query.EventEnvelope]], which makes it possible to resume the stream at + * a later point from a given offset. * - * The `offset` is exclusive, i.e. the event with the exact same sequence number will not be included - * in the returned stream. This means that you can use the offset that is returned in `EventEnvelope` - * as the `offset` parameter in a subsequent query. + *

The `offset` is exclusive, i.e. the event with the exact same sequence number will not be + * included in the returned stream. This means that you can use the offset that is returned in + * `EventEnvelope` as the `offset` parameter in a subsequent query. */ @Override public Source eventsByTag(String tag, Offset offset) { - if(offset instanceof Sequence){ + if (offset instanceof Sequence) { Sequence sequenceOffset = (Sequence) offset; - final Props props = MyEventsByTagPublisher.props(tag, sequenceOffset.value(), refreshInterval); - return Source.actorPublisher(props). - mapMaterializedValue(m -> NotUsed.getInstance()); + final Props props = + MyEventsByTagPublisher.props(tag, sequenceOffset.value(), refreshInterval); + return Source.actorPublisher(props) + .mapMaterializedValue(m -> NotUsed.getInstance()); } else if (offset == NoOffset.getInstance()) - return eventsByTag(tag, Offset.sequence(0L)); //recursive + return eventsByTag(tag, Offset.sequence(0L)); // recursive else - throw new IllegalArgumentException("MyJavadslReadJournal does not support " + offset.getClass().getName() + " offsets"); + throw new IllegalArgumentException( + "MyJavadslReadJournal does not support " + offset.getClass().getName() + " offsets"); } @Override - public Source eventsByPersistenceId(String persistenceId, - long fromSequenceNr, long toSequenceNr) { + public Source eventsByPersistenceId( + String persistenceId, long fromSequenceNr, long toSequenceNr) { // implement in a similar way as eventsByTag throw new UnsupportedOperationException("Not implemented yet"); } @@ -145,24 +147,23 @@ public class PersistenceQueryDocTest { // possibility to add more plugin specific queries - //#advanced-journal-query-definition + // #advanced-journal-query-definition public Source byTagsWithMeta(Set tags) { - //#advanced-journal-query-definition + // #advanced-journal-query-definition // implement in a similar way as eventsByTag throw new UnsupportedOperationException("Not implemented yet"); } - } - //#my-read-journal + // #my-read-journal - static - //#my-read-journal - public class MyScaladslReadJournal implements - akka.persistence.query.scaladsl.ReadJournal, - akka.persistence.query.scaladsl.EventsByTagQuery, - akka.persistence.query.scaladsl.EventsByPersistenceIdQuery, - akka.persistence.query.scaladsl.PersistenceIdsQuery, - akka.persistence.query.scaladsl.CurrentPersistenceIdsQuery { + public + // #my-read-journal + static class MyScaladslReadJournal + implements akka.persistence.query.scaladsl.ReadJournal, + akka.persistence.query.scaladsl.EventsByTagQuery, + akka.persistence.query.scaladsl.EventsByPersistenceIdQuery, + akka.persistence.query.scaladsl.PersistenceIdsQuery, + akka.persistence.query.scaladsl.CurrentPersistenceIdsQuery { private final MyJavadslReadJournal javadslReadJournal; @@ -179,8 +180,9 @@ public class PersistenceQueryDocTest { @Override public akka.stream.scaladsl.Source eventsByPersistenceId( String persistenceId, long fromSequenceNr, long toSequenceNr) { - return javadslReadJournal.eventsByPersistenceId(persistenceId, fromSequenceNr, - toSequenceNr).asScala(); + return javadslReadJournal + .eventsByPersistenceId(persistenceId, fromSequenceNr, toSequenceNr) + .asScala(); } @Override @@ -200,61 +202,64 @@ public class PersistenceQueryDocTest { Set jTags = scala.collection.JavaConverters.setAsJavaSetConverter(tags).asJava(); return javadslReadJournal.byTagsWithMeta(jTags).asScala(); } - } - //#my-read-journal + // #my-read-journal void demonstrateBasicUsage() { final ActorSystem system = ActorSystem.create(); - //#basic-usage + // #basic-usage // obtain read journal by plugin id final MyJavadslReadJournal readJournal = - PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class, - "akka.persistence.query.my-read-journal"); + PersistenceQuery.get(system) + .getReadJournalFor( + MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal"); // issue query to journal Source source = - readJournal.eventsByPersistenceId("user-1337", 0, Long.MAX_VALUE); + readJournal.eventsByPersistenceId("user-1337", 0, Long.MAX_VALUE); // materialize stream, consuming events ActorMaterializer mat = ActorMaterializer.create(system); source.runForeach(event -> System.out.println("Event: " + event), mat); - //#basic-usage + // #basic-usage } void demonstrateAllPersistenceIdsLive() { final MyJavadslReadJournal readJournal = - PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class, - "akka.persistence.query.my-read-journal"); + PersistenceQuery.get(system) + .getReadJournalFor( + MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal"); - //#all-persistence-ids-live + // #all-persistence-ids-live readJournal.persistenceIds(); - //#all-persistence-ids-live + // #all-persistence-ids-live } void demonstrateNoRefresh() { final ActorSystem system = ActorSystem.create(); final MyJavadslReadJournal readJournal = - PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class, - "akka.persistence.query.my-read-journal"); + PersistenceQuery.get(system) + .getReadJournalFor( + MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal"); - //#all-persistence-ids-snap + // #all-persistence-ids-snap readJournal.currentPersistenceIds(); - //#all-persistence-ids-snap + // #all-persistence-ids-snap } void demonstrateRefresh() { final ActorSystem system = ActorSystem.create(); final MyJavadslReadJournal readJournal = - PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class, - "akka.persistence.query.my-read-journal"); + PersistenceQuery.get(system) + .getReadJournalFor( + MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal"); - //#events-by-persistent-id + // #events-by-persistent-id readJournal.eventsByPersistenceId("user-us-1337", 0L, Long.MAX_VALUE); - //#events-by-persistent-id + // #events-by-persistent-id } void demonstrateEventsByTag() { @@ -262,58 +267,71 @@ public class PersistenceQueryDocTest { final ActorMaterializer mat = ActorMaterializer.create(system); final MyJavadslReadJournal readJournal = - PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class, - "akka.persistence.query.my-read-journal"); + PersistenceQuery.get(system) + .getReadJournalFor( + MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal"); - //#events-by-tag + // #events-by-tag // assuming journal is able to work with numeric offsets we can: final Source blueThings = - readJournal.eventsByTag("blue", new Sequence(0L)); + readJournal.eventsByTag("blue", new Sequence(0L)); // find top 10 blue things: final CompletionStage> top10BlueThings = - blueThings - .map(EventEnvelope::event) - .take(10) // cancels the query stream after pulling 10 elements - .runFold(new ArrayList<>(10), (acc, e) -> { - acc.add(e); - return acc; - }, mat); + blueThings + .map(EventEnvelope::event) + .take(10) // cancels the query stream after pulling 10 elements + .runFold( + new ArrayList<>(10), + (acc, e) -> { + acc.add(e); + return acc; + }, + mat); // start another query, from the known offset Source blue = readJournal.eventsByTag("blue", new Sequence(10)); - //#events-by-tag + // #events-by-tag } - void demonstrateMaterializedQueryValues() { final ActorSystem system = ActorSystem.create(); final ActorMaterializer mat = ActorMaterializer.create(system); final MyJavadslReadJournal readJournal = - PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class, - "akka.persistence.query.my-read-journal"); + PersistenceQuery.get(system) + .getReadJournalFor( + MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal"); - //#advanced-journal-query-usage + // #advanced-journal-query-usage Set tags = new HashSet(); tags.add("red"); tags.add("blue"); - final Source events = readJournal.byTagsWithMeta(tags) - .mapMaterializedValue(meta -> { - System.out.println("The query is: " + - "ordered deterministically: " + meta.deterministicOrder + " " + - "infinite: " + meta.infinite); - return meta; - }); + final Source events = + readJournal + .byTagsWithMeta(tags) + .mapMaterializedValue( + meta -> { + System.out.println( + "The query is: " + + "ordered deterministically: " + + meta.deterministicOrder + + " " + + "infinite: " + + meta.infinite); + return meta; + }); - events.map(event -> { - System.out.println("Event payload: " + event.payload); - return event.payload; - }).runWith(Sink.ignore(), mat); + events + .map( + event -> { + System.out.println("Event payload: " + event.payload); + return event.payload; + }) + .runWith(Sink.ignore(), mat); - - //#advanced-journal-query-usage + // #advanced-journal-query-usage } class ReactiveStreamsCompatibleDBDriver { @@ -327,54 +345,54 @@ public class PersistenceQueryDocTest { final ActorMaterializer mat = ActorMaterializer.create(system); final MyJavadslReadJournal readJournal = - PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class, - "akka.persistence.query.my-read-journal"); + PersistenceQuery.get(system) + .getReadJournalFor( + MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal"); - - //#projection-into-different-store-rs + // #projection-into-different-store-rs final ReactiveStreamsCompatibleDBDriver driver = new ReactiveStreamsCompatibleDBDriver(); final Subscriber> dbBatchWriter = driver.batchWriter(); // Using an example (Reactive Streams) Database driver readJournal - .eventsByPersistenceId("user-1337", 0L, Long.MAX_VALUE) - .map(envelope -> envelope.event()) - .grouped(20) // batch inserts into groups of 20 - .runWith(Sink.fromSubscriber(dbBatchWriter), mat); // write batches to read-side database - //#projection-into-different-store-rs + .eventsByPersistenceId("user-1337", 0L, Long.MAX_VALUE) + .map(envelope -> envelope.event()) + .grouped(20) // batch inserts into groups of 20 + .runWith(Sink.fromSubscriber(dbBatchWriter), mat); // write batches to read-side database + // #projection-into-different-store-rs } - //#projection-into-different-store-simple-classes + // #projection-into-different-store-simple-classes class ExampleStore { CompletionStage save(Object any) { // ... - //#projection-into-different-store-simple-classes + // #projection-into-different-store-simple-classes return null; - //#projection-into-different-store-simple-classes + // #projection-into-different-store-simple-classes } } - //#projection-into-different-store-simple-classes + // #projection-into-different-store-simple-classes void demonstrateWritingIntoDifferentStoreWithMapAsync() { final ActorSystem system = ActorSystem.create(); final ActorMaterializer mat = ActorMaterializer.create(system); final MyJavadslReadJournal readJournal = - PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class, - "akka.persistence.query.my-read-journal"); + PersistenceQuery.get(system) + .getReadJournalFor( + MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal"); - - //#projection-into-different-store-simple + // #projection-into-different-store-simple final ExampleStore store = new ExampleStore(); readJournal - .eventsByTag("bid", new Sequence(0L)) - .mapAsync(1, store::save) - .runWith(Sink.ignore(), mat); - //#projection-into-different-store-simple + .eventsByTag("bid", new Sequence(0L)) + .mapAsync(1, store::save) + .runWith(Sink.ignore(), mat); + // #projection-into-different-store-simple } - //#projection-into-different-store + // #projection-into-different-store class MyResumableProjection { private final String name; @@ -384,30 +402,30 @@ public class PersistenceQueryDocTest { public CompletionStage saveProgress(Offset offset) { // ... - //#projection-into-different-store + // #projection-into-different-store return null; - //#projection-into-different-store + // #projection-into-different-store } + public CompletionStage latestOffset() { // ... - //#projection-into-different-store + // #projection-into-different-store return null; - //#projection-into-different-store + // #projection-into-different-store } } - //#projection-into-different-store - + // #projection-into-different-store void demonstrateWritingIntoDifferentStoreWithResumableProjections() throws Exception { final ActorSystem system = ActorSystem.create(); final ActorMaterializer mat = ActorMaterializer.create(system); final MyJavadslReadJournal readJournal = - PersistenceQuery.get(system).getReadJournalFor(MyJavadslReadJournal.class, - "akka.persistence.query.my-read-journal"); + PersistenceQuery.get(system) + .getReadJournalFor( + MyJavadslReadJournal.class, "akka.persistence.query.my-read-journal"); - - //#projection-into-different-store-actor-run + // #projection-into-different-store-actor-run final Duration timeout = Duration.ofSeconds(3); final MyResumableProjection bidProjection = new MyResumableProjection("bid"); @@ -415,19 +433,22 @@ public class PersistenceQueryDocTest { final Props writerProps = Props.create(TheOneWhoWritesToQueryJournal.class, "bid"); final ActorRef writer = system.actorOf(writerProps, "bid-projection-writer"); - long startFromOffset = bidProjection.latestOffset().toCompletableFuture().get(3, TimeUnit.SECONDS); + long startFromOffset = + bidProjection.latestOffset().toCompletableFuture().get(3, TimeUnit.SECONDS); readJournal - .eventsByTag("bid", new Sequence(startFromOffset)) - .mapAsync(8, envelope -> { - final CompletionStage f = ask(writer, envelope.event(), timeout); - return f.thenApplyAsync(in -> envelope.offset(), system.dispatcher()); - }) - .mapAsync(1, offset -> bidProjection.saveProgress(offset)) - .runWith(Sink.ignore(), mat); + .eventsByTag("bid", new Sequence(startFromOffset)) + .mapAsync( + 8, + envelope -> { + final CompletionStage f = ask(writer, envelope.event(), timeout); + return f.thenApplyAsync(in -> envelope.offset(), system.dispatcher()); + }) + .mapAsync(1, offset -> bidProjection.saveProgress(offset)) + .runWith(Sink.ignore(), mat); } - //#projection-into-different-store-actor-run + // #projection-into-different-store-actor-run class ComplexState { @@ -442,7 +463,7 @@ public class PersistenceQueryDocTest { } } - //#projection-into-different-store-actor + // #projection-into-different-store-actor final class TheOneWhoWritesToQueryJournal extends AbstractActor { private final ExampleStore store; @@ -455,23 +476,21 @@ public class PersistenceQueryDocTest { @Override public Receive createReceive() { return receiveBuilder() - .matchAny(message -> { - state = updateState(state, message); + .matchAny( + message -> { + state = updateState(state, message); - // example saving logic that requires state to become ready: - if (state.readyToSave()) - store.save(Record.of(state)); - - }) - .build(); + // example saving logic that requires state to become ready: + if (state.readyToSave()) store.save(Record.of(state)); + }) + .build(); } - ComplexState updateState(ComplexState state, Object msg) { // some complicated aggregation logic here ... return state; } } - //#projection-into-different-store-actor + // #projection-into-different-store-actor } diff --git a/akka-docs/src/test/java/jdocs/persistence/PersistenceSchemaEvolutionDocTest.java b/akka-docs/src/test/java/jdocs/persistence/PersistenceSchemaEvolutionDocTest.java index 81fb4b34b5..e15eeb9d55 100644 --- a/akka-docs/src/test/java/jdocs/persistence/PersistenceSchemaEvolutionDocTest.java +++ b/akka-docs/src/test/java/jdocs/persistence/PersistenceSchemaEvolutionDocTest.java @@ -18,84 +18,88 @@ import akka.serialization.SerializerWithStringManifest; public class PersistenceSchemaEvolutionDocTest { - static - //#protobuf-read-optional-model - public enum SeatType { - Window("W"), Aisle("A"), Other("O"), Unknown(""); - + public + // #protobuf-read-optional-model + static enum SeatType { + Window("W"), + Aisle("A"), + Other("O"), + Unknown(""); + private final String code; - + private SeatType(String code) { this.code = code; } - + public static SeatType fromCode(String c) { - if (Window.code.equals(c)) - return Window; - else if (Aisle.code.equals(c)) - return Aisle; - else if (Other.code.equals(c)) - return Other; - else - return Unknown; + if (Window.code.equals(c)) return Window; + else if (Aisle.code.equals(c)) return Aisle; + else if (Other.code.equals(c)) return Other; + else return Unknown; } } - //#protobuf-read-optional-model - - static - //#protobuf-read-optional-model - public class SeatReserved { + // #protobuf-read-optional-model + + public + // #protobuf-read-optional-model + static class SeatReserved { public final String letter; public final int row; public final SeatType seatType; - + public SeatReserved(String letter, int row, SeatType seatType) { this.letter = letter; this.row = row; this.seatType = seatType; } } - //#protobuf-read-optional-model - - static - //#protobuf-read-optional + // #protobuf-read-optional-model + + public + // #protobuf-read-optional /** - * Example serializer impl which uses protocol buffers generated classes (proto.*) - * to perform the to/from binary marshalling. + * Example serializer impl which uses protocol buffers generated classes (proto.*) to perform the + * to/from binary marshalling. */ - public class AddedFieldsSerializerWithProtobuf extends SerializerWithStringManifest { - @Override public int identifier() { + static class AddedFieldsSerializerWithProtobuf extends SerializerWithStringManifest { + @Override + public int identifier() { return 67876; } private final String seatReservedManifest = SeatReserved.class.getName(); - @Override public String manifest(Object o){ + @Override + public String manifest(Object o) { return o.getClass().getName(); } - @Override public Object fromBinary(byte[] bytes, String manifest) throws NotSerializableException{ + @Override + public Object fromBinary(byte[] bytes, String manifest) throws NotSerializableException { if (seatReservedManifest.equals(manifest)) { // use generated protobuf serializer try { return seatReserved(FlightAppModels.SeatReserved.parseFrom(bytes)); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException(e.getMessage()); - } + } } else { - throw new NotSerializableException("Unable to handle manifest: " + manifest); + throw new NotSerializableException("Unable to handle manifest: " + manifest); } } - @Override public byte[] toBinary(Object o) { + @Override + public byte[] toBinary(Object o) { if (o instanceof SeatReserved) { SeatReserved s = (SeatReserved) o; return FlightAppModels.SeatReserved.newBuilder() - .setRow(s.row) - .setLetter(s.letter) - .setSeatType(s.seatType.code) - .build().toByteArray(); - + .setRow(s.row) + .setLetter(s.letter) + .setSeatType(s.seatType.code) + .build() + .toByteArray(); + } else { throw new IllegalArgumentException("Unable to handle: " + o); } @@ -109,20 +113,16 @@ public class PersistenceSchemaEvolutionDocTest { // handle missing field by assigning "Unknown" value private SeatType seatType(FlightAppModels.SeatReserved p) { - if (p.hasSeatType()) - return SeatType.fromCode(p.getSeatType()); - else - return SeatType.Unknown; + if (p.hasSeatType()) return SeatType.fromCode(p.getSeatType()); + else return SeatType.Unknown; } - } - //#protobuf-read-optional - - + // #protobuf-read-optional + public static class RenamePlainJson { - static - //#rename-plain-json - public class JsonRenamedFieldAdapter implements EventAdapter { + public + // #rename-plain-json + static class JsonRenamedFieldAdapter implements EventAdapter { // use your favorite json library private final ExampleJsonMarshaller marshaller = new ExampleJsonMarshaller(); @@ -130,103 +130,109 @@ public class PersistenceSchemaEvolutionDocTest { private final String V2 = "v2"; // this could be done independently for each event type - @Override public String manifest(Object event) { + @Override + public String manifest(Object event) { return V2; } - @Override public JsObject toJournal(Object event) { + @Override + public JsObject toJournal(Object event) { return marshaller.toJson(event); } - @Override public EventSeq fromJournal(Object event, String manifest) { + @Override + public EventSeq fromJournal(Object event, String manifest) { if (event instanceof JsObject) { JsObject json = (JsObject) event; - if (V1.equals(manifest)) - json = rename(json, "code", "seatNr"); + if (V1.equals(manifest)) json = rename(json, "code", "seatNr"); return EventSeq.single(json); - } else { - throw new IllegalArgumentException("Can only work with JSON, was: " + - event.getClass().getName()); + } else { + throw new IllegalArgumentException( + "Can only work with JSON, was: " + event.getClass().getName()); } } private JsObject rename(JsObject json, String from, String to) { // use your favorite json library to rename the field - JsObject renamed = json; + JsObject renamed = json; return renamed; } - } - //#rename-plain-json + // #rename-plain-json } - + public static class SimplestCustomSerializer { - static - //#simplest-custom-serializer-model - public class Person { + public + // #simplest-custom-serializer-model + static class Person { public final String name; public final String surname; + public Person(String name, String surname) { this.name = name; this.surname = surname; } } - //#simplest-custom-serializer-model + // #simplest-custom-serializer-model - static - //#simplest-custom-serializer + public + // #simplest-custom-serializer /** * Simplest possible serializer, uses a string representation of the Person class. * - * Usually a serializer like this would use a library like: - * protobuf, kryo, avro, cap'n proto, flatbuffers, SBE or some other dedicated serializer backend - * to perform the actual to/from bytes marshalling. + *

Usually a serializer like this would use a library like: protobuf, kryo, avro, cap'n + * proto, flatbuffers, SBE or some other dedicated serializer backend to perform the actual + * to/from bytes marshalling. */ - public class SimplestPossiblePersonSerializer extends SerializerWithStringManifest { + static class SimplestPossiblePersonSerializer extends SerializerWithStringManifest { private final Charset utf8 = Charset.forName("UTF-8"); private final String personManifest = Person.class.getName(); // unique identifier of the serializer - @Override public int identifier() { + @Override + public int identifier() { return 1234567; } // extract manifest to be stored together with serialized object - @Override public String manifest(Object o) { + @Override + public String manifest(Object o) { return o.getClass().getName(); } // serialize the object - @Override public byte[] toBinary(Object obj) { + @Override + public byte[] toBinary(Object obj) { if (obj instanceof Person) { Person p = (Person) obj; return (p.name + "|" + p.surname).getBytes(utf8); } else { - throw new IllegalArgumentException( - "Unable to serialize to bytes, clazz was: " + obj.getClass().getName()); + throw new IllegalArgumentException( + "Unable to serialize to bytes, clazz was: " + obj.getClass().getName()); } } // deserialize the object, using the manifest to indicate which logic to apply - @Override public Object fromBinary(byte[] bytes, String manifest) throws NotSerializableException { + @Override + public Object fromBinary(byte[] bytes, String manifest) throws NotSerializableException { if (personManifest.equals(manifest)) { String nameAndSurname = new String(bytes, utf8); String[] parts = nameAndSurname.split("[|]"); return new Person(parts[0], parts[1]); } else { throw new NotSerializableException( - "Unable to deserialize from bytes, manifest was: " + manifest + - "! Bytes length: " + bytes.length); + "Unable to deserialize from bytes, manifest was: " + + manifest + + "! Bytes length: " + + bytes.length); } } - } - //#simplest-custom-serializer + // #simplest-custom-serializer } - - + public static class SamplePayload { private final Object payload; @@ -239,78 +245,77 @@ public class PersistenceSchemaEvolutionDocTest { } } - //#split-events-during-recovery + // #split-events-during-recovery interface V1 {}; + interface V2 {} - - //#split-events-during-recovery - static - //#split-events-during-recovery + + // #split-events-during-recovery + public + // #split-events-during-recovery // V1 event: - public class UserDetailsChanged implements V1 { + static class UserDetailsChanged implements V1 { public final String name; public final String address; + public UserDetailsChanged(String name, String address) { this.name = name; this.address = address; } } - - //#split-events-during-recovery - static - //#split-events-during-recovery + + // #split-events-during-recovery + public + // #split-events-during-recovery // corresponding V2 events: - public class UserNameChanged implements V2 { + static class UserNameChanged implements V2 { public final String name; public UserNameChanged(String name) { this.name = name; } } - //#split-events-during-recovery - static - //#split-events-during-recovery - public class UserAddressChanged implements V2 { + // #split-events-during-recovery + public + // #split-events-during-recovery + static class UserAddressChanged implements V2 { public final String address; public UserAddressChanged(String address) { this.address = address; } } - - //#split-events-during-recovery - static - //#split-events-during-recovery + + // #split-events-during-recovery + public + // #split-events-during-recovery // event splitting adapter: - public class UserEventsAdapter implements EventAdapter { - @Override public String manifest(Object event) { + static class UserEventsAdapter implements EventAdapter { + @Override + public String manifest(Object event) { return ""; } - - @Override public EventSeq fromJournal(Object event, String manifest) { + + @Override + public EventSeq fromJournal(Object event, String manifest) { if (event instanceof UserDetailsChanged) { UserDetailsChanged c = (UserDetailsChanged) event; - if (c.name == null) - return EventSeq.single(new UserAddressChanged(c.address)); - else if (c.address == null) - return EventSeq.single(new UserNameChanged(c.name)); - else - return EventSeq.create( - new UserNameChanged(c.name), - new UserAddressChanged(c.address)); + if (c.name == null) return EventSeq.single(new UserAddressChanged(c.address)); + else if (c.address == null) return EventSeq.single(new UserNameChanged(c.name)); + else return EventSeq.create(new UserNameChanged(c.name), new UserAddressChanged(c.address)); } else { return EventSeq.single(event); } } - - @Override public Object toJournal(Object event) { + + @Override + public Object toJournal(Object event) { return event; } } - //#split-events-during-recovery - - - static public class CustomerBlinked { + // #split-events-during-recovery + + public static class CustomerBlinked { public final long customerId; public CustomerBlinked(long customerId) { @@ -318,92 +323,92 @@ public class PersistenceSchemaEvolutionDocTest { } } - static - //#string-serializer-skip-deleved-event-by-manifest - public class EventDeserializationSkipped { - public static EventDeserializationSkipped instance = - new EventDeserializationSkipped(); - - private EventDeserializationSkipped() { - } + public + // #string-serializer-skip-deleved-event-by-manifest + static class EventDeserializationSkipped { + public static EventDeserializationSkipped instance = new EventDeserializationSkipped(); + + private EventDeserializationSkipped() {} } - //#string-serializer-skip-deleved-event-by-manifest - static - //#string-serializer-skip-deleved-event-by-manifest - public class RemovedEventsAwareSerializer extends SerializerWithStringManifest { + // #string-serializer-skip-deleved-event-by-manifest + public + // #string-serializer-skip-deleved-event-by-manifest + static class RemovedEventsAwareSerializer extends SerializerWithStringManifest { private final Charset utf8 = Charset.forName("UTF-8"); private final String customerBlinkedManifest = "blinked"; // unique identifier of the serializer - @Override public int identifier() { + @Override + public int identifier() { return 8337; } // extract manifest to be stored together with serialized object - @Override public String manifest(Object o) { - if (o instanceof CustomerBlinked) - return customerBlinkedManifest; - else - return o.getClass().getName(); + @Override + public String manifest(Object o) { + if (o instanceof CustomerBlinked) return customerBlinkedManifest; + else return o.getClass().getName(); } - - @Override public byte[] toBinary(Object o) { + + @Override + public byte[] toBinary(Object o) { return o.toString().getBytes(utf8); // example serialization } - - @Override public Object fromBinary(byte[] bytes, String manifest) { - if (customerBlinkedManifest.equals(manifest)) - return EventDeserializationSkipped.instance; - else - return new String(bytes, utf8); + + @Override + public Object fromBinary(byte[] bytes, String manifest) { + if (customerBlinkedManifest.equals(manifest)) return EventDeserializationSkipped.instance; + else return new String(bytes, utf8); } } - //#string-serializer-skip-deleved-event-by-manifest + // #string-serializer-skip-deleved-event-by-manifest - static - //#string-serializer-skip-deleved-event-by-manifest-adapter - public class SkippedEventsAwareAdapter implements EventAdapter { - @Override public String manifest(Object event) { + public + // #string-serializer-skip-deleved-event-by-manifest-adapter + static class SkippedEventsAwareAdapter implements EventAdapter { + @Override + public String manifest(Object event) { return ""; } - - @Override public Object toJournal(Object event) { + + @Override + public Object toJournal(Object event) { return event; } - - @Override public EventSeq fromJournal(Object event, String manifest) { - if (event == EventDeserializationSkipped.instance) - return EventSeq.empty(); - else - return EventSeq.single(event); + + @Override + public EventSeq fromJournal(Object event, String manifest) { + if (event == EventDeserializationSkipped.instance) return EventSeq.empty(); + else return EventSeq.single(event); } } - //#string-serializer-skip-deleved-event-by-manifest-adapter - - - //#string-serializer-handle-rename - static - //#string-serializer-handle-rename - public class RenamedEventAwareSerializer extends SerializerWithStringManifest { + // #string-serializer-skip-deleved-event-by-manifest-adapter + + // #string-serializer-handle-rename + public + // #string-serializer-handle-rename + static class RenamedEventAwareSerializer extends SerializerWithStringManifest { private final Charset utf8 = Charset.forName("UTF-8"); // unique identifier of the serializer - @Override public int identifier() { + @Override + public int identifier() { return 8337; } - private final String oldPayloadClassName = + private final String oldPayloadClassName = "docs.persistence.OldPayload"; // class NOT available anymore - private final String myPayloadClassName = - SamplePayload.class.getName(); - + private final String myPayloadClassName = SamplePayload.class.getName(); + // extract manifest to be stored together with serialized object - @Override public String manifest(Object o) { + @Override + public String manifest(Object o) { return o.getClass().getName(); } - - @Override public byte[] toBinary(Object o) { + + @Override + public byte[] toBinary(Object o) { if (o instanceof SamplePayload) { SamplePayload s = (SamplePayload) o; return s.payload.toString().getBytes(utf8); @@ -413,78 +418,80 @@ public class PersistenceSchemaEvolutionDocTest { "Unable to serialize to bytes, clazz was: " + o.getClass().getName()); } } - - @Override public Object fromBinary(byte[] bytes, String manifest) throws NotSerializableException { - if (oldPayloadClassName.equals(manifest)) - return new SamplePayload(new String(bytes, utf8)); + + @Override + public Object fromBinary(byte[] bytes, String manifest) throws NotSerializableException { + if (oldPayloadClassName.equals(manifest)) return new SamplePayload(new String(bytes, utf8)); else if (myPayloadClassName.equals(manifest)) return new SamplePayload(new String(bytes, utf8)); else throw new NotSerializableException("unexpected manifest [" + manifest + "]"); } } - //#string-serializer-handle-rename - - static - //#detach-models + // #string-serializer-handle-rename + + public + // #detach-models // Domain model - highly optimised for domain language and maybe "fluent" usage - public class Customer { + static class Customer { public final String name; public Customer(String name) { this.name = name; } } - - //#detach-models - static - //#detach-models - public class Seat { + + // #detach-models + public + // #detach-models + static class Seat { public final String code; public Seat(String code) { this.code = code; } - + public SeatBooked bookFor(Customer customer) { return new SeatBooked(code, customer); } } - - //#detach-models - static - //#detach-models - public class SeatBooked { + + // #detach-models + public + // #detach-models + static class SeatBooked { public final String code; public final Customer customer; - + public SeatBooked(String code, Customer customer) { this.code = code; this.customer = customer; } } - - //#detach-models - static - //#detach-models + + // #detach-models + public + // #detach-models // Data model - highly optimised for schema evolution and persistence - public class SeatBookedData { + static class SeatBookedData { public final String code; public final String customerName; - + public SeatBookedData(String code, String customerName) { this.code = code; this.customerName = customerName; } } - //#detach-models - - //#detach-models-adapter + // #detach-models + + // #detach-models-adapter class DetachedModelsAdapter implements EventAdapter { - @Override public String manifest(Object event) { + @Override + public String manifest(Object event) { return ""; } - - @Override public Object toJournal(Object event) { + + @Override + public Object toJournal(Object event) { if (event instanceof SeatBooked) { SeatBooked s = (SeatBooked) event; return new SeatBookedData(s.code, s.customer.name); @@ -492,8 +499,9 @@ public class PersistenceSchemaEvolutionDocTest { throw new IllegalArgumentException("Unsupported: " + event.getClass()); } } - - @Override public EventSeq fromJournal(Object event, String manifest) { + + @Override + public EventSeq fromJournal(Object event, String manifest) { if (event instanceof SeatBookedData) { SeatBookedData d = (SeatBookedData) event; return EventSeq.single(new SeatBooked(d.code, new Customer(d.customerName))); @@ -502,35 +510,36 @@ public class PersistenceSchemaEvolutionDocTest { } } } - //#detach-models-adapter - - static - //#detach-models-adapter-json - public class JsonDataModelAdapter implements EventAdapter { + // #detach-models-adapter + + public + // #detach-models-adapter-json + static class JsonDataModelAdapter implements EventAdapter { // use your favorite json library - private final ExampleJsonMarshaller marshaller = - new ExampleJsonMarshaller(); - - @Override public String manifest(Object event) { + private final ExampleJsonMarshaller marshaller = new ExampleJsonMarshaller(); + + @Override + public String manifest(Object event) { return ""; } - - @Override public JsObject toJournal(Object event) { + + @Override + public JsObject toJournal(Object event) { return marshaller.toJson(event); } - @Override public EventSeq fromJournal(Object event, String manifest) { + @Override + public EventSeq fromJournal(Object event, String manifest) { if (event instanceof JsObject) { JsObject json = (JsObject) event; return EventSeq.single(marshaller.fromJson(json)); } else { throw new IllegalArgumentException( - "Unable to fromJournal a non-JSON object! Was: " + event.getClass()); + "Unable to fromJournal a non-JSON object! Was: " + event.getClass()); } } } - //#detach-models-adapter-json + // #detach-models-adapter-json } - diff --git a/akka-docs/src/test/java/jdocs/persistence/PersistentActorExample.java b/akka-docs/src/test/java/jdocs/persistence/PersistentActorExample.java index c984e735bf..b82d819000 100644 --- a/akka-docs/src/test/java/jdocs/persistence/PersistentActorExample.java +++ b/akka-docs/src/test/java/jdocs/persistence/PersistentActorExample.java @@ -4,7 +4,7 @@ package jdocs.persistence; -//#persistent-actor-example +// #persistent-actor-example import akka.actor.ActorRef; import akka.actor.ActorSystem; @@ -16,112 +16,119 @@ import java.io.Serializable; import java.util.ArrayList; class Cmd implements Serializable { - private static final long serialVersionUID = 1L; - private final String data; + private static final long serialVersionUID = 1L; + private final String data; - public Cmd(String data) { - this.data = data; - } + public Cmd(String data) { + this.data = data; + } - public String getData() { - return data; - } + public String getData() { + return data; + } } class Evt implements Serializable { - private static final long serialVersionUID = 1L; - private final String data; + private static final long serialVersionUID = 1L; + private final String data; - public Evt(String data) { - this.data = data; - } + public Evt(String data) { + this.data = data; + } - public String getData() { - return data; - } + public String getData() { + return data; + } } class ExampleState implements Serializable { - private static final long serialVersionUID = 1L; - private final ArrayList events; + private static final long serialVersionUID = 1L; + private final ArrayList events; - public ExampleState() { - this(new ArrayList<>()); - } + public ExampleState() { + this(new ArrayList<>()); + } - public ExampleState(ArrayList events) { - this.events = events; - } + public ExampleState(ArrayList events) { + this.events = events; + } - public ExampleState copy() { - return new ExampleState(new ArrayList<>(events)); - } + public ExampleState copy() { + return new ExampleState(new ArrayList<>(events)); + } - public void update(Evt evt) { - events.add(evt.getData()); - } + public void update(Evt evt) { + events.add(evt.getData()); + } - public int size() { - return events.size(); - } + public int size() { + return events.size(); + } - @Override - public String toString() { - return events.toString(); - } + @Override + public String toString() { + return events.toString(); + } } class ExamplePersistentActor extends AbstractPersistentActor { - private ExampleState state = new ExampleState(); - private int snapShotInterval = 1000; + private ExampleState state = new ExampleState(); + private int snapShotInterval = 1000; - public int getNumEvents() { - return state.size(); - } + public int getNumEvents() { + return state.size(); + } - @Override - public String persistenceId() { return "sample-id-1"; } + @Override + public String persistenceId() { + return "sample-id-1"; + } - @Override - public Receive createReceiveRecover() { - return receiveBuilder() - .match(Evt.class, state::update) - .match(SnapshotOffer.class, ss -> state = (ExampleState) ss.snapshot()) - .build(); - } + @Override + public Receive createReceiveRecover() { + return receiveBuilder() + .match(Evt.class, state::update) + .match(SnapshotOffer.class, ss -> state = (ExampleState) ss.snapshot()) + .build(); + } - @Override - public Receive createReceive() { - return receiveBuilder() - .match(Cmd.class, c -> { + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + Cmd.class, + c -> { final String data = c.getData(); final Evt evt = new Evt(data + "-" + getNumEvents()); - persist(evt, (Evt e) -> { - state.update(e); - getContext().getSystem().getEventStream().publish(e); - if (lastSequenceNr() % snapShotInterval == 0 && lastSequenceNr() != 0) + persist( + evt, + (Evt e) -> { + state.update(e); + getContext().getSystem().getEventStream().publish(e); + if (lastSequenceNr() % snapShotInterval == 0 && lastSequenceNr() != 0) // IMPORTANT: create a copy of snapshot because ExampleState is mutable saveSnapshot(state.copy()); - }); + }); }) - .matchEquals("print", s -> System.out.println(state)) - .build(); - } + .matchEquals("print", s -> System.out.println(state)) + .build(); + } } -//#persistent-actor-example +// #persistent-actor-example public class PersistentActorExample { - public static void main(String... args) throws Exception { - final ActorSystem system = ActorSystem.create("example"); - final ActorRef persistentActor = system.actorOf(Props.create(ExamplePersistentActor.class), "persistentActor-4-java8"); - persistentActor.tell(new Cmd("foo"), null); - persistentActor.tell(new Cmd("baz"), null); - persistentActor.tell(new Cmd("bar"), null); - persistentActor.tell(new Cmd("buzz"), null); - persistentActor.tell("print", null); + public static void main(String... args) throws Exception { + final ActorSystem system = ActorSystem.create("example"); + final ActorRef persistentActor = + system.actorOf(Props.create(ExamplePersistentActor.class), "persistentActor-4-java8"); + persistentActor.tell(new Cmd("foo"), null); + persistentActor.tell(new Cmd("baz"), null); + persistentActor.tell(new Cmd("bar"), null); + persistentActor.tell(new Cmd("buzz"), null); + persistentActor.tell("print", null); - Thread.sleep(10000); - system.terminate(); - } + Thread.sleep(10000); + system.terminate(); + } } diff --git a/akka-docs/src/test/java/jdocs/persistence/query/LeveldbPersistenceQueryDocTest.java b/akka-docs/src/test/java/jdocs/persistence/query/LeveldbPersistenceQueryDocTest.java index 8f13d4cda8..0d035a8b88 100644 --- a/akka-docs/src/test/java/jdocs/persistence/query/LeveldbPersistenceQueryDocTest.java +++ b/akka-docs/src/test/java/jdocs/persistence/query/LeveldbPersistenceQueryDocTest.java @@ -23,50 +23,49 @@ public class LeveldbPersistenceQueryDocTest { final ActorSystem system = ActorSystem.create(); public void demonstrateReadJournal() { - //#get-read-journal + // #get-read-journal final ActorMaterializer mat = ActorMaterializer.create(system); - + LeveldbReadJournal queries = - PersistenceQuery.get(system).getReadJournalFor(LeveldbReadJournal.class, - LeveldbReadJournal.Identifier()); - //#get-read-journal + PersistenceQuery.get(system) + .getReadJournalFor(LeveldbReadJournal.class, LeveldbReadJournal.Identifier()); + // #get-read-journal } - + public void demonstrateEventsByPersistenceId() { - //#EventsByPersistenceId + // #EventsByPersistenceId LeveldbReadJournal queries = - PersistenceQuery.get(system).getReadJournalFor(LeveldbReadJournal.class, - LeveldbReadJournal.Identifier()); - + PersistenceQuery.get(system) + .getReadJournalFor(LeveldbReadJournal.class, LeveldbReadJournal.Identifier()); + Source source = queries.eventsByPersistenceId("some-persistence-id", 0, Long.MAX_VALUE); - //#EventsByPersistenceId + // #EventsByPersistenceId } - + public void demonstrateAllPersistenceIds() { - //#AllPersistenceIds + // #AllPersistenceIds LeveldbReadJournal queries = - PersistenceQuery.get(system).getReadJournalFor(LeveldbReadJournal.class, - LeveldbReadJournal.Identifier()); - + PersistenceQuery.get(system) + .getReadJournalFor(LeveldbReadJournal.class, LeveldbReadJournal.Identifier()); + Source source = queries.persistenceIds(); - //#AllPersistenceIds + // #AllPersistenceIds } - + public void demonstrateEventsByTag() { - //#EventsByTag + // #EventsByTag LeveldbReadJournal queries = - PersistenceQuery.get(system).getReadJournalFor(LeveldbReadJournal.class, - LeveldbReadJournal.Identifier()); - - Source source = - queries.eventsByTag("green", new Sequence(0L)); - //#EventsByTag + PersistenceQuery.get(system) + .getReadJournalFor(LeveldbReadJournal.class, LeveldbReadJournal.Identifier()); + + Source source = queries.eventsByTag("green", new Sequence(0L)); + // #EventsByTag } - - static - //#tagger - public class MyTaggingEventAdapter implements WriteEventAdapter { + + public + // #tagger + static class MyTaggingEventAdapter implements WriteEventAdapter { @Override public Object toJournal(Object event) { @@ -76,19 +75,17 @@ public class LeveldbPersistenceQueryDocTest { if (s.contains("green")) tags.add("green"); if (s.contains("black")) tags.add("black"); if (s.contains("blue")) tags.add("blue"); - if (tags.isEmpty()) - return event; - else - return new Tagged(event, tags); + if (tags.isEmpty()) return event; + else return new Tagged(event, tags); } else { return event; } } - + @Override public String manifest(Object event) { return ""; } } - //#tagger + // #tagger } diff --git a/akka-docs/src/test/java/jdocs/persistence/query/MyEventsByTagJavaPublisher.java b/akka-docs/src/test/java/jdocs/persistence/query/MyEventsByTagJavaPublisher.java index e6fbf128b5..80ce7f558c 100644 --- a/akka-docs/src/test/java/jdocs/persistence/query/MyEventsByTagJavaPublisher.java +++ b/akka-docs/src/test/java/jdocs/persistence/query/MyEventsByTagJavaPublisher.java @@ -27,10 +27,9 @@ import java.time.Duration; import static java.util.stream.Collectors.toList; -//#events-by-tag-publisher +// #events-by-tag-publisher class MyEventsByTagJavaPublisher extends AbstractActorPublisher { - private final Serialization serialization = - SerializationExtension.get(getContext().getSystem()); + private final Serialization serialization = SerializationExtension.get(getContext().getSystem()); private final Connection connection; @@ -43,37 +42,44 @@ class MyEventsByTagJavaPublisher extends AbstractActorPublisher { private Cancellable continueTask; - public MyEventsByTagJavaPublisher(Connection connection, - String tag, - Long offset, - Duration refreshInterval) { + public MyEventsByTagJavaPublisher( + Connection connection, String tag, Long offset, Duration refreshInterval) { this.connection = connection; this.tag = tag; this.currentOffset = offset; final Scheduler scheduler = getContext().getSystem().scheduler(); - this.continueTask = scheduler - .schedule(refreshInterval, refreshInterval, getSelf(), CONTINUE, - getContext().getDispatcher(), getSelf()); + this.continueTask = + scheduler.schedule( + refreshInterval, + refreshInterval, + getSelf(), + CONTINUE, + getContext().getDispatcher(), + getSelf()); } @Override public Receive createReceive() { return receiveBuilder() - .matchEquals(CONTINUE, (in) -> { - query(); - deliverBuf(); - }) - .match(Cancel.class, (in) -> { - getContext().stop(getSelf()); - }) - .build(); + .matchEquals( + CONTINUE, + (in) -> { + query(); + deliverBuf(); + }) + .match( + Cancel.class, + (in) -> { + getContext().stop(getSelf()); + }) + .build(); } - public static Props props(Connection conn, String tag, Long offset, - Duration refreshInterval) { - return Props.create(MyEventsByTagJavaPublisher.class, () -> - new MyEventsByTagJavaPublisher(conn, tag, offset, refreshInterval)); + public static Props props(Connection conn, String tag, Long offset, Duration refreshInterval) { + return Props.create( + MyEventsByTagJavaPublisher.class, + () -> new MyEventsByTagJavaPublisher(conn, tag, offset, refreshInterval)); } @Override @@ -83,9 +89,10 @@ class MyEventsByTagJavaPublisher extends AbstractActorPublisher { private void query() { if (buf.isEmpty()) { - final String query = "SELECT id, persistent_repr " + - "FROM journal WHERE tag = ? AND id > ? " + - "ORDER BY id LIMIT ?"; + final String query = + "SELECT id, persistent_repr " + + "FROM journal WHERE tag = ? AND id > ? " + + "ORDER BY id LIMIT ?"; try (PreparedStatement s = connection.prepareStatement(query)) { s.setString(1, tag); @@ -94,32 +101,35 @@ class MyEventsByTagJavaPublisher extends AbstractActorPublisher { try (ResultSet rs = s.executeQuery()) { final List> res = new ArrayList<>(LIMIT); - while (rs.next()) - res.add(Pair.create(rs.getLong(1), rs.getBytes(2))); + while (rs.next()) res.add(Pair.create(rs.getLong(1), rs.getBytes(2))); if (!res.isEmpty()) { currentOffset = res.get(res.size() - 1).first(); } - buf = res.stream().map(in -> { - final Long id = in.first(); - final byte[] bytes = in.second(); + buf = + res.stream() + .map( + in -> { + final Long id = in.first(); + final byte[] bytes = in.second(); - final PersistentRepr p = - serialization.deserialize(bytes, PersistentRepr.class).get(); + final PersistentRepr p = + serialization.deserialize(bytes, PersistentRepr.class).get(); - return new EventEnvelope(Offset.sequence(id), p.persistenceId(), p.sequenceNr(), p.payload()); - }).collect(toList()); + return new EventEnvelope( + Offset.sequence(id), p.persistenceId(), p.sequenceNr(), p.payload()); + }) + .collect(toList()); } - } catch(Exception e) { - onErrorThenStop(e); + } catch (Exception e) { + onErrorThenStop(e); } } } private void deliverBuf() { - while (totalDemand() > 0 && !buf.isEmpty()) - onNext(buf.remove(0)); + while (totalDemand() > 0 && !buf.isEmpty()) onNext(buf.remove(0)); } } -//#events-by-tag-publisher +// #events-by-tag-publisher diff --git a/akka-docs/src/test/java/jdocs/remoting/RemoteDeploymentDocTest.java b/akka-docs/src/test/java/jdocs/remoting/RemoteDeploymentDocTest.java index 8617c7fe94..45b9b7ca16 100644 --- a/akka-docs/src/test/java/jdocs/remoting/RemoteDeploymentDocTest.java +++ b/akka-docs/src/test/java/jdocs/remoting/RemoteDeploymentDocTest.java @@ -11,7 +11,7 @@ import org.junit.Test; import com.typesafe.config.ConfigFactory; -//#import +// #import import akka.actor.ActorRef; import akka.actor.Address; import akka.actor.AddressFromURIString; @@ -19,7 +19,7 @@ import akka.actor.Deploy; import akka.actor.Props; import akka.actor.ActorSystem; import akka.remote.RemoteScope; -//#import +// #import import akka.actor.AbstractActor; @@ -28,60 +28,57 @@ public class RemoteDeploymentDocTest extends AbstractJavaTest { public static class SampleActor extends AbstractActor { @Override public Receive createReceive() { - return receiveBuilder() - .matchAny(message -> getSender().tell(getSelf(), getSelf())) - .build(); + return receiveBuilder().matchAny(message -> getSender().tell(getSelf(), getSelf())).build(); } } @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("RemoteDeploymentDocTest"); + new AkkaJUnitActorSystemResource("RemoteDeploymentDocTest"); private final ActorSystem system = actorSystemResource.getSystem(); - + @SuppressWarnings("unused") void makeAddress() { - //#make-address-artery + // #make-address-artery Address addr = new Address("akka", "sys", "host", 1234); addr = AddressFromURIString.parse("akka://sys@host:1234"); // the same - //#make-address-artery + // #make-address-artery } - + @Test public void demonstrateDeployment() { - //#make-address + // #make-address Address addr = new Address("akka.tcp", "sys", "host", 1234); addr = AddressFromURIString.parse("akka.tcp://sys@host:1234"); // the same - //#make-address - //#deploy - ActorRef ref = system.actorOf(Props.create(SampleActor.class).withDeploy( - new Deploy(new RemoteScope(addr)))); - //#deploy + // #make-address + // #deploy + ActorRef ref = + system.actorOf( + Props.create(SampleActor.class).withDeploy(new Deploy(new RemoteScope(addr)))); + // #deploy assert ref.path().address().equals(addr); } @Test public void demonstrateSampleActor() { - //#sample-actor + // #sample-actor ActorRef actor = system.actorOf(Props.create(SampleActor.class), "sampleActor"); actor.tell("Pretty slick", ActorRef.noSender()); - //#sample-actor - } - - @Test - public void demonstrateProgrammaticConfig() { - //#programmatic - ConfigFactory.parseString("akka.remote.netty.tcp.hostname=\"1.2.3.4\"") - .withFallback(ConfigFactory.load()); - //#programmatic - - //#programmatic-artery - ConfigFactory.parseString("akka.remote.artery.canonical.hostname=\"1.2.3.4\"") - .withFallback(ConfigFactory.load()); - //#programmatic-artery + // #sample-actor } - + @Test + public void demonstrateProgrammaticConfig() { + // #programmatic + ConfigFactory.parseString("akka.remote.netty.tcp.hostname=\"1.2.3.4\"") + .withFallback(ConfigFactory.load()); + // #programmatic + + // #programmatic-artery + ConfigFactory.parseString("akka.remote.artery.canonical.hostname=\"1.2.3.4\"") + .withFallback(ConfigFactory.load()); + // #programmatic-artery + } } diff --git a/akka-docs/src/test/java/jdocs/routing/ConsistentHashingRouterDocTest.java b/akka-docs/src/test/java/jdocs/routing/ConsistentHashingRouterDocTest.java index 681c9a404f..8cd2585a91 100644 --- a/akka-docs/src/test/java/jdocs/routing/ConsistentHashingRouterDocTest.java +++ b/akka-docs/src/test/java/jdocs/routing/ConsistentHashingRouterDocTest.java @@ -13,139 +13,149 @@ import org.junit.Test; import akka.actor.ActorSystem; -//#imports1 +// #imports1 import akka.actor.AbstractActor; import akka.routing.ConsistentHashingRouter.ConsistentHashable; import java.util.Map; import java.util.HashMap; import java.io.Serializable; -//#imports1 +// #imports1 - -//#imports2 +// #imports2 import akka.actor.Props; import akka.actor.ActorRef; import akka.routing.ConsistentHashingPool; import akka.routing.ConsistentHashingRouter.ConsistentHashMapper; import akka.routing.ConsistentHashingRouter.ConsistentHashableEnvelope; -//#imports2 +// #imports2 public class ConsistentHashingRouterDocTest extends AbstractJavaTest { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("ConsistentHashingRouterDocTest"); + new AkkaJUnitActorSystemResource("ConsistentHashingRouterDocTest"); private final ActorSystem system = actorSystemResource.getSystem(); - static - //#cache-actor - public class Cache extends AbstractActor { + public + // #cache-actor + static class Cache extends AbstractActor { Map cache = new HashMap(); @Override public Receive createReceive() { return receiveBuilder() - .match(Entry.class, entry -> { - cache.put(entry.key, entry.value); - }) - .match(Get.class, get -> { - Object value = cache.get(get.key); - getSender().tell(value == null ? NOT_FOUND : value, getSelf()); - }) - .match(Evict.class, evict -> { - cache.remove(evict.key); - }) - .build(); + .match( + Entry.class, + entry -> { + cache.put(entry.key, entry.value); + }) + .match( + Get.class, + get -> { + Object value = cache.get(get.key); + getSender().tell(value == null ? NOT_FOUND : value, getSelf()); + }) + .match( + Evict.class, + evict -> { + cache.remove(evict.key); + }) + .build(); } } - //#cache-actor - static - //#cache-actor - public final class Evict implements Serializable { + // #cache-actor + public + // #cache-actor + static final class Evict implements Serializable { private static final long serialVersionUID = 1L; public final String key; + public Evict(String key) { this.key = key; } } - //#cache-actor - static - //#cache-actor - public final class Get implements Serializable, ConsistentHashable { + // #cache-actor + public + // #cache-actor + static final class Get implements Serializable, ConsistentHashable { private static final long serialVersionUID = 1L; public final String key; + public Get(String key) { this.key = key; } + public Object consistentHashKey() { return key; - } + } } - //#cache-actor - static - //#cache-actor - public final class Entry implements Serializable { + // #cache-actor + public + // #cache-actor + static final class Entry implements Serializable { private static final long serialVersionUID = 1L; public final String key; public final String value; + public Entry(String key, String value) { this.key = key; this.value = value; } } - //#cache-actor - static - //#cache-actor - public final String NOT_FOUND = "NOT_FOUND"; - //#cache-actor - + // #cache-actor + public + // #cache-actor + static final String NOT_FOUND = "NOT_FOUND"; + // #cache-actor @Test public void demonstrateUsageOfConsistentHashableRouter() { - new TestKit(system) {{ + new TestKit(system) { + { - //#consistent-hashing-router - - final ConsistentHashMapper hashMapper = new ConsistentHashMapper() { - @Override - public Object hashKey(Object message) { - if (message instanceof Evict) { - return ((Evict) message).key; - } else { - return null; - } - } - }; + // #consistent-hashing-router - ActorRef cache = system.actorOf( - new ConsistentHashingPool(10).withHashMapper(hashMapper).props( - Props.create(Cache.class)), - "cache"); + final ConsistentHashMapper hashMapper = + new ConsistentHashMapper() { + @Override + public Object hashKey(Object message) { + if (message instanceof Evict) { + return ((Evict) message).key; + } else { + return null; + } + } + }; - cache.tell(new ConsistentHashableEnvelope( - new Entry("hello", "HELLO"), "hello"), getRef()); - cache.tell(new ConsistentHashableEnvelope( - new Entry("hi", "HI"), "hi"), getRef()); + ActorRef cache = + system.actorOf( + new ConsistentHashingPool(10) + .withHashMapper(hashMapper) + .props(Props.create(Cache.class)), + "cache"); - cache.tell(new Get("hello"), getRef()); - expectMsgEquals("HELLO"); + cache.tell(new ConsistentHashableEnvelope(new Entry("hello", "HELLO"), "hello"), getRef()); + cache.tell(new ConsistentHashableEnvelope(new Entry("hi", "HI"), "hi"), getRef()); - cache.tell(new Get("hi"), getRef()); - expectMsgEquals("HI"); + cache.tell(new Get("hello"), getRef()); + expectMsgEquals("HELLO"); - cache.tell(new Evict("hi"), getRef()); - cache.tell(new Get("hi"), getRef()); - expectMsgEquals(NOT_FOUND); + cache.tell(new Get("hi"), getRef()); + expectMsgEquals("HI"); - //#consistent-hashing-router - }}; + cache.tell(new Evict("hi"), getRef()); + cache.tell(new Get("hi"), getRef()); + expectMsgEquals(NOT_FOUND); + + // #consistent-hashing-router + } + }; } - } diff --git a/akka-docs/src/test/java/jdocs/routing/CustomRouterDocTest.java b/akka-docs/src/test/java/jdocs/routing/CustomRouterDocTest.java index 9000733a11..4a16dc2182 100644 --- a/akka-docs/src/test/java/jdocs/routing/CustomRouterDocTest.java +++ b/akka-docs/src/test/java/jdocs/routing/CustomRouterDocTest.java @@ -27,34 +27,34 @@ import docs.routing.CustomRouterDocSpec; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; -//#imports1 +// #imports1 import akka.actor.AbstractActor; import java.util.ArrayList; import java.util.List; -//#imports1 - +// #imports1 public class CustomRouterDocTest extends AbstractJavaTest { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("CustomRouterDocTest", - ConfigFactory.parseString(CustomRouterDocSpec.jconfig())); + new AkkaJUnitActorSystemResource( + "CustomRouterDocTest", ConfigFactory.parseString(CustomRouterDocSpec.jconfig())); private final ActorSystem system = actorSystemResource.getSystem(); - static - //#routing-logic - public class RedundancyRoutingLogic implements RoutingLogic { + public + // #routing-logic + static class RedundancyRoutingLogic implements RoutingLogic { private final int nbrCopies; - + public RedundancyRoutingLogic(int nbrCopies) { - this.nbrCopies = nbrCopies; + this.nbrCopies = nbrCopies; } + RoundRobinRoutingLogic roundRobin = new RoundRobinRoutingLogic(); - + @Override public Routee select(Object message, IndexedSeq routees) { List targets = new ArrayList(); @@ -64,11 +64,11 @@ public class CustomRouterDocTest extends AbstractJavaTest { return new SeveralRoutees(targets); } } - //#routing-logic - - static - //#unit-test-logic - public final class TestRoutee implements Routee { + // #routing-logic + + public + // #unit-test-logic + static final class TestRoutee implements Routee { public final int n; public TestRoutee(int n) { @@ -76,8 +76,7 @@ public class CustomRouterDocTest extends AbstractJavaTest { } @Override - public void send(Object message, ActorRef sender) { - } + public void send(Object message, ActorRef sender) {} @Override public int hashCode() { @@ -86,27 +85,27 @@ public class CustomRouterDocTest extends AbstractJavaTest { @Override public boolean equals(Object obj) { - return (obj instanceof TestRoutee) && - n == ((TestRoutee) obj).n; + return (obj instanceof TestRoutee) && n == ((TestRoutee) obj).n; } } - //#unit-test-logic - - static public class Storage extends AbstractActor { + // #unit-test-logic + + public static class Storage extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .matchAny(message -> { - getSender().tell(message, getSelf()); - }) - .build(); + .matchAny( + message -> { + getSender().tell(message, getSelf()); + }) + .build(); } } - + @Test public void unitTestRoutingLogic() { - //#unit-test-logic + // #unit-test-logic RedundancyRoutingLogic logic = new RedundancyRoutingLogic(3); List routeeList = new ArrayList(); @@ -119,7 +118,7 @@ public class CustomRouterDocTest extends AbstractJavaTest { assertEquals(r1.getRoutees().get(0), routeeList.get(0)); assertEquals(r1.getRoutees().get(1), routeeList.get(1)); assertEquals(r1.getRoutees().get(2), routeeList.get(2)); - + SeveralRoutees r2 = (SeveralRoutees) logic.select("msg", routees); assertEquals(r2.getRoutees().get(0), routeeList.get(3)); assertEquals(r2.getRoutees().get(1), routeeList.get(4)); @@ -130,42 +129,40 @@ public class CustomRouterDocTest extends AbstractJavaTest { assertEquals(r3.getRoutees().get(1), routeeList.get(0)); assertEquals(r3.getRoutees().get(2), routeeList.get(1)); - //#unit-test-logic + // #unit-test-logic } @Test public void demonstrateUsageOfCustomRouter() { - new TestKit(system) {{ - //#usage-1 - for (int n = 1; n <= 10; n++) { - system.actorOf(Props.create(Storage.class), "s" + n); + new TestKit(system) { + { + // #usage-1 + for (int n = 1; n <= 10; n++) { + system.actorOf(Props.create(Storage.class), "s" + n); + } + + List paths = new ArrayList(); + for (int n = 1; n <= 10; n++) { + paths.add("/user/s" + n); + } + + ActorRef redundancy1 = system.actorOf(new RedundancyGroup(paths, 3).props(), "redundancy1"); + redundancy1.tell("important", getTestActor()); + // #usage-1 + + for (int i = 0; i < 3; i++) { + expectMsgEquals("important"); + } + + // #usage-2 + ActorRef redundancy2 = system.actorOf(FromConfig.getInstance().props(), "redundancy2"); + redundancy2.tell("very important", getTestActor()); + // #usage-2 + + for (int i = 0; i < 5; i++) { + expectMsgEquals("very important"); + } } - - List paths = new ArrayList(); - for (int n = 1; n <= 10; n++) { - paths.add("/user/s" + n); - } - - ActorRef redundancy1 = - system.actorOf(new RedundancyGroup(paths, 3).props(), - "redundancy1"); - redundancy1.tell("important", getTestActor()); - //#usage-1 - - for (int i = 0; i < 3; i++) { - expectMsgEquals("important"); - } - - //#usage-2 - ActorRef redundancy2 = system.actorOf(FromConfig.getInstance().props(), - "redundancy2"); - redundancy2.tell("very important", getTestActor()); - //#usage-2 - - for (int i = 0; i < 5; i++) { - expectMsgEquals("very important"); - } - }}; + }; } - } diff --git a/akka-docs/src/test/java/jdocs/routing/RedundancyGroup.java b/akka-docs/src/test/java/jdocs/routing/RedundancyGroup.java index 55f08a638c..57307bacd0 100644 --- a/akka-docs/src/test/java/jdocs/routing/RedundancyGroup.java +++ b/akka-docs/src/test/java/jdocs/routing/RedundancyGroup.java @@ -4,7 +4,7 @@ package jdocs.routing; -//#group +// #group import java.util.List; import akka.actor.ActorSystem; @@ -19,17 +19,16 @@ import static jdocs.routing.CustomRouterDocTest.RedundancyRoutingLogic; public class RedundancyGroup extends GroupBase { private final List paths; private final int nbrCopies; - + public RedundancyGroup(List paths, int nbrCopies) { this.paths = paths; this.nbrCopies = nbrCopies; } public RedundancyGroup(Config config) { - this(config.getStringList("routees.paths"), - config.getInt("nbr-copies")); + this(config.getStringList("routees.paths"), config.getInt("nbr-copies")); } - + @Override public java.lang.Iterable getPaths(ActorSystem system) { return paths; @@ -40,10 +39,9 @@ public class RedundancyGroup extends GroupBase { return new Router(new RedundancyRoutingLogic(nbrCopies)); } - @Override + @Override public String routerDispatcher() { return Dispatchers.DefaultDispatcherId(); } - } -//#group +// #group diff --git a/akka-docs/src/test/java/jdocs/routing/RouterDocTest.java b/akka-docs/src/test/java/jdocs/routing/RouterDocTest.java index 53761c67ed..f79f30a5b8 100644 --- a/akka-docs/src/test/java/jdocs/routing/RouterDocTest.java +++ b/akka-docs/src/test/java/jdocs/routing/RouterDocTest.java @@ -24,8 +24,7 @@ import java.time.Duration; import akka.actor.ActorSystem; - -//#imports1 +// #imports1 import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.Terminated; @@ -34,10 +33,9 @@ import akka.routing.ActorRefRoutee; import akka.routing.Routee; import akka.routing.Router; -//#imports1 +// #imports1 - -//#imports2 +// #imports2 import akka.actor.Address; import akka.actor.AddressFromURIString; import akka.actor.Kill; @@ -64,34 +62,35 @@ import akka.routing.SmallestMailboxPool; import akka.routing.TailChoppingGroup; import akka.routing.TailChoppingPool; -//#imports2 +// #imports2 public class RouterDocTest extends AbstractJavaTest { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("RouterDocTest", - ConfigFactory.parseString(docs.routing.RouterDocSpec.config())); + new AkkaJUnitActorSystemResource( + "RouterDocTest", ConfigFactory.parseString(docs.routing.RouterDocSpec.config())); private final ActorSystem system = actorSystemResource.getSystem(); - - static - //#router-in-actor - public final class Work implements Serializable { + public + // #router-in-actor + static final class Work implements Serializable { private static final long serialVersionUID = 1L; public final String payload; + public Work(String payload) { this.payload = payload; } } - //#router-in-actor - static - //#router-in-actor - public class Master extends AbstractActor { - + // #router-in-actor + public + // #router-in-actor + static class Master extends AbstractActor { + Router router; + { List routees = new ArrayList(); for (int i = 0; i < 5; i++) { @@ -105,262 +104,251 @@ public class RouterDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .match(Work.class, message -> { - router.route(message, getSender()); - }) - .match(Terminated.class, message -> { - router = router.removeRoutee(message.actor()); - ActorRef r = getContext().actorOf(Props.create(Worker.class)); - getContext().watch(r); - router = router.addRoutee(new ActorRefRoutee(r)); - }) - .build(); + .match( + Work.class, + message -> { + router.route(message, getSender()); + }) + .match( + Terminated.class, + message -> { + router = router.removeRoutee(message.actor()); + ActorRef r = getContext().actorOf(Props.create(Worker.class)); + getContext().watch(r); + router = router.addRoutee(new ActorRefRoutee(r)); + }) + .build(); } } - //#router-in-actor - - static public class Worker extends AbstractActor { + // #router-in-actor + + public static class Worker extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder().build(); } } - - static public class Echo extends AbstractActor { + + public static class Echo extends AbstractActor { + @Override + public Receive createReceive() { + return receiveBuilder().matchAny(message -> getSender().tell(message, getSelf())).build(); + } + } + + public static class Replier extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .matchAny(message -> getSender().tell(message, getSelf())) - .build(); + .matchAny( + message -> { + // #reply-with-self + getSender().tell("reply", getSelf()); + // #reply-with-self + + // #reply-with-parent + getSender().tell("reply", getContext().getParent()); + // #reply-with-parent + }) + .build(); } } - - static public class Replier extends AbstractActor { + + public + // #create-worker-actors + static class Workers extends AbstractActor { @Override - public Receive createReceive() { - return receiveBuilder() - .matchAny(message -> { - //#reply-with-self - getSender().tell("reply", getSelf()); - //#reply-with-self - - //#reply-with-parent - getSender().tell("reply", getContext().getParent()); - //#reply-with-parent - }) - .build(); - } - } - - - - static - //#create-worker-actors - public class Workers extends AbstractActor { - @Override public void preStart() { + public void preStart() { getContext().actorOf(Props.create(Worker.class), "w1"); getContext().actorOf(Props.create(Worker.class), "w2"); getContext().actorOf(Props.create(Worker.class), "w3"); } // ... - //#create-worker-actors + // #create-worker-actors @Override public Receive createReceive() { return receiveBuilder().build(); } } - - static public class Parent extends AbstractActor { - //#paths - List paths = Arrays.asList("/user/workers/w1", "/user/workers/w2", - "/user/workers/w3"); - //#paths + public static class Parent extends AbstractActor { - //#round-robin-pool-1 + // #paths + List paths = Arrays.asList("/user/workers/w1", "/user/workers/w2", "/user/workers/w3"); + // #paths + + // #round-robin-pool-1 ActorRef router1 = - getContext().actorOf(FromConfig.getInstance().props(Props.create(Worker.class)), - "router1"); - //#round-robin-pool-1 + getContext().actorOf(FromConfig.getInstance().props(Props.create(Worker.class)), "router1"); + // #round-robin-pool-1 - //#round-robin-pool-2 + // #round-robin-pool-2 ActorRef router2 = - getContext().actorOf(new RoundRobinPool(5).props(Props.create(Worker.class)), - "router2"); - //#round-robin-pool-2 + getContext().actorOf(new RoundRobinPool(5).props(Props.create(Worker.class)), "router2"); + // #round-robin-pool-2 - //#round-robin-group-1 - ActorRef router3 = - getContext().actorOf(FromConfig.getInstance().props(), "router3"); - //#round-robin-group-1 + // #round-robin-group-1 + ActorRef router3 = getContext().actorOf(FromConfig.getInstance().props(), "router3"); + // #round-robin-group-1 - //#round-robin-group-2 - ActorRef router4 = - getContext().actorOf(new RoundRobinGroup(paths).props(), "router4"); - //#round-robin-group-2 + // #round-robin-group-2 + ActorRef router4 = getContext().actorOf(new RoundRobinGroup(paths).props(), "router4"); + // #round-robin-group-2 - //#random-pool-1 + // #random-pool-1 ActorRef router5 = - getContext().actorOf(FromConfig.getInstance().props( - Props.create(Worker.class)), "router5"); - //#random-pool-1 + getContext().actorOf(FromConfig.getInstance().props(Props.create(Worker.class)), "router5"); + // #random-pool-1 - //#random-pool-2 + // #random-pool-2 ActorRef router6 = - getContext().actorOf(new RandomPool(5).props(Props.create(Worker.class)), - "router6"); - //#random-pool-2 + getContext().actorOf(new RandomPool(5).props(Props.create(Worker.class)), "router6"); + // #random-pool-2 - //#random-group-1 - ActorRef router7 = - getContext().actorOf(FromConfig.getInstance().props(), "router7"); - //#random-group-1 + // #random-group-1 + ActorRef router7 = getContext().actorOf(FromConfig.getInstance().props(), "router7"); + // #random-group-1 - //#random-group-2 - ActorRef router8 = - getContext().actorOf(new RandomGroup(paths).props(), "router8"); - //#random-group-2 - - //#balancing-pool-1 + // #random-group-2 + ActorRef router8 = getContext().actorOf(new RandomGroup(paths).props(), "router8"); + // #random-group-2 + + // #balancing-pool-1 ActorRef router9 = - getContext().actorOf(FromConfig.getInstance().props( - Props.create(Worker.class)), "router9"); - //#balancing-pool-1 + getContext().actorOf(FromConfig.getInstance().props(Props.create(Worker.class)), "router9"); + // #balancing-pool-1 - //#balancing-pool-2 + // #balancing-pool-2 ActorRef router10 = - getContext().actorOf(new BalancingPool(5).props( - Props.create(Worker.class)), "router10"); - //#balancing-pool-2 + getContext().actorOf(new BalancingPool(5).props(Props.create(Worker.class)), "router10"); + // #balancing-pool-2 - //#smallest-mailbox-pool-1 + // #smallest-mailbox-pool-1 ActorRef router11 = - getContext().actorOf(FromConfig.getInstance().props( - Props.create(Worker.class)), "router11"); - //#smallest-mailbox-pool-1 + getContext() + .actorOf(FromConfig.getInstance().props(Props.create(Worker.class)), "router11"); + // #smallest-mailbox-pool-1 - //#smallest-mailbox-pool-2 + // #smallest-mailbox-pool-2 ActorRef router12 = - getContext().actorOf(new SmallestMailboxPool(5).props( - Props.create(Worker.class)), "router12"); - //#smallest-mailbox-pool-2 + getContext() + .actorOf(new SmallestMailboxPool(5).props(Props.create(Worker.class)), "router12"); + // #smallest-mailbox-pool-2 - //#broadcast-pool-1 + // #broadcast-pool-1 ActorRef router13 = - getContext().actorOf(FromConfig.getInstance().props( - Props.create(Worker.class)), "router13"); - //#broadcast-pool-1 + getContext() + .actorOf(FromConfig.getInstance().props(Props.create(Worker.class)), "router13"); + // #broadcast-pool-1 - //#broadcast-pool-2 + // #broadcast-pool-2 ActorRef router14 = - getContext().actorOf(new BroadcastPool(5).props(Props.create(Worker.class)), - "router14"); - //#broadcast-pool-2 + getContext().actorOf(new BroadcastPool(5).props(Props.create(Worker.class)), "router14"); + // #broadcast-pool-2 - //#broadcast-group-1 - ActorRef router15 = - getContext().actorOf(FromConfig.getInstance().props(), "router15"); - //#broadcast-group-1 + // #broadcast-group-1 + ActorRef router15 = getContext().actorOf(FromConfig.getInstance().props(), "router15"); + // #broadcast-group-1 - //#broadcast-group-2 - ActorRef router16 = - getContext().actorOf(new BroadcastGroup(paths).props(), "router16"); - //#broadcast-group-2 + // #broadcast-group-2 + ActorRef router16 = getContext().actorOf(new BroadcastGroup(paths).props(), "router16"); + // #broadcast-group-2 - //#scatter-gather-pool-1 + // #scatter-gather-pool-1 ActorRef router17 = - getContext().actorOf(FromConfig.getInstance().props( - Props.create(Worker.class)), "router17"); - //#scatter-gather-pool-1 + getContext() + .actorOf(FromConfig.getInstance().props(Props.create(Worker.class)), "router17"); + // #scatter-gather-pool-1 - //#scatter-gather-pool-2 + // #scatter-gather-pool-2 Duration within = Duration.ofSeconds(10); ActorRef router18 = - getContext().actorOf(new ScatterGatherFirstCompletedPool(5, within).props( - Props.create(Worker.class)), "router18"); - //#scatter-gather-pool-2 + getContext() + .actorOf( + new ScatterGatherFirstCompletedPool(5, within).props(Props.create(Worker.class)), + "router18"); + // #scatter-gather-pool-2 - //#scatter-gather-group-1 - ActorRef router19 = - getContext().actorOf(FromConfig.getInstance().props(), "router19"); - //#scatter-gather-group-1 + // #scatter-gather-group-1 + ActorRef router19 = getContext().actorOf(FromConfig.getInstance().props(), "router19"); + // #scatter-gather-group-1 - //#scatter-gather-group-2 + // #scatter-gather-group-2 Duration within2 = Duration.ofSeconds(10); ActorRef router20 = - getContext().actorOf(new ScatterGatherFirstCompletedGroup(paths, within2).props(), - "router20"); - //#scatter-gather-group-2 + getContext() + .actorOf(new ScatterGatherFirstCompletedGroup(paths, within2).props(), "router20"); + // #scatter-gather-group-2 - //#tail-chopping-pool-1 + // #tail-chopping-pool-1 ActorRef router21 = - getContext().actorOf(FromConfig.getInstance().props( - Props.create(Worker.class)), "router21"); - //#tail-chopping-pool-1 + getContext() + .actorOf(FromConfig.getInstance().props(Props.create(Worker.class)), "router21"); + // #tail-chopping-pool-1 - //#tail-chopping-pool-2 + // #tail-chopping-pool-2 Duration within3 = Duration.ofSeconds(10); Duration interval = Duration.ofMillis(20); ActorRef router22 = - getContext().actorOf(new TailChoppingPool(5, within3, interval).props( - Props.create(Worker.class)), "router22"); - //#tail-chopping-pool-2 + getContext() + .actorOf( + new TailChoppingPool(5, within3, interval).props(Props.create(Worker.class)), + "router22"); + // #tail-chopping-pool-2 - //#tail-chopping-group-1 - ActorRef router23 = - getContext().actorOf(FromConfig.getInstance().props(), "router23"); - //#tail-chopping-group-1 + // #tail-chopping-group-1 + ActorRef router23 = getContext().actorOf(FromConfig.getInstance().props(), "router23"); + // #tail-chopping-group-1 - //#tail-chopping-group-2 + // #tail-chopping-group-2 Duration within4 = Duration.ofSeconds(10); Duration interval2 = Duration.ofMillis(20); ActorRef router24 = - getContext().actorOf(new TailChoppingGroup(paths, within4, interval2).props(), - "router24"); - //#tail-chopping-group-2 + getContext().actorOf(new TailChoppingGroup(paths, within4, interval2).props(), "router24"); + // #tail-chopping-group-2 - //#consistent-hashing-pool-1 + // #consistent-hashing-pool-1 ActorRef router25 = - getContext().actorOf(FromConfig.getInstance().props(Props.create(Worker.class)), - "router25"); - //#consistent-hashing-pool-1 + getContext() + .actorOf(FromConfig.getInstance().props(Props.create(Worker.class)), "router25"); + // #consistent-hashing-pool-1 - //#consistent-hashing-pool-2 + // #consistent-hashing-pool-2 ActorRef router26 = - getContext().actorOf(new ConsistentHashingPool(5).props( - Props.create(Worker.class)), "router26"); - //#consistent-hashing-pool-2 + getContext() + .actorOf(new ConsistentHashingPool(5).props(Props.create(Worker.class)), "router26"); + // #consistent-hashing-pool-2 - //#consistent-hashing-group-1 - ActorRef router27 = - getContext().actorOf(FromConfig.getInstance().props(), "router27"); - //#consistent-hashing-group-1 + // #consistent-hashing-group-1 + ActorRef router27 = getContext().actorOf(FromConfig.getInstance().props(), "router27"); + // #consistent-hashing-group-1 - //#consistent-hashing-group-2 - ActorRef router28 = - getContext().actorOf(new ConsistentHashingGroup(paths).props(), "router28"); - //#consistent-hashing-group-2 + // #consistent-hashing-group-2 + ActorRef router28 = getContext().actorOf(new ConsistentHashingGroup(paths).props(), "router28"); + // #consistent-hashing-group-2 - //#resize-pool-1 + // #resize-pool-1 ActorRef router29 = - getContext().actorOf(FromConfig.getInstance().props( - Props.create(Worker.class)), "router29"); - //#resize-pool-1 + getContext() + .actorOf(FromConfig.getInstance().props(Props.create(Worker.class)), "router29"); + // #resize-pool-1 - //#resize-pool-2 + // #resize-pool-2 DefaultResizer resizer = new DefaultResizer(2, 15); ActorRef router30 = - getContext().actorOf(new RoundRobinPool(5).withResizer(resizer).props( - Props.create(Worker.class)), "router30"); - //#resize-pool-2 + getContext() + .actorOf( + new RoundRobinPool(5).withResizer(resizer).props(Props.create(Worker.class)), + "router30"); + // #resize-pool-2 - //#optimal-size-exploring-resize-pool + // #optimal-size-exploring-resize-pool ActorRef router31 = - getContext().actorOf(FromConfig.getInstance().props( - Props.create(Worker.class)), "router31"); - //#optimal-size-exploring-resize-pool + getContext() + .actorOf(FromConfig.getInstance().props(Props.create(Worker.class)), "router31"); + // #optimal-size-exploring-resize-pool @Override public Receive createReceive() { @@ -370,120 +358,134 @@ public class RouterDocTest extends AbstractJavaTest { @Test public void createActors() { - //#create-workers + // #create-workers system.actorOf(Props.create(Workers.class), "workers"); - //#create-workers - - //#create-parent + // #create-workers + + // #create-parent system.actorOf(Props.create(Parent.class), "parent"); - //#create-parent + // #create-parent } - + @Test public void demonstrateDispatcher() { - //#dispatchers - Props props = - // “head” router actor will run on "router-dispatcher" dispatcher - // Worker routees will run on "pool-dispatcher" dispatcher - new RandomPool(5).withDispatcher("router-dispatcher").props( - Props.create(Worker.class)); + // #dispatchers + Props props = + // “head” router actor will run on "router-dispatcher" dispatcher + // Worker routees will run on "pool-dispatcher" dispatcher + new RandomPool(5).withDispatcher("router-dispatcher").props(Props.create(Worker.class)); ActorRef router = system.actorOf(props, "poolWithDispatcher"); - //#dispatchers + // #dispatchers } - + @Test public void demonstrateBroadcast() { - new TestKit(system) {{ - ActorRef router = system.actorOf(new RoundRobinPool(5).props( - Props.create(Echo.class))); - //#broadcastDavyJonesWarning - router.tell(new Broadcast("Watch out for Davy Jones' locker"), getTestActor()); - //#broadcastDavyJonesWarning - assertEquals(5, receiveN(5).size()); - }}; + new TestKit(system) { + { + ActorRef router = system.actorOf(new RoundRobinPool(5).props(Props.create(Echo.class))); + // #broadcastDavyJonesWarning + router.tell(new Broadcast("Watch out for Davy Jones' locker"), getTestActor()); + // #broadcastDavyJonesWarning + assertEquals(5, receiveN(5).size()); + } + }; } - + @Test public void demonstratePoisonPill() { - new TestKit(system) {{ - ActorRef router = watch(system.actorOf(new RoundRobinPool(5).props( - Props.create(Echo.class)))); - //#poisonPill - router.tell(PoisonPill.getInstance(), getTestActor()); - //#poisonPill - expectTerminated(router); - }}; + new TestKit(system) { + { + ActorRef router = + watch(system.actorOf(new RoundRobinPool(5).props(Props.create(Echo.class)))); + // #poisonPill + router.tell(PoisonPill.getInstance(), getTestActor()); + // #poisonPill + expectTerminated(router); + } + }; } - + @Test public void demonstrateBroadcastPoisonPill() { - new TestKit(system) {{ - ActorRef router = watch(system.actorOf(new RoundRobinPool(5).props( - Props.create(Echo.class)))); - //#broadcastPoisonPill - router.tell(new Broadcast(PoisonPill.getInstance()), getTestActor()); - //#broadcastPoisonPill - expectTerminated(router); - }}; + new TestKit(system) { + { + ActorRef router = + watch(system.actorOf(new RoundRobinPool(5).props(Props.create(Echo.class)))); + // #broadcastPoisonPill + router.tell(new Broadcast(PoisonPill.getInstance()), getTestActor()); + // #broadcastPoisonPill + expectTerminated(router); + } + }; } - + @Test public void demonstrateKill() { - new TestKit(system) {{ - ActorRef router = watch(system.actorOf(new RoundRobinPool(5).props( - Props.create(Echo.class)))); - //#kill - router.tell(Kill.getInstance(), getTestActor()); - //#kill - expectTerminated(router); - }}; + new TestKit(system) { + { + ActorRef router = + watch(system.actorOf(new RoundRobinPool(5).props(Props.create(Echo.class)))); + // #kill + router.tell(Kill.getInstance(), getTestActor()); + // #kill + expectTerminated(router); + } + }; } - + @Test public void demonstrateBroadcastKill() { - new TestKit(system) {{ - ActorRef router = watch(system.actorOf(new RoundRobinPool(5).props( - Props.create(Echo.class)))); - //#broadcastKill - router.tell(new Broadcast(Kill.getInstance()), getTestActor()); - //#broadcastKill - expectTerminated(router); - }}; + new TestKit(system) { + { + ActorRef router = + watch(system.actorOf(new RoundRobinPool(5).props(Props.create(Echo.class)))); + // #broadcastKill + router.tell(new Broadcast(Kill.getInstance()), getTestActor()); + // #broadcastKill + expectTerminated(router); + } + }; } @Test public void demonstrateRemoteDeploy() { - //#remoteRoutees + // #remoteRoutees Address[] addresses = { new Address("akka.tcp", "remotesys", "otherhost", 1234), - AddressFromURIString.parse("akka.tcp://othersys@anotherhost:1234")}; - ActorRef routerRemote = system.actorOf( - new RemoteRouterConfig(new RoundRobinPool(5), addresses).props( - Props.create(Echo.class))); - //#remoteRoutees - } - - // only compile - public void demonstrateRemoteDeployWithArtery() { - //#remoteRoutees-artery - Address[] addresses = { - new Address("akka", "remotesys", "otherhost", 1234), - AddressFromURIString.parse("akka://othersys@anotherhost:1234")}; - ActorRef routerRemote = system.actorOf( - new RemoteRouterConfig(new RoundRobinPool(5), addresses).props( - Props.create(Echo.class))); - //#remoteRoutees-artery - } - - @Test - public void demonstrateSupervisor() { - //#supervision - final SupervisorStrategy strategy = - new OneForOneStrategy(5, Duration.ofMinutes(1), - Collections.>singletonList(Exception.class)); - final ActorRef router = system.actorOf(new RoundRobinPool(5). - withSupervisorStrategy(strategy).props(Props.create(Echo.class))); - //#supervision + AddressFromURIString.parse("akka.tcp://othersys@anotherhost:1234") + }; + ActorRef routerRemote = + system.actorOf( + new RemoteRouterConfig(new RoundRobinPool(5), addresses) + .props(Props.create(Echo.class))); + // #remoteRoutees } + // only compile + public void demonstrateRemoteDeployWithArtery() { + // #remoteRoutees-artery + Address[] addresses = { + new Address("akka", "remotesys", "otherhost", 1234), + AddressFromURIString.parse("akka://othersys@anotherhost:1234") + }; + ActorRef routerRemote = + system.actorOf( + new RemoteRouterConfig(new RoundRobinPool(5), addresses) + .props(Props.create(Echo.class))); + // #remoteRoutees-artery + } + + @Test + public void demonstrateSupervisor() { + // #supervision + final SupervisorStrategy strategy = + new OneForOneStrategy( + 5, + Duration.ofMinutes(1), + Collections.>singletonList(Exception.class)); + final ActorRef router = + system.actorOf( + new RoundRobinPool(5).withSupervisorStrategy(strategy).props(Props.create(Echo.class))); + // #supervision + } } diff --git a/akka-docs/src/test/java/jdocs/serialization/SerializationDocTest.java b/akka-docs/src/test/java/jdocs/serialization/SerializationDocTest.java index 0fd858087a..633f8e89b1 100644 --- a/akka-docs/src/test/java/jdocs/serialization/SerializationDocTest.java +++ b/akka-docs/src/test/java/jdocs/serialization/SerializationDocTest.java @@ -11,104 +11,104 @@ import org.junit.Test; import static org.junit.Assert.*; import java.nio.charset.StandardCharsets; -//#imports +// #imports import akka.actor.*; import akka.serialization.*; -//#imports +// #imports public class SerializationDocTest { - static - //#my-own-serializer - public class MyOwnSerializer extends JSerializer { + public + // #my-own-serializer + static class MyOwnSerializer extends JSerializer { // If you need logging here, introduce a constructor that takes an ExtendedActorSystem. - // public MyOwnSerializer(ExtendedActorSystem actorSystem) + // public MyOwnSerializer(ExtendedActorSystem actorSystem) // Get a logger using: - // private final LoggingAdapter logger = Logging.getLogger(actorSystem, this); + // private final LoggingAdapter logger = Logging.getLogger(actorSystem, this); // This is whether "fromBinary" requires a "clazz" or not - @Override public boolean includeManifest() { + @Override + public boolean includeManifest() { return false; } // Pick a unique identifier for your Serializer, // you've got a couple of billions to choose from, // 0 - 40 is reserved by Akka itself - @Override public int identifier() { + @Override + public int identifier() { return 1234567; } // "toBinary" serializes the given object to an Array of Bytes - @Override public byte[] toBinary(Object obj) { + @Override + public byte[] toBinary(Object obj) { // Put the code that serializes the object here - //#... + // #... return new byte[0]; - //#... + // #... } // "fromBinary" deserializes the given array, // using the type hint (if any, see "includeManifest" above) - @Override public Object fromBinaryJava(byte[] bytes, - Class clazz) { + @Override + public Object fromBinaryJava(byte[] bytes, Class clazz) { // Put your code that deserializes here - //#... + // #... return null; - //#... + // #... } } -//#my-own-serializer + // #my-own-serializer static class Customer { public final String name; - + Customer(String name) { this.name = name; } } - + static class User { public final String name; - + User(String name) { this.name = name; } } - - static - //#my-own-serializer2 - public class MyOwnSerializer2 extends SerializerWithStringManifest { + + public + // #my-own-serializer2 + static class MyOwnSerializer2 extends SerializerWithStringManifest { private static final String CUSTOMER_MANIFEST = "customer"; private static final String USER_MANIFEST = "user"; private static final String UTF_8 = StandardCharsets.UTF_8.name(); - + // Pick a unique identifier for your Serializer, // you've got a couple of billions to choose from, // 0 - 40 is reserved by Akka itself - @Override public int identifier() { + @Override + public int identifier() { return 1234567; } - - @Override public String manifest(Object obj) { - if (obj instanceof Customer) - return CUSTOMER_MANIFEST; - else if (obj instanceof User) - return USER_MANIFEST; - else - throw new IllegalArgumentException("Unknown type: " + obj); + + @Override + public String manifest(Object obj) { + if (obj instanceof Customer) return CUSTOMER_MANIFEST; + else if (obj instanceof User) return USER_MANIFEST; + else throw new IllegalArgumentException("Unknown type: " + obj); } // "toBinary" serializes the given object to an Array of Bytes - @Override public byte[] toBinary(Object obj) { + @Override + public byte[] toBinary(Object obj) { // Put the real code that serializes the object here try { - if (obj instanceof Customer) - return ((Customer) obj).name.getBytes(UTF_8); - else if (obj instanceof User) - return ((User) obj).name.getBytes(UTF_8); - else - throw new IllegalArgumentException("Unknown type: " + obj); + if (obj instanceof Customer) return ((Customer) obj).name.getBytes(UTF_8); + else if (obj instanceof User) return ((User) obj).name.getBytes(UTF_8); + else throw new IllegalArgumentException("Unknown type: " + obj); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } @@ -116,29 +116,26 @@ public class SerializationDocTest { // "fromBinary" deserializes the given array, // using the type hint - @Override public Object fromBinary(byte[] bytes, String manifest) { + @Override + public Object fromBinary(byte[] bytes, String manifest) { // Put the real code that deserializes here try { - if (manifest.equals(CUSTOMER_MANIFEST)) - return new Customer(new String(bytes, UTF_8)); - else if (manifest.equals(USER_MANIFEST)) - return new User(new String(bytes, UTF_8)); - else - throw new IllegalArgumentException("Unknown manifest: " + manifest); + if (manifest.equals(CUSTOMER_MANIFEST)) return new Customer(new String(bytes, UTF_8)); + else if (manifest.equals(USER_MANIFEST)) return new User(new String(bytes, UTF_8)); + else throw new IllegalArgumentException("Unknown manifest: " + manifest); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } } } -//#my-own-serializer2 + // #my-own-serializer2 - @Test public void serializeActorRefs() { - final ExtendedActorSystem extendedSystem = (ExtendedActorSystem) - ActorSystem.create("whatever"); - final ActorRef theActorRef = - extendedSystem.deadLetters(); // Of course this should be you + @Test + public void serializeActorRefs() { + final ExtendedActorSystem extendedSystem = (ExtendedActorSystem) ActorSystem.create("whatever"); + final ActorRef theActorRef = extendedSystem.deadLetters(); // Of course this should be you - //#actorref-serializer + // #actorref-serializer // Serialize // (beneath toBinary) String identifier = Serialization.serializedActorPath(theActorRef); @@ -147,16 +144,15 @@ public class SerializationDocTest { // Deserialize // (beneath fromBinary) - final ActorRef deserializedActorRef = extendedSystem.provider().resolveActorRef( - identifier); + final ActorRef deserializedActorRef = extendedSystem.provider().resolveActorRef(identifier); // Then just use the ActorRef - //#actorref-serializer + // #actorref-serializer TestKit.shutdownActorSystem(extendedSystem); } - static - //#external-address - public class ExternalAddressExt implements Extension { + public + // #external-address + static class ExternalAddressExt implements Extension { private final ExtendedActorSystem system; public ExternalAddressExt(ExtendedActorSystem system) { @@ -164,22 +160,20 @@ public class SerializationDocTest { } public Address getAddressFor(Address remoteAddress) { - final scala.Option

optAddr = system.provider() - .getExternalAddressFor(remoteAddress); + final scala.Option
optAddr = system.provider().getExternalAddressFor(remoteAddress); if (optAddr.isDefined()) { return optAddr.get(); } else { - throw new UnsupportedOperationException( - "cannot send to remote address " + remoteAddress); + throw new UnsupportedOperationException("cannot send to remote address " + remoteAddress); } } } - //#external-address - static - //#external-address - public class ExternalAddress extends - AbstractExtensionId implements ExtensionIdProvider { + // #external-address + public + // #external-address + static class ExternalAddress extends AbstractExtensionId + implements ExtensionIdProvider { public static final ExternalAddress ID = new ExternalAddress(); public ExternalAddress lookup() { @@ -191,24 +185,24 @@ public class SerializationDocTest { } } - //#external-address - static - //#external-address - public class ExternalAddressExample { - //#external-address + // #external-address + public + // #external-address + static class ExternalAddressExample { + // #external-address final ActorSystem system = ActorSystem.create(); - //#external-address + // #external-address public String serializeTo(ActorRef ref, Address remote) { - return ref.path().toSerializationFormatWithAddress( - ExternalAddress.ID.get(system).getAddressFor(remote)); + return ref.path() + .toSerializationFormatWithAddress(ExternalAddress.ID.get(system).getAddressFor(remote)); } } - //#external-address + // #external-address - static - //#external-address-default - public class DefaultAddressExt implements Extension { + public + // #external-address-default + static class DefaultAddressExt implements Extension { private final ExtendedActorSystem system; public DefaultAddressExt(ExtendedActorSystem system) { @@ -220,11 +214,11 @@ public class SerializationDocTest { } } - //#external-address-default - static - //#external-address-default - public class DefaultAddress extends - AbstractExtensionId implements ExtensionIdProvider { + // #external-address-default + public + // #external-address-default + static class DefaultAddress extends AbstractExtensionId + implements ExtensionIdProvider { public static final DefaultAddress ID = new DefaultAddress(); public DefaultAddress lookup() { @@ -236,7 +230,7 @@ public class SerializationDocTest { } } - //#external-address-default + // #external-address-default public void demonstrateDefaultAddress() { // this is not meant to be run, only to be compiled @@ -249,7 +243,7 @@ public class SerializationDocTest { @Test public void demonstrateTheProgrammaticAPI() { - //#programmatic + // #programmatic ActorSystem system = ActorSystem.create("example"); // Get the Serialization Extension @@ -271,7 +265,7 @@ public class SerializationDocTest { // Voilá! assertEquals(original, back); - //#programmatic + // #programmatic TestKit.shutdownActorSystem(system); } } diff --git a/akka-docs/src/test/java/jdocs/sharding/ClusterShardingTest.java b/akka-docs/src/test/java/jdocs/sharding/ClusterShardingTest.java index 240bfd59d1..013590382c 100644 --- a/akka-docs/src/test/java/jdocs/sharding/ClusterShardingTest.java +++ b/akka-docs/src/test/java/jdocs/sharding/ClusterShardingTest.java @@ -4,7 +4,6 @@ package jdocs.sharding; - import java.util.Optional; import java.time.Duration; @@ -17,17 +16,17 @@ import akka.actor.PoisonPill; import akka.actor.Props; import akka.actor.SupervisorStrategy; import akka.actor.ReceiveTimeout; -//#counter-extractor +// #counter-extractor import akka.cluster.sharding.ShardRegion; -//#counter-extractor +// #counter-extractor -//#counter-start +// #counter-start import akka.japi.Option; import akka.cluster.sharding.ClusterSharding; import akka.cluster.sharding.ClusterShardingSettings; -//#counter-start +// #counter-start import akka.persistence.AbstractPersistentActor; import akka.japi.pf.DeciderBuilder; @@ -41,127 +40,127 @@ public class ClusterShardingTest { } public void demonstrateUsage() { - //#counter-extractor - ShardRegion.MessageExtractor messageExtractor = new ShardRegion.MessageExtractor() { + // #counter-extractor + ShardRegion.MessageExtractor messageExtractor = + new ShardRegion.MessageExtractor() { - @Override - public String entityId(Object message) { - if (message instanceof Counter.EntityEnvelope) - return String.valueOf(((Counter.EntityEnvelope) message).id); - else if (message instanceof Counter.Get) - return String.valueOf(((Counter.Get) message).counterId); - else - return null; - } + @Override + public String entityId(Object message) { + if (message instanceof Counter.EntityEnvelope) + return String.valueOf(((Counter.EntityEnvelope) message).id); + else if (message instanceof Counter.Get) + return String.valueOf(((Counter.Get) message).counterId); + else return null; + } - @Override - public Object entityMessage(Object message) { - if (message instanceof Counter.EntityEnvelope) - return ((Counter.EntityEnvelope) message).payload; - else - return message; - } + @Override + public Object entityMessage(Object message) { + if (message instanceof Counter.EntityEnvelope) + return ((Counter.EntityEnvelope) message).payload; + else return message; + } - @Override - public String shardId(Object message) { - int numberOfShards = 100; - if (message instanceof Counter.EntityEnvelope) { - long id = ((Counter.EntityEnvelope) message).id; - return String.valueOf(id % numberOfShards); - } else if (message instanceof Counter.Get) { - long id = ((Counter.Get) message).counterId; - return String.valueOf(id % numberOfShards); - } else { - return null; - } - } + @Override + public String shardId(Object message) { + int numberOfShards = 100; + if (message instanceof Counter.EntityEnvelope) { + long id = ((Counter.EntityEnvelope) message).id; + return String.valueOf(id % numberOfShards); + } else if (message instanceof Counter.Get) { + long id = ((Counter.Get) message).counterId; + return String.valueOf(id % numberOfShards); + } else { + return null; + } + } + }; + // #counter-extractor - }; - //#counter-extractor - - //#counter-start + // #counter-start Option roleOption = Option.none(); ClusterShardingSettings settings = ClusterShardingSettings.create(system); - ActorRef startedCounterRegion = ClusterSharding.get(system).start("Counter", - Props.create(Counter.class), settings, messageExtractor); - //#counter-start + ActorRef startedCounterRegion = + ClusterSharding.get(system) + .start("Counter", Props.create(Counter.class), settings, messageExtractor); + // #counter-start - //#counter-usage + // #counter-usage ActorRef counterRegion = ClusterSharding.get(system).shardRegion("Counter"); counterRegion.tell(new Counter.Get(123), getSelf()); - counterRegion.tell(new Counter.EntityEnvelope(123, - Counter.CounterOp.INCREMENT), getSelf()); + counterRegion.tell(new Counter.EntityEnvelope(123, Counter.CounterOp.INCREMENT), getSelf()); counterRegion.tell(new Counter.Get(123), getSelf()); - //#counter-usage + // #counter-usage - //#counter-supervisor-start - ClusterSharding.get(system).start("SupervisedCounter", - Props.create(CounterSupervisor.class), settings, messageExtractor); - //#counter-supervisor-start + // #counter-supervisor-start + ClusterSharding.get(system) + .start( + "SupervisedCounter", Props.create(CounterSupervisor.class), settings, messageExtractor); + // #counter-supervisor-start - //#proxy-dc + // #proxy-dc ActorRef counterProxyDcB = - ClusterSharding.get(system).startProxy( - "Counter", - Optional.empty(), - Optional.of("B"), // data center name - messageExtractor); - //#proxy-dc + ClusterSharding.get(system) + .startProxy( + "Counter", + Optional.empty(), + Optional.of("B"), // data center name + messageExtractor); + // #proxy-dc } public void demonstrateUsage2() { - ShardRegion.MessageExtractor messageExtractor = new ShardRegion.MessageExtractor() { + ShardRegion.MessageExtractor messageExtractor = + new ShardRegion.MessageExtractor() { - @Override - public String entityId(Object message) { - if (message instanceof Counter.EntityEnvelope) - return String.valueOf(((Counter.EntityEnvelope) message).id); - else if (message instanceof Counter.Get) - return String.valueOf(((Counter.Get) message).counterId); - else - return null; - } + @Override + public String entityId(Object message) { + if (message instanceof Counter.EntityEnvelope) + return String.valueOf(((Counter.EntityEnvelope) message).id); + else if (message instanceof Counter.Get) + return String.valueOf(((Counter.Get) message).counterId); + else return null; + } - @Override - public Object entityMessage(Object message) { - if (message instanceof Counter.EntityEnvelope) - return ((Counter.EntityEnvelope) message).payload; - else - return message; - } + @Override + public Object entityMessage(Object message) { + if (message instanceof Counter.EntityEnvelope) + return ((Counter.EntityEnvelope) message).payload; + else return message; + } - //#extractShardId-StartEntity - @Override - public String shardId(Object message) { - int numberOfShards = 100; - if (message instanceof Counter.EntityEnvelope) { - long id = ((Counter.EntityEnvelope) message).id; - return String.valueOf(id % numberOfShards); - } else if (message instanceof Counter.Get) { - long id = ((Counter.Get) message).counterId; - return String.valueOf(id % numberOfShards); - } else if (message instanceof ShardRegion.StartEntity) { - long id = Long.valueOf(((ShardRegion.StartEntity) message).entityId()); - return String.valueOf(id % numberOfShards); - } else { - return null; - } - } - //#extractShardId-StartEntity + // #extractShardId-StartEntity + @Override + public String shardId(Object message) { + int numberOfShards = 100; + if (message instanceof Counter.EntityEnvelope) { + long id = ((Counter.EntityEnvelope) message).id; + return String.valueOf(id % numberOfShards); + } else if (message instanceof Counter.Get) { + long id = ((Counter.Get) message).counterId; + return String.valueOf(id % numberOfShards); + } else if (message instanceof ShardRegion.StartEntity) { + long id = Long.valueOf(((ShardRegion.StartEntity) message).entityId()); + return String.valueOf(id % numberOfShards); + } else { + return null; + } + } + // #extractShardId-StartEntity - }; + }; } - static//#counter-actor - public class Counter extends AbstractPersistentActor { + public // #counter-actor + static class Counter extends AbstractPersistentActor { public enum CounterOp { - INCREMENT, DECREMENT + INCREMENT, + DECREMENT } public static class Get { - final public long counterId; + public final long counterId; public Get(long counterId) { this.counterId = counterId; @@ -169,8 +168,8 @@ public class ClusterShardingTest { } public static class EntityEnvelope { - final public long id; - final public Object payload; + public final long id; + public final Object payload; public EntityEnvelope(long id, Object payload) { this.id = id; @@ -179,7 +178,7 @@ public class ClusterShardingTest { } public static class CounterChanged { - final public int delta; + public final int delta; public CounterChanged(int delta) { this.delta = delta; @@ -206,19 +205,17 @@ public class ClusterShardingTest { @Override public Receive createReceiveRecover() { - return receiveBuilder() - .match(CounterChanged.class, this::updateState) - .build(); + return receiveBuilder().match(CounterChanged.class, this::updateState).build(); } @Override public Receive createReceive() { return receiveBuilder() - .match(Get.class, this::receiveGet) - .matchEquals(CounterOp.INCREMENT, msg -> receiveIncrement()) - .matchEquals(CounterOp.DECREMENT, msg -> receiveDecrement()) - .matchEquals(ReceiveTimeout.getInstance(), msg -> passivate()) - .build(); + .match(Get.class, this::receiveGet) + .matchEquals(CounterOp.INCREMENT, msg -> receiveIncrement()) + .matchEquals(CounterOp.DECREMENT, msg -> receiveDecrement()) + .matchEquals(ReceiveTimeout.getInstance(), msg -> passivate()) + .build(); } private void receiveGet(Get msg) { @@ -234,26 +231,25 @@ public class ClusterShardingTest { } private void passivate() { - getContext().getParent().tell( - new ShardRegion.Passivate(PoisonPill.getInstance()), getSelf()); + getContext().getParent().tell(new ShardRegion.Passivate(PoisonPill.getInstance()), getSelf()); } - } - //#counter-actor + // #counter-actor - static//#supervisor - public class CounterSupervisor extends AbstractActor { + public // #supervisor + static class CounterSupervisor extends AbstractActor { - private final ActorRef counter = getContext().actorOf( - Props.create(Counter.class), "theCounter"); + private final ActorRef counter = + getContext().actorOf(Props.create(Counter.class), "theCounter"); private static final SupervisorStrategy strategy = - new OneForOneStrategy(DeciderBuilder. - match(IllegalArgumentException.class, e -> SupervisorStrategy.resume()). - match(ActorInitializationException.class, e -> SupervisorStrategy.stop()). - match(Exception.class, e -> SupervisorStrategy.restart()). - matchAny(o -> SupervisorStrategy.escalate()).build()); + new OneForOneStrategy( + DeciderBuilder.match(IllegalArgumentException.class, e -> SupervisorStrategy.resume()) + .match(ActorInitializationException.class, e -> SupervisorStrategy.stop()) + .match(Exception.class, e -> SupervisorStrategy.restart()) + .matchAny(o -> SupervisorStrategy.escalate()) + .build()); @Override public SupervisorStrategy supervisorStrategy() { @@ -263,11 +259,10 @@ public class ClusterShardingTest { @Override public Receive createReceive() { return receiveBuilder() - .match(Object.class, msg -> counter.forward(msg, getContext())) - .build(); + .match(Object.class, msg -> counter.forward(msg, getContext())) + .build(); } - } - //#supervisor + // #supervisor } diff --git a/akka-docs/src/test/java/jdocs/stream/ActorPublisherDocTest.java b/akka-docs/src/test/java/jdocs/stream/ActorPublisherDocTest.java index 45d370df89..ba9366850c 100644 --- a/akka-docs/src/test/java/jdocs/stream/ActorPublisherDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/ActorPublisherDocTest.java @@ -40,15 +40,14 @@ public class ActorPublisherDocTest extends AbstractJavaTest { mat = null; } - //#job-manager + // #job-manager public static class JobManagerProtocol { - final public static class Job { + public static final class Job { public final String payload; public Job(String payload) { this.payload = payload; } - } public static class JobAcceptedMessage { @@ -57,6 +56,7 @@ public class ActorPublisherDocTest extends AbstractJavaTest { return "JobAccepted"; } } + public static final JobAcceptedMessage JobAccepted = new JobAcceptedMessage(); public static class JobDeniedMessage { @@ -65,12 +65,15 @@ public class ActorPublisherDocTest extends AbstractJavaTest { return "JobDenied"; } } + public static final JobDeniedMessage JobDenied = new JobDeniedMessage(); } - + public static class JobManager extends AbstractActorPublisher { - public static Props props() { return Props.create(JobManager.class); } + public static Props props() { + return Props.create(JobManager.class); + } private final int MAX_BUFFER_SIZE = 100; private final List buf = new ArrayList<>(); @@ -78,46 +81,50 @@ public class ActorPublisherDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .match(JobManagerProtocol.Job.class, job -> buf.size() == MAX_BUFFER_SIZE, job -> { - getSender().tell(JobManagerProtocol.JobDenied, getSelf()); - }) - .match(JobManagerProtocol.Job.class, job -> { - getSender().tell(JobManagerProtocol.JobAccepted, getSelf()); + .match( + JobManagerProtocol.Job.class, + job -> buf.size() == MAX_BUFFER_SIZE, + job -> { + getSender().tell(JobManagerProtocol.JobDenied, getSelf()); + }) + .match( + JobManagerProtocol.Job.class, + job -> { + getSender().tell(JobManagerProtocol.JobAccepted, getSelf()); - if (buf.isEmpty() && totalDemand() > 0) - onNext(job); - else { - buf.add(job); - deliverBuf(); - } - }) - .match(ActorPublisherMessage.Request.class, request -> deliverBuf()) - .match(ActorPublisherMessage.Cancel.class, cancel -> getContext().stop(getSelf())) - .build(); + if (buf.isEmpty() && totalDemand() > 0) onNext(job); + else { + buf.add(job); + deliverBuf(); + } + }) + .match(ActorPublisherMessage.Request.class, request -> deliverBuf()) + .match(ActorPublisherMessage.Cancel.class, cancel -> getContext().stop(getSelf())) + .build(); } void deliverBuf() { while (totalDemand() > 0) { - /* - * totalDemand is a Long and could be larger than - * what buf.splitAt can accept - */ + /* + * totalDemand is a Long and could be larger than + * what buf.splitAt can accept + */ if (totalDemand() <= Integer.MAX_VALUE) { final List took = - buf.subList(0, Math.min(buf.size(), (int) totalDemand())); + buf.subList(0, Math.min(buf.size(), (int) totalDemand())); took.forEach(this::onNext); buf.removeAll(took); break; } else { final List took = - buf.subList(0, Math.min(buf.size(), Integer.MAX_VALUE)); + buf.subList(0, Math.min(buf.size(), Integer.MAX_VALUE)); took.forEach(this::onNext); buf.removeAll(took); } } } } - //#job-manager + // #job-manager @Test public void demonstrateActorPublisherUsage() { @@ -125,23 +132,25 @@ public class ActorPublisherDocTest extends AbstractJavaTest { private final SilenceSystemOut.System System = SilenceSystemOut.get(getTestActor()); { - //#actor-publisher-usage + // #actor-publisher-usage final Source jobManagerSource = - Source.actorPublisher(JobManager.props()); + Source.actorPublisher(JobManager.props()); - final ActorRef ref = jobManagerSource - .map(job -> job.payload.toUpperCase()) - .map(elem -> { - System.out.println(elem); - return elem; - }) - .to(Sink.ignore()) - .run(mat); + final ActorRef ref = + jobManagerSource + .map(job -> job.payload.toUpperCase()) + .map( + elem -> { + System.out.println(elem); + return elem; + }) + .to(Sink.ignore()) + .run(mat); ref.tell(new JobManagerProtocol.Job("a"), ActorRef.noSender()); ref.tell(new JobManagerProtocol.Job("b"), ActorRef.noSender()); ref.tell(new JobManagerProtocol.Job("c"), ActorRef.noSender()); - //#actor-publisher-usage + // #actor-publisher-usage expectMsgEquals("A"); expectMsgEquals("B"); @@ -149,5 +158,4 @@ public class ActorPublisherDocTest extends AbstractJavaTest { } }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/ActorSubscriberDocTest.java b/akka-docs/src/test/java/jdocs/stream/ActorSubscriberDocTest.java index 3eacff8458..d75c95e803 100644 --- a/akka-docs/src/test/java/jdocs/stream/ActorSubscriberDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/ActorSubscriberDocTest.java @@ -49,162 +49,181 @@ public class ActorSubscriberDocTest extends AbstractJavaTest { mat = null; } - //#worker-pool - public static class WorkerPoolProtocol { + // #worker-pool + public static class WorkerPoolProtocol { - public static class Msg { - public final int id; - public final ActorRef replyTo; + public static class Msg { + public final int id; + public final ActorRef replyTo; - public Msg(int id, ActorRef replyTo) { - this.id = id; - this.replyTo = replyTo; - } - - @Override - public String toString() { - return String.format("Msg(%s, %s)", id, replyTo); - } - } - public static Msg msg(int id, ActorRef replyTo) { - return new Msg(id, replyTo); + public Msg(int id, ActorRef replyTo) { + this.id = id; + this.replyTo = replyTo; } - - public static class Work { - public final int id; - public Work(int id) { this.id = id; } - - @Override - public String toString() { - return String.format("Work(%s)", id); - } + @Override + public String toString() { + return String.format("Msg(%s, %s)", id, replyTo); } - public static Work work(int id) { - return new Work(id); + } + + public static Msg msg(int id, ActorRef replyTo) { + return new Msg(id, replyTo); + } + + public static class Work { + public final int id; + + public Work(int id) { + this.id = id; } - - public static class Reply { - public final int id; - public Reply(int id) { this.id = id; } - - @Override - public String toString() { - return String.format("Reply(%s)", id); - } + @Override + public String toString() { + return String.format("Work(%s)", id); } - public static Reply reply(int id) { - return new Reply(id); + } + + public static Work work(int id) { + return new Work(id); + } + + public static class Reply { + public final int id; + + public Reply(int id) { + this.id = id; } + @Override + public String toString() { + return String.format("Reply(%s)", id); + } + } - public static class Done { - public final int id; - public Done(int id) { this.id = id; } + public static Reply reply(int id) { + return new Reply(id); + } - @Override - public String toString() { - return String.format("Done(%s)", id); - } + public static class Done { + public final int id; - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } + public Done(int id) { + this.id = id; + } - Done done = (Done) o; - - if (id != done.id) { - return false; - } + @Override + public String toString() { + return String.format("Done(%s)", id); + } + @Override + public boolean equals(Object o) { + if (this == o) { return true; } - - @Override - public int hashCode() { - return id; + if (o == null || getClass() != o.getClass()) { + return false; } - } - public static Done done(int id) { - return new Done(id); + + Done done = (Done) o; + + if (id != done.id) { + return false; + } + + return true; } + @Override + public int hashCode() { + return id; + } } - public static class WorkerPool extends AbstractActorSubscriber { + public static Done done(int id) { + return new Done(id); + } + } - public static Props props() { return Props.create(WorkerPool.class); } + public static class WorkerPool extends AbstractActorSubscriber { - final int MAX_QUEUE_SIZE = 10; - final Map queue = new HashMap<>(); + public static Props props() { + return Props.create(WorkerPool.class); + } - final Router router; + final int MAX_QUEUE_SIZE = 10; + final Map queue = new HashMap<>(); - @Override - public RequestStrategy requestStrategy() { - return new MaxInFlightRequestStrategy(MAX_QUEUE_SIZE) { - @Override - public int inFlightInternally() { - return queue.size(); - } - }; - } + final Router router; - public WorkerPool() { - final List routees = new ArrayList<>(); - for (int i = 0; i < 3; i++) - routees.add(new ActorRefRoutee(getContext().actorOf(Props.create(Worker.class)))); - router = new Router(new RoundRobinRoutingLogic(), routees); - } - - @Override - public Receive createReceive() { - return receiveBuilder() - .match(ActorSubscriberMessage.OnNext.class, on -> on.element() instanceof WorkerPoolProtocol.Msg, - onNext -> { - WorkerPoolProtocol.Msg msg = (WorkerPoolProtocol.Msg) onNext.element(); - queue.put(msg.id, msg.replyTo); - - if (queue.size() > MAX_QUEUE_SIZE) - throw new RuntimeException("queued too many: " + queue.size()); - - router.route(WorkerPoolProtocol.work(msg.id), getSelf()); - }) - .match(ActorSubscriberMessage.onCompleteInstance().getClass(), complete -> { - if (queue.isEmpty()) { - getContext().stop(getSelf()); - } - }) - .match(WorkerPoolProtocol.Reply.class, reply -> { - int id = reply.id; - queue.get(id).tell(WorkerPoolProtocol.done(id), getSelf()); - queue.remove(id); - if (canceled() && queue.isEmpty()) { - getContext().stop(getSelf()); - } - }) + @Override + public RequestStrategy requestStrategy() { + return new MaxInFlightRequestStrategy(MAX_QUEUE_SIZE) { + @Override + public int inFlightInternally() { + return queue.size(); + } + }; + } + + public WorkerPool() { + final List routees = new ArrayList<>(); + for (int i = 0; i < 3; i++) + routees.add(new ActorRefRoutee(getContext().actorOf(Props.create(Worker.class)))); + router = new Router(new RoundRobinRoutingLogic(), routees); + } + + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + ActorSubscriberMessage.OnNext.class, + on -> on.element() instanceof WorkerPoolProtocol.Msg, + onNext -> { + WorkerPoolProtocol.Msg msg = (WorkerPoolProtocol.Msg) onNext.element(); + queue.put(msg.id, msg.replyTo); + + if (queue.size() > MAX_QUEUE_SIZE) + throw new RuntimeException("queued too many: " + queue.size()); + + router.route(WorkerPoolProtocol.work(msg.id), getSelf()); + }) + .match( + ActorSubscriberMessage.onCompleteInstance().getClass(), + complete -> { + if (queue.isEmpty()) { + getContext().stop(getSelf()); + } + }) + .match( + WorkerPoolProtocol.Reply.class, + reply -> { + int id = reply.id; + queue.get(id).tell(WorkerPoolProtocol.done(id), getSelf()); + queue.remove(id); + if (canceled() && queue.isEmpty()) { + getContext().stop(getSelf()); + } + }) .build(); - } } + } - static class Worker extends AbstractActor { - @Override - public Receive createReceive() { - return receiveBuilder() - .match(WorkerPoolProtocol.Work.class, work -> { - // ... - getSender().tell(WorkerPoolProtocol.reply(work.id), getSelf()); - }) + static class Worker extends AbstractActor { + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + WorkerPoolProtocol.Work.class, + work -> { + // ... + getSender().tell(WorkerPoolProtocol.reply(work.id), getSelf()); + }) .build(); - } } - //#worker-pool + } + // #worker-pool @Test public void demonstrateActorPublisherUsage() { @@ -213,38 +232,43 @@ public class ActorSubscriberDocTest extends AbstractJavaTest { { final ActorRef replyTo = getTestActor(); - //#actor-subscriber-usage + // #actor-subscriber-usage final int N = 117; final List data = new ArrayList<>(N); for (int i = 0; i < N; i++) { data.add(i); } - final ActorRef worker = Source.from(data) - .map(i -> WorkerPoolProtocol.msg(i, replyTo)) - .runWith(Sink.actorSubscriber(WorkerPool.props()), mat); - //#actor-subscriber-usage + final ActorRef worker = + Source.from(data) + .map(i -> WorkerPoolProtocol.msg(i, replyTo)) + .runWith(Sink.actorSubscriber(WorkerPool.props()), mat); + // #actor-subscriber-usage watch(worker); List got = new ArrayList<>(receiveN(N)); - Collections.sort(got, new Comparator() { - @Override - public int compare(Object o1, Object o2) { - if (o1 instanceof WorkerPoolProtocol.Done && o2 instanceof WorkerPoolProtocol.Done) { - return ((WorkerPoolProtocol.Done) o1).id - ((WorkerPoolProtocol.Done) o2).id; - } else return 0; - } - }); + Collections.sort( + got, + new Comparator() { + @Override + public int compare(Object o1, Object o2) { + if (o1 instanceof WorkerPoolProtocol.Done + && o2 instanceof WorkerPoolProtocol.Done) { + return ((WorkerPoolProtocol.Done) o1).id - ((WorkerPoolProtocol.Done) o2).id; + } else return 0; + } + }); int i = 0; for (; i < N; i++) { - assertEquals(String.format("Expected %d, but got %s", i, got.get(i)), WorkerPoolProtocol.done(i), got.get(i)); + assertEquals( + String.format("Expected %d, but got %s", i, got.get(i)), + WorkerPoolProtocol.done(i), + got.get(i)); } assertEquals(String.format("Expected 117 messages but got %d", i), i, 117); expectTerminated(Duration.ofSeconds(10), worker); } }; } - - } diff --git a/akka-docs/src/test/java/jdocs/stream/BidiFlowDocTest.java b/akka-docs/src/test/java/jdocs/stream/BidiFlowDocTest.java index e61634cdce..0494bf6156 100644 --- a/akka-docs/src/test/java/jdocs/stream/BidiFlowDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/BidiFlowDocTest.java @@ -46,90 +46,99 @@ public class BidiFlowDocTest extends AbstractJavaTest { mat = null; } - //#codec + // #codec static interface Message {} + static class Ping implements Message { final int id; - public Ping(int id) { this.id = id; } + + public Ping(int id) { + this.id = id; + } + @Override public boolean equals(Object o) { if (o instanceof Ping) { return ((Ping) o).id == id; } else return false; } + @Override public int hashCode() { return id; } } + static class Pong implements Message { final int id; - public Pong(int id) { this.id = id; } + + public Pong(int id) { + this.id = id; + } + @Override public boolean equals(Object o) { if (o instanceof Pong) { return ((Pong) o).id == id; } else return false; } + @Override public int hashCode() { return id; } } - - //#codec-impl + + // #codec-impl public static ByteString toBytes(Message msg) { - //#implementation-details-elided + // #implementation-details-elided if (msg instanceof Ping) { final int id = ((Ping) msg).id; - return new ByteStringBuilder().putByte((byte) 1) - .putInt(id, ByteOrder.LITTLE_ENDIAN).result(); + return new ByteStringBuilder().putByte((byte) 1).putInt(id, ByteOrder.LITTLE_ENDIAN).result(); } else { final int id = ((Pong) msg).id; - return new ByteStringBuilder().putByte((byte) 2) - .putInt(id, ByteOrder.LITTLE_ENDIAN).result(); + return new ByteStringBuilder().putByte((byte) 2).putInt(id, ByteOrder.LITTLE_ENDIAN).result(); } - //#implementation-details-elided + // #implementation-details-elided } - + public static Message fromBytes(ByteString bytes) { - //#implementation-details-elided + // #implementation-details-elided final ByteIterator it = bytes.iterator(); - switch(it.getByte()) { - case 1: - return new Ping(it.getInt(ByteOrder.LITTLE_ENDIAN)); - case 2: - return new Pong(it.getInt(ByteOrder.LITTLE_ENDIAN)); - default: - throw new RuntimeException("message format error"); + switch (it.getByte()) { + case 1: + return new Ping(it.getInt(ByteOrder.LITTLE_ENDIAN)); + case 2: + return new Pong(it.getInt(ByteOrder.LITTLE_ENDIAN)); + default: + throw new RuntimeException("message format error"); } - //#implementation-details-elided + // #implementation-details-elided } - //#codec-impl - - //#codec + // #codec-impl + + // #codec @SuppressWarnings("unused") - //#codec + // #codec public final BidiFlow codecVerbose = - BidiFlow.fromGraph(GraphDSL.create(b -> { - final FlowShape top = - b.add(Flow.of(Message.class).map(BidiFlowDocTest::toBytes)); - final FlowShape bottom = - b.add(Flow.of(ByteString.class).map(BidiFlowDocTest::fromBytes)); - return BidiShape.fromFlows(top, bottom); - })); + BidiFlow.fromGraph( + GraphDSL.create( + b -> { + final FlowShape top = + b.add(Flow.of(Message.class).map(BidiFlowDocTest::toBytes)); + final FlowShape bottom = + b.add(Flow.of(ByteString.class).map(BidiFlowDocTest::fromBytes)); + return BidiShape.fromFlows(top, bottom); + })); public final BidiFlow codec = BidiFlow.fromFunctions(BidiFlowDocTest::toBytes, BidiFlowDocTest::fromBytes); - //#codec - - //#framing + // #codec + + // #framing public static ByteString addLengthHeader(ByteString bytes) { final int len = bytes.size(); - return new ByteStringBuilder() - .putInt(len, ByteOrder.LITTLE_ENDIAN) - .append(bytes) - .result(); + return new ByteStringBuilder().putInt(len, ByteOrder.LITTLE_ENDIAN).append(bytes).result(); } public static class FrameParser extends GraphStage> { @@ -152,32 +161,36 @@ public class BidiFlowDocTest extends AbstractJavaTest { private int needed = -1; { - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() throws Exception { - ByteString bytes = grab(in); - stash = stash.concat(bytes); - run(); - } + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() throws Exception { + ByteString bytes = grab(in); + stash = stash.concat(bytes); + run(); + } - @Override - public void onUpstreamFinish() throws Exception { - // either we are done - if (stash.isEmpty()) completeStage(); - // or we still have bytes to emit - // wait with completion and let run() complete when the - // rest of the stash has been sent downstream - else if (isAvailable(out)) run(); - } - }); + @Override + public void onUpstreamFinish() throws Exception { + // either we are done + if (stash.isEmpty()) completeStage(); + // or we still have bytes to emit + // wait with completion and let run() complete when the + // rest of the stash has been sent downstream + else if (isAvailable(out)) run(); + } + }); - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - if (isClosed(in)) run(); - else pull(in); - } - }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + if (isClosed(in)) run(); + else pull(in); + } + }); } private void run() { @@ -207,20 +220,22 @@ public class BidiFlowDocTest extends AbstractJavaTest { }; } } - + public final BidiFlow framing = - BidiFlow.fromGraph(GraphDSL.create(b -> { - final FlowShape top = - b.add(Flow.of(ByteString.class).map(BidiFlowDocTest::addLengthHeader)); - final FlowShape bottom = - b.add(Flow.of(ByteString.class).via(new FrameParser())); - return BidiShape.fromFlows(top, bottom); - })); - //#framing - + BidiFlow.fromGraph( + GraphDSL.create( + b -> { + final FlowShape top = + b.add(Flow.of(ByteString.class).map(BidiFlowDocTest::addLengthHeader)); + final FlowShape bottom = + b.add(Flow.of(ByteString.class).via(new FrameParser())); + return BidiShape.fromFlows(top, bottom); + })); + // #framing + @Test public void mustCompose() throws Exception { - //#compose + // #compose /* construct protocol stack * +------------------------------------+ * | stack | @@ -232,26 +247,23 @@ public class BidiFlowDocTest extends AbstractJavaTest { * | +-------+ +---------+ | * +------------------------------------+ */ - final BidiFlow stack = - codec.atop(framing); + final BidiFlow stack = codec.atop(framing); // test it by plugging it into its own inverse and closing the right end final Flow pingpong = - Flow.of(Message.class).collect(new PFBuilder() - .match(Ping.class, p -> new Pong(p.id)) - .build() - ); - final Flow flow = - stack.atop(stack.reversed()).join(pingpong); - final CompletionStage> result = Source - .from(Arrays.asList(0, 1, 2)) - . map(id -> new Ping(id)) - .via(flow) - .grouped(10) - .runWith(Sink.> head(), mat); + Flow.of(Message.class) + .collect( + new PFBuilder().match(Ping.class, p -> new Pong(p.id)).build()); + final Flow flow = stack.atop(stack.reversed()).join(pingpong); + final CompletionStage> result = + Source.from(Arrays.asList(0, 1, 2)) + .map(id -> new Ping(id)) + .via(flow) + .grouped(10) + .runWith(Sink.>head(), mat); assertArrayEquals( - new Message[] { new Pong(0), new Pong(1), new Pong(2) }, + new Message[] {new Pong(0), new Pong(1), new Pong(2)}, result.toCompletableFuture().get(1, TimeUnit.SECONDS).toArray(new Message[0])); - //#compose + // #compose } } diff --git a/akka-docs/src/test/java/jdocs/stream/CompositionDocTest.java b/akka-docs/src/test/java/jdocs/stream/CompositionDocTest.java index a3ab3e1995..09e819dd1f 100644 --- a/akka-docs/src/test/java/jdocs/stream/CompositionDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/CompositionDocTest.java @@ -44,177 +44,186 @@ public class CompositionDocTest extends AbstractJavaTest { @Test public void nonNestedFlow() throws Exception { - //#non-nested-flow + // #non-nested-flow Source.single(0) - .map(i -> i + 1) - .filter(i -> i != 0) - .map(i -> i - 2) - .to(Sink.fold(0, (acc, i) -> acc + i)); + .map(i -> i + 1) + .filter(i -> i != 0) + .map(i -> i - 2) + .to(Sink.fold(0, (acc, i) -> acc + i)); // ... where is the nesting? - //#non-nested-flow + // #non-nested-flow } @Test public void nestedFlow() throws Exception { - //#nested-flow + // #nested-flow final Source nestedSource = - Source.single(0) // An atomic source - .map(i -> i + 1) // an atomic processing stage - .named("nestedSource"); // wraps up the current Source and gives it a name + Source.single(0) // An atomic source + .map(i -> i + 1) // an atomic processing stage + .named("nestedSource"); // wraps up the current Source and gives it a name final Flow nestedFlow = - Flow.of(Integer.class).filter(i -> i != 0) // an atomic processing stage - .map(i -> i - 2) // another atomic processing stage - .named("nestedFlow"); // wraps up the Flow, and gives it a name + Flow.of(Integer.class) + .filter(i -> i != 0) // an atomic processing stage + .map(i -> i - 2) // another atomic processing stage + .named("nestedFlow"); // wraps up the Flow, and gives it a name final Sink nestedSink = - nestedFlow.to(Sink.fold(0, (acc, i) -> acc + i)) // wire an atomic sink to the nestedFlow - .named("nestedSink"); // wrap it up + nestedFlow + .to(Sink.fold(0, (acc, i) -> acc + i)) // wire an atomic sink to the nestedFlow + .named("nestedSink"); // wrap it up // Create a RunnableGraph final RunnableGraph runnableGraph = nestedSource.to(nestedSink); - //#nested-flow + // #nested-flow } @Test public void reusingComponents() throws Exception { final Source nestedSource = - Source.single(0) // An atomic source - .map(i -> i + 1) // an atomic processing stage - .named("nestedSource"); // wraps up the current Source and gives it a name + Source.single(0) // An atomic source + .map(i -> i + 1) // an atomic processing stage + .named("nestedSource"); // wraps up the current Source and gives it a name final Flow nestedFlow = - Flow.of(Integer.class).filter(i -> i != 0) // an atomic processing stage - .map(i -> i - 2) // another atomic processing stage - .named("nestedFlow"); // wraps up the Flow, and gives it a name + Flow.of(Integer.class) + .filter(i -> i != 0) // an atomic processing stage + .map(i -> i - 2) // another atomic processing stage + .named("nestedFlow"); // wraps up the Flow, and gives it a name final Sink nestedSink = - nestedFlow.to(Sink.fold(0, (acc, i) -> acc + i)) // wire an atomic sink to the nestedFlow - .named("nestedSink"); // wrap it up + nestedFlow + .to(Sink.fold(0, (acc, i) -> acc + i)) // wire an atomic sink to the nestedFlow + .named("nestedSink"); // wrap it up - //#reuse + // #reuse // Create a RunnableGraph from our components final RunnableGraph runnableGraph = nestedSource.to(nestedSink); // Usage is uniform, no matter if modules are composite or atomic final RunnableGraph runnableGraph2 = - Source.single(0).to(Sink.fold(0, (acc, i) -> acc + i)); - //#reuse + Source.single(0).to(Sink.fold(0, (acc, i) -> acc + i)); + // #reuse } @Test public void complexGraph() throws Exception { - //#complex-graph + // #complex-graph RunnableGraph.fromGraph( - GraphDSL.create(builder -> { - final Outlet A = builder.add(Source.single(0)).out(); - final UniformFanOutShape B = builder.add(Broadcast.create(2)); - final UniformFanInShape C = builder.add(Merge.create(2)); - final FlowShape D = - builder.add(Flow.of(Integer.class).map(i -> i + 1)); - final UniformFanOutShape E = builder.add(Balance.create(2)); - final UniformFanInShape F = builder.add(Merge.create(2)); - final Inlet G = builder.add(Sink. foreach(System.out::println)).in(); + GraphDSL.create( + builder -> { + final Outlet A = builder.add(Source.single(0)).out(); + final UniformFanOutShape B = builder.add(Broadcast.create(2)); + final UniformFanInShape C = builder.add(Merge.create(2)); + final FlowShape D = + builder.add(Flow.of(Integer.class).map(i -> i + 1)); + final UniformFanOutShape E = builder.add(Balance.create(2)); + final UniformFanInShape F = builder.add(Merge.create(2)); + final Inlet G = builder.add(Sink.foreach(System.out::println)).in(); - builder.from(F).toFanIn(C); - builder.from(A).viaFanOut(B).viaFanIn(C).toFanIn(F); - builder.from(B).via(D).viaFanOut(E).toFanIn(F); - builder.from(E).toInlet(G); - return ClosedShape.getInstance(); - })); - //#complex-graph + builder.from(F).toFanIn(C); + builder.from(A).viaFanOut(B).viaFanIn(C).toFanIn(F); + builder.from(B).via(D).viaFanOut(E).toFanIn(F); + builder.from(E).toInlet(G); + return ClosedShape.getInstance(); + })); + // #complex-graph - //#complex-graph-alt + // #complex-graph-alt RunnableGraph.fromGraph( - GraphDSL.create(builder -> { - final SourceShape A = builder.add(Source.single(0)); - final UniformFanOutShape B = builder.add(Broadcast.create(2)); - final UniformFanInShape C = builder.add(Merge.create(2)); - final FlowShape D = - builder.add(Flow.of(Integer.class).map(i -> i + 1)); - final UniformFanOutShape E = builder.add(Balance.create(2)); - final UniformFanInShape F = builder.add(Merge.create(2)); - final SinkShape G = builder.add(Sink.foreach(System.out::println)); + GraphDSL.create( + builder -> { + final SourceShape A = builder.add(Source.single(0)); + final UniformFanOutShape B = builder.add(Broadcast.create(2)); + final UniformFanInShape C = builder.add(Merge.create(2)); + final FlowShape D = + builder.add(Flow.of(Integer.class).map(i -> i + 1)); + final UniformFanOutShape E = builder.add(Balance.create(2)); + final UniformFanInShape F = builder.add(Merge.create(2)); + final SinkShape G = builder.add(Sink.foreach(System.out::println)); - builder.from(F.out()).toInlet(C.in(0)); - builder.from(A).toInlet(B.in()); - builder.from(B.out(0)).toInlet(C.in(1)); - builder.from(C.out()).toInlet(F.in(0)); - builder.from(B.out(1)).via(D).toInlet(E.in()); - builder.from(E.out(0)).toInlet(F.in(1)); - builder.from(E.out(1)).to(G); - return ClosedShape.getInstance(); - })); - //#complex-graph-alt + builder.from(F.out()).toInlet(C.in(0)); + builder.from(A).toInlet(B.in()); + builder.from(B.out(0)).toInlet(C.in(1)); + builder.from(C.out()).toInlet(F.in(0)); + builder.from(B.out(1)).via(D).toInlet(E.in()); + builder.from(E.out(0)).toInlet(F.in(1)); + builder.from(E.out(1)).to(G); + return ClosedShape.getInstance(); + })); + // #complex-graph-alt } @Test public void partialGraph() throws Exception { - //#partial-graph + // #partial-graph final Graph, NotUsed> partial = - GraphDSL.create(builder -> { - final UniformFanOutShape B = builder.add(Broadcast.create(2)); - final UniformFanInShape C = builder.add(Merge.create(2)); - final UniformFanOutShape E = builder.add(Balance.create(2)); - final UniformFanInShape F = builder.add(Merge.create(2)); + GraphDSL.create( + builder -> { + final UniformFanOutShape B = builder.add(Broadcast.create(2)); + final UniformFanInShape C = builder.add(Merge.create(2)); + final UniformFanOutShape E = builder.add(Balance.create(2)); + final UniformFanInShape F = builder.add(Merge.create(2)); - builder.from(F.out()).toInlet(C.in(0)); - builder.from(B).viaFanIn(C).toFanIn(F); - builder.from(B).via(builder.add(Flow.of(Integer.class).map(i -> i + 1))).viaFanOut(E).toFanIn(F); + builder.from(F.out()).toInlet(C.in(0)); + builder.from(B).viaFanIn(C).toFanIn(F); + builder + .from(B) + .via(builder.add(Flow.of(Integer.class).map(i -> i + 1))) + .viaFanOut(E) + .toFanIn(F); - return new FlowShape(B.in(), E.out(1)); - }); + return new FlowShape(B.in(), E.out(1)); + }); - //#partial-graph + // #partial-graph - //#partial-use + // #partial-use Source.single(0).via(partial).to(Sink.ignore()); - //#partial-use + // #partial-use - //#partial-flow-dsl + // #partial-flow-dsl // Convert the partial graph of FlowShape to a Flow to get // access to the fluid DSL (for example to be able to call .filter()) final Flow flow = Flow.fromGraph(partial); // Simple way to create a graph backed Source - final Source source = Source.fromGraph( - GraphDSL.create(builder -> { - final UniformFanInShape merge = builder.add(Merge.create(2)); - builder.from(builder.add(Source.single(0))).toFanIn(merge); - builder.from(builder.add(Source.from(Arrays.asList(2, 3, 4)))).toFanIn(merge); - // Exposing exactly one output port - return new SourceShape(merge.out()); - }) - ); + final Source source = + Source.fromGraph( + GraphDSL.create( + builder -> { + final UniformFanInShape merge = builder.add(Merge.create(2)); + builder.from(builder.add(Source.single(0))).toFanIn(merge); + builder.from(builder.add(Source.from(Arrays.asList(2, 3, 4)))).toFanIn(merge); + // Exposing exactly one output port + return new SourceShape(merge.out()); + })); // Building a Sink with a nested Flow, using the fluid DSL - final Sink sink = Flow.of(Integer.class) - .map(i -> i * 2) - .drop(10) - .named("nestedFlow") - .to(Sink.head()); + final Sink sink = + Flow.of(Integer.class).map(i -> i * 2).drop(10).named("nestedFlow").to(Sink.head()); // Putting all together final RunnableGraph closed = source.via(flow.filter(i -> i > 1)).to(sink); - //#partial-flow-dsl + // #partial-flow-dsl } @Test public void closedGraph() throws Exception { - //#embed-closed - final RunnableGraph closed1 = - Source.single(0).to(Sink.foreach(System.out::println)); + // #embed-closed + final RunnableGraph closed1 = Source.single(0).to(Sink.foreach(System.out::println)); final RunnableGraph closed2 = - RunnableGraph.fromGraph( - GraphDSL.create(builder -> { - final ClosedShape embeddedClosed = builder.add(closed1); - return embeddedClosed; // Could return ClosedShape.getInstance() - })); - //#embed-closed + RunnableGraph.fromGraph( + GraphDSL.create( + builder -> { + final ClosedShape embeddedClosed = builder.add(closed1); + return embeddedClosed; // Could return ClosedShape.getInstance() + })); + // #embed-closed } - //#mat-combine-4a + // #mat-combine-4a static class MyClass { private CompletableFuture> p; private OutgoingConnection conn; @@ -230,16 +239,17 @@ public class CompositionDocTest extends AbstractJavaTest { } static class Combiner { - static CompletionStage f(CompletableFuture> p, + static CompletionStage f( + CompletableFuture> p, Pair, CompletionStage> rest) { return rest.first().thenApply(c -> new MyClass(p, c)); } } - //#mat-combine-4a + // #mat-combine-4a @Test public void materializedValues() throws Exception { - //#mat-combine-1 + // #mat-combine-1 // Materializes to CompletableFuture> (red) final Source>> source = Source.maybe(); @@ -248,60 +258,60 @@ public class CompositionDocTest extends AbstractJavaTest { // Materializes to CompletableFuture> (red) final Source>> nestedSource = - source.viaMat(flow1, Keep.left()).named("nestedSource"); - //#mat-combine-1 + source.viaMat(flow1, Keep.left()).named("nestedSource"); + // #mat-combine-1 - //#mat-combine-2 + // #mat-combine-2 // Materializes to NotUsed (orange) - final Flow flow2 = Flow.of(Integer.class) - .map(i -> ByteString.fromString(i.toString())); + final Flow flow2 = + Flow.of(Integer.class).map(i -> ByteString.fromString(i.toString())); // Materializes to Future (yellow) final Flow> flow3 = - Tcp.get(system).outgoingConnection("localhost", 8080); + Tcp.get(system).outgoingConnection("localhost", 8080); // Materializes to Future (yellow) final Flow> nestedFlow = - flow2.viaMat(flow3, Keep.right()).named("nestedFlow"); - //#mat-combine-2 + flow2.viaMat(flow3, Keep.right()).named("nestedFlow"); + // #mat-combine-2 - //#mat-combine-3 + // #mat-combine-3 // Materializes to Future (green) final Sink> sink = - Sink. fold("", (acc, i) -> acc + i.utf8String()); + Sink.fold("", (acc, i) -> acc + i.utf8String()); // Materializes to Pair, Future> (blue) - final Sink, CompletionStage>> nestedSink = - nestedFlow.toMat(sink, Keep.both()); - //#mat-combine-3 + final Sink, CompletionStage>> + nestedSink = nestedFlow.toMat(sink, Keep.both()); + // #mat-combine-3 - //#mat-combine-4b + // #mat-combine-4b // Materializes to Future (purple) final RunnableGraph> runnableGraph = - nestedSource.toMat(nestedSink, Combiner::f); - //#mat-combine-4b + nestedSource.toMat(nestedSink, Combiner::f); + // #mat-combine-4b } @Test public void attributes() throws Exception { - //#attributes-inheritance + // #attributes-inheritance final Source nestedSource = - Source.single(0) - .map(i -> i + 1) - .named("nestedSource"); // Wrap, no inputBuffer set + Source.single(0).map(i -> i + 1).named("nestedSource"); // Wrap, no inputBuffer set final Flow nestedFlow = - Flow.of(Integer.class).filter(i -> i != 0) - .via(Flow.of(Integer.class) - .map(i -> i - 2) - .withAttributes(Attributes.inputBuffer(4, 4))) // override - .named("nestedFlow"); // Wrap, no inputBuffer set + Flow.of(Integer.class) + .filter(i -> i != 0) + .via( + Flow.of(Integer.class) + .map(i -> i - 2) + .withAttributes(Attributes.inputBuffer(4, 4))) // override + .named("nestedFlow"); // Wrap, no inputBuffer set final Sink nestedSink = - nestedFlow.to(Sink.fold(0, (acc, i) -> acc + i)) // wire an atomic sink to the nestedFlow - .withAttributes(Attributes.name("nestedSink") - .and(Attributes.inputBuffer(3, 3))); // override - //#attributes-inheritance + nestedFlow + .to(Sink.fold(0, (acc, i) -> acc + i)) // wire an atomic sink to the nestedFlow + .withAttributes( + Attributes.name("nestedSink").and(Attributes.inputBuffer(3, 3))); // override + // #attributes-inheritance } - } diff --git a/akka-docs/src/test/java/jdocs/stream/FlowDocTest.java b/akka-docs/src/test/java/jdocs/stream/FlowDocTest.java index ac0024f4d7..92ef653a9d 100644 --- a/akka-docs/src/test/java/jdocs/stream/FlowDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/FlowDocTest.java @@ -48,178 +48,177 @@ public class FlowDocTest extends AbstractJavaTest { mat = null; } - @Test - public void sourceIsImmutable() throws Exception { - //#source-immutable - final Source source = - Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); - source.map(x -> 0); // has no effect on source, since it's immutable - source.runWith(Sink.fold(0, (agg, next) -> agg + next), mat); // 55 + @Test + public void sourceIsImmutable() throws Exception { + // #source-immutable + final Source source = + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); + source.map(x -> 0); // has no effect on source, since it's immutable + source.runWith(Sink.fold(0, (agg, next) -> agg + next), mat); // 55 - // returns new Source, with `map()` appended - final Source zeroes = source.map(x -> 0); - final Sink> fold = - Sink. fold(0, (agg, next) -> agg + next); - zeroes.runWith(fold, mat); // 0 - //#source-immutable + // returns new Source, with `map()` appended + final Source zeroes = source.map(x -> 0); + final Sink> fold = + Sink.fold(0, (agg, next) -> agg + next); + zeroes.runWith(fold, mat); // 0 + // #source-immutable - int result = zeroes.runWith(fold, mat).toCompletableFuture().get(3, TimeUnit.SECONDS); - assertEquals(0, result); - } + int result = zeroes.runWith(fold, mat).toCompletableFuture().get(3, TimeUnit.SECONDS); + assertEquals(0, result); + } - @Test - public void materializationInSteps() throws Exception { - //#materialization-in-steps - final Source source = - Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); - // note that the Future is scala.concurrent.Future - final Sink> sink = - Sink. fold(0, (aggr, next) -> aggr + next); + @Test + public void materializationInSteps() throws Exception { + // #materialization-in-steps + final Source source = + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); + // note that the Future is scala.concurrent.Future + final Sink> sink = + Sink.fold(0, (aggr, next) -> aggr + next); - // connect the Source to the Sink, obtaining a RunnableFlow - final RunnableGraph> runnable = - source.toMat(sink, Keep.right()); + // connect the Source to the Sink, obtaining a RunnableFlow + final RunnableGraph> runnable = source.toMat(sink, Keep.right()); - // materialize the flow - final CompletionStage sum = runnable.run(mat); - //#materialization-in-steps + // materialize the flow + final CompletionStage sum = runnable.run(mat); + // #materialization-in-steps - int result = sum.toCompletableFuture().get(3, TimeUnit.SECONDS); - assertEquals(55, result); - } + int result = sum.toCompletableFuture().get(3, TimeUnit.SECONDS); + assertEquals(55, result); + } - @Test - public void materializationRunWith() throws Exception { - //#materialization-runWith - final Source source = - Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); - final Sink> sink = - Sink. fold(0, (aggr, next) -> aggr + next); + @Test + public void materializationRunWith() throws Exception { + // #materialization-runWith + final Source source = + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); + final Sink> sink = + Sink.fold(0, (aggr, next) -> aggr + next); - // materialize the flow, getting the Sinks materialized value - final CompletionStage sum = source.runWith(sink, mat); - //#materialization-runWith + // materialize the flow, getting the Sinks materialized value + final CompletionStage sum = source.runWith(sink, mat); + // #materialization-runWith - int result = sum.toCompletableFuture().get(3, TimeUnit.SECONDS); - assertEquals(55, result); - } + int result = sum.toCompletableFuture().get(3, TimeUnit.SECONDS); + assertEquals(55, result); + } - @Test - public void materializedMapUnique() throws Exception { - //#stream-reuse - // connect the Source to the Sink, obtaining a RunnableGraph - final Sink> sink = - Sink. fold(0, (aggr, next) -> aggr + next); - final RunnableGraph> runnable = - Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).toMat(sink, Keep.right()); + @Test + public void materializedMapUnique() throws Exception { + // #stream-reuse + // connect the Source to the Sink, obtaining a RunnableGraph + final Sink> sink = + Sink.fold(0, (aggr, next) -> aggr + next); + final RunnableGraph> runnable = + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).toMat(sink, Keep.right()); - // get the materialized value of the FoldSink - final CompletionStage sum1 = runnable.run(mat); - final CompletionStage sum2 = runnable.run(mat); + // get the materialized value of the FoldSink + final CompletionStage sum1 = runnable.run(mat); + final CompletionStage sum2 = runnable.run(mat); - // sum1 and sum2 are different Futures! - //#stream-reuse + // sum1 and sum2 are different Futures! + // #stream-reuse - int result1 = sum1.toCompletableFuture().get(3, TimeUnit.SECONDS); - assertEquals(55, result1); - int result2 = sum2.toCompletableFuture().get(3, TimeUnit.SECONDS); - assertEquals(55, result2); - } + int result1 = sum1.toCompletableFuture().get(3, TimeUnit.SECONDS); + assertEquals(55, result1); + int result2 = sum2.toCompletableFuture().get(3, TimeUnit.SECONDS); + assertEquals(55, result2); + } - @Test - @SuppressWarnings("unused") - public void compoundSourceCannotBeUsedAsKey() throws Exception { - //#compound-source-is-not-keyed-runWith - final Object tick = new Object(); + @Test + @SuppressWarnings("unused") + public void compoundSourceCannotBeUsedAsKey() throws Exception { + // #compound-source-is-not-keyed-runWith + final Object tick = new Object(); - final Duration oneSecond = Duration.ofSeconds(1); - //akka.actor.Cancellable - final Source timer = - Source.tick(oneSecond, oneSecond, tick); + final Duration oneSecond = Duration.ofSeconds(1); + // akka.actor.Cancellable + final Source timer = Source.tick(oneSecond, oneSecond, tick); - Sink.ignore().runWith(timer, mat); + Sink.ignore().runWith(timer, mat); - final Source timerMap = timer.map(t -> "tick"); - // WRONG: returned type is not the timers Cancellable! - // Cancellable timerCancellable = Sink.ignore().runWith(timerMap, mat); - //#compound-source-is-not-keyed-runWith + final Source timerMap = timer.map(t -> "tick"); + // WRONG: returned type is not the timers Cancellable! + // Cancellable timerCancellable = Sink.ignore().runWith(timerMap, mat); + // #compound-source-is-not-keyed-runWith - //#compound-source-is-not-keyed-run - // retain the materialized map, in order to retrieve the timer's Cancellable - final Cancellable timerCancellable = timer.to(Sink.ignore()).run(mat); - timerCancellable.cancel(); - //#compound-source-is-not-keyed-run - } + // #compound-source-is-not-keyed-run + // retain the materialized map, in order to retrieve the timer's Cancellable + final Cancellable timerCancellable = timer.to(Sink.ignore()).run(mat); + timerCancellable.cancel(); + // #compound-source-is-not-keyed-run + } - @Test - public void creatingSourcesSinks() throws Exception { - //#source-sink - // Create a source from an Iterable - List list = new LinkedList(); - list.add(1); - list.add(2); - list.add(3); - Source.from(list); + @Test + public void creatingSourcesSinks() throws Exception { + // #source-sink + // Create a source from an Iterable + List list = new LinkedList(); + list.add(1); + list.add(2); + list.add(3); + Source.from(list); - // Create a source form a Future - Source.fromFuture(Futures.successful("Hello Streams!")); + // Create a source form a Future + Source.fromFuture(Futures.successful("Hello Streams!")); - // Create a source from a single element - Source.single("only one element"); + // Create a source from a single element + Source.single("only one element"); - // an empty source - Source.empty(); + // an empty source + Source.empty(); - // Sink that folds over the stream and returns a Future - // of the final result in the MaterializedMap - Sink.fold(0, (Integer aggr, Integer next) -> aggr + next); + // Sink that folds over the stream and returns a Future + // of the final result in the MaterializedMap + Sink.fold(0, (Integer aggr, Integer next) -> aggr + next); - // Sink that returns a Future in the MaterializedMap, - // containing the first element of the stream - Sink.head(); + // Sink that returns a Future in the MaterializedMap, + // containing the first element of the stream + Sink.head(); - // A Sink that consumes a stream without doing anything with the elements - Sink.ignore(); + // A Sink that consumes a stream without doing anything with the elements + Sink.ignore(); - // A Sink that executes a side-effecting call for every element of the stream - Sink.foreach(System.out::println); - //#source-sink - } + // A Sink that executes a side-effecting call for every element of the stream + Sink.foreach(System.out::println); + // #source-sink + } - @Test - public void variousWaysOfConnecting() throws Exception { - //#flow-connecting - // Explicitly creating and wiring up a Source, Sink and Flow - Source.from(Arrays.asList(1, 2, 3, 4)) + @Test + public void variousWaysOfConnecting() throws Exception { + // #flow-connecting + // Explicitly creating and wiring up a Source, Sink and Flow + Source.from(Arrays.asList(1, 2, 3, 4)) .via(Flow.of(Integer.class).map(elem -> elem * 2)) .to(Sink.foreach(System.out::println)); - // Starting from a Source - final Source source = Source.from(Arrays.asList(1, 2, 3, 4)) - .map(elem -> elem * 2); - source.to(Sink.foreach(System.out::println)); + // Starting from a Source + final Source source = + Source.from(Arrays.asList(1, 2, 3, 4)).map(elem -> elem * 2); + source.to(Sink.foreach(System.out::println)); - // Starting from a Sink - final Sink sink = Flow.of(Integer.class) - .map(elem -> elem * 2).to(Sink.foreach(System.out::println)); - Source.from(Arrays.asList(1, 2, 3, 4)).to(sink); - //#flow-connecting - } + // Starting from a Sink + final Sink sink = + Flow.of(Integer.class).map(elem -> elem * 2).to(Sink.foreach(System.out::println)); + Source.from(Arrays.asList(1, 2, 3, 4)).to(sink); + // #flow-connecting + } @Test public void transformingMaterialized() throws Exception { Duration oneSecond = Duration.ofSeconds(1); Flow throttler = - Flow.fromGraph(GraphDSL.create( - Source.tick(oneSecond, oneSecond, ""), - (b, tickSource) -> { - FanInShape2 zip = b.add(ZipWith.create(Keep.right())); - b.from(tickSource).toInlet(zip.in0()); - return FlowShape.of(zip.in1(), zip.out()); - })); + Flow.fromGraph( + GraphDSL.create( + Source.tick(oneSecond, oneSecond, ""), + (b, tickSource) -> { + FanInShape2 zip = b.add(ZipWith.create(Keep.right())); + b.from(tickSource).toInlet(zip.in0()); + return FlowShape.of(zip.in1(), zip.out()); + })); - //#flow-mat-combine + // #flow-mat-combine // An empty source that can be shut down explicitly from the outside Source>> source = Source.maybe(); @@ -231,7 +230,6 @@ public class FlowDocTest extends AbstractJavaTest { // A sink that returns the first element of a stream in the returned Future Sink> sink = Sink.head(); - // By default, the materialized value of the leftmost stage is preserved RunnableGraph>> r1 = source.via(flow).to(sink); @@ -243,42 +241,43 @@ public class FlowDocTest extends AbstractJavaTest { // by runWith() itself CompletionStage r4 = source.via(flow).runWith(sink, mat); CompletableFuture> r5 = flow.to(sink).runWith(source, mat); - Pair>, CompletionStage> r6 = flow.runWith(source, sink, mat); + Pair>, CompletionStage> r6 = + flow.runWith(source, sink, mat); // Using more complex combinations RunnableGraph>, Cancellable>> r7 = - source.viaMat(flow, Keep.both()).to(sink); + source.viaMat(flow, Keep.both()).to(sink); RunnableGraph>, CompletionStage>> r8 = - source.via(flow).toMat(sink, Keep.both()); + source.via(flow).toMat(sink, Keep.both()); - RunnableGraph>, Cancellable>, CompletionStage>> r9 = - source.viaMat(flow, Keep.both()).toMat(sink, Keep.both()); + RunnableGraph< + Pair>, Cancellable>, CompletionStage>> + r9 = source.viaMat(flow, Keep.both()).toMat(sink, Keep.both()); RunnableGraph>> r10 = - source.viaMat(flow, Keep.right()).toMat(sink, Keep.both()); + source.viaMat(flow, Keep.right()).toMat(sink, Keep.both()); // It is also possible to map over the materialized values. In r9 we had a // doubly nested pair, but we want to flatten it out - RunnableGraph r11 = - r9.mapMaterializedValue( (nestedTuple) -> { - CompletableFuture> p = nestedTuple.first().first(); - Cancellable c = nestedTuple.first().second(); - CompletionStage f = nestedTuple.second(); + r9.mapMaterializedValue( + (nestedTuple) -> { + CompletableFuture> p = nestedTuple.first().first(); + Cancellable c = nestedTuple.first().second(); + CompletionStage f = nestedTuple.second(); - // Picking the Cancellable, but we could also construct a domain class here - return c; - }); - //#flow-mat-combine + // Picking the Cancellable, but we could also construct a domain class here + return c; + }); + // #flow-mat-combine } @Test public void sourcePreMaterialization() { - //#source-prematerialization - Source matValuePoweredSource = - Source.actorRef(100, OverflowStrategy.fail()); + // #source-prematerialization + Source matValuePoweredSource = Source.actorRef(100, OverflowStrategy.fail()); Pair> actorRefSourcePair = matValuePoweredSource.preMaterialize(mat); @@ -287,76 +286,85 @@ public class FlowDocTest extends AbstractJavaTest { // pass source around for materialization actorRefSourcePair.second().runWith(Sink.foreach(System.out::println), mat); - //#source-prematerialization + // #source-prematerialization } public void fusingAndAsync() { - //#flow-async - Source.range(1, 3) - .map(x -> x + 1).async() - .map(x -> x * 2) - .to(Sink.ignore()); - //#flow-async + // #flow-async + Source.range(1, 3).map(x -> x + 1).async().map(x -> x * 2).to(Sink.ignore()); + // #flow-async } - static { - //#materializer-from-system - ActorSystem system = ActorSystem.create("ExampleSystem"); + static { + // #materializer-from-system + ActorSystem system = ActorSystem.create("ExampleSystem"); - // created from `system`: - ActorMaterializer mat = ActorMaterializer.create(system); - //#materializer-from-system + // created from `system`: + ActorMaterializer mat = ActorMaterializer.create(system); + // #materializer-from-system + } + + // #materializer-from-actor-context + final class RunWithMyself extends AbstractActor { + + ActorMaterializer mat = ActorMaterializer.create(context()); + + @Override + public void preStart() throws Exception { + Source.repeat("hello") + .runWith( + Sink.onComplete( + tryDone -> { + System.out.println("Terminated stream: " + tryDone); + }), + mat); } - //#materializer-from-actor-context - final class RunWithMyself extends AbstractActor { - - ActorMaterializer mat = ActorMaterializer.create(context()); - - @Override - public void preStart() throws Exception { - Source - .repeat("hello") - .runWith(Sink.onComplete(tryDone -> { - System.out.println("Terminated stream: " + tryDone); - }), mat); - } - - @Override - public Receive createReceive() { - return receiveBuilder().match(String.class, p -> { + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + String.class, + p -> { // this WILL terminate the above stream as well context().stop(self()); - }).build(); - } + }) + .build(); } - //#materializer-from-actor-context + } + // #materializer-from-actor-context - //#materializer-from-system-in-actor - final class RunForever extends AbstractActor { - final ActorMaterializer mat; + // #materializer-from-system-in-actor + final class RunForever extends AbstractActor { + final ActorMaterializer mat; - RunForever(ActorMaterializer mat) { - this.mat = mat; - } + RunForever(ActorMaterializer mat) { + this.mat = mat; + } - @Override - public void preStart() throws Exception { - Source - .repeat("hello") - .runWith(Sink.onComplete(tryDone -> { - System.out.println("Terminated stream: " + tryDone); - }), mat); - } + @Override + public void preStart() throws Exception { + Source.repeat("hello") + .runWith( + Sink.onComplete( + tryDone -> { + System.out.println("Terminated stream: " + tryDone); + }), + mat); + } - @Override - public Receive createReceive() { - return receiveBuilder().match(String.class, p -> { + @Override + public Receive createReceive() { + return receiveBuilder() + .match( + String.class, + p -> { // will NOT terminate the stream (it's bound to the system!) context().stop(self()); - }).build(); - } - //#materializer-from-system-in-actor - + }) + .build(); } + // #materializer-from-system-in-actor + + } } diff --git a/akka-docs/src/test/java/jdocs/stream/FlowErrorDocTest.java b/akka-docs/src/test/java/jdocs/stream/FlowErrorDocTest.java index 7abb892429..d7d63d1fca 100644 --- a/akka-docs/src/test/java/jdocs/stream/FlowErrorDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/FlowErrorDocTest.java @@ -36,168 +36,166 @@ public class FlowErrorDocTest extends AbstractJavaTest { @BeforeClass public static void setup() { - system = ActorSystem.create("FlowDocTest"); + system = ActorSystem.create("FlowDocTest"); } @AfterClass public static void tearDown() { - TestKit.shutdownActorSystem(system); - system = null; + TestKit.shutdownActorSystem(system); + system = null; } - + @Test(expected = ExecutionException.class) public void demonstrateFailStream() throws Exception { - //#stop + // #stop final Materializer mat = ActorMaterializer.create(system); - final Source source = Source.from(Arrays.asList(0, 1, 2, 3, 4, 5)) - .map(elem -> 100 / elem); + final Source source = + Source.from(Arrays.asList(0, 1, 2, 3, 4, 5)).map(elem -> 100 / elem); final Sink> fold = - Sink. fold(0, (acc, elem) -> acc + elem); + Sink.fold(0, (acc, elem) -> acc + elem); final CompletionStage result = source.runWith(fold, mat); // division by zero will fail the stream and the // result here will be a Future completed with Failure(ArithmeticException) - //#stop + // #stop result.toCompletableFuture().get(3, TimeUnit.SECONDS); } @Test public void demonstrateResumeStream() throws Exception { - //#resume - final Function decider = exc -> { - if (exc instanceof ArithmeticException) - return Supervision.resume(); - else - return Supervision.stop(); - }; - final Materializer mat = ActorMaterializer.create( - ActorMaterializerSettings.create(system).withSupervisionStrategy(decider), - system); - final Source source = Source.from(Arrays.asList(0, 1, 2, 3, 4, 5)) - .map(elem -> 100 / elem); - final Sink> fold = - Sink.fold(0, (acc, elem) -> acc + elem); + // #resume + final Function decider = + exc -> { + if (exc instanceof ArithmeticException) return Supervision.resume(); + else return Supervision.stop(); + }; + final Materializer mat = + ActorMaterializer.create( + ActorMaterializerSettings.create(system).withSupervisionStrategy(decider), system); + final Source source = + Source.from(Arrays.asList(0, 1, 2, 3, 4, 5)).map(elem -> 100 / elem); + final Sink> fold = Sink.fold(0, (acc, elem) -> acc + elem); final CompletionStage result = source.runWith(fold, mat); // the element causing division by zero will be dropped // result here will be a Future completed with Success(228) - //#resume + // #resume assertEquals(Integer.valueOf(228), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); } @Test public void demonstrateResumeSectionStream() throws Exception { - //#resume-section + // #resume-section final Materializer mat = ActorMaterializer.create(system); - final Function decider = exc -> { - if (exc instanceof ArithmeticException) - return Supervision.resume(); - else - return Supervision.stop(); - }; + final Function decider = + exc -> { + if (exc instanceof ArithmeticException) return Supervision.resume(); + else return Supervision.stop(); + }; final Flow flow = - Flow.of(Integer.class).filter(elem -> 100 / elem < 50).map(elem -> 100 / (5 - elem)) - .withAttributes(ActorAttributes.withSupervisionStrategy(decider)); - final Source source = Source.from(Arrays.asList(0, 1, 2, 3, 4, 5)) - .via(flow); + Flow.of(Integer.class) + .filter(elem -> 100 / elem < 50) + .map(elem -> 100 / (5 - elem)) + .withAttributes(ActorAttributes.withSupervisionStrategy(decider)); + final Source source = Source.from(Arrays.asList(0, 1, 2, 3, 4, 5)).via(flow); final Sink> fold = - Sink. fold(0, (acc, elem) -> acc + elem); + Sink.fold(0, (acc, elem) -> acc + elem); final CompletionStage result = source.runWith(fold, mat); // the elements causing division by zero will be dropped // result here will be a Future completed with Success(150) - //#resume-section + // #resume-section assertEquals(Integer.valueOf(150), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); } @Test public void demonstrateRestartSectionStream() throws Exception { - //#restart-section + // #restart-section final Materializer mat = ActorMaterializer.create(system); - final Function decider = exc -> { - if (exc instanceof IllegalArgumentException) - return Supervision.restart(); - else - return Supervision.stop(); - }; + final Function decider = + exc -> { + if (exc instanceof IllegalArgumentException) return Supervision.restart(); + else return Supervision.stop(); + }; final Flow flow = - Flow.of(Integer.class).scan(0, (acc, elem) -> { - if (elem < 0) throw new IllegalArgumentException("negative not allowed"); - else return acc + elem; - }) - .withAttributes(ActorAttributes.withSupervisionStrategy(decider)); - final Source source = Source.from(Arrays.asList(1, 3, -1, 5, 7)) - .via(flow); - final CompletionStage> result = source.grouped(1000) - .runWith(Sink.>head(), mat); + Flow.of(Integer.class) + .scan( + 0, + (acc, elem) -> { + if (elem < 0) throw new IllegalArgumentException("negative not allowed"); + else return acc + elem; + }) + .withAttributes(ActorAttributes.withSupervisionStrategy(decider)); + final Source source = Source.from(Arrays.asList(1, 3, -1, 5, 7)).via(flow); + final CompletionStage> result = + source.grouped(1000).runWith(Sink.>head(), mat); // the negative element cause the scan stage to be restarted, // i.e. start from 0 again // result here will be a Future completed with Success(List(0, 1, 4, 0, 5, 12)) - //#restart-section - + // #restart-section + assertEquals( - Arrays.asList(0, 1, 4, 0, 5, 12), - result.toCompletableFuture().get(3, TimeUnit.SECONDS)); + Arrays.asList(0, 1, 4, 0, 5, 12), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); } @Test public void demonstrateRecover() { - //#recover + // #recover final Materializer mat = ActorMaterializer.create(system); - Source.from(Arrays.asList(0, 1, 2, 3, 4, 5, 6)).map(n -> { - if (n < 5) return n.toString(); - else throw new RuntimeException("Boom!"); - }).recover(new PFBuilder() - .match(RuntimeException.class, ex -> "stream truncated") - .build() - ).runForeach(System.out::println, mat); - //#recover + Source.from(Arrays.asList(0, 1, 2, 3, 4, 5, 6)) + .map( + n -> { + if (n < 5) return n.toString(); + else throw new RuntimeException("Boom!"); + }) + .recover(new PFBuilder().match(RuntimeException.class, ex -> "stream truncated").build()) + .runForeach(System.out::println, mat); + // #recover -/* -Output: -//#recover-output -0 -1 -2 -3 -4 -stream truncated -//#recover-output -*/ + /* + Output: + //#recover-output + 0 + 1 + 2 + 3 + 4 + stream truncated + //#recover-output + */ } @Test - public void demonstrateRecoverWithRetries() { - //#recoverWithRetries + public void demonstrateRecoverWithRetries() { + // #recoverWithRetries final Materializer mat = ActorMaterializer.create(system); Source planB = Source.from(Arrays.asList("five", "six", "seven", "eight")); - Source.from(Arrays.asList(0, 1, 2, 3, 4, 5, 6)).map(n -> { - if (n < 5) return n.toString(); - else throw new RuntimeException("Boom!"); - }).recoverWithRetries( - 1, // max attempts - new PFBuilder() - .match(RuntimeException.class, ex -> planB) - .build() - ).runForeach(System.out::println, mat); - //#recoverWithRetries + Source.from(Arrays.asList(0, 1, 2, 3, 4, 5, 6)) + .map( + n -> { + if (n < 5) return n.toString(); + else throw new RuntimeException("Boom!"); + }) + .recoverWithRetries( + 1, // max attempts + new PFBuilder().match(RuntimeException.class, ex -> planB).build()) + .runForeach(System.out::println, mat); + // #recoverWithRetries -/* -Output: -//#recoverWithRetries-output -0 -1 -2 -3 -4 -five -six -seven -eight -//#recoverWithRetries-output - */ + /* + Output: + //#recoverWithRetries-output + 0 + 1 + 2 + 3 + 4 + five + six + seven + eight + //#recoverWithRetries-output + */ } - - } diff --git a/akka-docs/src/test/java/jdocs/stream/FlowParallelismDocTest.java b/akka-docs/src/test/java/jdocs/stream/FlowParallelismDocTest.java index 8ceb744d57..d009f60912 100644 --- a/akka-docs/src/test/java/jdocs/stream/FlowParallelismDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/FlowParallelismDocTest.java @@ -4,7 +4,6 @@ package jdocs.stream; - import static org.junit.Assert.assertEquals; import akka.NotUsed; @@ -36,115 +35,137 @@ public class FlowParallelismDocTest extends AbstractJavaTest { } static class ScoopOfBatter {} + static class HalfCookedPancake {} + static class Pancake {} - //#pipelining - Flow fryingPan1 = + // #pipelining + Flow fryingPan1 = Flow.of(ScoopOfBatter.class).map(batter -> new HalfCookedPancake()); - Flow fryingPan2 = + Flow fryingPan2 = Flow.of(HalfCookedPancake.class).map(halfCooked -> new Pancake()); - //#pipelining + // #pipelining @Test public void demonstratePipelining() { - //#pipelining + // #pipelining // With the two frying pans we can fully cook pancakes - Flow pancakeChef = - fryingPan1.async().via(fryingPan2.async()); - //#pipelining + Flow pancakeChef = fryingPan1.async().via(fryingPan2.async()); + // #pipelining } @Test public void demonstrateParallelism() { - //#parallelism + // #parallelism Flow fryingPan = - Flow.of(ScoopOfBatter.class).map(batter -> new Pancake()); + Flow.of(ScoopOfBatter.class).map(batter -> new Pancake()); Flow pancakeChef = - Flow.fromGraph(GraphDSL.create(b -> { - final UniformFanInShape mergePancakes = - b.add(Merge.create(2)); - final UniformFanOutShape dispatchBatter = - b.add(Balance.create(2)); + Flow.fromGraph( + GraphDSL.create( + b -> { + final UniformFanInShape mergePancakes = b.add(Merge.create(2)); + final UniformFanOutShape dispatchBatter = + b.add(Balance.create(2)); - // Using two frying pans in parallel, both fully cooking a pancake from the batter. - // We always put the next scoop of batter to the first frying pan that becomes available. - b.from(dispatchBatter.out(0)).via(b.add(fryingPan.async())).toInlet(mergePancakes.in(0)); - // Notice that we used the "fryingPan" flow without importing it via builder.add(). - // Flows used this way are auto-imported, which in this case means that the two - // uses of "fryingPan" mean actually different stages in the graph. - b.from(dispatchBatter.out(1)).via(b.add(fryingPan.async())).toInlet(mergePancakes.in(1)); + // Using two frying pans in parallel, both fully cooking a pancake from the + // batter. + // We always put the next scoop of batter to the first frying pan that becomes + // available. + b.from(dispatchBatter.out(0)) + .via(b.add(fryingPan.async())) + .toInlet(mergePancakes.in(0)); + // Notice that we used the "fryingPan" flow without importing it via + // builder.add(). + // Flows used this way are auto-imported, which in this case means that the two + // uses of "fryingPan" mean actually different stages in the graph. + b.from(dispatchBatter.out(1)) + .via(b.add(fryingPan.async())) + .toInlet(mergePancakes.in(1)); - return FlowShape.of(dispatchBatter.in(), mergePancakes.out()); - })); - //#parallelism + return FlowShape.of(dispatchBatter.in(), mergePancakes.out()); + })); + // #parallelism } @Test public void parallelPipeline() { - //#parallel-pipeline + // #parallel-pipeline Flow pancakeChef = - Flow.fromGraph(GraphDSL.create(b -> { - final UniformFanInShape mergePancakes = - b.add(Merge.create(2)); - final UniformFanOutShape dispatchBatter = - b.add(Balance.create(2)); + Flow.fromGraph( + GraphDSL.create( + b -> { + final UniformFanInShape mergePancakes = b.add(Merge.create(2)); + final UniformFanOutShape dispatchBatter = + b.add(Balance.create(2)); - // Using two pipelines, having two frying pans each, in total using - // four frying pans - b.from(dispatchBatter.out(0)) - .via(b.add(fryingPan1.async())) - .via(b.add(fryingPan2.async())) - .toInlet(mergePancakes.in(0)); + // Using two pipelines, having two frying pans each, in total using + // four frying pans + b.from(dispatchBatter.out(0)) + .via(b.add(fryingPan1.async())) + .via(b.add(fryingPan2.async())) + .toInlet(mergePancakes.in(0)); - b.from(dispatchBatter.out(1)) - .via(b.add(fryingPan1.async())) - .via(b.add(fryingPan2.async())) - .toInlet(mergePancakes.in(1)); + b.from(dispatchBatter.out(1)) + .via(b.add(fryingPan1.async())) + .via(b.add(fryingPan2.async())) + .toInlet(mergePancakes.in(1)); - return FlowShape.of(dispatchBatter.in(), mergePancakes.out()); - })); - //#parallel-pipeline + return FlowShape.of(dispatchBatter.in(), mergePancakes.out()); + })); + // #parallel-pipeline } @Test public void pipelinedParallel() { - //#pipelined-parallel + // #pipelined-parallel Flow pancakeChefs1 = - Flow.fromGraph(GraphDSL.create(b -> { - final UniformFanInShape mergeHalfCooked = - b.add(Merge.create(2)); - final UniformFanOutShape dispatchBatter = - b.add(Balance.create(2)); + Flow.fromGraph( + GraphDSL.create( + b -> { + final UniformFanInShape mergeHalfCooked = + b.add(Merge.create(2)); + final UniformFanOutShape dispatchBatter = + b.add(Balance.create(2)); - // Two chefs work with one frying pan for each, half-frying the pancakes then putting - // them into a common pool - b.from(dispatchBatter.out(0)).via(b.add(fryingPan1.async())).toInlet(mergeHalfCooked.in(0)); - b.from(dispatchBatter.out(1)).via(b.add(fryingPan1.async())).toInlet(mergeHalfCooked.in(1)); + // Two chefs work with one frying pan for each, half-frying the pancakes then + // putting + // them into a common pool + b.from(dispatchBatter.out(0)) + .via(b.add(fryingPan1.async())) + .toInlet(mergeHalfCooked.in(0)); + b.from(dispatchBatter.out(1)) + .via(b.add(fryingPan1.async())) + .toInlet(mergeHalfCooked.in(1)); - return FlowShape.of(dispatchBatter.in(), mergeHalfCooked.out()); - })); + return FlowShape.of(dispatchBatter.in(), mergeHalfCooked.out()); + })); Flow pancakeChefs2 = - Flow.fromGraph(GraphDSL.create(b -> { - final UniformFanInShape mergePancakes = - b.add(Merge.create(2)); - final UniformFanOutShape dispatchHalfCooked = - b.add(Balance.create(2)); + Flow.fromGraph( + GraphDSL.create( + b -> { + final UniformFanInShape mergePancakes = b.add(Merge.create(2)); + final UniformFanOutShape + dispatchHalfCooked = b.add(Balance.create(2)); - // Two chefs work with one frying pan for each, finishing the pancakes then putting - // them into a common pool - b.from(dispatchHalfCooked.out(0)).via(b.add(fryingPan2.async())).toInlet(mergePancakes.in(0)); - b.from(dispatchHalfCooked.out(1)).via(b.add(fryingPan2.async())).toInlet(mergePancakes.in(1)); + // Two chefs work with one frying pan for each, finishing the pancakes then + // putting + // them into a common pool + b.from(dispatchHalfCooked.out(0)) + .via(b.add(fryingPan2.async())) + .toInlet(mergePancakes.in(0)); + b.from(dispatchHalfCooked.out(1)) + .via(b.add(fryingPan2.async())) + .toInlet(mergePancakes.in(1)); - return FlowShape.of(dispatchHalfCooked.in(), mergePancakes.out()); - })); + return FlowShape.of(dispatchHalfCooked.in(), mergePancakes.out()); + })); - Flow kitchen = - pancakeChefs1.via(pancakeChefs2); - //#pipelined-parallel + Flow kitchen = pancakeChefs1.via(pancakeChefs2); + // #pipelined-parallel } } diff --git a/akka-docs/src/test/java/jdocs/stream/FlowStreamRefsDocTest.java b/akka-docs/src/test/java/jdocs/stream/FlowStreamRefsDocTest.java index 001a9d6194..9ff432412b 100644 --- a/akka-docs/src/test/java/jdocs/stream/FlowStreamRefsDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/FlowStreamRefsDocTest.java @@ -30,7 +30,7 @@ public class FlowStreamRefsDocTest extends AbstractJavaTest { // do nothing } - //#offer-source + // #offer-source static class RequestLogs { public final long streamId; @@ -50,9 +50,7 @@ public class FlowStreamRefsDocTest extends AbstractJavaTest { static class DataSource extends AbstractActor { @Override public Receive createReceive() { - return receiveBuilder() - .match(RequestLogs.class, this::handleRequestLogs) - .build(); + return receiveBuilder().match(RequestLogs.class, this::handleRequestLogs).build(); } private void handleRequestLogs(RequestLogs requestLogs) { @@ -67,25 +65,26 @@ public class FlowStreamRefsDocTest extends AbstractJavaTest { return Source.repeat("[INFO] some interesting logs here (for id: " + streamId + ")"); } } - //#offer-source + // #offer-source public void offerSource() { - new TestKit(system) {{ + new TestKit(system) { + { - //#offer-source-use - ActorRef sourceActor = system.actorOf(Props.create(DataSource.class), "dataSource"); + // #offer-source-use + ActorRef sourceActor = system.actorOf(Props.create(DataSource.class), "dataSource"); - sourceActor.tell(new RequestLogs(1337), getTestActor()); - LogsOffer offer = expectMsgClass(LogsOffer.class); + sourceActor.tell(new RequestLogs(1337), getTestActor()); + LogsOffer offer = expectMsgClass(LogsOffer.class); - offer.sourceRef.getSource() - .runWith(Sink.foreach(log -> System.out.println(log)), mat); + offer.sourceRef.getSource().runWith(Sink.foreach(log -> System.out.println(log)), mat); - //#offer-source-use - }}; + // #offer-source-use + } + }; } - //#offer-sink + // #offer-sink static class PrepareUpload { final String id; @@ -93,6 +92,7 @@ public class FlowStreamRefsDocTest extends AbstractJavaTest { this.id = id; } } + static class MeasurementsSinkReady { final String id; final SinkRef sinkRef; @@ -107,13 +107,18 @@ public class FlowStreamRefsDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .match(PrepareUpload.class, prepare -> { - Sink sink = logsSinkFor(prepare.id); - CompletionStage> sinkRef = StreamRefs.sinkRef().to(sink).run(mat); + .match( + PrepareUpload.class, + prepare -> { + Sink sink = logsSinkFor(prepare.id); + CompletionStage> sinkRef = + StreamRefs.sinkRef().to(sink).run(mat); - Patterns.pipe(sinkRef.thenApply(ref -> new MeasurementsSinkReady(prepare.id, ref)), context().dispatcher()) - .to(sender()); - }) + Patterns.pipe( + sinkRef.thenApply(ref -> new MeasurementsSinkReady(prepare.id, ref)), + context().dispatcher()) + .to(sender()); + }) .build(); } @@ -121,40 +126,43 @@ public class FlowStreamRefsDocTest extends AbstractJavaTest { return Sink.ignore().mapMaterializedValue(done -> NotUsed.getInstance()); } } - //#offer-sink + // #offer-sink public void offerSink() { - new TestKit(system) {{ + new TestKit(system) { + { - //#offer-sink-use - ActorRef receiver = system.actorOf(Props.create(DataReceiver.class), "dataReceiver"); + // #offer-sink-use + ActorRef receiver = system.actorOf(Props.create(DataReceiver.class), "dataReceiver"); - receiver.tell(new PrepareUpload("system-42-tmp"), getTestActor()); - MeasurementsSinkReady ready = expectMsgClass(MeasurementsSinkReady.class); + receiver.tell(new PrepareUpload("system-42-tmp"), getTestActor()); + MeasurementsSinkReady ready = expectMsgClass(MeasurementsSinkReady.class); - Source.repeat("hello") - .runWith(ready.sinkRef.getSink(), mat); - //#offer-sink-use - }}; + Source.repeat("hello").runWith(ready.sinkRef.getSink(), mat); + // #offer-sink-use + } + }; } public void configureTimeouts() { - new TestKit(system) {{ + new TestKit(system) { + { - //#attr-sub-timeout - FiniteDuration timeout = FiniteDuration.create(5, TimeUnit.SECONDS); - Attributes timeoutAttributes = StreamRefAttributes.subscriptionTimeout(timeout); + // #attr-sub-timeout + FiniteDuration timeout = FiniteDuration.create(5, TimeUnit.SECONDS); + Attributes timeoutAttributes = StreamRefAttributes.subscriptionTimeout(timeout); - // configuring Sink.sourceRef (notice that we apply the attributes to the Sink!): - Source.repeat("hello") - .runWith(StreamRefs.sourceRef().addAttributes(timeoutAttributes), mat); + // configuring Sink.sourceRef (notice that we apply the attributes to the Sink!): + Source.repeat("hello") + .runWith(StreamRefs.sourceRef().addAttributes(timeoutAttributes), mat); - // configuring SinkRef.source: - StreamRefs.sinkRef().addAttributes(timeoutAttributes) - .runWith(Sink.ignore(), mat); // not very interesting sink, just an example + // configuring SinkRef.source: + StreamRefs.sinkRef() + .addAttributes(timeoutAttributes) + .runWith(Sink.ignore(), mat); // not very interesting sink, just an example - //#attr-sub-timeout - }}; + // #attr-sub-timeout + } + }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/GraphCyclesDocTest.java b/akka-docs/src/test/java/jdocs/stream/GraphCyclesDocTest.java index 7edc237dcc..8c93c15fca 100644 --- a/akka-docs/src/test/java/jdocs/stream/GraphCyclesDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/GraphCyclesDocTest.java @@ -18,7 +18,6 @@ import akka.stream.*; import akka.stream.javadsl.*; import akka.stream.scaladsl.MergePreferred.MergePreferredShape; - public class GraphCyclesDocTest extends AbstractJavaTest { static ActorSystem system; @@ -37,128 +36,147 @@ public class GraphCyclesDocTest extends AbstractJavaTest { mat = null; } - final static SilenceSystemOut.System System = SilenceSystemOut.get(); + static final SilenceSystemOut.System System = SilenceSystemOut.get(); final Source source = Source.from(Arrays.asList(1, 2, 3, 4, 5)); @Test public void demonstrateDeadlockedCycle() { - //#deadlocked + // #deadlocked // WARNING! The graph below deadlocks! final Flow printFlow = - Flow.of(Integer.class).map(s -> { - System.out.println(s); - return s; - }); + Flow.of(Integer.class) + .map( + s -> { + System.out.println(s); + return s; + }); - RunnableGraph.fromGraph(GraphDSL.create(b -> { - final UniformFanInShape merge = b.add(Merge.create(2)); - final UniformFanOutShape bcast = b.add(Broadcast.create(2)); - final Outlet src = b.add(source).out(); - final FlowShape printer = b.add(printFlow); - final SinkShape ignore = b.add(Sink.ignore()); - - b.from(src).viaFanIn(merge).via(printer).viaFanOut(bcast).to(ignore); - b.to(merge) .fromFanOut(bcast); - return ClosedShape.getInstance(); - })); - //#deadlocked + RunnableGraph.fromGraph( + GraphDSL.create( + b -> { + final UniformFanInShape merge = b.add(Merge.create(2)); + final UniformFanOutShape bcast = b.add(Broadcast.create(2)); + final Outlet src = b.add(source).out(); + final FlowShape printer = b.add(printFlow); + final SinkShape ignore = b.add(Sink.ignore()); + + b.from(src).viaFanIn(merge).via(printer).viaFanOut(bcast).to(ignore); + b.to(merge).fromFanOut(bcast); + return ClosedShape.getInstance(); + })); + // #deadlocked } @Test public void demonstrateUnfairCycle() { final Flow printFlow = - Flow.of(Integer.class).map(s -> { - System.out.println(s); - return s; - }); - //#unfair + Flow.of(Integer.class) + .map( + s -> { + System.out.println(s); + return s; + }); + // #unfair // WARNING! The graph below stops consuming from "source" after a few steps - RunnableGraph.fromGraph(GraphDSL.create(b -> { - final MergePreferredShape merge = b.add(MergePreferred.create(1)); - final UniformFanOutShape bcast = b.add(Broadcast.create(2)); - final Outlet src = b.add(source).out(); - final FlowShape printer = b.add(printFlow); - final SinkShape ignore = b.add(Sink.ignore()); - - b.from(src).viaFanIn(merge).via(printer).viaFanOut(bcast).to(ignore); - b.to(merge.preferred()).fromFanOut(bcast); - return ClosedShape.getInstance(); - })); - //#unfair + RunnableGraph.fromGraph( + GraphDSL.create( + b -> { + final MergePreferredShape merge = b.add(MergePreferred.create(1)); + final UniformFanOutShape bcast = b.add(Broadcast.create(2)); + final Outlet src = b.add(source).out(); + final FlowShape printer = b.add(printFlow); + final SinkShape ignore = b.add(Sink.ignore()); + + b.from(src).viaFanIn(merge).via(printer).viaFanOut(bcast).to(ignore); + b.to(merge.preferred()).fromFanOut(bcast); + return ClosedShape.getInstance(); + })); + // #unfair } @Test public void demonstrateDroppingCycle() { final Flow printFlow = - Flow.of(Integer.class).map(s -> { - System.out.println(s); - return s; - }); - //#dropping - RunnableGraph.fromGraph(GraphDSL.create(b -> { - final UniformFanInShape merge = b.add(Merge.create(2)); - final UniformFanOutShape bcast = b.add(Broadcast.create(2)); - final FlowShape droppyFlow = b.add( - Flow.of(Integer.class).buffer(10, OverflowStrategy.dropHead())); - final Outlet src = b.add(source).out(); - final FlowShape printer = b.add(printFlow); - final SinkShape ignore = b.add(Sink.ignore()); - - b.from(src).viaFanIn(merge).via(printer).viaFanOut(bcast).to(ignore); - b.to(merge).via(droppyFlow).fromFanOut(bcast); - return ClosedShape.getInstance(); - })); - //#dropping + Flow.of(Integer.class) + .map( + s -> { + System.out.println(s); + return s; + }); + // #dropping + RunnableGraph.fromGraph( + GraphDSL.create( + b -> { + final UniformFanInShape merge = b.add(Merge.create(2)); + final UniformFanOutShape bcast = b.add(Broadcast.create(2)); + final FlowShape droppyFlow = + b.add(Flow.of(Integer.class).buffer(10, OverflowStrategy.dropHead())); + final Outlet src = b.add(source).out(); + final FlowShape printer = b.add(printFlow); + final SinkShape ignore = b.add(Sink.ignore()); + + b.from(src).viaFanIn(merge).via(printer).viaFanOut(bcast).to(ignore); + b.to(merge).via(droppyFlow).fromFanOut(bcast); + return ClosedShape.getInstance(); + })); + // #dropping } @Test public void demonstrateZippingCycle() { final Flow printFlow = - Flow.of(Integer.class).map(s -> { - System.out.println(s); - return s; - }); - //#zipping-dead + Flow.of(Integer.class) + .map( + s -> { + System.out.println(s); + return s; + }); + // #zipping-dead // WARNING! The graph below never processes any elements - RunnableGraph.fromGraph(GraphDSL.create(b -> { - final FanInShape2 zip = - b.add(ZipWith.create((Integer left, Integer right) -> left)); - final UniformFanOutShape bcast = b.add(Broadcast.create(2)); - final FlowShape printer = b.add(printFlow); - final SinkShape ignore = b.add(Sink.ignore()); + RunnableGraph.fromGraph( + GraphDSL.create( + b -> { + final FanInShape2 zip = + b.add(ZipWith.create((Integer left, Integer right) -> left)); + final UniformFanOutShape bcast = b.add(Broadcast.create(2)); + final FlowShape printer = b.add(printFlow); + final SinkShape ignore = b.add(Sink.ignore()); - b.from(b.add(source)).toInlet(zip.in0()); - b.from(zip.out()).via(printer).viaFanOut(bcast).to(ignore); - b.to(zip.in1()) .fromFanOut(bcast); - return ClosedShape.getInstance(); - })); - //#zipping-dead + b.from(b.add(source)).toInlet(zip.in0()); + b.from(zip.out()).via(printer).viaFanOut(bcast).to(ignore); + b.to(zip.in1()).fromFanOut(bcast); + return ClosedShape.getInstance(); + })); + // #zipping-dead } @Test public void demonstrateLiveZippingCycle() { final Flow printFlow = - Flow.of(Integer.class).map(s -> { - System.out.println(s); - return s; - }); - //#zipping-live - RunnableGraph.fromGraph(GraphDSL.create(b -> { - final FanInShape2 zip = - b.add(ZipWith.create((Integer left, Integer right) -> left)); - final UniformFanOutShape bcast = b.add(Broadcast.create(2)); - final UniformFanInShape concat = b.add(Concat.create()); - final FlowShape printer = b.add(printFlow); - final SinkShape ignore = b.add(Sink.ignore()); + Flow.of(Integer.class) + .map( + s -> { + System.out.println(s); + return s; + }); + // #zipping-live + RunnableGraph.fromGraph( + GraphDSL.create( + b -> { + final FanInShape2 zip = + b.add(ZipWith.create((Integer left, Integer right) -> left)); + final UniformFanOutShape bcast = b.add(Broadcast.create(2)); + final UniformFanInShape concat = b.add(Concat.create()); + final FlowShape printer = b.add(printFlow); + final SinkShape ignore = b.add(Sink.ignore()); - b.from(b.add(source)).toInlet(zip.in0()); - b.from(zip.out()).via(printer).viaFanOut(bcast).to(ignore); - b.to(zip.in1()).viaFanIn(concat).from(b.add(Source.single(1))); - b.to(concat).fromFanOut(bcast); - return ClosedShape.getInstance(); - })); - //#zipping-live + b.from(b.add(source)).toInlet(zip.in0()); + b.from(zip.out()).via(printer).viaFanOut(bcast).to(ignore); + b.to(zip.in1()).viaFanIn(concat).from(b.add(Source.single(1))); + b.to(concat).fromFanOut(bcast); + return ClosedShape.getInstance(); + })); + // #zipping-live } - } diff --git a/akka-docs/src/test/java/jdocs/stream/GraphStageDocTest.java b/akka-docs/src/test/java/jdocs/stream/GraphStageDocTest.java index 98b01f8e9b..51515dde70 100644 --- a/akka-docs/src/test/java/jdocs/stream/GraphStageDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/GraphStageDocTest.java @@ -4,7 +4,7 @@ package jdocs.stream; -//#imports +// #imports import akka.Done; import akka.NotUsed; import akka.actor.ActorSystem; @@ -16,7 +16,7 @@ import akka.japi.function.Procedure; import akka.stream.*; import akka.stream.javadsl.*; import akka.stream.stage.*; -//#imports +// #imports import akka.stream.testkit.TestPublisher; import akka.stream.testkit.TestSubscriber; import jdocs.AbstractJavaTest; @@ -51,14 +51,14 @@ public class GraphStageDocTest extends AbstractJavaTest { mat = null; } - - //#simple-source + // #simple-source public class NumbersSource extends GraphStage> { // Define the (sole) output port of this stage public final Outlet out = Outlet.create("NumbersSource.out"); // Define the shape of this stage, which is SourceShape with the port we defined above private final SourceShape shape = SourceShape.of(out); + @Override public SourceShape shape() { return shape; @@ -76,26 +76,27 @@ public class GraphStageDocTest extends AbstractJavaTest { private int counter = 1; { - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - push(out, counter); - counter += 1; - } - }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + push(out, counter); + counter += 1; + } + }); } - }; } - } - //#simple-source + // #simple-source - //#simple-sink + // #simple-sink public class StdoutSink extends GraphStage> { public final Inlet in = Inlet.create("StdoutSink.in"); private final SinkShape shape = SinkShape.of(in); + @Override public SinkShape shape() { return shape; @@ -112,23 +113,25 @@ public class GraphStageDocTest extends AbstractJavaTest { } { - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() throws Exception { - Integer element = grab(in); - System.out.println(element); - pull(in); - } - }); + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() throws Exception { + Integer element = grab(in); + System.out.println(element); + pull(in); + } + }); } }; } } - //#simple-sink + // #simple-sink @Test public void demonstrateCustomSourceUsage() throws Exception { - //#simple-source-usage + // #simple-source-usage // A GraphStage is a proper Graph, just like what GraphDSL.create would return Graph, NotUsed> sourceGraph = new NumbersSource(); @@ -139,8 +142,9 @@ public class GraphStageDocTest extends AbstractJavaTest { CompletionStage result1 = mySource.take(10).runFold(0, (sum, next) -> sum + next, mat); // The source is reusable. This returns 5050 - CompletionStage result2 = mySource.take(100).runFold(0, (sum, next) -> sum + next, mat); - //#simple-source-usage + CompletionStage result2 = + mySource.take(100).runFold(0, (sum, next) -> sum + next, mat); + // #simple-source-usage assertEquals(result1.toCompletableFuture().get(3, TimeUnit.SECONDS), (Integer) 55); assertEquals(result2.toCompletableFuture().get(3, TimeUnit.SECONDS), (Integer) 5050); @@ -155,7 +159,7 @@ public class GraphStageDocTest extends AbstractJavaTest { Source.from(Arrays.asList(1, 2, 3)).runWith(mySink, mat); } - //#one-to-one + // #one-to-one public class Map extends GraphStage> { private final Function f; @@ -168,8 +172,9 @@ public class GraphStageDocTest extends AbstractJavaTest { public final Outlet out = Outlet.create("Map.out"); private final FlowShape shape = FlowShape.of(in, out); + @Override - public FlowShape shape() { + public FlowShape shape() { return shape; } @@ -178,45 +183,50 @@ public class GraphStageDocTest extends AbstractJavaTest { return new GraphStageLogic(shape) { { - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() throws Exception { - push(out, f.apply(grab(in))); - } - }); - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - pull(in); - } - }); + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() throws Exception { + push(out, f.apply(grab(in))); + } + }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + pull(in); + } + }); } }; } - } - //#one-to-one + // #one-to-one @Test public void demonstrateOneToOne() throws Exception { // tests: final Graph, NotUsed> stringLength = - Flow.fromGraph(new Map(new Function() { - @Override - public Integer apply(String str) { - return str.length(); - } - })); + Flow.fromGraph( + new Map( + new Function() { + @Override + public Integer apply(String str) { + return str.length(); + } + })); CompletionStage result = - Source.from(Arrays.asList("one", "two", "three")) - .via(stringLength) - .runFold(0, (sum, n) -> sum + n, mat); + Source.from(Arrays.asList("one", "two", "three")) + .via(stringLength) + .runFold(0, (sum, n) -> sum + n, mat); assertEquals(new Integer(11), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); } - //#many-to-one + // #many-to-one public final class Filter extends GraphStage> { private final Predicate p; @@ -238,47 +248,50 @@ public class GraphStageDocTest extends AbstractJavaTest { public GraphStageLogic createLogic(Attributes inheritedAttributes) { return new GraphStageLogic(shape) { { + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() { + A elem = grab(in); + if (p.test(elem)) { + push(out, elem); + } else { + pull(in); + } + } + }); - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() { - A elem = grab(in); - if (p.test(elem)) { - push(out, elem); - } else { - pull(in); - } - } - }); - - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - pull(in); - } - }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + pull(in); + } + }); } }; } } - //#many-to-one + // #many-to-one @Test public void demonstrateAManyToOneElementGraphStage() throws Exception { // tests: Graph, NotUsed> evenFilter = - Flow.fromGraph(new Filter(n -> n % 2 == 0)); + Flow.fromGraph(new Filter(n -> n % 2 == 0)); CompletionStage result = - Source.from(Arrays.asList(1, 2, 3, 4, 5, 6)) - .via(evenFilter) - .runFold(0, (elem, sum) -> sum + elem, mat); + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6)) + .via(evenFilter) + .runFold(0, (elem, sum) -> sum + elem, mat); assertEquals(new Integer(12), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); } - //#one-to-many + // #one-to-many public class Duplicator extends GraphStage> { public final Inlet in = Inlet.create("Duplicator.in"); @@ -298,57 +311,57 @@ public class GraphStageDocTest extends AbstractJavaTest { Option lastElem = Option.none(); { - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() { - A elem = grab(in); - lastElem = Option.some(elem); - push(out, elem); - } + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() { + A elem = grab(in); + lastElem = Option.some(elem); + push(out, elem); + } - @Override - public void onUpstreamFinish() { - if (lastElem.isDefined()) { - emit(out, lastElem.get()); - } - complete(out); - } - }); + @Override + public void onUpstreamFinish() { + if (lastElem.isDefined()) { + emit(out, lastElem.get()); + } + complete(out); + } + }); - - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - if (lastElem.isDefined()) { - push(out, lastElem.get()); - lastElem = Option.none(); - } else { - pull(in); - } - } - }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + if (lastElem.isDefined()) { + push(out, lastElem.get()); + lastElem = Option.none(); + } else { + pull(in); + } + } + }); } }; } } - //#one-to-many + // #one-to-many @Test public void demonstrateAOneToManyElementGraphStage() throws Exception { // tests: Graph, NotUsed> duplicator = - Flow.fromGraph(new Duplicator()); + Flow.fromGraph(new Duplicator()); CompletionStage result = - Source.from(Arrays.asList(1, 2, 3)) - .via(duplicator) - .runFold(0, (n, sum) -> n + sum, mat); + Source.from(Arrays.asList(1, 2, 3)).via(duplicator).runFold(0, (n, sum) -> n + sum, mat); assertEquals(new Integer(12), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); - } - //#simpler-one-to-many + // #simpler-one-to-many public class Duplicator2 extends GraphStage> { public final Inlet in = Inlet.create("Duplicator.in"); @@ -366,62 +379,63 @@ public class GraphStageDocTest extends AbstractJavaTest { return new GraphStageLogic(shape) { { - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() { - A elem = grab(in); - // this will temporarily suspend this handler until the two elems - // are emitted and then reinstates it - emitMultiple(out, Arrays.asList(elem, elem).iterator()); - } - }); + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() { + A elem = grab(in); + // this will temporarily suspend this handler until the two elems + // are emitted and then reinstates it + emitMultiple(out, Arrays.asList(elem, elem).iterator()); + } + }); - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - pull(in); - } - }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + pull(in); + } + }); } }; } } - //#simpler-one-to-many - - + // #simpler-one-to-many @Test public void demonstrateASimplerOneToManyStage() throws Exception { // tests: Graph, NotUsed> duplicator = - Flow.fromGraph(new Duplicator2()); + Flow.fromGraph(new Duplicator2()); CompletionStage result = - Source.from(Arrays.asList(1, 2, 3)) - .via(duplicator) - .runFold(0, (n, sum) -> n + sum, mat); + Source.from(Arrays.asList(1, 2, 3)).via(duplicator).runFold(0, (n, sum) -> n + sum, mat); assertEquals(new Integer(12), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); } @Test public void demonstrateChainingOfGraphStages() throws Exception { - Graph, CompletionStage> sink = Sink.fold("", (acc, n) -> acc + n.toString()); + Graph, CompletionStage> sink = + Sink.fold("", (acc, n) -> acc + n.toString()); - //#graph-operator-chain - CompletionStage resultFuture = Source.from(Arrays.asList(1,2,3,4,5)) + // #graph-operator-chain + CompletionStage resultFuture = + Source.from(Arrays.asList(1, 2, 3, 4, 5)) .via(new Filter((n) -> n % 2 == 0)) .via(new Duplicator()) .via(new Map((n) -> n / 2)) .runWith(sink, mat); - //#graph-operator-chain + // #graph-operator-chain assertEquals("1122", resultFuture.toCompletableFuture().get(3, TimeUnit.SECONDS)); } - - //#async-side-channel + // #async-side-channel // will close upstream in all materializations of the stage instance // when the completion stage completes public class KillSwitch extends GraphStage> { @@ -436,6 +450,7 @@ public class GraphStageDocTest extends AbstractJavaTest { public final Outlet out = Outlet.create("KillSwitch.out"); private final FlowShape shape = FlowShape.of(in, out); + @Override public FlowShape shape() { return shape; @@ -446,28 +461,34 @@ public class GraphStageDocTest extends AbstractJavaTest { return new GraphStageLogic(shape) { { - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() { - push(out, grab(in)); - } - }); - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - pull(in); - } - }); + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() { + push(out, grab(in)); + } + }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + pull(in); + } + }); } @Override public void preStart() { - AsyncCallback callback = createAsyncCallback(new Procedure() { - @Override - public void apply(Done param) throws Exception { - completeStage(); - } - }); + AsyncCallback callback = + createAsyncCallback( + new Procedure() { + @Override + public void apply(Done param) throws Exception { + completeStage(); + } + }); ExecutionContext ec = system.dispatcher(); switchF.thenAccept(callback::invoke); @@ -475,10 +496,10 @@ public class GraphStageDocTest extends AbstractJavaTest { }; } } - //#async-side-channel + // #async-side-channel @Test - public void demonstrateAnAsynchronousSideChannel() throws Exception{ + public void demonstrateAnAsynchronousSideChannel() throws Exception { // tests: TestSubscriber.Probe out = TestSubscriber.probe(system); @@ -486,7 +507,7 @@ public class GraphStageDocTest extends AbstractJavaTest { CompletableFuture switchF = new CompletableFuture<>(); Graph, NotUsed> killSwitch = - Flow.fromGraph(new KillSwitch<>(switchF)); + Flow.fromGraph(new KillSwitch<>(switchF)); Source.fromPublisher(in).via(killSwitch).to(Sink.fromSubscriber(out)).run(mat); @@ -499,8 +520,7 @@ public class GraphStageDocTest extends AbstractJavaTest { out.expectComplete(); } - - //#timed + // #timed // each time an event is pushed through it will trigger a period of silence public class TimedGate extends GraphStage> { @@ -514,6 +534,7 @@ public class GraphStageDocTest extends AbstractJavaTest { public final Outlet out = Outlet.create("TimedGate.out"); private final FlowShape shape = FlowShape.of(in, out); + @Override public FlowShape shape() { return shape; @@ -526,24 +547,28 @@ public class GraphStageDocTest extends AbstractJavaTest { private boolean open = false; { - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() throws Exception { - A elem = grab(in); - if (open) pull(in); - else { - push(out, elem); - open = true; - scheduleOnce("key", java.time.Duration.ofSeconds(silencePeriodInSeconds)); - } - } - }); - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - pull(in); - } - }); + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() throws Exception { + A elem = grab(in); + if (open) pull(in); + else { + push(out, elem); + open = true; + scheduleOnce("key", java.time.Duration.ofSeconds(silencePeriodInSeconds)); + } + } + }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + pull(in); + } + }); } @Override @@ -555,82 +580,91 @@ public class GraphStageDocTest extends AbstractJavaTest { }; } } - //#timed + // #timed public void demonstrateAGraphStageWithATimer() throws Exception { // tests: CompletionStage result = - Source.from(Arrays.asList(1, 2, 3)) - .via(new TimedGate<>(2)) - .takeWithin(java.time.Duration.ofMillis(250)) - .runFold(0, (n, sum) -> n + sum, mat); + Source.from(Arrays.asList(1, 2, 3)) + .via(new TimedGate<>(2)) + .takeWithin(java.time.Duration.ofMillis(250)) + .runFold(0, (n, sum) -> n + sum, mat); assertEquals(new Integer(1), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); } - - //#materialized - public class FirstValue extends AbstractGraphStageWithMaterializedValue, CompletionStage> { + // #materialized + public class FirstValue + extends AbstractGraphStageWithMaterializedValue, CompletionStage> { public final Inlet in = Inlet.create("FirstValue.in"); public final Outlet out = Outlet.create("FirstValue.out"); private final FlowShape shape = FlowShape.of(in, out); + @Override public FlowShape shape() { return shape; } @Override - public Pair> createLogicAndMaterializedValuePair(Attributes inheritedAttributes) { + public Pair> createLogicAndMaterializedValuePair( + Attributes inheritedAttributes) { CompletableFuture promise = new CompletableFuture<>(); - GraphStageLogic logic = new GraphStageLogic(shape) { - { - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() { - A elem = grab(in); - promise.complete(elem); - push(out, elem); + GraphStageLogic logic = + new GraphStageLogic(shape) { + { + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() { + A elem = grab(in); + promise.complete(elem); + push(out, elem); - // replace handler with one that only forwards elements - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() { - push(out, grab(in)); - } - }); - } - }); + // replace handler with one that only forwards elements + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() { + push(out, grab(in)); + } + }); + } + }); - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - pull(in); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + pull(in); + } + }); } - }); - } - }; - + }; + return new Pair<>(logic, promise); } } - //#materialized + // #materialized public void demonstrateACustomMaterializedValue() throws Exception { // tests: - RunnableGraph> flow = Source.from(Arrays.asList(1, 2, 3)) - .viaMat(new FirstValue(), Keep.right()) - .to(Sink.ignore()); + RunnableGraph> flow = + Source.from(Arrays.asList(1, 2, 3)) + .viaMat(new FirstValue(), Keep.right()) + .to(Sink.ignore()); CompletionStage result = flow.run(mat); assertEquals(new Integer(1), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); } - - //#detached + // #detached public class TwoBuffer extends GraphStage> { public final Inlet in = Inlet.create("TwoBuffer.in"); @@ -663,68 +697,68 @@ public class GraphStageDocTest extends AbstractJavaTest { } { - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() { - A elem = grab(in); - buffer.add(elem); - if (downstreamWaiting) { - downstreamWaiting = false; - A bufferedElem = buffer.poll(); - push(out, bufferedElem); - } - if (!isBufferFull()) { - pull(in); - } - } + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() { + A elem = grab(in); + buffer.add(elem); + if (downstreamWaiting) { + downstreamWaiting = false; + A bufferedElem = buffer.poll(); + push(out, bufferedElem); + } + if (!isBufferFull()) { + pull(in); + } + } - @Override - public void onUpstreamFinish() { - if (!buffer.isEmpty()) { - // emit the rest if possible - emitMultiple(out, buffer.iterator()); - } - completeStage(); - } - }); + @Override + public void onUpstreamFinish() { + if (!buffer.isEmpty()) { + // emit the rest if possible + emitMultiple(out, buffer.iterator()); + } + completeStage(); + } + }); - - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - if (buffer.isEmpty()) { - downstreamWaiting = true; - } else { - A elem = buffer.poll(); - push(out, elem); - } - if (!isBufferFull() && !hasBeenPulled(in)) { - pull(in); - } - } - }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + if (buffer.isEmpty()) { + downstreamWaiting = true; + } else { + A elem = buffer.poll(); + push(out, elem); + } + if (!isBufferFull() && !hasBeenPulled(in)) { + pull(in); + } + } + }); } }; - } } - //#detached - + // #detached public void demonstrateADetachedGraphStage() throws Exception { // tests: - CompletionStage result1 = Source.from(Arrays.asList(1, 2, 3)) - .via(new TwoBuffer<>()) - .runFold(0, (acc, n) -> acc + n, mat); + CompletionStage result1 = + Source.from(Arrays.asList(1, 2, 3)) + .via(new TwoBuffer<>()) + .runFold(0, (acc, n) -> acc + n, mat); assertEquals(new Integer(6), result1.toCompletableFuture().get(3, TimeUnit.SECONDS)); TestSubscriber.ManualProbe subscriber = TestSubscriber.manualProbe(system); TestPublisher.Probe publisher = TestPublisher.probe(0, system); RunnableGraph flow2 = - Source.fromPublisher(publisher) - .via(new TwoBuffer<>()) - .to(Sink.fromSubscriber(subscriber)); + Source.fromPublisher(publisher).via(new TwoBuffer<>()).to(Sink.fromSubscriber(subscriber)); flow2.run(mat); @@ -735,5 +769,4 @@ public class GraphStageDocTest extends AbstractJavaTest { sub.cancel(); } - } diff --git a/akka-docs/src/test/java/jdocs/stream/GraphStageLoggingDocTest.java b/akka-docs/src/test/java/jdocs/stream/GraphStageLoggingDocTest.java index b93e5ab6c7..85b54e1a03 100644 --- a/akka-docs/src/test/java/jdocs/stream/GraphStageLoggingDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/GraphStageLoggingDocTest.java @@ -9,13 +9,13 @@ import akka.stream.Attributes; import akka.stream.Materializer; import akka.stream.Outlet; import akka.stream.SourceShape; -//#stage-with-logging +// #stage-with-logging import akka.stream.stage.AbstractOutHandler; import akka.stream.stage.GraphStage; import akka.stream.stage.GraphStageLogic; import akka.stream.stage.GraphStageLogicWithLogging; -//#stage-with-logging +// #stage-with-logging import jdocs.AbstractJavaTest; import org.junit.Test; @@ -26,9 +26,9 @@ public class GraphStageLoggingDocTest extends AbstractJavaTest { static Materializer mat; @Test - public void compileOnlyTestClass() throws Exception { } + public void compileOnlyTestClass() throws Exception {} - //#operator-with-logging + // #operator-with-logging public class RandomLettersSource extends GraphStage> { public final Outlet out = Outlet.create("RandomLettersSource.in"); @@ -44,27 +44,28 @@ public class GraphStageLoggingDocTest extends AbstractJavaTest { return new GraphStageLogicWithLogging(shape()) { { - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - final String s = nextChar();// ASCII lower case letters + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + final String s = nextChar(); // ASCII lower case letters - // `log` is obtained from materializer automatically (via StageLogging) - log().debug("Randomly generated: [{}]", s); + // `log` is obtained from materializer automatically (via StageLogging) + log().debug("Randomly generated: [{}]", s); - push(out, s); - } + push(out, s); + } - private String nextChar() { - final char i = (char) ThreadLocalRandom.current().nextInt('a', 'z' + 1); - return String.valueOf(i); - } - - }); + private String nextChar() { + final char i = (char) ThreadLocalRandom.current().nextInt('a', 'z' + 1); + return String.valueOf(i); + } + }); } }; } } - //#operator-with-logging + // #operator-with-logging } diff --git a/akka-docs/src/test/java/jdocs/stream/HubDocTest.java b/akka-docs/src/test/java/jdocs/stream/HubDocTest.java index 7deca14428..9717414f76 100644 --- a/akka-docs/src/test/java/jdocs/stream/HubDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/HubDocTest.java @@ -43,14 +43,13 @@ public class HubDocTest extends AbstractJavaTest { @Test public void dynamicMerge() { - //#merge-hub + // #merge-hub // A simple consumer that will print to the console for now Sink> consumer = Sink.foreach(System.out::println); // Attach a MergeHub Source to the consumer. This will materialize to a // corresponding Sink. - RunnableGraph> runnableGraph = - MergeHub.of(String.class, 16).to(consumer); + RunnableGraph> runnableGraph = MergeHub.of(String.class, 16).to(consumer); // By running/materializing the consumer we get back a Sink, and hence // now have access to feed elements into it. This Sink can be materialized @@ -60,7 +59,7 @@ public class HubDocTest extends AbstractJavaTest { Source.single("Hello!").runWith(toConsumer, materializer); Source.single("Hub!").runWith(toConsumer, materializer); - //#merge-hub + // #merge-hub } @Test @@ -68,20 +67,17 @@ public class HubDocTest extends AbstractJavaTest { // Used to be able to clean up the running stream ActorMaterializer materializer = ActorMaterializer.create(system); - //#broadcast-hub + // #broadcast-hub // A simple producer that publishes a new "message" every second - Source producer = Source.tick( - Duration.ofSeconds(1), - Duration.ofSeconds(1), - "New message" - ); + Source producer = + Source.tick(Duration.ofSeconds(1), Duration.ofSeconds(1), "New message"); // Attach a BroadcastHub Sink to the producer. This will materialize to a // corresponding Source. // (We need to use toMat and Keep.right since by default the materialized // value to the left is used) RunnableGraph> runnableGraph = - producer.toMat(BroadcastHub.of(String.class, 256), Keep.right()); + producer.toMat(BroadcastHub.of(String.class, 256), Keep.right()); // By running/materializing the producer, we get back a Source, which // gives us access to the elements published by the producer. @@ -90,7 +86,7 @@ public class HubDocTest extends AbstractJavaTest { // Print out messages from the producer in two independent consumers fromProducer.runForeach(msg -> System.out.println("consumer1: " + msg), materializer); fromProducer.runForeach(msg -> System.out.println("consumer2: " + msg), materializer); - //#broadcast-hub + // #broadcast-hub // Cleanup materializer.shutdown(); @@ -98,68 +94,65 @@ public class HubDocTest extends AbstractJavaTest { @Test public void mergeBroadcastCombination() { - //#pub-sub-1 + // #pub-sub-1 // Obtain a Sink and Source which will publish and receive from the "bus" respectively. Pair, Source> sinkAndSource = - MergeHub.of(String.class, 16) - .toMat(BroadcastHub.of(String.class, 256), Keep.both()) - .run(materializer); + MergeHub.of(String.class, 16) + .toMat(BroadcastHub.of(String.class, 256), Keep.both()) + .run(materializer); Sink sink = sinkAndSource.first(); Source source = sinkAndSource.second(); - //#pub-sub-1 + // #pub-sub-1 - //#pub-sub-2 + // #pub-sub-2 // Ensure that the Broadcast output is dropped if there are no listening parties. // If this dropping Sink is not attached, then the broadcast hub will not drop any // elements itself when there are no subscribers, backpressuring the producer instead. source.runWith(Sink.ignore(), materializer); - //#pub-sub-2 + // #pub-sub-2 - //#pub-sub-3 + // #pub-sub-3 // We create now a Flow that represents a publish-subscribe channel using the above // started stream as its "topic". We add two more features, external cancellation of // the registration and automatic cleanup for very slow subscribers. Flow busFlow = - Flow.fromSinkAndSource(sink, source) - .joinMat(KillSwitches.singleBidi(), Keep.right()) - .backpressureTimeout(Duration.ofSeconds(1)); - //#pub-sub-3 + Flow.fromSinkAndSource(sink, source) + .joinMat(KillSwitches.singleBidi(), Keep.right()) + .backpressureTimeout(Duration.ofSeconds(1)); + // #pub-sub-3 - //#pub-sub-4 + // #pub-sub-4 UniqueKillSwitch killSwitch = - Source.repeat("Hello World!") - .viaMat(busFlow, Keep.right()) - .to(Sink.foreach(System.out::println)) - .run(materializer); + Source.repeat("Hello World!") + .viaMat(busFlow, Keep.right()) + .to(Sink.foreach(System.out::println)) + .run(materializer); // Shut down externally killSwitch.shutdown(); - //#pub-sub-4 + // #pub-sub-4 } - + @Test public void dynamicPartition() { // Used to be able to clean up the running stream ActorMaterializer materializer = ActorMaterializer.create(system); - //#partition-hub + // #partition-hub // A simple producer that publishes a new "message-n" every second - Source producer = Source.tick( - Duration.ofSeconds(1), - Duration.ofSeconds(1), - "message" - ).zipWith(Source.range(0, 100), (a, b) -> a + "-" + b); + Source producer = + Source.tick(Duration.ofSeconds(1), Duration.ofSeconds(1), "message") + .zipWith(Source.range(0, 100), (a, b) -> a + "-" + b); // Attach a PartitionHub Sink to the producer. This will materialize to a // corresponding Source. // (We need to use toMat and Keep.right since by default the materialized // value to the left is used) RunnableGraph> runnableGraph = - producer.toMat(PartitionHub.of( - String.class, - (size, elem) -> Math.abs(elem.hashCode() % size), - 2, 256), Keep.right()); + producer.toMat( + PartitionHub.of(String.class, (size, elem) -> Math.abs(elem.hashCode() % size), 2, 256), + Keep.right()); // By running/materializing the producer, we get back a Source, which // gives us access to the elements published by the producer. @@ -168,52 +161,46 @@ public class HubDocTest extends AbstractJavaTest { // Print out messages from the producer in two independent consumers fromProducer.runForeach(msg -> System.out.println("consumer1: " + msg), materializer); fromProducer.runForeach(msg -> System.out.println("consumer2: " + msg), materializer); - //#partition-hub - + // #partition-hub + // Cleanup materializer.shutdown(); } - - //#partition-hub-stateful-function + + // #partition-hub-stateful-function // Using a class since variable must otherwise be final. // New instance is created for each materialization of the PartitionHub. static class RoundRobin implements ToLongBiFunction { private long i = -1; - + @Override public long applyAsLong(ConsumerInfo info, T elem) { i++; return info.consumerIdByIdx((int) (i % info.size())); } } - //#partition-hub-stateful-function - + // #partition-hub-stateful-function + @Test public void dynamicStatefulPartition() { // Used to be able to clean up the running stream ActorMaterializer materializer = ActorMaterializer.create(system); - //#partition-hub-stateful + // #partition-hub-stateful // A simple producer that publishes a new "message-n" every second - Source producer = Source.tick( - Duration.ofSeconds(1), - Duration.ofSeconds(1), - "message" - ).zipWith(Source.range(0, 100), (a, b) -> a + "-" + b); - + Source producer = + Source.tick(Duration.ofSeconds(1), Duration.ofSeconds(1), "message") + .zipWith(Source.range(0, 100), (a, b) -> a + "-" + b); + // Attach a PartitionHub Sink to the producer. This will materialize to a // corresponding Source. // (We need to use toMat and Keep.right since by default the materialized // value to the left is used) RunnableGraph> runnableGraph = - producer.toMat( - PartitionHub.ofStateful( - String.class, - () -> new RoundRobin(), - 2, - 256), - Keep.right()); + producer.toMat( + PartitionHub.ofStateful(String.class, () -> new RoundRobin(), 2, 256), + Keep.right()); // By running/materializing the producer, we get back a Source, which // gives us access to the elements published by the producer. @@ -222,49 +209,51 @@ public class HubDocTest extends AbstractJavaTest { // Print out messages from the producer in two independent consumers fromProducer.runForeach(msg -> System.out.println("consumer1: " + msg), materializer); fromProducer.runForeach(msg -> System.out.println("consumer2: " + msg), materializer); - //#partition-hub-stateful - + // #partition-hub-stateful + // Cleanup materializer.shutdown(); } - + @Test public void dynamicFastestPartition() { // Used to be able to clean up the running stream ActorMaterializer materializer = ActorMaterializer.create(system); - //#partition-hub-fastest + // #partition-hub-fastest Source producer = Source.range(0, 100); // ConsumerInfo.queueSize is the approximate number of buffered elements for a consumer. // Note that this is a moving target since the elements are consumed concurrently. RunnableGraph> runnableGraph = - producer.toMat( - PartitionHub.ofStateful( - Integer.class, - () -> (info, elem) -> { - final List ids = info.getConsumerIds(); - int minValue = info.queueSize(0); - long fastest = info.consumerIdByIdx(0); - for (int i = 1; i < ids.size(); i++) { - int value = info.queueSize(i); - if (value < minValue) { - minValue = value; - fastest = info.consumerIdByIdx(i); - } - } - return fastest; - }, - 2, - 8), - Keep.right()); + producer.toMat( + PartitionHub.ofStateful( + Integer.class, + () -> + (info, elem) -> { + final List ids = info.getConsumerIds(); + int minValue = info.queueSize(0); + long fastest = info.consumerIdByIdx(0); + for (int i = 1; i < ids.size(); i++) { + int value = info.queueSize(i); + if (value < minValue) { + minValue = value; + fastest = info.consumerIdByIdx(i); + } + } + return fastest; + }, + 2, + 8), + Keep.right()); Source fromProducer = runnableGraph.run(materializer); fromProducer.runForeach(msg -> System.out.println("consumer1: " + msg), materializer); - fromProducer.throttle(10, Duration.ofMillis(100)) - .runForeach(msg -> System.out.println("consumer2: " + msg), materializer); - //#partition-hub-fastest + fromProducer + .throttle(10, Duration.ofMillis(100)) + .runForeach(msg -> System.out.println("consumer2: " + msg), materializer); + // #partition-hub-fastest // Cleanup materializer.shutdown(); diff --git a/akka-docs/src/test/java/jdocs/stream/IntegrationDocTest.java b/akka-docs/src/test/java/jdocs/stream/IntegrationDocTest.java index b1fc89f533..3f2cc87717 100644 --- a/akka-docs/src/test/java/jdocs/stream/IntegrationDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/IntegrationDocTest.java @@ -48,15 +48,17 @@ public class IntegrationDocTest extends AbstractJavaTest { @BeforeClass public static void setup() { - final Config config = ConfigFactory.parseString("" + - "blocking-dispatcher { \n" + - " executor = thread-pool-executor \n" + - " thread-pool-executor { \n" + - " core-pool-size-min = 10 \n" + - " core-pool-size-max = 10 \n" + - " } \n" + - "} \n" + - "akka.actor.default-mailbox.mailbox-type = akka.dispatch.UnboundedMailbox\n"); + final Config config = + ConfigFactory.parseString( + "" + + "blocking-dispatcher { \n" + + " executor = thread-pool-executor \n" + + " thread-pool-executor { \n" + + " core-pool-size-min = 10 \n" + + " core-pool-size-max = 10 \n" + + " } \n" + + "} \n" + + "akka.actor.default-mailbox.mailbox-type = akka.dispatch.UnboundedMailbox\n"); system = ActorSystem.create("ActorPublisherDocTest", config); mat = ActorMaterializer.create(system); @@ -71,28 +73,27 @@ public class IntegrationDocTest extends AbstractJavaTest { ref = null; } - class AddressSystem { - //#email-address-lookup + // #email-address-lookup public CompletionStage> lookupEmail(String handle) - //#email-address-lookup - { + // #email-address-lookup + { return CompletableFuture.completedFuture(Optional.of(handle + "@somewhere.com")); } - //#phone-lookup + // #phone-lookup public CompletionStage> lookupPhoneNumber(String handle) - //#phone-lookup - { + // #phone-lookup + { return CompletableFuture.completedFuture(Optional.of("" + handle.hashCode())); } } class AddressSystem2 { - //#email-address-lookup2 + // #email-address-lookup2 public CompletionStage lookupEmail(String handle) - //#email-address-lookup2 - { + // #email-address-lookup2 + { return CompletableFuture.completedFuture(handle + "@somewhere.com"); } } @@ -186,18 +187,17 @@ public class IntegrationDocTest extends AbstractJavaTest { this.probe = probe; } - //#email-server-send + // #email-server-send public CompletionStage send(Email email) { // ... - //#email-server-send + // #email-server-send probe.tell(email.to, ActorRef.noSender()); return CompletableFuture.completedFuture(email); - //#email-server-send + // #email-server-send } - //#email-server-send + // #email-server-send } - static class SmsServer { public final ActorRef probe; @@ -205,15 +205,15 @@ public class IntegrationDocTest extends AbstractJavaTest { this.probe = probe; } - //#sms-server-send + // #sms-server-send public boolean send(TextMessage text) { // ... - //#sms-server-send + // #sms-server-send probe.tell(text.to, ActorRef.noSender()); - //#sms-server-send + // #sms-server-send return true; } - //#sms-server-send + // #sms-server-send } static class Save { @@ -246,12 +246,12 @@ public class IntegrationDocTest extends AbstractJavaTest { return tweet != null ? tweet.hashCode() : 0; } } + static class SaveDone { public static SaveDone INSTANCE = new SaveDone(); - private SaveDone() { - } - } + private SaveDone() {} + } static class DatabaseService extends AbstractActor { public final ActorRef probe; @@ -263,15 +263,17 @@ public class IntegrationDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .match(Save.class, s -> { - probe.tell(s.tweet.author.handle, ActorRef.noSender()); - getSender().tell(SaveDone.INSTANCE, getSelf()); - }) - .build(); + .match( + Save.class, + s -> { + probe.tell(s.tweet.author.handle, ActorRef.noSender()); + getSender().tell(SaveDone.INSTANCE, getSelf()); + }) + .build(); } } - //#sometimes-slow-service + // #sometimes-slow-service static class SometimesSlowService { private final Executor ec; @@ -283,46 +285,63 @@ public class IntegrationDocTest extends AbstractJavaTest { public CompletionStage convert(String s) { System.out.println("running: " + s + "(" + runningCount.incrementAndGet() + ")"); - return CompletableFuture.supplyAsync(() -> { - if (!s.isEmpty() && Character.isLowerCase(s.charAt(0))) - try { Thread.sleep(500); } catch (InterruptedException e) {} - else - try { Thread.sleep(20); } catch (InterruptedException e) {} - System.out.println("completed: " + s + "(" + runningCount.decrementAndGet() + ")"); - return s.toUpperCase(); - }, ec); + return CompletableFuture.supplyAsync( + () -> { + if (!s.isEmpty() && Character.isLowerCase(s.charAt(0))) + try { + Thread.sleep(500); + } catch (InterruptedException e) { + } + else + try { + Thread.sleep(20); + } catch (InterruptedException e) { + } + System.out.println("completed: " + s + "(" + runningCount.decrementAndGet() + ")"); + return s.toUpperCase(); + }, + ec); } } - //#sometimes-slow-service + // #sometimes-slow-service - //#ask-actor + // #ask-actor static class Translator extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(String.class, word -> { - // ... process message - String reply = word.toUpperCase(); - // reply to the ask - getSender().tell(reply, getSelf()); - }) - .build(); + .match( + String.class, + word -> { + // ... process message + String reply = word.toUpperCase(); + // reply to the ask + getSender().tell(reply, getSelf()); + }) + .build(); } } - //#ask-actor + // #ask-actor - //#actorRefWithAck-actor + // #actorRefWithAck-actor enum Ack { INSTANCE; } static class StreamInitialized {} + static class StreamCompleted {} + static class StreamFailure { private final Throwable cause; - public StreamFailure(Throwable cause) { this.cause = cause; } - public Throwable getCause() { return cause; } + public StreamFailure(Throwable cause) { + this.cause = cause; + } + + public Throwable getCause() { + return cause; + } } static class AckingReceiver extends AbstractLoggingActor { @@ -336,72 +355,76 @@ public class IntegrationDocTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .match(StreamInitialized.class, init -> { - log().info("Stream initialized"); - probe.tell("Stream initialized", getSelf()); - sender().tell(Ack.INSTANCE, self()); - }) - .match(String.class, element -> { - log().info("Received element: {}", element); - probe.tell(element, getSelf()); - sender().tell(Ack.INSTANCE, self()); - }) - .match(StreamCompleted.class, completed -> { - log().info("Stream completed"); - probe.tell("Stream completed", getSelf()); - }) - .match(StreamFailure.class, failed -> { - log().error(failed.getCause(),"Stream failed!"); - probe.tell("Stream failed!", getSelf()); - }) - .build(); + .match( + StreamInitialized.class, + init -> { + log().info("Stream initialized"); + probe.tell("Stream initialized", getSelf()); + sender().tell(Ack.INSTANCE, self()); + }) + .match( + String.class, + element -> { + log().info("Received element: {}", element); + probe.tell(element, getSelf()); + sender().tell(Ack.INSTANCE, self()); + }) + .match( + StreamCompleted.class, + completed -> { + log().info("Stream completed"); + probe.tell("Stream completed", getSelf()); + }) + .match( + StreamFailure.class, + failed -> { + log().error(failed.getCause(), "Stream failed!"); + probe.tell("Stream failed!", getSelf()); + }) + .build(); } } - //#actorRefWithAck-actor + // #actorRefWithAck-actor @SuppressWarnings("unchecked") @Test public void askStage() throws Exception { - //#ask - Source words = - Source.from(Arrays.asList("hello", "hi")); + // #ask + Source words = Source.from(Arrays.asList("hello", "hi")); Timeout askTimeout = Timeout.apply(5, TimeUnit.SECONDS); words - .ask(5, ref, String.class, askTimeout) - // continue processing of the replies from the actor - .map(elem -> elem.toLowerCase()) - .runWith(Sink.ignore(), mat); - //#ask + .ask(5, ref, String.class, askTimeout) + // continue processing of the replies from the actor + .map(elem -> elem.toLowerCase()) + .runWith(Sink.ignore(), mat); + // #ask } @Test public void actorRefWithAckExample() throws Exception { - //#actorRefWithAck - Source words = - Source.from(Arrays.asList("hello", "hi")); + // #actorRefWithAck + Source words = Source.from(Arrays.asList("hello", "hi")); final TestKit probe = new TestKit(system); - ActorRef receiver = - system.actorOf(Props.create(AckingReceiver.class, probe.getRef())); + ActorRef receiver = system.actorOf(Props.create(AckingReceiver.class, probe.getRef())); - Sink sink = Sink.actorRefWithAck(receiver, - new StreamInitialized(), - Ack.INSTANCE, - new StreamCompleted(), - ex -> new StreamFailure(ex) - ); + Sink sink = + Sink.actorRefWithAck( + receiver, + new StreamInitialized(), + Ack.INSTANCE, + new StreamCompleted(), + ex -> new StreamFailure(ex)); - words - .map(el -> el.toLowerCase()) - .runWith(sink, mat); + words.map(el -> el.toLowerCase()).runWith(sink, mat); probe.expectMsg("Stream initialized"); probe.expectMsg("hello"); probe.expectMsg("hi"); probe.expectMsg("Stream completed"); - //#actorRefWithAck + // #actorRefWithAck } @Test @@ -412,29 +435,30 @@ public class IntegrationDocTest extends AbstractJavaTest { final EmailServer emailServer = new EmailServer(probe.getRef()); { - //#tweet-authors - final Source authors = tweets - .filter(t -> t.hashtags().contains(AKKA)) - .map(t -> t.author); + // #tweet-authors + final Source authors = + tweets.filter(t -> t.hashtags().contains(AKKA)).map(t -> t.author); - //#tweet-authors + // #tweet-authors - //#email-addresses-mapAsync - final Source emailAddresses = authors - .mapAsync(4, author -> addressSystem.lookupEmail(author.handle)) - .filter(o -> o.isPresent()) - .map(o -> o.get()); + // #email-addresses-mapAsync + final Source emailAddresses = + authors + .mapAsync(4, author -> addressSystem.lookupEmail(author.handle)) + .filter(o -> o.isPresent()) + .map(o -> o.get()); - //#email-addresses-mapAsync + // #email-addresses-mapAsync - //#send-emails - final RunnableGraph sendEmails = emailAddresses - .mapAsync(4, address -> - emailServer.send(new Email(address, "Akka", "I like your tweet"))) - .to(Sink.ignore()); + // #send-emails + final RunnableGraph sendEmails = + emailAddresses + .mapAsync( + 4, address -> emailServer.send(new Email(address, "Akka", "I like your tweet"))) + .to(Sink.ignore()); sendEmails.run(mat); - //#send-emails + // #send-emails probe.expectMsg("rolandkuhn@somewhere.com"); probe.expectMsg("patriknw@somewhere.com"); @@ -454,20 +478,19 @@ public class IntegrationDocTest extends AbstractJavaTest { final AddressSystem2 addressSystem = new AddressSystem2(); { - final Source authors = tweets - .filter(t -> t.hashtags().contains(AKKA)) - .map(t -> t.author); + final Source authors = + tweets.filter(t -> t.hashtags().contains(AKKA)).map(t -> t.author); - //#email-addresses-mapAsync-supervision + // #email-addresses-mapAsync-supervision final Attributes resumeAttrib = - ActorAttributes.withSupervisionStrategy(Supervision.getResumingDecider()); + ActorAttributes.withSupervisionStrategy(Supervision.getResumingDecider()); final Flow lookupEmail = Flow.of(Author.class) - .mapAsync(4, author -> addressSystem.lookupEmail(author.handle)) - .withAttributes(resumeAttrib); + .mapAsync(4, author -> addressSystem.lookupEmail(author.handle)) + .withAttributes(resumeAttrib); final Source emailAddresses = authors.via(lookupEmail); - //#email-addresses-mapAsync-supervision + // #email-addresses-mapAsync-supervision } }; } @@ -480,26 +503,24 @@ public class IntegrationDocTest extends AbstractJavaTest { final EmailServer emailServer = new EmailServer(probe.ref()); { - //#external-service-mapAsyncUnordered + // #external-service-mapAsyncUnordered final Source authors = - tweets - .filter(t -> t.hashtags().contains(AKKA)) - .map(t -> t.author); + tweets.filter(t -> t.hashtags().contains(AKKA)).map(t -> t.author); final Source emailAddresses = - authors - .mapAsyncUnordered(4, author -> addressSystem.lookupEmail(author.handle)) - .filter(o -> o.isPresent()) - .map(o -> o.get()); + authors + .mapAsyncUnordered(4, author -> addressSystem.lookupEmail(author.handle)) + .filter(o -> o.isPresent()) + .map(o -> o.get()); final RunnableGraph sendEmails = - emailAddresses - .mapAsyncUnordered(4, address -> - emailServer.send(new Email(address, "Akka", "I like your tweet"))) - .to(Sink.ignore()); + emailAddresses + .mapAsyncUnordered( + 4, address -> emailServer.send(new Email(address, "Akka", "I like your tweet"))) + .to(Sink.ignore()); sendEmails.run(mat); - //#external-service-mapAsyncUnordered + // #external-service-mapAsyncUnordered } }; } @@ -513,25 +534,29 @@ public class IntegrationDocTest extends AbstractJavaTest { { final Source authors = - tweets - .filter(t -> t.hashtags().contains(AKKA)) - .map(t -> t.author); + tweets.filter(t -> t.hashtags().contains(AKKA)).map(t -> t.author); - final Source phoneNumbers = authors.mapAsync(4, author -> addressSystem.lookupPhoneNumber(author.handle)) - .filter(o -> o.isPresent()) - .map(o -> o.get()); + final Source phoneNumbers = + authors + .mapAsync(4, author -> addressSystem.lookupPhoneNumber(author.handle)) + .filter(o -> o.isPresent()) + .map(o -> o.get()); - //#blocking-mapAsync + // #blocking-mapAsync final Executor blockingEc = system.dispatchers().lookup("blocking-dispatcher"); final RunnableGraph sendTextMessages = - phoneNumbers - .mapAsync(4, phoneNo -> CompletableFuture.supplyAsync(() -> - smsServer.send(new TextMessage(phoneNo, "I like your tweet")), blockingEc)) - .to(Sink.ignore()); + phoneNumbers + .mapAsync( + 4, + phoneNo -> + CompletableFuture.supplyAsync( + () -> smsServer.send(new TextMessage(phoneNo, "I like your tweet")), + blockingEc)) + .to(Sink.ignore()); sendTextMessages.run(mat); - //#blocking-mapAsync + // #blocking-mapAsync final List got = receiveN(7); final Set set = new HashSet<>(got); @@ -557,24 +582,23 @@ public class IntegrationDocTest extends AbstractJavaTest { { final Source authors = - tweets - .filter(t -> t.hashtags().contains(AKKA)) - .map(t -> t.author); + tweets.filter(t -> t.hashtags().contains(AKKA)).map(t -> t.author); - final Source phoneNumbers = authors.mapAsync(4, author -> addressSystem.lookupPhoneNumber(author.handle)) - .filter(o -> o.isPresent()) - .map(o -> o.get()); + final Source phoneNumbers = + authors + .mapAsync(4, author -> addressSystem.lookupPhoneNumber(author.handle)) + .filter(o -> o.isPresent()) + .map(o -> o.get()); - //#blocking-map + // #blocking-map final Flow send = - Flow.of(String.class) - .map(phoneNo -> smsServer.send(new TextMessage(phoneNo, "I like your tweet"))) - .withAttributes(ActorAttributes.dispatcher("blocking-dispatcher")); - final RunnableGraph sendTextMessages = - phoneNumbers.via(send).to(Sink.ignore()); + Flow.of(String.class) + .map(phoneNo -> smsServer.send(new TextMessage(phoneNo, "I like your tweet"))) + .withAttributes(ActorAttributes.dispatcher("blocking-dispatcher")); + final RunnableGraph sendTextMessages = phoneNumbers.via(send).to(Sink.ignore()); sendTextMessages.run(mat); - //#blocking-map + // #blocking-map probe.expectMsg(String.valueOf("rolandkuhn".hashCode())); probe.expectMsg(String.valueOf("patriknw".hashCode())); @@ -593,17 +617,18 @@ public class IntegrationDocTest extends AbstractJavaTest { final TestProbe probe = new TestProbe(system); final EmailServer emailServer = new EmailServer(probe.ref()); - final ActorRef database = system.actorOf(Props.create(DatabaseService.class, probe.ref()), "db"); + final ActorRef database = + system.actorOf(Props.create(DatabaseService.class, probe.ref()), "db"); { - //#save-tweets + // #save-tweets final Source akkaTweets = tweets.filter(t -> t.hashtags().contains(AKKA)); final RunnableGraph saveTweets = - akkaTweets - .mapAsync(4, tweet -> ask(database, new Save(tweet), Duration.ofMillis(300L))) - .to(Sink.ignore()); - //#save-tweets + akkaTweets + .mapAsync(4, tweet -> ask(database, new Save(tweet), Duration.ofMillis(300L))) + .to(Sink.ignore()); + // #save-tweets saveTweets.run(mat); @@ -627,28 +652,33 @@ public class IntegrationDocTest extends AbstractJavaTest { class MockSystem { class Println { public void println(T s) { - if (s.toString().startsWith("after:")) - probe.ref().tell(s, ActorRef.noSender()); + if (s.toString().startsWith("after:")) probe.ref().tell(s, ActorRef.noSender()); } } public final Println out = new Println(); } + private final MockSystem System = new MockSystem(); { - //#sometimes-slow-mapAsync + // #sometimes-slow-mapAsync final Executor blockingEc = system.dispatchers().lookup("blocking-dispatcher"); final SometimesSlowService service = new SometimesSlowService(blockingEc); - final ActorMaterializer mat = ActorMaterializer.create( - ActorMaterializerSettings.create(system).withInputBuffer(4, 4), system); + final ActorMaterializer mat = + ActorMaterializer.create( + ActorMaterializerSettings.create(system).withInputBuffer(4, 4), system); Source.from(Arrays.asList("a", "B", "C", "D", "e", "F", "g", "H", "i", "J")) - .map(elem -> { System.out.println("before: " + elem); return elem; }) - .mapAsync(4, service::convert) - .runForeach(elem -> System.out.println("after: " + elem), mat); - //#sometimes-slow-mapAsync + .map( + elem -> { + System.out.println("before: " + elem); + return elem; + }) + .mapAsync(4, service::convert) + .runForeach(elem -> System.out.println("after: " + elem), mat); + // #sometimes-slow-mapAsync probe.expectMsg("after: A"); probe.expectMsg("after: B"); @@ -672,28 +702,33 @@ public class IntegrationDocTest extends AbstractJavaTest { class MockSystem { class Println { public void println(T s) { - if (s.toString().startsWith("after:")) - getRef().tell(s, ActorRef.noSender()); + if (s.toString().startsWith("after:")) getRef().tell(s, ActorRef.noSender()); } } public final Println out = new Println(); } + private final MockSystem System = new MockSystem(); { - //#sometimes-slow-mapAsyncUnordered + // #sometimes-slow-mapAsyncUnordered final Executor blockingEc = system.dispatchers().lookup("blocking-dispatcher"); final SometimesSlowService service = new SometimesSlowService(blockingEc); - final ActorMaterializer mat = ActorMaterializer.create( - ActorMaterializerSettings.create(system).withInputBuffer(4, 4), system); + final ActorMaterializer mat = + ActorMaterializer.create( + ActorMaterializerSettings.create(system).withInputBuffer(4, 4), system); Source.from(Arrays.asList("a", "B", "C", "D", "e", "F", "g", "H", "i", "J")) - .map(elem -> { System.out.println("before: " + elem); return elem; }) - .mapAsyncUnordered(4, service::convert) - .runForeach(elem -> System.out.println("after: " + elem), mat); - //#sometimes-slow-mapAsyncUnordered + .map( + elem -> { + System.out.println("before: " + elem); + return elem; + }) + .mapAsyncUnordered(4, service::convert) + .runForeach(elem -> System.out.println("after: " + elem), mat); + // #sometimes-slow-mapAsyncUnordered final List got = receiveN(10); final Set set = new HashSet<>(got); @@ -716,7 +751,7 @@ public class IntegrationDocTest extends AbstractJavaTest { public void illustrateSourceQueue() throws Exception { new TestKit(system) { { - //#source-queue + // #source-queue int bufferSize = 5; int elementsToProcess = 3; @@ -727,14 +762,12 @@ public class IntegrationDocTest extends AbstractJavaTest { .to(Sink.foreach(x -> System.out.println("got: " + x))) .run(mat); - Source source - = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); + Source source = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); source.map(x -> sourceQueue.offer(x)).runWith(Sink.ignore(), mat); - //#source-queue + // #source-queue } }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/KillSwitchDocTest.java b/akka-docs/src/test/java/jdocs/stream/KillSwitchDocTest.java index 032e220e51..7eeaae0fb6 100644 --- a/akka-docs/src/test/java/jdocs/stream/KillSwitchDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/KillSwitchDocTest.java @@ -45,19 +45,20 @@ class KillSwitchDocTest extends AbstractJavaTest { } @Test - public void compileOnlyTest() { - } + public void compileOnlyTest() {} public void uniqueKillSwitchShutdownExample() throws Exception { - //#unique-shutdown + // #unique-shutdown final Source countingSrc = - Source.from(new ArrayList<>(Arrays.asList(1, 2, 3, 4))) - .delay(Duration.ofSeconds(1), DelayOverflowStrategy.backpressure()); + Source.from(new ArrayList<>(Arrays.asList(1, 2, 3, 4))) + .delay(Duration.ofSeconds(1), DelayOverflowStrategy.backpressure()); final Sink> lastSnk = Sink.last(); - final Pair> stream = countingSrc - .viaMat(KillSwitches.single(), Keep.right()) - .toMat(lastSnk, Keep.both()).run(mat); + final Pair> stream = + countingSrc + .viaMat(KillSwitches.single(), Keep.right()) + .toMat(lastSnk, Keep.both()) + .run(mat); final UniqueKillSwitch killSwitch = stream.first(); final CompletionStage completionStage = stream.second(); @@ -65,22 +66,23 @@ class KillSwitchDocTest extends AbstractJavaTest { doSomethingElse(); killSwitch.shutdown(); - final int finalCount = - completionStage.toCompletableFuture().get(1, TimeUnit.SECONDS); + final int finalCount = completionStage.toCompletableFuture().get(1, TimeUnit.SECONDS); assertEquals(2, finalCount); - //#unique-shutdown + // #unique-shutdown } public static void uniqueKillSwitchAbortExample() throws Exception { - //#unique-abort + // #unique-abort final Source countingSrc = - Source.from(new ArrayList<>(Arrays.asList(1, 2, 3, 4))) - .delay(Duration.ofSeconds(1), DelayOverflowStrategy.backpressure()); + Source.from(new ArrayList<>(Arrays.asList(1, 2, 3, 4))) + .delay(Duration.ofSeconds(1), DelayOverflowStrategy.backpressure()); final Sink> lastSnk = Sink.last(); - final Pair> stream = countingSrc - .viaMat(KillSwitches.single(), Keep.right()) - .toMat(lastSnk, Keep.both()).run(mat); + final Pair> stream = + countingSrc + .viaMat(KillSwitches.single(), Keep.right()) + .toMat(lastSnk, Keep.both()) + .run(mat); final UniqueKillSwitch killSwitch = stream.first(); final CompletionStage completionStage = stream.second(); @@ -89,68 +91,65 @@ class KillSwitchDocTest extends AbstractJavaTest { killSwitch.abort(error); final int result = - completionStage.toCompletableFuture().exceptionally(e -> -1).get(1, TimeUnit.SECONDS); + completionStage.toCompletableFuture().exceptionally(e -> -1).get(1, TimeUnit.SECONDS); assertEquals(-1, result); - //#unique-abort + // #unique-abort } public void sharedKillSwitchShutdownExample() throws Exception { - //#shared-shutdown + // #shared-shutdown final Source countingSrc = - Source.from(new ArrayList<>(Arrays.asList(1, 2, 3, 4))) - .delay( Duration.ofSeconds(1), DelayOverflowStrategy.backpressure()); + Source.from(new ArrayList<>(Arrays.asList(1, 2, 3, 4))) + .delay(Duration.ofSeconds(1), DelayOverflowStrategy.backpressure()); final Sink> lastSnk = Sink.last(); final SharedKillSwitch killSwitch = KillSwitches.shared("my-kill-switch"); - final CompletionStage completionStage = countingSrc - .viaMat(killSwitch.flow(), Keep.right()) - .toMat(lastSnk, Keep.right()).run(mat); - final CompletionStage completionStageDelayed = countingSrc - .delay( Duration.ofSeconds(1), DelayOverflowStrategy.backpressure()) - .viaMat(killSwitch.flow(), Keep.right()) - .toMat(lastSnk, Keep.right()).run(mat); + final CompletionStage completionStage = + countingSrc.viaMat(killSwitch.flow(), Keep.right()).toMat(lastSnk, Keep.right()).run(mat); + final CompletionStage completionStageDelayed = + countingSrc + .delay(Duration.ofSeconds(1), DelayOverflowStrategy.backpressure()) + .viaMat(killSwitch.flow(), Keep.right()) + .toMat(lastSnk, Keep.right()) + .run(mat); doSomethingElse(); killSwitch.shutdown(); - final int finalCount = - completionStage.toCompletableFuture().get(1, TimeUnit.SECONDS); + final int finalCount = completionStage.toCompletableFuture().get(1, TimeUnit.SECONDS); final int finalCountDelayed = - completionStageDelayed.toCompletableFuture().get(1, TimeUnit.SECONDS); + completionStageDelayed.toCompletableFuture().get(1, TimeUnit.SECONDS); assertEquals(2, finalCount); assertEquals(1, finalCountDelayed); - //#shared-shutdown + // #shared-shutdown } public static void sharedKillSwitchAbortExample() throws Exception { - //#shared-abort + // #shared-abort final Source countingSrc = - Source.from(new ArrayList<>(Arrays.asList(1, 2, 3, 4))) - .delay( Duration.ofSeconds(1), DelayOverflowStrategy.backpressure()); + Source.from(new ArrayList<>(Arrays.asList(1, 2, 3, 4))) + .delay(Duration.ofSeconds(1), DelayOverflowStrategy.backpressure()); final Sink> lastSnk = Sink.last(); final SharedKillSwitch killSwitch = KillSwitches.shared("my-kill-switch"); - final CompletionStage completionStage1 = countingSrc - .viaMat(killSwitch.flow(), Keep.right()) - .toMat(lastSnk, Keep.right()).run(mat); - final CompletionStage completionStage2 = countingSrc - .viaMat(killSwitch.flow(), Keep.right()) - .toMat(lastSnk, Keep.right()).run(mat); + final CompletionStage completionStage1 = + countingSrc.viaMat(killSwitch.flow(), Keep.right()).toMat(lastSnk, Keep.right()).run(mat); + final CompletionStage completionStage2 = + countingSrc.viaMat(killSwitch.flow(), Keep.right()).toMat(lastSnk, Keep.right()).run(mat); final Exception error = new Exception("boom!"); killSwitch.abort(error); final int result1 = - completionStage1.toCompletableFuture().exceptionally(e -> -1).get(1, TimeUnit.SECONDS); + completionStage1.toCompletableFuture().exceptionally(e -> -1).get(1, TimeUnit.SECONDS); final int result2 = - completionStage2.toCompletableFuture().exceptionally(e -> -1).get(1, TimeUnit.SECONDS); + completionStage2.toCompletableFuture().exceptionally(e -> -1).get(1, TimeUnit.SECONDS); assertEquals(-1, result1); assertEquals(-1, result2); - //#shared-abort + // #shared-abort } - private static void doSomethingElse(){ - } + private static void doSomethingElse() {} } diff --git a/akka-docs/src/test/java/jdocs/stream/Main.java b/akka-docs/src/test/java/jdocs/stream/Main.java index d2396c9a20..c11f2a2f00 100644 --- a/akka-docs/src/test/java/jdocs/stream/Main.java +++ b/akka-docs/src/test/java/jdocs/stream/Main.java @@ -4,10 +4,10 @@ package jdocs.stream; -//#main-app +// #main-app public class Main { public static void main(String[] argv) { // Code here } } -//#main-app +// #main-app diff --git a/akka-docs/src/test/java/jdocs/stream/MigrationsJava.java b/akka-docs/src/test/java/jdocs/stream/MigrationsJava.java index bfd60ff366..d7babb24e4 100644 --- a/akka-docs/src/test/java/jdocs/stream/MigrationsJava.java +++ b/akka-docs/src/test/java/jdocs/stream/MigrationsJava.java @@ -9,31 +9,31 @@ import java.util.stream.Stream; import akka.NotUsed; import akka.japi.Pair; import akka.stream.javadsl.*; -//#asPublisher-import +// #asPublisher-import import static akka.stream.javadsl.AsPublisher.*; -//#asPublisher-import +// #asPublisher-import public class MigrationsJava { public static void main(String[] args) { - //#expand-continually + // #expand-continually Flow.of(Integer.class).expand(in -> Stream.iterate(in, i -> i).iterator()); - //#expand-continually - //#expand-state - Flow.of(Integer.class).expand(in -> - Stream.iterate(new Pair<>(in, 0), - p -> new Pair<>(in, p.second() + 1)).iterator()); - //#expand-state - - //#asPublisher - Sink.asPublisher(WITH_FANOUT); // instead of Sink.asPublisher(true) - Sink.asPublisher(WITHOUT_FANOUT); // instead of Sink.asPublisher(false) - //#asPublisher + // #expand-continually + // #expand-state + Flow.of(Integer.class) + .expand( + in -> + Stream.iterate(new Pair<>(in, 0), p -> new Pair<>(in, p.second() + 1)).iterator()); + // #expand-state - //#async + // #asPublisher + Sink.asPublisher(WITH_FANOUT); // instead of Sink.asPublisher(true) + Sink.asPublisher(WITHOUT_FANOUT); // instead of Sink.asPublisher(false) + // #asPublisher + + // #async Flow flow = Flow.of(Integer.class).map(n -> n + 1); Source.range(1, 10).via(flow.async()); - //#async + // #async } - } diff --git a/akka-docs/src/test/java/jdocs/stream/QuickStartDocTest.java b/akka-docs/src/test/java/jdocs/stream/QuickStartDocTest.java index 00c536369b..b71304dbfd 100644 --- a/akka-docs/src/test/java/jdocs/stream/QuickStartDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/QuickStartDocTest.java @@ -4,12 +4,12 @@ package jdocs.stream; -//#stream-imports +// #stream-imports import akka.stream.*; import akka.stream.javadsl.*; -//#stream-imports +// #stream-imports -//#other-imports +// #other-imports import akka.Done; import akka.NotUsed; import akka.actor.ActorSystem; @@ -22,72 +22,70 @@ import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import jdocs.AbstractJavaTest; -//#other-imports +// #other-imports import org.junit.*; /** - * This class is not meant to be run as a test in the test suite, but it - * is set up such that it can be run interactively from within an IDE. + * This class is not meant to be run as a test in the test suite, but it is set up such that it can + * be run interactively from within an IDE. */ public class QuickStartDocTest extends AbstractJavaTest { - + @Test public void demonstrateSource() throws InterruptedException, ExecutionException { - //#create-materializer + // #create-materializer final ActorSystem system = ActorSystem.create("QuickStart"); final Materializer materializer = ActorMaterializer.create(system); - //#create-materializer + // #create-materializer - //#create-source + // #create-source final Source source = Source.range(1, 100); - //#create-source - - //#run-source - source.runForeach(i -> System.out.println(i), materializer); - //#run-source - - //#transform-source - final Source factorials = - source - .scan(BigInteger.ONE, (acc, next) -> acc.multiply(BigInteger.valueOf(next))); - - final CompletionStage result = - factorials - .map(num -> ByteString.fromString(num.toString() + "\n")) - .runWith(FileIO.toPath(Paths.get("factorials.txt")), materializer); - //#transform-source + // #create-source - //#use-transformed-sink + // #run-source + source.runForeach(i -> System.out.println(i), materializer); + // #run-source + + // #transform-source + final Source factorials = + source.scan(BigInteger.ONE, (acc, next) -> acc.multiply(BigInteger.valueOf(next))); + + final CompletionStage result = + factorials + .map(num -> ByteString.fromString(num.toString() + "\n")) + .runWith(FileIO.toPath(Paths.get("factorials.txt")), materializer); + // #transform-source + + // #use-transformed-sink factorials.map(BigInteger::toString).runWith(lineSink("factorial2.txt"), materializer); - //#use-transformed-sink - - //#add-streams + // #use-transformed-sink + + // #add-streams factorials - .zipWith(Source.range(0, 99), (num, idx) -> String.format("%d! = %s", idx, num)) - .throttle(1, Duration.ofSeconds(1)) - //#add-streams - .take(2) - //#add-streams - .runForeach(s -> System.out.println(s), materializer); - //#add-streams - - //#run-source-and-terminate - final CompletionStage done = - source.runForeach(i -> System.out.println(i), materializer); + .zipWith(Source.range(0, 99), (num, idx) -> String.format("%d! = %s", idx, num)) + .throttle(1, Duration.ofSeconds(1)) + // #add-streams + .take(2) + // #add-streams + .runForeach(s -> System.out.println(s), materializer); + // #add-streams + + // #run-source-and-terminate + final CompletionStage done = source.runForeach(i -> System.out.println(i), materializer); done.thenRun(() -> system.terminate()); - //#run-source-and-terminate + // #run-source-and-terminate done.toCompletableFuture().get(); } - - //#transform-sink + + // #transform-sink public Sink> lineSink(String filename) { return Flow.of(String.class) - .map(s -> ByteString.fromString(s.toString() + "\n")) - .toMat(FileIO.toPath(Paths.get(filename)), Keep.right()); + .map(s -> ByteString.fromString(s.toString() + "\n")) + .toMat(FileIO.toPath(Paths.get(filename)), Keep.right()); } - //#transform-sink - + // #transform-sink + } diff --git a/akka-docs/src/test/java/jdocs/stream/RateTransformationDocTest.java b/akka-docs/src/test/java/jdocs/stream/RateTransformationDocTest.java index 7f1c5a52b8..84485201f3 100644 --- a/akka-docs/src/test/java/jdocs/stream/RateTransformationDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/RateTransformationDocTest.java @@ -61,65 +61,73 @@ public class RateTransformationDocTest extends AbstractJavaTest { @Test public void conflateShouldSummarize() throws Exception { - //#conflate-summarize + // #conflate-summarize final Flow, NotUsed> statsFlow = - Flow.of(Double.class) - .conflateWithSeed(elem -> Collections.singletonList(elem), (acc, elem) -> { - return Stream - .concat(acc.stream(), Collections.singletonList(elem).stream()) - .collect(Collectors.toList()); - }) - .map(s -> { - final Double mean = s.stream().mapToDouble(d -> d).sum() / s.size(); - final DoubleStream se = s.stream().mapToDouble(x -> Math.pow(x - mean, 2)); - final Double stdDev = Math.sqrt(se.sum() / s.size()); - return new Tuple3<>(stdDev, mean, s.size()); - }); - //#conflate-summarize + Flow.of(Double.class) + .conflateWithSeed( + elem -> Collections.singletonList(elem), + (acc, elem) -> { + return Stream.concat(acc.stream(), Collections.singletonList(elem).stream()) + .collect(Collectors.toList()); + }) + .map( + s -> { + final Double mean = s.stream().mapToDouble(d -> d).sum() / s.size(); + final DoubleStream se = s.stream().mapToDouble(x -> Math.pow(x - mean, 2)); + final Double stdDev = Math.sqrt(se.sum() / s.size()); + return new Tuple3<>(stdDev, mean, s.size()); + }); + // #conflate-summarize - final CompletionStage>> fut = Source.repeat(0).map(i -> r.nextGaussian()) - .via(statsFlow) - .grouped(10) - .runWith(Sink.head(), mat); + final CompletionStage>> fut = + Source.repeat(0) + .map(i -> r.nextGaussian()) + .via(statsFlow) + .grouped(10) + .runWith(Sink.head(), mat); fut.toCompletableFuture().get(1, TimeUnit.SECONDS); } @Test public void conflateShouldSample() throws Exception { - //#conflate-sample + // #conflate-sample final Double p = 0.01; - final Flow sampleFlow = Flow.of(Double.class) - .conflateWithSeed(elem -> Collections.singletonList(elem), (acc, elem) -> { - if (r.nextDouble() < p) { - return Stream - .concat(acc.stream(), Collections.singletonList(elem).stream()) - .collect(Collectors.toList()); - } - return acc; - }) - .mapConcat(d -> d); - //#conflate-sample + final Flow sampleFlow = + Flow.of(Double.class) + .conflateWithSeed( + elem -> Collections.singletonList(elem), + (acc, elem) -> { + if (r.nextDouble() < p) { + return Stream.concat(acc.stream(), Collections.singletonList(elem).stream()) + .collect(Collectors.toList()); + } + return acc; + }) + .mapConcat(d -> d); + // #conflate-sample - final CompletionStage fut = Source.from(new ArrayList(Collections.nCopies(1000, 1.0))) - .via(sampleFlow) - .runWith(Sink.fold(0.0, (agg, next) -> agg + next), mat); + final CompletionStage fut = + Source.from(new ArrayList(Collections.nCopies(1000, 1.0))) + .via(sampleFlow) + .runWith(Sink.fold(0.0, (agg, next) -> agg + next), mat); final Double count = fut.toCompletableFuture().get(1, TimeUnit.SECONDS); } @Test public void extrapolateShouldRepeatLast() throws Exception { - //#extrapolate-last - final Flow lastFlow = Flow.of(Double.class) - .extrapolate(in -> Stream.iterate(in, i -> i).iterator()); - //#extrapolate-last + // #extrapolate-last + final Flow lastFlow = + Flow.of(Double.class).extrapolate(in -> Stream.iterate(in, i -> i).iterator()); + // #extrapolate-last - final Pair, CompletionStage>> probeFut = TestSource. probe(system) - .via(lastFlow) - .grouped(10) - .toMat(Sink.head(), Keep.both()) - .run(mat); + final Pair, CompletionStage>> probeFut = + TestSource.probe(system) + .via(lastFlow) + .grouped(10) + .toMat(Sink.head(), Keep.both()) + .run(mat); final TestPublisher.Probe probe = probeFut.first(); final CompletionStage> fut = probeFut.second(); @@ -131,13 +139,14 @@ public class RateTransformationDocTest extends AbstractJavaTest { @Test public void extrapolateShouldSeedFirst() throws Exception { - //#extrapolate-seed + // #extrapolate-seed Double initial = 2.0; - final Flow lastFlow = Flow.of(Double.class) - .extrapolate(in -> Stream.iterate(in, i -> i).iterator(), initial); - //#extrapolate-seed + final Flow lastFlow = + Flow.of(Double.class).extrapolate(in -> Stream.iterate(in, i -> i).iterator(), initial); + // #extrapolate-seed - final CompletionStage> fut = TestSource. probe(system) + final CompletionStage> fut = + TestSource.probe(system) .via(lastFlow) .grouped(10) .toMat(Sink.head(), Keep.right()) @@ -145,28 +154,39 @@ public class RateTransformationDocTest extends AbstractJavaTest { final List extrapolated = fut.toCompletableFuture().get(1, TimeUnit.SECONDS); assertEquals(extrapolated.size(), 10); - assertEquals(extrapolated.stream().mapToDouble(d -> d).sum(), 10*initial, 0.1); + assertEquals(extrapolated.stream().mapToDouble(d -> d).sum(), 10 * initial, 0.1); } @Test public void extrapolateShouldTrackDrift() throws Exception { @SuppressWarnings("unused") - //#extrapolate-drift - final Flow, NotUsed> driftFlow = Flow.of(Double.class) + // #extrapolate-drift + final Flow, NotUsed> driftFlow = + Flow.of(Double.class) .map(d -> new Pair<>(d, 0)) - .extrapolate(d -> Stream.iterate(1, i -> i + 1).map(i -> new Pair<>(d.first(), i)).iterator()); - //#extrapolate-drift + .extrapolate( + d -> Stream.iterate(1, i -> i + 1).map(i -> new Pair<>(d.first(), i)).iterator()); + // #extrapolate-drift final TestLatch latch = new TestLatch(2, system); - final Flow, NotUsed> realDriftFlow = Flow.of(Double.class) - .map(d -> { - latch.countDown(); - return new Pair<>(d, 0); - }) - .extrapolate(d -> { latch.countDown(); return Stream.iterate(1, i -> i + 1).map(i -> new Pair<>(d.first(), i)).iterator(); }); + final Flow, NotUsed> realDriftFlow = + Flow.of(Double.class) + .map( + d -> { + latch.countDown(); + return new Pair<>(d, 0); + }) + .extrapolate( + d -> { + latch.countDown(); + return Stream.iterate(1, i -> i + 1) + .map(i -> new Pair<>(d.first(), i)) + .iterator(); + }); - final Pair, TestSubscriber.Probe>> pubSub = TestSource. probe(system) + final Pair, TestSubscriber.Probe>> pubSub = + TestSource.probe(system) .via(realDriftFlow) - .toMat(TestSink.> probe(system), Keep.both()) + .toMat(TestSink.>probe(system), Keep.both()) .run(mat); final TestPublisher.Probe pub = pubSub.first(); @@ -187,18 +207,25 @@ public class RateTransformationDocTest extends AbstractJavaTest { @Test public void expandShouldTrackDrift() throws Exception { @SuppressWarnings("unused") - //#expand-drift - final Flow, NotUsed> driftFlow = Flow.of(Double.class) - .expand(d -> Stream.iterate(0, i -> i + 1).map(i -> new Pair<>(d, i)).iterator()); - //#expand-drift + // #expand-drift + final Flow, NotUsed> driftFlow = + Flow.of(Double.class) + .expand(d -> Stream.iterate(0, i -> i + 1).map(i -> new Pair<>(d, i)).iterator()); + // #expand-drift final TestLatch latch = new TestLatch(2, system); - final Flow, NotUsed> realDriftFlow = Flow.of(Double.class) - .expand(d -> { latch.countDown(); return Stream.iterate(0, i -> i + 1).map(i -> new Pair<>(d, i)).iterator(); }); + final Flow, NotUsed> realDriftFlow = + Flow.of(Double.class) + .expand( + d -> { + latch.countDown(); + return Stream.iterate(0, i -> i + 1).map(i -> new Pair<>(d, i)).iterator(); + }); - final Pair, TestSubscriber.Probe>> pubSub = TestSource. probe(system) - .via(realDriftFlow) - .toMat(TestSink.> probe(system), Keep.both()) - .run(mat); + final Pair, TestSubscriber.Probe>> pubSub = + TestSource.probe(system) + .via(realDriftFlow) + .toMat(TestSink.>probe(system), Keep.both()) + .run(mat); final TestPublisher.Probe pub = pubSub.first(); final TestSubscriber.Probe> sub = pubSub.second(); @@ -214,5 +241,4 @@ public class RateTransformationDocTest extends AbstractJavaTest { Await.ready(latch, Duration.create(1, TimeUnit.SECONDS)); sub.requestNext(new Pair<>(2.0, 0)); } - } diff --git a/akka-docs/src/test/java/jdocs/stream/ReactiveStreamsDocTest.java b/akka-docs/src/test/java/jdocs/stream/ReactiveStreamsDocTest.java index a223ef1abe..f7c88f595d 100644 --- a/akka-docs/src/test/java/jdocs/stream/ReactiveStreamsDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/ReactiveStreamsDocTest.java @@ -19,14 +19,13 @@ import akka.testkit.javadsl.TestKit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -//#imports +// #imports import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Processor; -//#imports +// #imports import org.reactivestreams.Subscription; - import java.lang.Exception; import static jdocs.stream.ReactiveStreamsDocTest.Fixture.Data.authors; @@ -60,82 +59,81 @@ public class ReactiveStreamsDocTest extends AbstractJavaTest { // below class additionally helps with aligning code includes nicely static class Data { - static //#authors - final Flow authors = Flow.of(Tweet.class) - .filter(t -> t.hashtags().contains(AKKA)) - .map(t -> t.author); + static // #authors + final Flow authors = + Flow.of(Tweet.class).filter(t -> t.hashtags().contains(AKKA)).map(t -> t.author); - //#authors + // #authors } static interface RS { - //#tweets-publisher + // #tweets-publisher Publisher tweets(); - //#tweets-publisher + // #tweets-publisher - //#author-storage-subscriber + // #author-storage-subscriber Subscriber storage(); - //#author-storage-subscriber + // #author-storage-subscriber - //#author-alert-subscriber + // #author-alert-subscriber Subscriber alert(); - //#author-alert-subscriber + // #author-alert-subscriber } } - final Fixture.RS rs = new Fixture.RS() { - @Override - public Publisher tweets() { - return TwitterStreamQuickstartDocTest.Model.tweets.runWith(Sink.asPublisher(AsPublisher.WITHOUT_FANOUT), mat); - } + final Fixture.RS rs = + new Fixture.RS() { + @Override + public Publisher tweets() { + return TwitterStreamQuickstartDocTest.Model.tweets.runWith( + Sink.asPublisher(AsPublisher.WITHOUT_FANOUT), mat); + } - /** - * This is a minimal version of SubscriberProbe, - * which lives in akka-stream-testkit (test scope) and for - * now wanted to avoid setting up (test -> compile) dependency for Maven). - * - * TODO: Once SubscriberProbe is easily used here replace this MPS with it. - */ - class MinimalProbeSubscriber implements Subscriber { + /** + * This is a minimal version of SubscriberProbe, which lives in akka-stream-testkit (test + * scope) and for now wanted to avoid setting up (test -> compile) dependency for Maven). + * + *

TODO: Once SubscriberProbe is easily used here replace this MPS with it. + */ + class MinimalProbeSubscriber implements Subscriber { - private final ActorRef ref; + private final ActorRef ref; - public MinimalProbeSubscriber(ActorRef ref) { - this.ref = ref; - } + public MinimalProbeSubscriber(ActorRef ref) { + this.ref = ref; + } - @Override - public void onSubscribe(Subscription s) { - s.request(Long.MAX_VALUE); - } + @Override + public void onSubscribe(Subscription s) { + s.request(Long.MAX_VALUE); + } - @Override - public void onNext(T t) { - ref.tell(t, ActorRef.noSender()); - } + @Override + public void onNext(T t) { + ref.tell(t, ActorRef.noSender()); + } - @Override - public void onError(Throwable t) { - ref.tell(t, ActorRef.noSender()); - } + @Override + public void onError(Throwable t) { + ref.tell(t, ActorRef.noSender()); + } - @Override - public void onComplete() { - ref.tell("complete", ActorRef.noSender()); - } - } + @Override + public void onComplete() { + ref.tell("complete", ActorRef.noSender()); + } + } - @Override - public Subscriber storage() { - return new MinimalProbeSubscriber<>(storageProbe.ref()); - } - - @Override - public Subscriber alert() { - return new MinimalProbeSubscriber<>(alertProbe.ref()); - } - }; + @Override + public Subscriber storage() { + return new MinimalProbeSubscriber<>(storageProbe.ref()); + } + @Override + public Subscriber alert() { + return new MinimalProbeSubscriber<>(alertProbe.ref()); + } + }; @Test public void reactiveStreamsPublisherViaFlowToSubscriber() throws Exception { @@ -143,11 +141,9 @@ public class ReactiveStreamsDocTest extends AbstractJavaTest { final TestProbe probe = new TestProbe(system); { - //#connect-all - Source.fromPublisher(rs.tweets()) - .via(authors) - .to(Sink.fromSubscriber(rs.storage())); - //#connect-all + // #connect-all + Source.fromPublisher(rs.tweets()).via(authors).to(Sink.fromSubscriber(rs.storage())); + // #connect-all } }; } @@ -158,14 +154,12 @@ public class ReactiveStreamsDocTest extends AbstractJavaTest { final TestProbe probe = new TestProbe(system); { - //#flow-publisher-subscriber - final Processor processor = - authors.toProcessor().run(mat); - + // #flow-publisher-subscriber + final Processor processor = authors.toProcessor().run(mat); rs.tweets().subscribe(processor); processor.subscribe(rs.storage()); - //#flow-publisher-subscriber + // #flow-publisher-subscriber assertStorageResult(); } @@ -178,14 +172,14 @@ public class ReactiveStreamsDocTest extends AbstractJavaTest { final TestProbe probe = new TestProbe(system); { - //#source-publisher + // #source-publisher final Publisher authorPublisher = - Source.fromPublisher(rs.tweets()) - .via(authors) - .runWith(Sink.asPublisher(AsPublisher.WITHOUT_FANOUT), mat); + Source.fromPublisher(rs.tweets()) + .via(authors) + .runWith(Sink.asPublisher(AsPublisher.WITHOUT_FANOUT), mat); authorPublisher.subscribe(rs.storage()); - //#source-publisher + // #source-publisher assertStorageResult(); } @@ -198,15 +192,15 @@ public class ReactiveStreamsDocTest extends AbstractJavaTest { final TestProbe probe = new TestProbe(system); { - //#source-fanoutPublisher + // #source-fanoutPublisher final Publisher authorPublisher = - Source.fromPublisher(rs.tweets()) - .via(authors) - .runWith(Sink.asPublisher(AsPublisher.WITH_FANOUT), mat); + Source.fromPublisher(rs.tweets()) + .via(authors) + .runWith(Sink.asPublisher(AsPublisher.WITH_FANOUT), mat); authorPublisher.subscribe(rs.storage()); authorPublisher.subscribe(rs.alert()); - //#source-fanoutPublisher + // #source-fanoutPublisher assertStorageResult(); } @@ -219,16 +213,14 @@ public class ReactiveStreamsDocTest extends AbstractJavaTest { final TestProbe probe = new TestProbe(system); { - //#sink-subscriber + // #sink-subscriber final Subscriber storage = rs.storage(); final Subscriber tweetSubscriber = - authors - .to(Sink.fromSubscriber(storage)) - .runWith(Source.asSubscriber(), mat); + authors.to(Sink.fromSubscriber(storage)).runWith(Source.asSubscriber(), mat); rs.tweets().subscribe(tweetSubscriber); - //#sink-subscriber + // #sink-subscriber assertStorageResult(); } @@ -239,18 +231,18 @@ public class ReactiveStreamsDocTest extends AbstractJavaTest { public void useProcessor() throws Exception { new TestKit(system) { { - //#use-processor + // #use-processor // An example Processor factory final Creator> factory = - new Creator>() { - public Processor create() { - return Flow.of(Integer.class).toProcessor().run(mat); - } - }; + new Creator>() { + public Processor create() { + return Flow.of(Integer.class).toProcessor().run(mat); + } + }; final Flow flow = Flow.fromProcessor(factory); - //#use-processor + // #use-processor } }; } @@ -265,5 +257,4 @@ public class ReactiveStreamsDocTest extends AbstractJavaTest { storageProbe.expectMsg(new Author("akkateam")); storageProbe.expectMsg("complete"); } - } diff --git a/akka-docs/src/test/java/jdocs/stream/RestartDocTest.java b/akka-docs/src/test/java/jdocs/stream/RestartDocTest.java index 05c297c960..670164ac0f 100644 --- a/akka-docs/src/test/java/jdocs/stream/RestartDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/RestartDocTest.java @@ -28,62 +28,69 @@ public class RestartDocTest { public static Http get(ActorSystem system) { return new Http(); } + public CompletionStage singleRequest(String uri) { return new CompletableFuture<>(); } + public NotUsed entity() { return NotUsed.getInstance(); } } + public static class HttpRequest { public static String create(String uri) { return uri; } } + public static class ServerSentEvent {} + public static class EventStreamUnmarshalling { public static EventStreamUnmarshalling fromEventStream() { return new EventStreamUnmarshalling(); } - public CompletionStage> unmarshall(Http http, Materializer mat) { + + public CompletionStage> unmarshall( + Http http, Materializer mat) { return new CompletableFuture<>(); } } - public void doSomethingElse() { - } + public void doSomethingElse() {} public void recoverWithBackoffSource() { - //#restart-with-backoff-source - Source eventStream = RestartSource.withBackoff( + // #restart-with-backoff-source + Source eventStream = + RestartSource.withBackoff( Duration.ofSeconds(3), // min backoff Duration.ofSeconds(30), // max backoff - 0.2, // adds 20% "noise" to vary the intervals slightly - 20, // limits the amount of restarts to 20 - () -> - // Create a source from a future of a source - Source.fromSourceCompletionStage( - // Issue a GET request on the event stream - Http.get(system).singleRequest(HttpRequest.create("http://example.com/eventstream")) - .thenCompose(response -> - // Unmarshall it to a stream of ServerSentEvents - EventStreamUnmarshalling.fromEventStream() - .unmarshall(response, materializer) - ) - ) - ); - //#restart-with-backoff-source + 0.2, // adds 20% "noise" to vary the intervals slightly + 20, // limits the amount of restarts to 20 + () -> + // Create a source from a future of a source + Source.fromSourceCompletionStage( + // Issue a GET request on the event stream + Http.get(system) + .singleRequest(HttpRequest.create("http://example.com/eventstream")) + .thenCompose( + response -> + // Unmarshall it to a stream of ServerSentEvents + EventStreamUnmarshalling.fromEventStream() + .unmarshall(response, materializer)))); + // #restart-with-backoff-source - //#with-kill-switch - KillSwitch killSwitch = eventStream - .viaMat(KillSwitches.single(), Keep.right()) - .toMat(Sink.foreach(event -> System.out.println("Got event: " + event)), Keep.left()) - .run(materializer); + // #with-kill-switch + KillSwitch killSwitch = + eventStream + .viaMat(KillSwitches.single(), Keep.right()) + .toMat(Sink.foreach(event -> System.out.println("Got event: " + event)), Keep.left()) + .run(materializer); doSomethingElse(); killSwitch.shutdown(); - //#with-kill-switch + // #with-kill-switch } -} \ No newline at end of file +} diff --git a/akka-docs/src/test/java/jdocs/stream/SilenceSystemOut.java b/akka-docs/src/test/java/jdocs/stream/SilenceSystemOut.java index 3fc58c6a8b..b3677b0ab8 100644 --- a/akka-docs/src/test/java/jdocs/stream/SilenceSystemOut.java +++ b/akka-docs/src/test/java/jdocs/stream/SilenceSystemOut.java @@ -9,39 +9,41 @@ import akka.actor.ActorRef; import java.util.function.Predicate; /** - * Acts as if `System.out.println()` yet swallows all messages. Useful for putting printlines in examples yet without polluting the build with them. + * Acts as if `System.out.println()` yet swallows all messages. Useful for putting printlines in + * examples yet without polluting the build with them. */ public class SilenceSystemOut { - private SilenceSystemOut() { - } + private SilenceSystemOut() {} public static System get() { - return new System(new System.Println() { - @Override - public void println(String s) { - // ignore - } - }); + return new System( + new System.Println() { + @Override + public void println(String s) { + // ignore + } + }); } public static System get(ActorRef probe) { - return new System(new System.Println() { - @Override - public void println(String s) { - probe.tell(s, ActorRef.noSender()); - } - }); + return new System( + new System.Println() { + @Override + public void println(String s) { + probe.tell(s, ActorRef.noSender()); + } + }); } public static System get(Predicate filter, ActorRef probe) { - return new System(new System.Println() { - @Override - public void println(String s) { - if (filter.test(s)) - probe.tell(s, ActorRef.noSender()); - } - }); + return new System( + new System.Println() { + @Override + public void println(String s) { + if (filter.test(s)) probe.tell(s, ActorRef.noSender()); + } + }); } public static class System { @@ -51,7 +53,7 @@ public class SilenceSystemOut { this.out = out; } - public static abstract class Println { + public abstract static class Println { public abstract void println(String s); public void println(Object s) { @@ -62,7 +64,5 @@ public class SilenceSystemOut { println(String.format(format, args)); } } - } - } diff --git a/akka-docs/src/test/java/jdocs/stream/SinkRecipeDocTest.java b/akka-docs/src/test/java/jdocs/stream/SinkRecipeDocTest.java index 6fdb315ddd..8473828142 100644 --- a/akka-docs/src/test/java/jdocs/stream/SinkRecipeDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/SinkRecipeDocTest.java @@ -19,26 +19,26 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; public class SinkRecipeDocTest extends AbstractJavaTest { - static ActorSystem system; - static Materializer mat; + static ActorSystem system; + static Materializer mat; - @BeforeClass - public static void setup() { - system = ActorSystem.create("SinkRecipeDocTest"); - mat = ActorMaterializer.create(system); - } + @BeforeClass + public static void setup() { + system = ActorSystem.create("SinkRecipeDocTest"); + mat = ActorMaterializer.create(system); + } - @Test - public void foreachAsync() { - final Function> asyncProcessing = param -> CompletableFuture.completedFuture(param).thenAccept(System.out::println); + @Test + public void foreachAsync() { + final Function> asyncProcessing = + param -> CompletableFuture.completedFuture(param).thenAccept(System.out::println); - //#forseachAsync-processing - //final Function> asyncProcessing = _ + // #forseachAsync-processing + // final Function> asyncProcessing = _ - final Source numberSource = Source.range(1, 100); + final Source numberSource = Source.range(1, 100); - numberSource - .runWith(Sink.foreachAsync(10, asyncProcessing), mat); - //#forseachAsync-processing - } + numberSource.runWith(Sink.foreachAsync(10, asyncProcessing), mat); + // #forseachAsync-processing + } } diff --git a/akka-docs/src/test/java/jdocs/stream/StreamBuffersRateDocTest.java b/akka-docs/src/test/java/jdocs/stream/StreamBuffersRateDocTest.java index d80fe8c2f1..a4626e5e3d 100644 --- a/akka-docs/src/test/java/jdocs/stream/StreamBuffersRateDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/StreamBuffersRateDocTest.java @@ -42,88 +42,104 @@ public class StreamBuffersRateDocTest extends AbstractJavaTest { @Test public void demonstratePipelining() { - //#pipelining + // #pipelining Source.from(Arrays.asList(1, 2, 3)) - .map(i -> {System.out.println("A: " + i); return i;}).async() - .map(i -> {System.out.println("B: " + i); return i;}).async() - .map(i -> {System.out.println("C: " + i); return i;}).async() - .runWith(Sink.ignore(), mat); - //#pipelining + .map( + i -> { + System.out.println("A: " + i); + return i; + }) + .async() + .map( + i -> { + System.out.println("B: " + i); + return i; + }) + .async() + .map( + i -> { + System.out.println("C: " + i); + return i; + }) + .async() + .runWith(Sink.ignore(), mat); + // #pipelining } @Test @SuppressWarnings("unused") public void demonstrateBufferSizes() { - //#materializer-buffer - final Materializer materializer = ActorMaterializer.create( - ActorMaterializerSettings.create(system) - .withInputBuffer(64, 64), system); - //#materializer-buffer + // #materializer-buffer + final Materializer materializer = + ActorMaterializer.create( + ActorMaterializerSettings.create(system).withInputBuffer(64, 64), system); + // #materializer-buffer - //#section-buffer + // #section-buffer final Flow flow1 = - Flow.of(Integer.class) - .map(elem -> elem * 2).async() - .addAttributes(Attributes.inputBuffer(1, 1)); // the buffer size of this map is 1 - final Flow flow2 = - flow1.via( Flow.of(Integer.class) - .map(elem -> elem / 2)).async(); // the buffer size of this map is the default - //#section-buffer + .map(elem -> elem * 2) + .async() + .addAttributes(Attributes.inputBuffer(1, 1)); // the buffer size of this map is 1 + final Flow flow2 = + flow1 + .via(Flow.of(Integer.class).map(elem -> elem / 2)) + .async(); // the buffer size of this map is the default + // #section-buffer } @Test public void demonstrateBufferAbstractionLeak() { - //#buffering-abstraction-leak + // #buffering-abstraction-leak final Duration oneSecond = Duration.ofSeconds(1); - final Source msgSource = - Source.tick(oneSecond, oneSecond, "message!"); + final Source msgSource = Source.tick(oneSecond, oneSecond, "message!"); final Source tickSource = Source.tick(oneSecond.multipliedBy(3), oneSecond.multipliedBy(3), "tick"); final Flow conflate = - Flow.of(String.class).conflateWithSeed( - first -> 1, (count, elem) -> count + 1); + Flow.of(String.class).conflateWithSeed(first -> 1, (count, elem) -> count + 1); - RunnableGraph.fromGraph(GraphDSL.create(b -> { - // this is the asynchronous stage in this graph - final FanInShape2 zipper = - b.add(ZipWith.create((String tick, Integer count) -> count).async()); - b.from(b.add(msgSource)).via(b.add(conflate)).toInlet(zipper.in1()); - b.from(b.add(tickSource)).toInlet(zipper.in0()); - b.from(zipper.out()).to(b.add(Sink.foreach(elem -> System.out.println(elem)))); - return ClosedShape.getInstance(); - })).run(mat); - //#buffering-abstraction-leak + RunnableGraph.fromGraph( + GraphDSL.create( + b -> { + // this is the asynchronous stage in this graph + final FanInShape2 zipper = + b.add(ZipWith.create((String tick, Integer count) -> count).async()); + b.from(b.add(msgSource)).via(b.add(conflate)).toInlet(zipper.in1()); + b.from(b.add(tickSource)).toInlet(zipper.in0()); + b.from(zipper.out()).to(b.add(Sink.foreach(elem -> System.out.println(elem)))); + return ClosedShape.getInstance(); + })) + .run(mat); + // #buffering-abstraction-leak } @Test public void demonstrateExplicitBuffers() { final Source inboundJobsConnector = Source.empty(); - //#explicit-buffers-backpressure + // #explicit-buffers-backpressure // Getting a stream of jobs from an imaginary external system as a Source final Source jobs = inboundJobsConnector; jobs.buffer(1000, OverflowStrategy.backpressure()); - //#explicit-buffers-backpressure + // #explicit-buffers-backpressure - //#explicit-buffers-droptail + // #explicit-buffers-droptail jobs.buffer(1000, OverflowStrategy.dropTail()); - //#explicit-buffers-droptail + // #explicit-buffers-droptail - //#explicit-buffers-dropnew + // #explicit-buffers-dropnew jobs.buffer(1000, OverflowStrategy.dropNew()); - //#explicit-buffers-dropnew + // #explicit-buffers-dropnew - //#explicit-buffers-drophead + // #explicit-buffers-drophead jobs.buffer(1000, OverflowStrategy.dropHead()); - //#explicit-buffers-drophead + // #explicit-buffers-drophead - //#explicit-buffers-dropbuffer + // #explicit-buffers-dropbuffer jobs.buffer(1000, OverflowStrategy.dropBuffer()); - //#explicit-buffers-dropbuffer + // #explicit-buffers-dropbuffer - //#explicit-buffers-fail + // #explicit-buffers-fail jobs.buffer(1000, OverflowStrategy.fail()); - //#explicit-buffers-fail + // #explicit-buffers-fail } - } diff --git a/akka-docs/src/test/java/jdocs/stream/StreamPartialGraphDSLDocTest.java b/akka-docs/src/test/java/jdocs/stream/StreamPartialGraphDSLDocTest.java index 6cda99c778..89909c1175 100644 --- a/akka-docs/src/test/java/jdocs/stream/StreamPartialGraphDSLDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/StreamPartialGraphDSLDocTest.java @@ -42,120 +42,129 @@ public class StreamPartialGraphDSLDocTest extends AbstractJavaTest { system = null; mat = null; } - + @Test public void demonstrateBuildWithOpenPorts() throws Exception { - //#simple-partial-graph-dsl + // #simple-partial-graph-dsl final Graph, NotUsed> zip = - ZipWith.create((Integer left, Integer right) -> Math.max(left, right)); - + ZipWith.create((Integer left, Integer right) -> Math.max(left, right)); + final Graph, NotUsed> pickMaxOfThree = - GraphDSL.create(builder -> { - final FanInShape2 zip1 = builder.add(zip); - final FanInShape2 zip2 = builder.add(zip); - - builder.from(zip1.out()).toInlet(zip2.in0()); - // return the shape, which has three inputs and one output - return new UniformFanInShape(zip2.out(), - new Inlet[] {zip1.in0(), zip1.in1(), zip2.in1()}); - }); + GraphDSL.create( + builder -> { + final FanInShape2 zip1 = builder.add(zip); + final FanInShape2 zip2 = builder.add(zip); + + builder.from(zip1.out()).toInlet(zip2.in0()); + // return the shape, which has three inputs and one output + return new UniformFanInShape( + zip2.out(), new Inlet[] {zip1.in0(), zip1.in1(), zip2.in1()}); + }); final Sink> resultSink = Sink.head(); final RunnableGraph> g = - RunnableGraph.>fromGraph( - GraphDSL.create(resultSink, (builder, sink) -> { - // import the partial graph explicitly - final UniformFanInShape pm = builder.add(pickMaxOfThree); - - builder.from(builder.add(Source.single(1))).toInlet(pm.in(0)); - builder.from(builder.add(Source.single(2))).toInlet(pm.in(1)); - builder.from(builder.add(Source.single(3))).toInlet(pm.in(2)); - builder.from(pm.out()).to(sink); - return ClosedShape.getInstance(); - })); - + RunnableGraph.>fromGraph( + GraphDSL.create( + resultSink, + (builder, sink) -> { + // import the partial graph explicitly + final UniformFanInShape pm = builder.add(pickMaxOfThree); + + builder.from(builder.add(Source.single(1))).toInlet(pm.in(0)); + builder.from(builder.add(Source.single(2))).toInlet(pm.in(1)); + builder.from(builder.add(Source.single(3))).toInlet(pm.in(2)); + builder.from(pm.out()).to(sink); + return ClosedShape.getInstance(); + })); + final CompletionStage max = g.run(mat); - //#simple-partial-graph-dsl + // #simple-partial-graph-dsl assertEquals(Integer.valueOf(3), max.toCompletableFuture().get(3, TimeUnit.SECONDS)); } - //#source-from-partial-graph-dsl - // first create an indefinite source of integer numbers - class Ints implements Iterator { - private int next = 0; - @Override - public boolean hasNext() { - return true; - } - @Override - public Integer next() { - return next++; - } + // #source-from-partial-graph-dsl + // first create an indefinite source of integer numbers + class Ints implements Iterator { + private int next = 0; + + @Override + public boolean hasNext() { + return true; } - //#source-from-partial-graph-dsl - + + @Override + public Integer next() { + return next++; + } + } + // #source-from-partial-graph-dsl + @Test public void demonstrateBuildSourceFromPartialGraphDSLCreate() throws Exception { - //#source-from-partial-graph-dsl + // #source-from-partial-graph-dsl final Source ints = Source.fromIterator(() -> new Ints()); - - final Source, NotUsed> pairs = Source.fromGraph( - GraphDSL.create( - builder -> { - final FanInShape2> zip = - builder.add(Zip.create()); - builder.from(builder.add(ints.filter(i -> i % 2 == 0))).toInlet(zip.in0()); - builder.from(builder.add(ints.filter(i -> i % 2 == 1))).toInlet(zip.in1()); - - return SourceShape.of(zip.out()); - })); - - final CompletionStage> firstPair = + final Source, NotUsed> pairs = + Source.fromGraph( + GraphDSL.create( + builder -> { + final FanInShape2> zip = + builder.add(Zip.create()); + + builder.from(builder.add(ints.filter(i -> i % 2 == 0))).toInlet(zip.in0()); + builder.from(builder.add(ints.filter(i -> i % 2 == 1))).toInlet(zip.in1()); + + return SourceShape.of(zip.out()); + })); + + final CompletionStage> firstPair = pairs.runWith(Sink.>head(), mat); - //#source-from-partial-graph-dsl + // #source-from-partial-graph-dsl assertEquals(new Pair<>(0, 1), firstPair.toCompletableFuture().get(3, TimeUnit.SECONDS)); } - + @Test public void demonstrateBuildFlowFromPartialGraphDSLCreate() throws Exception { - //#flow-from-partial-graph-dsl - final Flow, NotUsed> pairs = Flow.fromGraph(GraphDSL.create( - b -> { - final UniformFanOutShape bcast = b.add(Broadcast.create(2)); - final FanInShape2> zip = - b.add(Zip.create()); + // #flow-from-partial-graph-dsl + final Flow, NotUsed> pairs = + Flow.fromGraph( + GraphDSL.create( + b -> { + final UniformFanOutShape bcast = b.add(Broadcast.create(2)); + final FanInShape2> zip = + b.add(Zip.create()); - b.from(bcast).toInlet(zip.in0()); - b.from(bcast).via(b.add(Flow.of(Integer.class).map(i -> i.toString()))).toInlet(zip.in1()); - - return FlowShape.of(bcast.in(), zip.out()); - })); - - //#flow-from-partial-graph-dsl + b.from(bcast).toInlet(zip.in0()); + b.from(bcast) + .via(b.add(Flow.of(Integer.class).map(i -> i.toString()))) + .toInlet(zip.in1()); + + return FlowShape.of(bcast.in(), zip.out()); + })); + + // #flow-from-partial-graph-dsl final CompletionStage> matSink = - //#flow-from-partial-graph-dsl - Source.single(1).via(pairs).runWith(Sink.>head(), mat); - //#flow-from-partial-graph-dsl + // #flow-from-partial-graph-dsl + Source.single(1).via(pairs).runWith(Sink.>head(), mat); + // #flow-from-partial-graph-dsl assertEquals(new Pair<>(1, "1"), matSink.toCompletableFuture().get(3, TimeUnit.SECONDS)); } - @Test public void demonstrateBuildSourceWithCombine() throws Exception { - //#source-combine + // #source-combine Source source1 = Source.single(1); Source source2 = Source.single(2); - final Source sources = Source.combine(source1, source2, new ArrayList<>(), - i -> Merge.create(i)); - //#source-combine - final CompletionStage result= - //#source-combine - sources.runWith(Sink.fold(0, (a,b) -> a + b), mat); - //#source-combine + final Source sources = + Source.combine(source1, source2, new ArrayList<>(), i -> Merge.create(i)); + // #source-combine + final CompletionStage result = + // #source-combine + sources.runWith(Sink.fold(0, (a, b) -> a + b), mat); + // #source-combine assertEquals(Integer.valueOf(3), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); } @@ -163,15 +172,20 @@ public class StreamPartialGraphDSLDocTest extends AbstractJavaTest { @Test public void demonstrateBuildSinkWithCombine() throws Exception { final TestKit probe = new TestKit(system); - ActorRef actorRef = probe.getRef(); + ActorRef actorRef = probe.getRef(); - //#sink-combine + // #sink-combine Sink sendRemotely = Sink.actorRef(actorRef, "Done"); - Sink> localProcessing = Sink.foreach(a -> { /*do something useful*/ } ); - Sink sinks = Sink.combine(sendRemotely,localProcessing, new ArrayList<>(), a -> Broadcast.create(a)); + Sink> localProcessing = + Sink.foreach( + a -> { + /*do something useful*/ + }); + Sink sinks = + Sink.combine(sendRemotely, localProcessing, new ArrayList<>(), a -> Broadcast.create(a)); - Source.from(Arrays.asList(new Integer[]{0, 1, 2})).runWith(sinks, mat); - //#sink-combine + Source.from(Arrays.asList(new Integer[] {0, 1, 2})).runWith(sinks, mat); + // #sink-combine probe.expectMsgEquals(0); probe.expectMsgEquals(1); probe.expectMsgEquals(2); diff --git a/akka-docs/src/test/java/jdocs/stream/StreamTestKitDocTest.java b/akka-docs/src/test/java/jdocs/stream/StreamTestKitDocTest.java index e31d287b8c..1be940ebe9 100644 --- a/akka-docs/src/test/java/jdocs/stream/StreamTestKitDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/StreamTestKitDocTest.java @@ -26,7 +26,6 @@ import akka.stream.javadsl.*; import akka.stream.testkit.*; import akka.stream.testkit.javadsl.*; - public class StreamTestKitDocTest extends AbstractJavaTest { static ActorSystem system; @@ -47,92 +46,93 @@ public class StreamTestKitDocTest extends AbstractJavaTest { @Test public void strictCollection() throws Exception { - //#strict-collection - final Sink> sinkUnderTest = Flow.of(Integer.class) - .map(i -> i * 2) - .toMat(Sink.fold(0, (agg, next) -> agg + next), Keep.right()); + // #strict-collection + final Sink> sinkUnderTest = + Flow.of(Integer.class) + .map(i -> i * 2) + .toMat(Sink.fold(0, (agg, next) -> agg + next), Keep.right()); - final CompletionStage future = Source.from(Arrays.asList(1, 2, 3, 4)) - .runWith(sinkUnderTest, mat); + final CompletionStage future = + Source.from(Arrays.asList(1, 2, 3, 4)).runWith(sinkUnderTest, mat); final Integer result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); - assert(result == 20); - //#strict-collection + assert (result == 20); + // #strict-collection } @Test public void groupedPartOfInfiniteStream() throws Exception { - //#grouped-infinite - final Source sourceUnderTest = Source.repeat(1) - .map(i -> i * 2); + // #grouped-infinite + final Source sourceUnderTest = Source.repeat(1).map(i -> i * 2); - final CompletionStage> future = sourceUnderTest - .take(10) - .runWith(Sink.seq(), mat); + final CompletionStage> future = sourceUnderTest.take(10).runWith(Sink.seq(), mat); final List result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals(result, Collections.nCopies(10, 2)); - //#grouped-infinite + // #grouped-infinite } @Test public void foldedStream() throws Exception { - //#folded-stream - final Flow flowUnderTest = Flow.of(Integer.class) - .takeWhile(i -> i < 5); + // #folded-stream + final Flow flowUnderTest = + Flow.of(Integer.class).takeWhile(i -> i < 5); - final CompletionStage future = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6)) - .via(flowUnderTest).runWith(Sink.fold(0, (agg, next) -> agg + next), mat); + final CompletionStage future = + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6)) + .via(flowUnderTest) + .runWith(Sink.fold(0, (agg, next) -> agg + next), mat); final Integer result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); - assert(result == 10); - //#folded-stream + assert (result == 10); + // #folded-stream } @Test public void pipeToTestProbe() throws Exception { - //#pipeto-testprobe - final Source, NotUsed> sourceUnderTest = Source - .from(Arrays.asList(1, 2, 3, 4)) - .grouped(2); + // #pipeto-testprobe + final Source, NotUsed> sourceUnderTest = + Source.from(Arrays.asList(1, 2, 3, 4)).grouped(2); final TestKit probe = new TestKit(system); - final CompletionStage>> future = sourceUnderTest - .grouped(2) - .runWith(Sink.head(), mat); + final CompletionStage>> future = + sourceUnderTest.grouped(2).runWith(Sink.head(), mat); akka.pattern.Patterns.pipe(future, system.dispatcher()).to(probe.getRef()); probe.expectMsg(Duration.ofSeconds(3), Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3, 4))); - //#pipeto-testprobe + // #pipeto-testprobe } - public enum Tick { TOCK, COMPLETED }; + public enum Tick { + TOCK, + COMPLETED + }; @Test public void sinkActorRef() throws Exception { - //#sink-actorref - final Source sourceUnderTest = Source.tick( - Duration.ZERO, - Duration.ofMillis(200), - Tick.TOCK); + // #sink-actorref + final Source sourceUnderTest = + Source.tick(Duration.ZERO, Duration.ofMillis(200), Tick.TOCK); final TestKit probe = new TestKit(system); - final Cancellable cancellable = sourceUnderTest.to(Sink.actorRef(probe.getRef(), Tick.COMPLETED)).run(mat); + final Cancellable cancellable = + sourceUnderTest.to(Sink.actorRef(probe.getRef(), Tick.COMPLETED)).run(mat); probe.expectMsg(Duration.ofSeconds(3), Tick.TOCK); probe.expectNoMessage(Duration.ofMillis(100)); probe.expectMsg(Duration.ofSeconds(3), Tick.TOCK); cancellable.cancel(); probe.expectMsg(Duration.ofSeconds(3), Tick.COMPLETED); - //#sink-actorref + // #sink-actorref } @Test public void sourceActorRef() throws Exception { - //#source-actorref - final Sink> sinkUnderTest = Flow.of(Integer.class) - .map(i -> i.toString()) - .toMat(Sink.fold("", (agg, next) -> agg + next), Keep.right()); + // #source-actorref + final Sink> sinkUnderTest = + Flow.of(Integer.class) + .map(i -> i.toString()) + .toMat(Sink.fold("", (agg, next) -> agg + next), Keep.right()); final Pair> refAndCompletionStage = - Source.actorRef(8, OverflowStrategy.fail()) - .toMat(sinkUnderTest, Keep.both()) - .run(mat); + Source.actorRef(8, OverflowStrategy.fail()) + .toMat(sinkUnderTest, Keep.both()) + .run(mat); final ActorRef ref = refAndCompletionStage.first(); final CompletionStage future = refAndCompletionStage.second(); @@ -143,45 +143,42 @@ public class StreamTestKitDocTest extends AbstractJavaTest { final String result = future.toCompletableFuture().get(1, TimeUnit.SECONDS); assertEquals(result, "123"); - //#source-actorref + // #source-actorref } @Test public void testSinkProbe() { - //#test-sink-probe - final Source sourceUnderTest = Source.from(Arrays.asList(1, 2, 3, 4)) - .filter(elem -> elem % 2 == 0) - .map(elem -> elem * 2); + // #test-sink-probe + final Source sourceUnderTest = + Source.from(Arrays.asList(1, 2, 3, 4)).filter(elem -> elem % 2 == 0).map(elem -> elem * 2); sourceUnderTest - .runWith(TestSink.probe(system), mat) - .request(2) - .expectNext(4, 8) - .expectComplete(); - //#test-sink-probe + .runWith(TestSink.probe(system), mat) + .request(2) + .expectNext(4, 8) + .expectComplete(); + // #test-sink-probe } @Test public void testSourceProbe() { - //#test-source-probe + // #test-source-probe final Sink sinkUnderTest = Sink.cancelled(); TestSource.probe(system) - .toMat(sinkUnderTest, Keep.left()) - .run(mat) - .expectCancellation(); - //#test-source-probe + .toMat(sinkUnderTest, Keep.left()) + .run(mat) + .expectCancellation(); + // #test-source-probe } @Test public void injectingFailure() throws Exception { - //#injecting-failure + // #injecting-failure final Sink> sinkUnderTest = Sink.head(); final Pair, CompletionStage> probeAndCompletionStage = - TestSource.probe(system) - .toMat(sinkUnderTest, Keep.both()) - .run(mat); + TestSource.probe(system).toMat(sinkUnderTest, Keep.both()).run(mat); final TestPublisher.Probe probe = probeAndCompletionStage.first(); final CompletionStage future = probeAndCompletionStage.second(); probe.sendError(new Exception("boom")); @@ -193,25 +190,28 @@ public class StreamTestKitDocTest extends AbstractJavaTest { final Throwable exception = ee.getCause(); assertEquals(exception.getMessage(), "boom"); } - //#injecting-failure + // #injecting-failure } @Test public void testSourceAndTestSink() throws Exception { - //#test-source-and-sink - final Flow flowUnderTest = Flow.of(Integer.class) - .mapAsyncUnordered(2, sleep -> akka.pattern.Patterns.after( - Duration.ofMillis(10), - system.scheduler(), - system.dispatcher(), - CompletableFuture.completedFuture(sleep) - )); + // #test-source-and-sink + final Flow flowUnderTest = + Flow.of(Integer.class) + .mapAsyncUnordered( + 2, + sleep -> + akka.pattern.Patterns.after( + Duration.ofMillis(10), + system.scheduler(), + system.dispatcher(), + CompletableFuture.completedFuture(sleep))); final Pair, TestSubscriber.Probe> pubAndSub = - TestSource.probe(system) - .via(flowUnderTest) - .toMat(TestSink.probe(system), Keep.both()) - .run(mat); + TestSource.probe(system) + .via(flowUnderTest) + .toMat(TestSink.probe(system), Keep.both()) + .run(mat); final TestPublisher.Probe pub = pubAndSub.first(); final TestSubscriber.Probe sub = pubAndSub.second(); @@ -223,7 +223,7 @@ public class StreamTestKitDocTest extends AbstractJavaTest { pub.sendError(new Exception("Power surge in the linear subroutine C-47!")); final Throwable ex = sub.expectError(); - assert(ex.getMessage().contains("C-47")); - //#test-source-and-sink + assert (ex.getMessage().contains("C-47")); + // #test-source-and-sink } } diff --git a/akka-docs/src/test/java/jdocs/stream/SubstreamDocTest.java b/akka-docs/src/test/java/jdocs/stream/SubstreamDocTest.java index d21eef0f38..59af91c0ab 100644 --- a/akka-docs/src/test/java/jdocs/stream/SubstreamDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/SubstreamDocTest.java @@ -19,98 +19,93 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -public class SubstreamDocTest extends AbstractJavaTest { +public class SubstreamDocTest extends AbstractJavaTest { - static ActorSystem system; - static Materializer mat; + static ActorSystem system; + static Materializer mat; - @BeforeClass - public static void setup() { - system = ActorSystem.create("FlowDocTest"); - mat = ActorMaterializer.create(system); - } + @BeforeClass + public static void setup() { + system = ActorSystem.create("FlowDocTest"); + mat = ActorMaterializer.create(system); + } - @AfterClass - public static void tearDown() { - TestKit.shutdownActorSystem(system); - system = null; - mat = null; - } + @AfterClass + public static void tearDown() { + TestKit.shutdownActorSystem(system); + system = null; + mat = null; + } - @Test - public void demonstrateGroupBy() throws Exception { - //#groupBy1 - Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) - .groupBy(3, elem -> elem % 3); - //#groupBy1 + @Test + public void demonstrateGroupBy() throws Exception { + // #groupBy1 + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).groupBy(3, elem -> elem % 3); + // #groupBy1 - //#groupBy2 - Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) - .groupBy(3, elem -> elem % 3) - .to(Sink.ignore()) - .run(mat); - //#groupBy2 + // #groupBy2 + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) + .groupBy(3, elem -> elem % 3) + .to(Sink.ignore()) + .run(mat); + // #groupBy2 - //#groupBy3 - Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) - .groupBy(3, elem -> elem % 3) - .mergeSubstreams() - .runWith(Sink.ignore(), mat); - //#groupBy3 + // #groupBy3 + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) + .groupBy(3, elem -> elem % 3) + .mergeSubstreams() + .runWith(Sink.ignore(), mat); + // #groupBy3 - //#groupBy4 - Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) - .groupBy(3, elem -> elem % 3) - .mergeSubstreamsWithParallelism(2) - .runWith(Sink.ignore(), mat); - //concatSubstreams is equivalent to mergeSubstreamsWithParallelism(1) - Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) - .groupBy(3, elem -> elem % 3) - .concatSubstreams() - .runWith(Sink.ignore(), mat); - //#groupBy4 - } + // #groupBy4 + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) + .groupBy(3, elem -> elem % 3) + .mergeSubstreamsWithParallelism(2) + .runWith(Sink.ignore(), mat); + // concatSubstreams is equivalent to mergeSubstreamsWithParallelism(1) + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) + .groupBy(3, elem -> elem % 3) + .concatSubstreams() + .runWith(Sink.ignore(), mat); + // #groupBy4 + } - @Test - public void demonstrateSplitWhenAfter() throws Exception { - //#splitWhenAfter - Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) - .splitWhen(elem -> elem == 3); + @Test + public void demonstrateSplitWhenAfter() throws Exception { + // #splitWhenAfter + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).splitWhen(elem -> elem == 3); - Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) - .splitAfter(elem -> elem == 3); - //#splitWhenAfter + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)).splitAfter(elem -> elem == 3); + // #splitWhenAfter - //#wordCount - String text = - "This is the first line.\n" + - "The second line.\n" + - "There is also the 3rd line\n"; + // #wordCount + String text = + "This is the first line.\n" + "The second line.\n" + "There is also the 3rd line\n"; - Source.from(Arrays.asList(text.split(""))) - .map(x -> x.charAt(0)) - .splitAfter(x -> x == '\n') - .filter(x -> x != '\n') - .map(x -> 1) - .reduce((x,y) -> x + y) - .to(Sink.foreach(x -> System.out.println(x))) - .run(mat); - //#wordCount - Thread.sleep(1000); - } + Source.from(Arrays.asList(text.split(""))) + .map(x -> x.charAt(0)) + .splitAfter(x -> x == '\n') + .filter(x -> x != '\n') + .map(x -> 1) + .reduce((x, y) -> x + y) + .to(Sink.foreach(x -> System.out.println(x))) + .run(mat); + // #wordCount + Thread.sleep(1000); + } - @Test - public void demonstrateflatMapConcatMerge() throws Exception { - //#flatMapConcat - Source.from(Arrays.asList(1, 2)) - .flatMapConcat(i -> Source.from(Arrays.asList(i, i, i))) - .runWith(Sink.ignore(), mat); - //#flatMapConcat + @Test + public void demonstrateflatMapConcatMerge() throws Exception { + // #flatMapConcat + Source.from(Arrays.asList(1, 2)) + .flatMapConcat(i -> Source.from(Arrays.asList(i, i, i))) + .runWith(Sink.ignore(), mat); + // #flatMapConcat - //#flatMapMerge - Source.from(Arrays.asList(1, 2)) - .flatMapMerge(2, i -> Source.from(Arrays.asList(i, i, i))) - .runWith(Sink.ignore(), mat); - //#flatMapMerge - } + // #flatMapMerge + Source.from(Arrays.asList(1, 2)) + .flatMapMerge(2, i -> Source.from(Arrays.asList(i, i, i))) + .runWith(Sink.ignore(), mat); + // #flatMapMerge + } } diff --git a/akka-docs/src/test/java/jdocs/stream/TwitterStreamQuickstartDocTest.java b/akka-docs/src/test/java/jdocs/stream/TwitterStreamQuickstartDocTest.java index 8227825bba..b8cab386ca 100644 --- a/akka-docs/src/test/java/jdocs/stream/TwitterStreamQuickstartDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/TwitterStreamQuickstartDocTest.java @@ -8,10 +8,10 @@ import akka.Done; import akka.NotUsed; import akka.actor.ActorSystem; import akka.japi.JavaPartialFunction; -//#imports +// #imports import akka.stream.*; import akka.stream.javadsl.*; -//#imports +// #imports import jdocs.AbstractJavaTest; import jdocs.stream.TwitterStreamQuickstartDocTest.Model.Author; import jdocs.stream.TwitterStreamQuickstartDocTest.Model.Hashtag; @@ -56,8 +56,8 @@ public class TwitterStreamQuickstartDocTest extends AbstractJavaTest { mat = null; } - static abstract class Model { - //#model + abstract static class Model { + // #model public static class Author { public final String handle; @@ -67,7 +67,7 @@ public class TwitterStreamQuickstartDocTest extends AbstractJavaTest { // ... - //#model + // #model @Override public String toString() { @@ -96,11 +96,11 @@ public class TwitterStreamQuickstartDocTest extends AbstractJavaTest { public int hashCode() { return handle != null ? handle.hashCode() : 0; } - //#model + // #model } - //#model + // #model - //#model + // #model public static class Hashtag { public final String name; @@ -110,7 +110,7 @@ public class TwitterStreamQuickstartDocTest extends AbstractJavaTest { } // ... - //#model + // #model @Override public int hashCode() { @@ -119,12 +119,9 @@ public class TwitterStreamQuickstartDocTest extends AbstractJavaTest { @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; Hashtag other = (Hashtag) obj; return name.equals(other.name); } @@ -133,11 +130,11 @@ public class TwitterStreamQuickstartDocTest extends AbstractJavaTest { public String toString() { return "Hashtag(" + name + ")"; } - //#model + // #model } - //#model + // #model - //#model + // #model public static class Tweet { public final Author author; @@ -151,69 +148,85 @@ public class TwitterStreamQuickstartDocTest extends AbstractJavaTest { } public Set hashtags() { - return Arrays.asList(body.split(" ")).stream() - .filter(a -> a.startsWith("#")) - .map(a -> new Hashtag(a)) - .collect(Collectors.toSet()); + return Arrays.asList(body.split(" ")) + .stream() + .filter(a -> a.startsWith("#")) + .map(a -> new Hashtag(a)) + .collect(Collectors.toSet()); } // ... - //#model + // #model @Override public String toString() { return "Tweet(" + author + "," + timestamp + "," + body + ")"; } - //#model + // #model } - //#model + // #model - //#model + // #model public static final Hashtag AKKA = new Hashtag("#akka"); - //#model + // #model - public static final Source tweets = Source.from( - Arrays.asList(new Tweet[] { - new Tweet(new Author("rolandkuhn"), System.currentTimeMillis(), "#akka rocks!"), - new Tweet(new Author("patriknw"), System.currentTimeMillis(), "#akka !"), - new Tweet(new Author("bantonsson"), System.currentTimeMillis(), "#akka !"), - new Tweet(new Author("drewhk"), System.currentTimeMillis(), "#akka !"), - new Tweet(new Author("ktosopl"), System.currentTimeMillis(), "#akka on the rocks!"), - new Tweet(new Author("mmartynas"), System.currentTimeMillis(), "wow #akka !"), - new Tweet(new Author("akkateam"), System.currentTimeMillis(), "#akka rocks!"), - new Tweet(new Author("bananaman"), System.currentTimeMillis(), "#bananas rock!"), - new Tweet(new Author("appleman"), System.currentTimeMillis(), "#apples rock!"), - new Tweet(new Author("drama"), System.currentTimeMillis(), "we compared #apples to #oranges!") - })); + public static final Source tweets = + Source.from( + Arrays.asList( + new Tweet[] { + new Tweet(new Author("rolandkuhn"), System.currentTimeMillis(), "#akka rocks!"), + new Tweet(new Author("patriknw"), System.currentTimeMillis(), "#akka !"), + new Tweet(new Author("bantonsson"), System.currentTimeMillis(), "#akka !"), + new Tweet(new Author("drewhk"), System.currentTimeMillis(), "#akka !"), + new Tweet( + new Author("ktosopl"), System.currentTimeMillis(), "#akka on the rocks!"), + new Tweet(new Author("mmartynas"), System.currentTimeMillis(), "wow #akka !"), + new Tweet(new Author("akkateam"), System.currentTimeMillis(), "#akka rocks!"), + new Tweet(new Author("bananaman"), System.currentTimeMillis(), "#bananas rock!"), + new Tweet(new Author("appleman"), System.currentTimeMillis(), "#apples rock!"), + new Tweet( + new Author("drama"), + System.currentTimeMillis(), + "we compared #apples to #oranges!") + })); } - static abstract class Example0 { - //#tweet-source + abstract static class Example0 { + // #tweet-source Source tweets; - //#tweet-source + // #tweet-source } - static abstract class Example1 { - //#first-sample - //#materializer-setup + abstract static class Example1 { + // #first-sample + // #materializer-setup final ActorSystem system = ActorSystem.create("reactive-tweets"); final Materializer mat = ActorMaterializer.create(system); - //#first-sample - //#materializer-setup + // #first-sample + // #materializer-setup } static class Example2 { - public void run(final Materializer mat) throws TimeoutException, InterruptedException, ExecutionException { - //#backpressure-by-readline + public void run(final Materializer mat) + throws TimeoutException, InterruptedException, ExecutionException { + // #backpressure-by-readline final CompletionStage completion = - Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) - .map(i -> { System.out.println("map => " + i); return i; }) - .runForeach(i -> System.console().readLine("Element = %s continue reading? [press enter]\n", i), mat); + Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) + .map( + i -> { + System.out.println("map => " + i); + return i; + }) + .runForeach( + i -> + System.console() + .readLine("Element = %s continue reading? [press enter]\n", i), + mat); completion.toCompletableFuture().get(1, TimeUnit.SECONDS); - //#backpressure-by-readline + // #backpressure-by-readline } } @@ -221,60 +234,57 @@ public class TwitterStreamQuickstartDocTest extends AbstractJavaTest { public void demonstrateFilterAndMap() { final SilenceSystemOut.System System = SilenceSystemOut.get(); - //#first-sample + // #first-sample - //#authors-filter-map + // #authors-filter-map final Source authors = - tweets - .filter(t -> t.hashtags().contains(AKKA)) - .map(t -> t.author); - //#first-sample - //#authors-filter-map + tweets.filter(t -> t.hashtags().contains(AKKA)).map(t -> t.author); + // #first-sample + // #authors-filter-map new Object() { - //#authors-collect + // #authors-collect JavaPartialFunction collectFunction = - new JavaPartialFunction() { - public Author apply(Tweet t, boolean isCheck) { - if (t.hashtags().contains(AKKA)) { - if (isCheck) return null; // to spare the expensive or side-effecting code - return t.author; - } else { - throw noMatch(); + new JavaPartialFunction() { + public Author apply(Tweet t, boolean isCheck) { + if (t.hashtags().contains(AKKA)) { + if (isCheck) return null; // to spare the expensive or side-effecting code + return t.author; + } else { + throw noMatch(); + } } - } - }; + }; - final Source authors = - tweets.collect(collectFunction); - //#authors-collect + final Source authors = tweets.collect(collectFunction); + // #authors-collect }; - //#first-sample + // #first-sample - //#authors-foreachsink-println + // #authors-foreachsink-println authors.runWith(Sink.foreach(a -> System.out.println(a)), mat); - //#first-sample - //#authors-foreachsink-println + // #first-sample + // #authors-foreachsink-println - //#authors-foreach-println + // #authors-foreach-println authors.runForeach(a -> System.out.println(a), mat); - //#authors-foreach-println + // #authors-foreach-println } @Test public void demonstrateMapConcat() { - //#hashtags-mapConcat + // #hashtags-mapConcat final Source hashtags = - tweets.mapConcat(t -> new ArrayList(t.hashtags())); - //#hashtags-mapConcat + tweets.mapConcat(t -> new ArrayList(t.hashtags())); + // #hashtags-mapConcat } - static abstract class HiddenDefinitions { - //#graph-dsl-broadcast + abstract static class HiddenDefinitions { + // #graph-dsl-broadcast Sink writeAuthors; Sink writeHashtags; - //#graph-dsl-broadcast + // #graph-dsl-broadcast } @Test @@ -282,82 +292,88 @@ public class TwitterStreamQuickstartDocTest extends AbstractJavaTest { final Sink> writeAuthors = Sink.ignore(); final Sink> writeHashtags = Sink.ignore(); - //#graph-dsl-broadcast - RunnableGraph.fromGraph(GraphDSL.create(b -> { - final UniformFanOutShape bcast = b.add(Broadcast.create(2)); - final FlowShape toAuthor = - b.add(Flow.of(Tweet.class).map(t -> t.author)); - final FlowShape toTags = - b.add(Flow.of(Tweet.class).mapConcat(t -> new ArrayList(t.hashtags()))); - final SinkShape authors = b.add(writeAuthors); - final SinkShape hashtags = b.add(writeHashtags); + // #graph-dsl-broadcast + RunnableGraph.fromGraph( + GraphDSL.create( + b -> { + final UniformFanOutShape bcast = b.add(Broadcast.create(2)); + final FlowShape toAuthor = + b.add(Flow.of(Tweet.class).map(t -> t.author)); + final FlowShape toTags = + b.add( + Flow.of(Tweet.class) + .mapConcat(t -> new ArrayList(t.hashtags()))); + final SinkShape authors = b.add(writeAuthors); + final SinkShape hashtags = b.add(writeHashtags); - b.from(b.add(tweets)).viaFanOut(bcast).via(toAuthor).to(authors); - b.from(bcast).via(toTags).to(hashtags); - return ClosedShape.getInstance(); - })).run(mat); - //#graph-dsl-broadcast + b.from(b.add(tweets)).viaFanOut(bcast).via(toAuthor).to(authors); + b.from(bcast).via(toTags).to(hashtags); + return ClosedShape.getInstance(); + })) + .run(mat); + // #graph-dsl-broadcast } long slowComputation(Tweet t) { try { // act as if performing some heavy computation Thread.sleep(500); - } catch (InterruptedException e) {} + } catch (InterruptedException e) { + } return 42; } @Test public void demonstrateSlowProcessing() { - //#tweets-slow-consumption-dropHead + // #tweets-slow-consumption-dropHead tweets - .buffer(10, OverflowStrategy.dropHead()) - .map(t -> slowComputation(t)) - .runWith(Sink.ignore(), mat); - //#tweets-slow-consumption-dropHead + .buffer(10, OverflowStrategy.dropHead()) + .map(t -> slowComputation(t)) + .runWith(Sink.ignore(), mat); + // #tweets-slow-consumption-dropHead } @Test public void demonstrateCountOnFiniteStream() { - //#tweets-fold-count + // #tweets-fold-count final Sink> sumSink = - Sink.fold(0, (acc, elem) -> acc + elem); + Sink.fold(0, (acc, elem) -> acc + elem); final RunnableGraph> counter = tweets.map(t -> 1).toMat(sumSink, Keep.right()); final CompletionStage sum = counter.run(mat); - sum.thenAcceptAsync(c -> System.out.println("Total tweets processed: " + c), - system.dispatcher()); - //#tweets-fold-count + sum.thenAcceptAsync( + c -> System.out.println("Total tweets processed: " + c), system.dispatcher()); + // #tweets-fold-count new Object() { - //#tweets-fold-count-oneline + // #tweets-fold-count-oneline final CompletionStage sum = tweets.map(t -> 1).runWith(sumSink, mat); - //#tweets-fold-count-oneline + // #tweets-fold-count-oneline }; } @Test public void demonstrateMaterializeMultipleTimes() { - final Source tweetsInMinuteFromNow = tweets; // not really in second, just acting as if + final Source tweetsInMinuteFromNow = + tweets; // not really in second, just acting as if - //#tweets-runnable-flow-materialized-twice + // #tweets-runnable-flow-materialized-twice final Sink> sumSink = - Sink.fold(0, (acc, elem) -> acc + elem); + Sink.fold(0, (acc, elem) -> acc + elem); final RunnableGraph> counterRunnableGraph = - tweetsInMinuteFromNow - .filter(t -> t.hashtags().contains(AKKA)) - .map(t -> 1) - .toMat(sumSink, Keep.right()); + tweetsInMinuteFromNow + .filter(t -> t.hashtags().contains(AKKA)) + .map(t -> 1) + .toMat(sumSink, Keep.right()); // materialize the stream once in the morning final CompletionStage morningTweetsCount = counterRunnableGraph.run(mat); // and once in the evening, reusing the blueprint final CompletionStage eveningTweetsCount = counterRunnableGraph.run(mat); - //#tweets-runnable-flow-materialized-twice + // #tweets-runnable-flow-materialized-twice } - } diff --git a/akka-docs/src/test/java/jdocs/stream/io/StreamFileDocTest.java b/akka-docs/src/test/java/jdocs/stream/io/StreamFileDocTest.java index ed80219b9f..e72f15a268 100644 --- a/akka-docs/src/test/java/jdocs/stream/io/StreamFileDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/io/StreamFileDocTest.java @@ -46,20 +46,19 @@ public class StreamFileDocTest extends AbstractJavaTest { mat = null; } - final SilenceSystemOut.System System = SilenceSystemOut.get(); { - // Using 4 spaces here to align with code in try block below. - //#file-source - final Path file = Paths.get("example.csv"); - //#file-source + // Using 4 spaces here to align with code in try block below. + // #file-source + final Path file = Paths.get("example.csv"); + // #file-source } { - //#file-sink - final Path file = Paths.get("greeting.txt"); - //#file-sink + // #file-sink + final Path file = Paths.get("greeting.txt"); + // #file-sink } @Test @@ -67,15 +66,12 @@ public class StreamFileDocTest extends AbstractJavaTest { final Path file = Files.createTempFile(getClass().getName(), ".tmp"); try { - //#file-source + // #file-source Sink> printlnSink = - Sink. foreach(chunk -> System.out.println(chunk.utf8String())); + Sink.foreach(chunk -> System.out.println(chunk.utf8String())); - CompletionStage ioResult = - FileIO.fromPath(file) - .to(printlnSink) - .run(mat); - //#file-source + CompletionStage ioResult = FileIO.fromPath(file).to(printlnSink).run(mat); + // #file-source } finally { Files.delete(file); } @@ -87,10 +83,10 @@ public class StreamFileDocTest extends AbstractJavaTest { try { Sink> fileSink = - //#custom-dispatcher-code - FileIO.toPath(file) - .withAttributes(ActorAttributes.dispatcher("custom-blocking-io-dispatcher")); - //#custom-dispatcher-code + // #custom-dispatcher-code + FileIO.toPath(file) + .withAttributes(ActorAttributes.dispatcher("custom-blocking-io-dispatcher")); + // #custom-dispatcher-code } finally { Files.delete(file); } @@ -101,14 +97,13 @@ public class StreamFileDocTest extends AbstractJavaTest { final Path file = Files.createTempFile(getClass().getName(), ".tmp"); try { - //#file-sink + // #file-sink Sink> fileSink = FileIO.toPath(file); Source textSource = Source.single("Hello Akka Stream!"); - CompletionStage ioResult = textSource - .map(ByteString::fromString) - .runWith(fileSink, mat); - //#file-sink + CompletionStage ioResult = + textSource.map(ByteString::fromString).runWith(fileSink, mat); + // #file-sink } finally { Files.delete(file); } diff --git a/akka-docs/src/test/java/jdocs/stream/io/StreamTcpDocTest.java b/akka-docs/src/test/java/jdocs/stream/io/StreamTcpDocTest.java index e73b162a52..09b1a1af25 100644 --- a/akka-docs/src/test/java/jdocs/stream/io/StreamTcpDocTest.java +++ b/akka-docs/src/test/java/jdocs/stream/io/StreamTcpDocTest.java @@ -46,10 +46,10 @@ public class StreamTcpDocTest extends AbstractJavaTest { mat = null; } - final SilenceSystemOut.System System = SilenceSystemOut.get(); private final ConcurrentLinkedQueue input = new ConcurrentLinkedQueue<>(); + { input.add("Hello world"); input.add("What a lovely day"); @@ -57,37 +57,41 @@ public class StreamTcpDocTest extends AbstractJavaTest { private String readLine(String prompt) { String s = input.poll(); - return (s == null ? "q": s); + return (s == null ? "q" : s); } @Test public void demonstrateSimpleServerConnection() { { - //#echo-server-simple-bind + // #echo-server-simple-bind // IncomingConnection and ServerBinding imported from Tcp final Source> connections = Tcp.get(system).bind("127.0.0.1", 8888); - //#echo-server-simple-bind + // #echo-server-simple-bind } { - final InetSocketAddress localhost = SocketUtil.temporaryServerAddress("127.0.0.1", false); final Source> connections = - Tcp.get(system).bind(localhost.getHostString(), localhost.getPort()); + Tcp.get(system).bind(localhost.getHostString(), localhost.getPort()); - //#echo-server-simple-handle - connections.runForeach(connection -> { - System.out.println("New connection from: " + connection.remoteAddress()); + // #echo-server-simple-handle + connections.runForeach( + connection -> { + System.out.println("New connection from: " + connection.remoteAddress()); - final Flow echo = Flow.of(ByteString.class) - .via(Framing.delimiter(ByteString.fromString("\n"), 256, FramingTruncation.DISALLOW)) - .map(ByteString::utf8String) - .map(s -> s + "!!!\n") - .map(ByteString::fromString); + final Flow echo = + Flow.of(ByteString.class) + .via( + Framing.delimiter( + ByteString.fromString("\n"), 256, FramingTruncation.DISALLOW)) + .map(ByteString::utf8String) + .map(s -> s + "!!!\n") + .map(ByteString::fromString); - connection.handleWith(echo, mat); - }, mat); - //#echo-server-simple-handle + connection.handleWith(echo, mat); + }, + mat); + // #echo-server-simple-handle } } @@ -97,80 +101,93 @@ public class StreamTcpDocTest extends AbstractJavaTest { final InetSocketAddress localhost = SocketUtil.temporaryServerAddress("127.0.0.1", false); final TestProbe serverProbe = new TestProbe(system); - final Source> connections = - Tcp.get(system).bind(localhost.getHostString(), localhost.getPort()); + final Source> connections = + Tcp.get(system).bind(localhost.getHostString(), localhost.getPort()); final CompletionStage bindingCS = - //#welcome-banner-chat-server - connections.to(Sink.foreach((IncomingConnection connection) -> { - // server logic, parses incoming commands - final Flow commandParser = - Flow.create() - .takeWhile(elem -> !elem.equals("BYE")) - .map(elem -> elem + "!"); + // #welcome-banner-chat-server + connections + .to( + Sink.foreach( + (IncomingConnection connection) -> { + // server logic, parses incoming commands + final Flow commandParser = + Flow.create() + .takeWhile(elem -> !elem.equals("BYE")) + .map(elem -> elem + "!"); - final String welcomeMsg = "Welcome to: " + connection.localAddress() + - " you are: " + connection.remoteAddress() + "!"; + final String welcomeMsg = + "Welcome to: " + + connection.localAddress() + + " you are: " + + connection.remoteAddress() + + "!"; - final Source welcome = Source.single(welcomeMsg); - final Flow serverLogic = - Flow.of(ByteString.class) - .via(Framing.delimiter(ByteString.fromString("\n"), 256, FramingTruncation.DISALLOW)) - .map(ByteString::utf8String) - //#welcome-banner-chat-server - .map(command -> { - serverProbe.ref().tell(command, null); - return command; - }) - //#welcome-banner-chat-server - .via(commandParser) - .merge(welcome) - .map(s -> s + "\n") - .map(ByteString::fromString); + final Source welcome = Source.single(welcomeMsg); + final Flow serverLogic = + Flow.of(ByteString.class) + .via( + Framing.delimiter( + ByteString.fromString("\n"), 256, FramingTruncation.DISALLOW)) + .map(ByteString::utf8String) + // #welcome-banner-chat-server + .map( + command -> { + serverProbe.ref().tell(command, null); + return command; + }) + // #welcome-banner-chat-server + .via(commandParser) + .merge(welcome) + .map(s -> s + "\n") + .map(ByteString::fromString); - connection.handleWith(serverLogic, mat); - })).run(mat); - //#welcome-banner-chat-server + connection.handleWith(serverLogic, mat); + })) + .run(mat); + // #welcome-banner-chat-server // make sure server is bound before we do anything else bindingCS.toCompletableFuture().get(3, TimeUnit.SECONDS); - { // just for docs, never actually used - //#repl-client + // #repl-client final Flow> connection = Tcp.get(system).outgoingConnection("127.0.0.1", 8888); - //#repl-client + // #repl-client } { final Flow> connection = - Tcp.get(system).outgoingConnection(localhost.getHostString(), localhost.getPort()); - //#repl-client + Tcp.get(system).outgoingConnection(localhost.getHostString(), localhost.getPort()); + // #repl-client final Flow replParser = - Flow.create() - .takeWhile(elem -> !elem.equals("q")) - .concat(Source.single("BYE")) // will run after the original flow completes - .map(elem -> ByteString.fromString(elem + "\n")); + Flow.create() + .takeWhile(elem -> !elem.equals("q")) + .concat(Source.single("BYE")) // will run after the original flow completes + .map(elem -> ByteString.fromString(elem + "\n")); - final Flow repl = Flow.of(ByteString.class) - .via(Framing.delimiter(ByteString.fromString("\n"), 256, FramingTruncation.DISALLOW)) - .map(ByteString::utf8String) - .map(text -> {System.out.println("Server: " + text); return "next";}) - .map(elem -> readLine("> ")) - .via(replParser); + final Flow repl = + Flow.of(ByteString.class) + .via(Framing.delimiter(ByteString.fromString("\n"), 256, FramingTruncation.DISALLOW)) + .map(ByteString::utf8String) + .map( + text -> { + System.out.println("Server: " + text); + return "next"; + }) + .map(elem -> readLine("> ")) + .via(replParser); CompletionStage connectionCS = connection.join(repl).run(mat); - //#repl-client + // #repl-client // make sure it got connected (or fails the test) connectionCS.toCompletableFuture().get(5L, TimeUnit.SECONDS); } - serverProbe.expectMsg("Hello world"); serverProbe.expectMsg("What a lovely day"); serverProbe.expectMsg("BYE"); } - } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeAdhocSourceTest.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeAdhocSourceTest.java index ee86b7c6ed..d9804f60a9 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeAdhocSourceTest.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeAdhocSourceTest.java @@ -48,18 +48,21 @@ public class RecipeAdhocSourceTest extends RecipeTest { mat = null; } - //#adhoc-source + // #adhoc-source public Source adhocSource(Source source, Duration timeout, int maxRetries) { return Source.lazily( - () -> source.backpressureTimeout(timeout).recoverWithRetries( - maxRetries, - new PFBuilder() - .match(TimeoutException.class, ex -> Source.lazily(() -> source.backpressureTimeout(timeout))) - .build() - ) - ); + () -> + source + .backpressureTimeout(timeout) + .recoverWithRetries( + maxRetries, + new PFBuilder() + .match( + TimeoutException.class, + ex -> Source.lazily(() -> source.backpressureTimeout(timeout))) + .build())); } - //#adhoc-source + // #adhoc-source @Test @Ignore @@ -68,7 +71,14 @@ public class RecipeAdhocSourceTest extends RecipeTest { { AtomicBoolean isStarted = new AtomicBoolean(); adhocSource( - Source.empty().mapMaterializedValue(x -> {isStarted.set(true); return x;}), duration200mills, 3); + Source.empty() + .mapMaterializedValue( + x -> { + isStarted.set(true); + return x; + }), + duration200mills, + 3); Thread.sleep(300); assertEquals(false, isStarted.get()); } @@ -80,9 +90,10 @@ public class RecipeAdhocSourceTest extends RecipeTest { public void startStream() throws Exception { new TestKit(system) { { - TestSubscriber.Probe probe = adhocSource(Source.repeat("a"), duration200mills, 3) - .toMat(TestSink.probe(system), Keep.right()) - .run(mat); + TestSubscriber.Probe probe = + adhocSource(Source.repeat("a"), duration200mills, 3) + .toMat(TestSink.probe(system), Keep.right()) + .run(mat); probe.requestNext("a"); } }; @@ -94,12 +105,15 @@ public class RecipeAdhocSourceTest extends RecipeTest { new TestKit(system) { { Promise shutdown = Futures.promise(); - TestSubscriber.Probe probe = adhocSource( - Source.repeat("a").watchTermination((a, term) -> - term.thenRun(() -> shutdown.success(Done.getInstance())) - ), duration200mills, 3) - .toMat(TestSink.probe(system), Keep.right()) - .run(mat); + TestSubscriber.Probe probe = + adhocSource( + Source.repeat("a") + .watchTermination( + (a, term) -> term.thenRun(() -> shutdown.success(Done.getInstance()))), + duration200mills, + 3) + .toMat(TestSink.probe(system), Keep.right()) + .run(mat); probe.requestNext("a"); Thread.sleep(300); @@ -115,12 +129,14 @@ public class RecipeAdhocSourceTest extends RecipeTest { { Promise shutdown = Futures.promise(); TestSubscriber.Probe probe = - adhocSource( - Source.repeat("a").watchTermination((a, term) -> - term.thenRun(() -> shutdown.success(Done.getInstance())) - ), duration200mills, 3) - .toMat(TestSink.probe(system), Keep.right()) - .run(mat); + adhocSource( + Source.repeat("a") + .watchTermination( + (a, term) -> term.thenRun(() -> shutdown.success(Done.getInstance()))), + duration200mills, + 3) + .toMat(TestSink.probe(system), Keep.right()) + .run(mat); probe.requestNext("a"); Thread.sleep(100); @@ -146,16 +162,19 @@ public class RecipeAdhocSourceTest extends RecipeTest { Promise shutdown = Futures.promise(); AtomicInteger startedCount = new AtomicInteger(0); - Source source = Source.empty() - .mapMaterializedValue(x -> startedCount.incrementAndGet()) - .concat(Source.repeat("a")); + Source source = + Source.empty() + .mapMaterializedValue(x -> startedCount.incrementAndGet()) + .concat(Source.repeat("a")); TestSubscriber.Probe probe = - adhocSource(source.watchTermination((a, term) -> - term.thenRun(() -> shutdown.success(Done.getInstance())) - ), duration200mills, 3) - .toMat(TestSink.probe(system), Keep.right()) - .run(mat); + adhocSource( + source.watchTermination( + (a, term) -> term.thenRun(() -> shutdown.success(Done.getInstance()))), + duration200mills, + 3) + .toMat(TestSink.probe(system), Keep.right()) + .run(mat); probe.requestNext("a"); assertEquals(1, startedCount.get()); @@ -173,16 +192,19 @@ public class RecipeAdhocSourceTest extends RecipeTest { Promise shutdown = Futures.promise(); AtomicInteger startedCount = new AtomicInteger(0); - Source source = Source.empty() - .mapMaterializedValue(x -> startedCount.incrementAndGet()) - .concat(Source.repeat("a")); + Source source = + Source.empty() + .mapMaterializedValue(x -> startedCount.incrementAndGet()) + .concat(Source.repeat("a")); TestSubscriber.Probe probe = - adhocSource(source.watchTermination((a, term) -> - term.thenRun(() -> shutdown.success(Done.getInstance())) - ), duration200mills, 3) - .toMat(TestSink.probe(system), Keep.right()) - .run(mat); + adhocSource( + source.watchTermination( + (a, term) -> term.thenRun(() -> shutdown.success(Done.getInstance()))), + duration200mills, + 3) + .toMat(TestSink.probe(system), Keep.right()) + .run(mat); probe.requestNext("a"); assertEquals(1, startedCount.get()); @@ -200,14 +222,13 @@ public class RecipeAdhocSourceTest extends RecipeTest { Thread.sleep(500); probe.requestNext("a"); - assertEquals(4, startedCount.get()); //startCount == 4, which means "re"-tried 3 times + assertEquals(4, startedCount.get()); // startCount == 4, which means "re"-tried 3 times Thread.sleep(500); assertEquals(TimeoutException.class, probe.expectError().getClass()); - probe.request(1); //send demand - probe.expectNoMessage(FiniteDuration.create(200, "milliseconds")); //but no more restart + probe.request(1); // send demand + probe.expectNoMessage(FiniteDuration.create(200, "milliseconds")); // but no more restart } }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeByteStrings.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeByteStrings.java index 26c5bef32f..936d6a2810 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeByteStrings.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeByteStrings.java @@ -44,19 +44,20 @@ public class RecipeByteStrings extends RecipeTest { mat = null; } - - final Source rawBytes = Source.from(Arrays.asList( - ByteString.fromArray(new byte[] { 1, 2 }), - ByteString.fromArray(new byte[] { 3 }), - ByteString.fromArray(new byte[] { 4, 5, 6 }), - ByteString.fromArray(new byte[] { 7, 8, 9 }))); + final Source rawBytes = + Source.from( + Arrays.asList( + ByteString.fromArray(new byte[] {1, 2}), + ByteString.fromArray(new byte[] {3}), + ByteString.fromArray(new byte[] {4, 5, 6}), + ByteString.fromArray(new byte[] {7, 8, 9}))); @Test public void chunker() throws Exception { new TestKit(system) { final int CHUNK_LIMIT = 2; - //#bytestring-chunker + // #bytestring-chunker class Chunker extends GraphStage> { private final int chunkSize; @@ -80,36 +81,42 @@ public class RecipeByteStrings extends RecipeTest { private ByteString buffer = ByteString.empty(); { - setHandler(out, new AbstractOutHandler(){ - @Override - public void onPull() throws Exception { - emitChunk(); - } - }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + emitChunk(); + } + }); - setHandler(in, new AbstractInHandler() { + setHandler( + in, + new AbstractInHandler() { - @Override - public void onPush() throws Exception { - ByteString elem = grab(in); - buffer = buffer.concat(elem); - emitChunk(); - } + @Override + public void onPush() throws Exception { + ByteString elem = grab(in); + buffer = buffer.concat(elem); + emitChunk(); + } - @Override - public void onUpstreamFinish() throws Exception { - if (buffer.isEmpty()) completeStage(); - else { - // There are elements left in buffer, so - // we keep accepting downstream pulls and push from buffer until emptied. - // - // It might be though, that the upstream finished while it was pulled, in which - // case we will not get an onPull from the downstream, because we already had one. - // In that case we need to emit from the buffer. - if (isAvailable(out)) emitChunk(); - } - } - }); + @Override + public void onUpstreamFinish() throws Exception { + if (buffer.isEmpty()) completeStage(); + else { + // There are elements left in buffer, so + // we keep accepting downstream pulls and push from buffer until emptied. + // + // It might be though, that the upstream finished while it was pulled, in + // which + // case we will not get an onPull from the downstream, because we already + // had one. + // In that case we need to emit from the buffer. + if (isAvailable(out)) emitChunk(); + } + } + }); } private void emitChunk() { @@ -125,17 +132,16 @@ public class RecipeByteStrings extends RecipeTest { } }; } - } - //#bytestring-chunker + // #bytestring-chunker { - //#bytestring-chunker2 - Source chunksStream = - rawBytes.via(new Chunker(CHUNK_LIMIT)); - //#bytestring-chunker2 + // #bytestring-chunker2 + Source chunksStream = rawBytes.via(new Chunker(CHUNK_LIMIT)); + // #bytestring-chunker2 - CompletionStage> chunksFuture = chunksStream.limit(10).runWith(Sink.seq(), mat); + CompletionStage> chunksFuture = + chunksStream.limit(10).runWith(Sink.seq(), mat); List chunks = chunksFuture.toCompletableFuture().get(3, TimeUnit.SECONDS); @@ -147,9 +153,8 @@ public class RecipeByteStrings extends RecipeTest { for (ByteString chunk : chunks) { sum = sum.concat(chunk); } - assertEquals(sum, ByteString.fromArray(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })); + assertEquals(sum, ByteString.fromArray(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9})); } - }; } @@ -158,7 +163,7 @@ public class RecipeByteStrings extends RecipeTest { new TestKit(system) { final int SIZE_LIMIT = 9; - //#bytes-limiter + // #bytes-limiter class ByteLimiter extends GraphStage> { final long maximumBytes; @@ -175,71 +180,89 @@ public class RecipeByteStrings extends RecipeTest { public FlowShape shape() { return shape; } + @Override public GraphStageLogic createLogic(Attributes inheritedAttributes) { return new GraphStageLogic(shape) { private int count = 0; { - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - pull(in); - } - }); - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() throws Exception { - ByteString chunk = grab(in); - count += chunk.size(); - if (count > maximumBytes) { - failStage(new IllegalStateException("Too much bytes")); - } else { - push(out, chunk); - } - } - }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + pull(in); + } + }); + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() throws Exception { + ByteString chunk = grab(in); + count += chunk.size(); + if (count > maximumBytes) { + failStage(new IllegalStateException("Too much bytes")); + } else { + push(out, chunk); + } + } + }); } - }; } } - //#bytes-limiter + // #bytes-limiter { - //#bytes-limiter2 + // #bytes-limiter2 Flow limiter = - Flow.of(ByteString.class).via(new ByteLimiter(SIZE_LIMIT)); - //#bytes-limiter2 + Flow.of(ByteString.class).via(new ByteLimiter(SIZE_LIMIT)); + // #bytes-limiter2 - final Source bytes1 = Source.from(Arrays.asList( - ByteString.fromArray(new byte[] { 1, 2 }), - ByteString.fromArray(new byte[] { 3 }), - ByteString.fromArray(new byte[] { 4, 5, 6 }), - ByteString.fromArray(new byte[] { 7, 8, 9 }))); + final Source bytes1 = + Source.from( + Arrays.asList( + ByteString.fromArray(new byte[] {1, 2}), + ByteString.fromArray(new byte[] {3}), + ByteString.fromArray(new byte[] {4, 5, 6}), + ByteString.fromArray(new byte[] {7, 8, 9}))); - final Source bytes2 = Source.from(Arrays.asList( - ByteString.fromArray(new byte[] { 1, 2 }), - ByteString.fromArray(new byte[] { 3 }), - ByteString.fromArray(new byte[] { 4, 5, 6 }), - ByteString.fromArray(new byte[] { 7, 8, 9, 10 }))); + final Source bytes2 = + Source.from( + Arrays.asList( + ByteString.fromArray(new byte[] {1, 2}), + ByteString.fromArray(new byte[] {3}), + ByteString.fromArray(new byte[] {4, 5, 6}), + ByteString.fromArray(new byte[] {7, 8, 9, 10}))); - List got = bytes1.via(limiter).limit(10).runWith(Sink.seq(), mat).toCompletableFuture().get(3, TimeUnit.SECONDS); + List got = + bytes1 + .via(limiter) + .limit(10) + .runWith(Sink.seq(), mat) + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); ByteString acc = ByteString.empty(); for (ByteString b : got) { acc = acc.concat(b); } - assertEquals(acc, ByteString.fromArray(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })); + assertEquals(acc, ByteString.fromArray(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9})); boolean thrown = false; try { - bytes2.via(limiter).limit(10).runWith(Sink.seq(), mat).toCompletableFuture().get(3, TimeUnit.SECONDS); + bytes2 + .via(limiter) + .limit(10) + .runWith(Sink.seq(), mat) + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); } catch (ExecutionException ex) { assertEquals(ex.getCause().getClass(), IllegalStateException.class); thrown = true; } assertTrue("Expected IllegalStateException to be thrown", thrown); - } }; } @@ -248,17 +271,24 @@ public class RecipeByteStrings extends RecipeTest { public void compacting() throws Exception { new TestKit(system) { { - final Source rawBytes = Source.from(Arrays.asList( - ByteString.fromArray(new byte[] { 1, 2 }), - ByteString.fromArray(new byte[] { 3 }), - ByteString.fromArray(new byte[] { 4, 5, 6 }), - ByteString.fromArray(new byte[] { 7, 8, 9 }))); + final Source rawBytes = + Source.from( + Arrays.asList( + ByteString.fromArray(new byte[] {1, 2}), + ByteString.fromArray(new byte[] {3}), + ByteString.fromArray(new byte[] {4, 5, 6}), + ByteString.fromArray(new byte[] {7, 8, 9}))); - //#compacting-bytestrings + // #compacting-bytestrings Source compacted = rawBytes.map(ByteString::compact); - //#compacting-bytestrings + // #compacting-bytestrings - List got = compacted.limit(10).runWith(Sink.seq(), mat).toCompletableFuture().get(3, TimeUnit.SECONDS); + List got = + compacted + .limit(10) + .runWith(Sink.seq(), mat) + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); for (ByteString byteString : got) { assertTrue(byteString.isCompact()); @@ -266,5 +296,4 @@ public class RecipeByteStrings extends RecipeTest { } }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeDecompress.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeDecompress.java index ec97cd6e9a..2249f3ad61 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeDecompress.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeDecompress.java @@ -21,42 +21,40 @@ import java.util.concurrent.TimeUnit; public class RecipeDecompress extends RecipeTest { - static ActorSystem system; - static Materializer mat; + static ActorSystem system; + static Materializer mat; - @BeforeClass - public static void setup() { - system = ActorSystem.create("RecipeDecompress"); - mat = ActorMaterializer.create(system); - } + @BeforeClass + public static void setup() { + system = ActorSystem.create("RecipeDecompress"); + mat = ActorMaterializer.create(system); + } - @AfterClass - public static void tearDown() { - TestKit.shutdownActorSystem(system); - system = null; - mat = null; - } + @AfterClass + public static void tearDown() { + TestKit.shutdownActorSystem(system); + system = null; + mat = null; + } - @Test - public void parseLines() throws Exception { - final Source dataStream = - Source.single(ByteString.fromString("Hello World")); + @Test + public void parseLines() throws Exception { + final Source dataStream = + Source.single(ByteString.fromString("Hello World")); - final Source compressedStream = - dataStream.via(Compression.gzip()); + final Source compressedStream = dataStream.via(Compression.gzip()); - //#decompress-gzip - final Source decompressedStream = - compressedStream.via(Compression.gunzip(100)); - //#decompress-gzip - - ByteString decompressedData = - decompressedStream - .runFold(ByteString.empty(), ByteString::concat, mat) - .toCompletableFuture() - .get(1, TimeUnit.SECONDS); - String decompressedString = decompressedData.utf8String(); - Assert.assertEquals("Hello World", decompressedString); - } + // #decompress-gzip + final Source decompressedStream = + compressedStream.via(Compression.gunzip(100)); + // #decompress-gzip + ByteString decompressedData = + decompressedStream + .runFold(ByteString.empty(), ByteString::concat, mat) + .toCompletableFuture() + .get(1, TimeUnit.SECONDS); + String decompressedString = decompressedData.utf8String(); + Assert.assertEquals("Hello World", decompressedString); + } } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeDigest.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeDigest.java index 958c99cc78..524dbf0269 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeDigest.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeDigest.java @@ -39,7 +39,7 @@ public class RecipeDigest extends RecipeTest { mat = null; } - //#calculating-digest + // #calculating-digest class DigestCalculator extends GraphStage> { private final String algorithm; public Inlet in = Inlet.create("DigestCalculator.in"); @@ -63,38 +63,42 @@ public class RecipeDigest extends RecipeTest { { try { digest = MessageDigest.getInstance(algorithm); - } catch(NoSuchAlgorithmException ex) { + } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() { - pull(in); - } - }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() { + pull(in); + } + }); - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() { - ByteString chunk = grab(in); - digest.update(chunk.toArray()); - pull(in); - } + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() { + ByteString chunk = grab(in); + digest.update(chunk.toArray()); + pull(in); + } - @Override - public void onUpstreamFinish() { - // If the stream is finished, we need to emit the digest - // before completing - emit(out, ByteString.fromArray(digest.digest())); - completeStage(); - } - }); + @Override + public void onUpstreamFinish() { + // If the stream is finished, we need to emit the digest + // before completing + emit(out, ByteString.fromArray(digest.digest())); + completeStage(); + } + }); } }; } } - //#calculating-digest + // #calculating-digest @Test public void work() throws Exception { @@ -102,21 +106,19 @@ public class RecipeDigest extends RecipeTest { { Source data = Source.single(ByteString.fromString("abc")); - //#calculating-digest2 + // #calculating-digest2 final Source digest = data.via(new DigestCalculator("SHA-256")); - //#calculating-digest2 + // #calculating-digest2 - ByteString got = digest.runWith(Sink.head(), mat).toCompletableFuture().get(3, TimeUnit.SECONDS); + ByteString got = + digest.runWith(Sink.head(), mat).toCompletableFuture().get(3, TimeUnit.SECONDS); - assertEquals(ByteString.fromInts( - 0xba, 0x78, 0x16, 0xbf, - 0x8f, 0x01, 0xcf, 0xea, - 0x41, 0x41, 0x40, 0xde, - 0x5d, 0xae, 0x22, 0x23, - 0xb0, 0x03, 0x61, 0xa3, - 0x96, 0x17, 0x7a, 0x9c, - 0xb4, 0x10, 0xff, 0x61, - 0xf2, 0x00, 0x15, 0xad), got); + assertEquals( + ByteString.fromInts( + 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, + 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, + 0xf2, 0x00, 0x15, 0xad), + got); } }; } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeDroppyBroadcast.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeDroppyBroadcast.java index 0653434433..58a7dfda8a 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeDroppyBroadcast.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeDroppyBroadcast.java @@ -38,14 +38,13 @@ public class RecipeDroppyBroadcast extends RecipeTest { @Test public void work() throws Exception { new TestKit(system) { - //#droppy-bcast + // #droppy-bcast // Makes a sink drop elements if too slow - public Sink> droppySink(Sink> sink, int size) { - return Flow. create() - .buffer(size, OverflowStrategy.dropHead()) - .toMat(sink, Keep.right()); + public Sink> droppySink( + Sink> sink, int size) { + return Flow.create().buffer(size, OverflowStrategy.dropHead()).toMat(sink, Keep.right()); } - //#droppy-bcast + // #droppy-bcast { final List nums = new ArrayList<>(); @@ -59,20 +58,21 @@ public class RecipeDroppyBroadcast extends RecipeTest { final Source myData = Source.from(nums); - //#droppy-bcast2 - RunnableGraph.fromGraph(GraphDSL.create(builder -> { - final int outputCount = 3; - final UniformFanOutShape bcast = - builder.add(Broadcast.create(outputCount)); - builder.from(builder.add(myData)).toFanOut(bcast); - builder.from(bcast).to(builder.add(droppySink(mySink1, 10))); - builder.from(bcast).to(builder.add(droppySink(mySink2, 10))); - builder.from(bcast).to(builder.add(droppySink(mySink3, 10))); - return ClosedShape.getInstance(); - })); - //#droppy-bcast2 + // #droppy-bcast2 + RunnableGraph.fromGraph( + GraphDSL.create( + builder -> { + final int outputCount = 3; + final UniformFanOutShape bcast = + builder.add(Broadcast.create(outputCount)); + builder.from(builder.add(myData)).toFanOut(bcast); + builder.from(bcast).to(builder.add(droppySink(mySink1, 10))); + builder.from(bcast).to(builder.add(droppySink(mySink2, 10))); + builder.from(bcast).to(builder.add(droppySink(mySink3, 10))); + return ClosedShape.getInstance(); + })); + // #droppy-bcast2 } }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeFlattenList.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeFlattenList.java index cae6037065..73f7770e61 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeFlattenList.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeFlattenList.java @@ -42,20 +42,27 @@ public class RecipeFlattenList extends RecipeTest { public void workWithMapConcat() throws Exception { new TestKit(system) { { - Source, NotUsed> someDataSource = Source - .from(Arrays.asList(Arrays.asList(new Message("1")), Arrays.asList(new Message("2"), new Message("3")))); + Source, NotUsed> someDataSource = + Source.from( + Arrays.asList( + Arrays.asList(new Message("1")), + Arrays.asList(new Message("2"), new Message("3")))); - //#flattening-lists + // #flattening-lists Source, NotUsed> myData = someDataSource; Source flattened = myData.mapConcat(i -> i); - //#flattening-lists + // #flattening-lists - List got = flattened.limit(10).runWith(Sink.seq(), mat).toCompletableFuture().get(1, TimeUnit.SECONDS); + List got = + flattened + .limit(10) + .runWith(Sink.seq(), mat) + .toCompletableFuture() + .get(1, TimeUnit.SECONDS); assertEquals(got.get(0), new Message("1")); assertEquals(got.get(1), new Message("2")); assertEquals(got.get(2), new Message("3")); } }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeGlobalRateLimit.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeGlobalRateLimit.java index 5cecf7418e..5d91d14c59 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeGlobalRateLimit.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeGlobalRateLimit.java @@ -39,17 +39,20 @@ public class RecipeGlobalRateLimit extends RecipeTest { mat = null; } - static - //#global-limiter-actor - public class Limiter extends AbstractActor { + public + // #global-limiter-actor + static class Limiter extends AbstractActor { public static class WantToPass {} + public static final WantToPass WANT_TO_PASS = new WantToPass(); public static class MayPass {} + public static final MayPass MAY_PASS = new MayPass(); public static class ReplenishTokens {} + public static final ReplenishTokens REPLENISH_TOKENS = new ReplenishTokens(); private final int maxAvailableTokens; @@ -61,26 +64,28 @@ public class RecipeGlobalRateLimit extends RecipeTest { private int permitTokens; - public static Props props(int maxAvailableTokens, Duration tokenRefreshPeriod, - int tokenRefreshAmount) { - return Props.create(Limiter.class, maxAvailableTokens, tokenRefreshPeriod, - tokenRefreshAmount); + public static Props props( + int maxAvailableTokens, Duration tokenRefreshPeriod, int tokenRefreshAmount) { + return Props.create( + Limiter.class, maxAvailableTokens, tokenRefreshPeriod, tokenRefreshAmount); } - private Limiter(int maxAvailableTokens, Duration tokenRefreshPeriod, - int tokenRefreshAmount) { + private Limiter(int maxAvailableTokens, Duration tokenRefreshPeriod, int tokenRefreshAmount) { this.maxAvailableTokens = maxAvailableTokens; this.tokenRefreshPeriod = tokenRefreshPeriod; this.tokenRefreshAmount = tokenRefreshAmount; this.permitTokens = maxAvailableTokens; - this.replenishTimer = system.scheduler().schedule( - this.tokenRefreshPeriod, - this.tokenRefreshPeriod, - getSelf(), - REPLENISH_TOKENS, - getContext().getSystem().dispatcher(), - getSelf()); + this.replenishTimer = + system + .scheduler() + .schedule( + this.tokenRefreshPeriod, + this.tokenRefreshPeriod, + getSelf(), + REPLENISH_TOKENS, + getContext().getSystem().dispatcher(), + getSelf()); } @Override @@ -90,37 +95,45 @@ public class RecipeGlobalRateLimit extends RecipeTest { private Receive open() { return receiveBuilder() - .match(ReplenishTokens.class, rt -> { - permitTokens = Math.min(permitTokens + tokenRefreshAmount, maxAvailableTokens); - }) - .match(WantToPass.class, wtp -> { - permitTokens -= 1; - getSender().tell(MAY_PASS, getSelf()); - if (permitTokens == 0) { - getContext().become(closed()); - } - }) - .build(); + .match( + ReplenishTokens.class, + rt -> { + permitTokens = Math.min(permitTokens + tokenRefreshAmount, maxAvailableTokens); + }) + .match( + WantToPass.class, + wtp -> { + permitTokens -= 1; + getSender().tell(MAY_PASS, getSelf()); + if (permitTokens == 0) { + getContext().become(closed()); + } + }) + .build(); } private Receive closed() { return receiveBuilder() - .match(ReplenishTokens.class, rt -> { - permitTokens = Math.min(permitTokens + tokenRefreshAmount, maxAvailableTokens); - releaseWaiting(); - }) - .match(WantToPass.class, wtp -> { - waitQueue.add(getSender()); - }) - .build(); + .match( + ReplenishTokens.class, + rt -> { + permitTokens = Math.min(permitTokens + tokenRefreshAmount, maxAvailableTokens); + releaseWaiting(); + }) + .match( + WantToPass.class, + wtp -> { + waitQueue.add(getSender()); + }) + .build(); } private void releaseWaiting() { final List toBeReleased = new ArrayList<>(permitTokens); - for (Iterator it = waitQueue.iterator(); permitTokens > 0 && it.hasNext();) { - toBeReleased.add(it.next()); - it.remove(); - permitTokens --; + for (Iterator it = waitQueue.iterator(); permitTokens > 0 && it.hasNext(); ) { + toBeReleased.add(it.next()); + it.remove(); + permitTokens--; } toBeReleased.stream().forEach(ref -> ref.tell(MAY_PASS, getSelf())); @@ -132,76 +145,91 @@ public class RecipeGlobalRateLimit extends RecipeTest { @Override public void postStop() { replenishTimer.cancel(); - waitQueue.stream().forEach(ref -> { - ref.tell(new Status.Failure(new IllegalStateException("limiter stopped")), getSelf()); - }); + waitQueue + .stream() + .forEach( + ref -> { + ref.tell( + new Status.Failure(new IllegalStateException("limiter stopped")), getSelf()); + }); } } - //#global-limiter-actor + // #global-limiter-actor @Test public void work() throws Exception { new TestKit(system) { - //#global-limiter-flow + // #global-limiter-flow public Flow limitGlobal(ActorRef limiter, Duration maxAllowedWait) { final int parallelism = 4; final Flow f = Flow.create(); - return f.mapAsync(parallelism, element -> { - final CompletionStage limiterTriggerFuture = - Patterns.ask(limiter, Limiter.WANT_TO_PASS, maxAllowedWait); - return limiterTriggerFuture.thenApplyAsync(response -> element, system.dispatcher()); - }); + return f.mapAsync( + parallelism, + element -> { + final CompletionStage limiterTriggerFuture = + Patterns.ask(limiter, Limiter.WANT_TO_PASS, maxAllowedWait); + return limiterTriggerFuture.thenApplyAsync(response -> element, system.dispatcher()); + }); } - //#global-limiter-flow + // #global-limiter-flow { // Use a large period and emulate the timer by hand instead ActorRef limiter = system.actorOf(Limiter.props(2, Duration.ofDays(100), 1), "limiter"); - final Iterator e1 = new Iterator() { - @Override - public boolean hasNext() { - return true; - } + final Iterator e1 = + new Iterator() { + @Override + public boolean hasNext() { + return true; + } - @Override - public String next() { - return "E1"; - } - }; - final Iterator e2 = new Iterator() { - @Override - public boolean hasNext() { - return true; - } + @Override + public String next() { + return "E1"; + } + }; + final Iterator e2 = + new Iterator() { + @Override + public boolean hasNext() { + return true; + } - @Override - public String next() { - return "E2"; - } - }; + @Override + public String next() { + return "E2"; + } + }; final Duration twoSeconds = dilated(Duration.ofSeconds(2)); final Sink> sink = TestSink.probe(system); final TestSubscriber.Probe probe = - RunnableGraph.>fromGraph( - GraphDSL.create(sink, (builder, s) -> { - final int inputPorts = 2; - final UniformFanInShape merge = builder.add(Merge.create(inputPorts)); + RunnableGraph.>fromGraph( + GraphDSL.create( + sink, + (builder, s) -> { + final int inputPorts = 2; + final UniformFanInShape merge = + builder.add(Merge.create(inputPorts)); - final SourceShape source1 = - builder.add(Source.fromIterator(() -> e1).via(limitGlobal(limiter, twoSeconds))); - final SourceShape source2 = - builder.add(Source.fromIterator(() -> e2).via(limitGlobal(limiter, twoSeconds))); + final SourceShape source1 = + builder.add( + Source.fromIterator(() -> e1) + .via(limitGlobal(limiter, twoSeconds))); + final SourceShape source2 = + builder.add( + Source.fromIterator(() -> e2) + .via(limitGlobal(limiter, twoSeconds))); - builder.from(source1).toFanIn(merge); - builder.from(source2).toFanIn(merge); - builder.from(merge).to(s); - return ClosedShape.getInstance(); - }) - ).run(mat); + builder.from(source1).toFanIn(merge); + builder.from(source2).toFanIn(merge); + builder.from(merge).to(s); + return ClosedShape.getInstance(); + })) + .run(mat); probe.expectSubscription().request(1000); diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeHold.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeHold.java index cf6c59093e..dd0a4e733e 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeHold.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeHold.java @@ -41,7 +41,7 @@ public class RecipeHold extends RecipeTest { mat = null; } - //#hold-version-1 + // #hold-version-1 class HoldWithInitial extends GraphStage> { public Inlet in = Inlet.create("HoldWithInitial.in"); @@ -65,19 +65,23 @@ public class RecipeHold extends RecipeTest { private T currentValue = initial; { - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() throws Exception { - currentValue = grab(in); - pull(in); - } - }); - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - push(out, currentValue); - } - }); + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() throws Exception { + currentValue = grab(in); + pull(in); + } + }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + push(out, currentValue); + } + }); } @Override @@ -87,9 +91,9 @@ public class RecipeHold extends RecipeTest { }; } } - //#hold-version-1 + // #hold-version-1 - //#hold-version-2 + // #hold-version-2 class HoldWithWait extends GraphStage> { public Inlet in = Inlet.create("HoldWithInitial.in"); public Outlet out = Outlet.create("HoldWithInitial.out"); @@ -107,34 +111,37 @@ public class RecipeHold extends RecipeTest { private boolean waitingFirstValue = true; { - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() throws Exception { - currentValue = grab(in); - if (waitingFirstValue) { - waitingFirstValue = false; - if (isAvailable(out)) push(out, currentValue); - } - pull(in); - } - }); - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - if (!waitingFirstValue) push(out, currentValue); - } - }); + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() throws Exception { + currentValue = grab(in); + if (waitingFirstValue) { + waitingFirstValue = false; + if (isAvailable(out)) push(out, currentValue); + } + pull(in); + } + }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + if (!waitingFirstValue) push(out, currentValue); + } + }); } @Override public void preStart() { pull(in); } - }; } } - //#hold-version-2 + // #hold-version-2 @Test public void workForVersion1() throws Exception { @@ -144,7 +151,7 @@ public class RecipeHold extends RecipeTest { final Sink> sink = TestSink.probe(system); Pair, TestSubscriber.Probe> pubSub = - source.via(new HoldWithInitial<>(0)).toMat(sink, Keep.both()).run(mat); + source.via(new HoldWithInitial<>(0)).toMat(sink, Keep.both()).run(mat); TestPublisher.Probe pub = pubSub.first(); TestSubscriber.Probe sub = pubSub.second(); @@ -172,7 +179,7 @@ public class RecipeHold extends RecipeTest { final Sink> sink = TestSink.probe(system); Pair, TestSubscriber.Probe> pubSub = - source.via(new HoldWithWait<>()).toMat(sink, Keep.both()).run(mat); + source.via(new HoldWithWait<>()).toMat(sink, Keep.both()).run(mat); TestPublisher.Probe pub = pubSub.first(); TestSubscriber.Probe sub = pubSub.second(); @@ -196,5 +203,4 @@ public class RecipeHold extends RecipeTest { } }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeKeepAlive.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeKeepAlive.java index e8c5fec7a7..29ae4754d7 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeKeepAlive.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeKeepAlive.java @@ -35,26 +35,24 @@ public class RecipeKeepAlive extends RecipeTest { } class Tick {} + public final Tick TICK = new Tick(); @Test public void workForVersion1() throws Exception { new TestKit(system) { { - final ByteString keepAliveMessage = ByteString.fromArray(new byte[]{11}); + final ByteString keepAliveMessage = ByteString.fromArray(new byte[] {11}); - //@formatter:off - //#inject-keepalive + // @formatter:off + // #inject-keepalive Flow keepAliveInject = - Flow.of(ByteString.class).keepAlive( - Duration.ofSeconds(1), - () -> keepAliveMessage); - //#inject-keepalive - //@formatter:on + Flow.of(ByteString.class).keepAlive(Duration.ofSeconds(1), () -> keepAliveMessage); + // #inject-keepalive + // @formatter:on // Enough to compile, tested elsewhere as a built-in stage } }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeLoggingElements.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeLoggingElements.java index c164e3924e..d79be96ce2 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeLoggingElements.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeLoggingElements.java @@ -30,7 +30,11 @@ public class RecipeLoggingElements extends RecipeTest { @BeforeClass public static void setup() { - system = ActorSystem.create("RecipeLoggingElements", ConfigFactory.parseString("akka.loglevel=DEBUG\nakka.loggers = [akka.testkit.TestEventListener]")); + system = + ActorSystem.create( + "RecipeLoggingElements", + ConfigFactory.parseString( + "akka.loglevel=DEBUG\nakka.loggers = [akka.testkit.TestEventListener]")); mat = ActorMaterializer.create(system); } @@ -49,12 +53,13 @@ public class RecipeLoggingElements extends RecipeTest { { final Source mySource = Source.from(Arrays.asList("1", "2", "3")); - //#println-debug - mySource.map(elem -> { - System.out.println(elem); - return elem; - }); - //#println-debug + // #println-debug + mySource.map( + elem -> { + System.out.println(elem); + return elem; + }); + // #println-debug } }; } @@ -69,28 +74,32 @@ public class RecipeLoggingElements extends RecipeTest { { final Source mySource = Source.from(Arrays.asList("1", "2", "3")); - //#log-custom + // #log-custom // customise log levels - mySource.log("before-map") - .withAttributes(Attributes.createLogLevels( - Logging.WarningLevel(), //onElement - Logging.InfoLevel(), //onFinish - Logging.DebugLevel() //onFailure - )) - .map(i -> analyse(i)); + mySource + .log("before-map") + .withAttributes( + Attributes.createLogLevels( + Logging.WarningLevel(), // onElement + Logging.InfoLevel(), // onFinish + Logging.DebugLevel() // onFailure + )) + .map(i -> analyse(i)); // or provide custom logging adapter final LoggingAdapter adapter = Logging.getLogger(system, "customLogger"); mySource.log("custom", adapter); - //#log-custom + // #log-custom - - new DebugFilter("customLogger", "[custom] Element: ", false, false, 3).intercept(new AbstractFunction0 () { - public Void apply() { - mySource.log("custom", adapter).runWith(Sink.ignore(), mat); - return null; - } - }, system); + new DebugFilter("customLogger", "[custom] Element: ", false, false, 3) + .intercept( + new AbstractFunction0() { + public Void apply() { + mySource.log("custom", adapter).runWith(Sink.ignore(), mat); + return null; + } + }, + system); } }; } @@ -99,14 +108,13 @@ public class RecipeLoggingElements extends RecipeTest { public void errorLog() throws Exception { new TestKit(system) { { - //#log-error + // #log-error Source.from(Arrays.asList(-1, 0, 1)) - .map(x -> 1 / x) //throwing ArithmeticException: / by zero - .log("error logging") - .runWith(Sink.ignore(), mat); - //#log-error + .map(x -> 1 / x) // throwing ArithmeticException: / by zero + .log("error logging") + .runWith(Sink.ignore(), mat); + // #log-error } }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeManualTrigger.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeManualTrigger.java index 6bc5b55dfb..f6377330b9 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeManualTrigger.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeManualTrigger.java @@ -38,8 +38,7 @@ public class RecipeManualTrigger extends RecipeTest { mat = null; } - class Trigger { - } + class Trigger {} public final Trigger TRIGGER = new Trigger(); @@ -47,31 +46,34 @@ public class RecipeManualTrigger extends RecipeTest { public void zipped() throws Exception { new TestKit(system) { { - final Source> triggerSource = TestSource.probe(system); + final Source> triggerSource = + TestSource.probe(system); final Sink> messageSink = TestSink.probe(system); - //#manually-triggered-stream + // #manually-triggered-stream final RunnableGraph, TestSubscriber.Probe>> g = - RunnableGraph., TestSubscriber.Probe>>fromGraph( - GraphDSL.create( - triggerSource, - messageSink, - (p, s) -> new Pair<>(p, s), - (builder, source, sink) -> { - SourceShape elements = - builder.add(Source.from(Arrays.asList("1", "2", "3", "4")).map(t -> new Message(t))); - FlowShape, Message> takeMessage = - builder.add(Flow.>create().map(p -> p.first())); - final FanInShape2> zip = - builder.add(Zip.create()); - builder.from(elements).toInlet(zip.in0()); - builder.from(source).toInlet(zip.in1()); - builder.from(zip.out()).via(takeMessage).to(sink); - return ClosedShape.getInstance(); - } - ) - ); - //#manually-triggered-stream + RunnableGraph + ., TestSubscriber.Probe>>fromGraph( + GraphDSL.create( + triggerSource, + messageSink, + (p, s) -> new Pair<>(p, s), + (builder, source, sink) -> { + SourceShape elements = + builder.add( + Source.from(Arrays.asList("1", "2", "3", "4")) + .map(t -> new Message(t))); + FlowShape, Message> takeMessage = + builder.add( + Flow.>create().map(p -> p.first())); + final FanInShape2> zip = + builder.add(Zip.create()); + builder.from(elements).toInlet(zip.in0()); + builder.from(source).toInlet(zip.in1()); + builder.from(zip.out()).via(takeMessage).to(sink); + return ClosedShape.getInstance(); + })); + // #manually-triggered-stream Pair, TestSubscriber.Probe> pubSub = g.run(mat); TestPublisher.Probe pub = pubSub.first(); @@ -102,29 +104,31 @@ public class RecipeManualTrigger extends RecipeTest { public void zipWith() throws Exception { new TestKit(system) { { - final Source> triggerSource = TestSource.probe(system); + final Source> triggerSource = + TestSource.probe(system); final Sink> messageSink = TestSink.probe(system); - //#manually-triggered-stream-zipwith + // #manually-triggered-stream-zipwith final RunnableGraph, TestSubscriber.Probe>> g = - RunnableGraph., TestSubscriber.Probe>>fromGraph( - GraphDSL.create( - triggerSource, - messageSink, - (p, s) -> new Pair<>(p, s), - (builder, source, sink) -> { - final SourceShape elements = - builder.add(Source.from(Arrays.asList("1", "2", "3", "4")).map(t -> new Message(t))); - final FanInShape2 zipWith = - builder.add(ZipWith.create((msg, trigger) -> msg)); - builder.from(elements).toInlet(zipWith.in0()); - builder.from(source).toInlet(zipWith.in1()); - builder.from(zipWith.out()).to(sink); - return ClosedShape.getInstance(); - } - ) - ); - //#manually-triggered-stream-zipwith + RunnableGraph + ., TestSubscriber.Probe>>fromGraph( + GraphDSL.create( + triggerSource, + messageSink, + (p, s) -> new Pair<>(p, s), + (builder, source, sink) -> { + final SourceShape elements = + builder.add( + Source.from(Arrays.asList("1", "2", "3", "4")) + .map(t -> new Message(t))); + final FanInShape2 zipWith = + builder.add(ZipWith.create((msg, trigger) -> msg)); + builder.from(elements).toInlet(zipWith.in0()); + builder.from(source).toInlet(zipWith.in1()); + builder.from(zipWith.out()).to(sink); + return ClosedShape.getInstance(); + })); + // #manually-triggered-stream-zipwith Pair, TestSubscriber.Probe> pubSub = g.run(mat); TestPublisher.Probe pub = pubSub.first(); @@ -147,9 +151,7 @@ public class RecipeManualTrigger extends RecipeTest { pub.sendNext(TRIGGER); sub.expectNext(new Message("4")); sub.expectComplete(); - } }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeMissedTicks.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeMissedTicks.java index 1de4950cfc..14eeeb2477 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeMissedTicks.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeMissedTicks.java @@ -46,8 +46,7 @@ public class RecipeMissedTicks extends RecipeTest { @Test public void work() throws Exception { new TestKit(system) { - class Tick { - } + class Tick {} final Tick Tick = new Tick(); @@ -56,16 +55,22 @@ public class RecipeMissedTicks extends RecipeTest { final Sink> sink = TestSink.probe(system); @SuppressWarnings("unused") - //#missed-ticks + // #missed-ticks final Flow missedTicks = - Flow.of(Tick.class).conflateWithSeed(tick -> 0, (missed, tick) -> missed + 1); - //#missed-ticks + Flow.of(Tick.class).conflateWithSeed(tick -> 0, (missed, tick) -> missed + 1); + // #missed-ticks final TestLatch latch = new TestLatch(3, system); final Flow realMissedTicks = - Flow.of(Tick.class).conflateWithSeed(tick -> 0, (missed, tick) -> { latch.countDown(); return missed + 1; }); + Flow.of(Tick.class) + .conflateWithSeed( + tick -> 0, + (missed, tick) -> { + latch.countDown(); + return missed + 1; + }); Pair, TestSubscriber.Probe> pubSub = - tickStream.via(realMissedTicks).toMat(sink, Keep.both()).run(mat); + tickStream.via(realMissedTicks).toMat(sink, Keep.both()).run(mat); TestPublisher.Probe pub = pubSub.first(); TestSubscriber.Probe sub = pubSub.second(); @@ -75,7 +80,7 @@ public class RecipeMissedTicks extends RecipeTest { pub.sendNext(Tick); scala.concurrent.duration.FiniteDuration timeout = - scala.concurrent.duration.FiniteDuration.create(200, TimeUnit.MILLISECONDS); + scala.concurrent.duration.FiniteDuration.create(200, TimeUnit.MILLISECONDS); Await.ready(latch, scala.concurrent.duration.Duration.create(1, TimeUnit.SECONDS)); @@ -90,9 +95,7 @@ public class RecipeMissedTicks extends RecipeTest { pub.sendComplete(); sub.request(1); sub.expectComplete(); - } }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeMultiGroupByTest.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeMultiGroupByTest.java index 9f3caec9f9..ea10f75a41 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeMultiGroupByTest.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeMultiGroupByTest.java @@ -92,48 +92,57 @@ public class RecipeMultiGroupByTest extends RecipeTest { } { + final Source elems = + Source.from(Arrays.asList("1: a", "1: b", "all: c", "all: d", "1: e")) + .map(s -> new Message(s)); - final Source elems = Source - .from(Arrays.asList("1: a", "1: b", "all: c", "all: d", "1: e")) - .map(s -> new Message(s)); - - //#multi-groupby + // #multi-groupby final Function> topicMapper = m -> extractTopics(m); - final Source, NotUsed> messageAndTopic = elems - .mapConcat((Message msg) -> { - List topicsForMessage = topicMapper.apply(msg); - // Create a (Msg, Topic) pair for each of the topics + final Source, NotUsed> messageAndTopic = + elems.mapConcat( + (Message msg) -> { + List topicsForMessage = topicMapper.apply(msg); + // Create a (Msg, Topic) pair for each of the topics - // the message belongs to - return topicsForMessage - .stream() - .map(topic -> new Pair(msg, topic)) - .collect(toList()); - }); + // the message belongs to + return topicsForMessage + .stream() + .map(topic -> new Pair(msg, topic)) + .collect(toList()); + }); - SubSource, NotUsed> multiGroups = messageAndTopic - .groupBy(2, pair -> pair.second()) - .map(pair -> { - Message message = pair.first(); - Topic topic = pair.second(); + SubSource, NotUsed> multiGroups = + messageAndTopic + .groupBy(2, pair -> pair.second()) + .map( + pair -> { + Message message = pair.first(); + Topic topic = pair.second(); - // do what needs to be done - //#multi-groupby - return pair; - //#multi-groupby - }); - //#multi-groupby + // do what needs to be done + // #multi-groupby + return pair; + // #multi-groupby + }); + // #multi-groupby - CompletionStage> result = multiGroups - .grouped(10) - .mergeSubstreams() - .map(pair -> { - Topic topic = pair.get(0).second(); - return topic.name + mkString(pair.stream().map(p -> p.first().msg).collect(toList()), "[", ", ", "]"); - }) - .grouped(10) - .runWith(Sink.head(), mat); + CompletionStage> result = + multiGroups + .grouped(10) + .mergeSubstreams() + .map( + pair -> { + Topic topic = pair.get(0).second(); + return topic.name + + mkString( + pair.stream().map(p -> p.first().msg).collect(toList()), + "[", + ", ", + "]"); + }) + .grouped(10) + .runWith(Sink.head(), mat); List got = result.toCompletableFuture().get(3, TimeUnit.SECONDS); assertTrue(got.contains("1[1: a, 1: b, all: c, all: d, 1: e]")); @@ -147,8 +156,6 @@ public class RecipeMultiGroupByTest extends RecipeTest { for (String s : l) { sb.append(s).append(separate); } - return sb - .delete(sb.length() - separate.length(), sb.length()) - .append(end).toString(); + return sb.delete(sb.length() - separate.length(), sb.length()).append(end).toString(); } } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeParseLines.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeParseLines.java index ed10aa4960..7251fe1a86 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeParseLines.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeParseLines.java @@ -41,19 +41,21 @@ public class RecipeParseLines extends RecipeTest { @Test public void parseLines() throws Exception { - final Source rawData = Source.from(Arrays.asList( - ByteString.fromString("Hello World"), - ByteString.fromString("\r"), - ByteString.fromString("!\r"), - ByteString.fromString("\nHello Akka!\r\nHello Streams!"), - ByteString.fromString("\r\n\r\n"))); + final Source rawData = + Source.from( + Arrays.asList( + ByteString.fromString("Hello World"), + ByteString.fromString("\r"), + ByteString.fromString("!\r"), + ByteString.fromString("\nHello Akka!\r\nHello Streams!"), + ByteString.fromString("\r\n\r\n"))); - //#parse-lines - final Source lines = rawData - .via(Framing.delimiter(ByteString.fromString("\r\n"), 100, FramingTruncation.ALLOW)) - .map(b -> b.utf8String()); - //#parse-lines + // #parse-lines + final Source lines = + rawData + .via(Framing.delimiter(ByteString.fromString("\r\n"), 100, FramingTruncation.ALLOW)) + .map(b -> b.utf8String()); + // #parse-lines lines.limit(10).runWith(Sink.seq(), mat).toCompletableFuture().get(1, TimeUnit.SECONDS); } - } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeReduceByKeyTest.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeReduceByKeyTest.java index 6284d09b43..2f7e253347 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeReduceByKeyTest.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeReduceByKeyTest.java @@ -49,24 +49,28 @@ public class RecipeReduceByKeyTest extends RecipeTest { public void work() throws Exception { new TestKit(system) { { - final Source words = Source.from(Arrays.asList("hello", "world", "and", "hello", "akka")); + final Source words = + Source.from(Arrays.asList("hello", "world", "and", "hello", "akka")); - //#word-count + // #word-count final int MAXIMUM_DISTINCT_WORDS = 1000; - - final Source, NotUsed> counts = words - // split the words into separate streams first - .groupBy(MAXIMUM_DISTINCT_WORDS, i -> i) - //transform each element to pair with number of words in it - .map(i -> new Pair<>(i, 1)) - // add counting logic to the streams - .reduce((left, right) -> new Pair<>(left.first(), left.second() + right.second())) - // get a stream of word counts - .mergeSubstreams(); - //#word-count - final CompletionStage>> f = counts.grouped(10).runWith(Sink.head(), mat); - final Set> result = f.toCompletableFuture().get(3, TimeUnit.SECONDS).stream().collect(Collectors.toSet()); + final Source, NotUsed> counts = + words + // split the words into separate streams first + .groupBy(MAXIMUM_DISTINCT_WORDS, i -> i) + // transform each element to pair with number of words in it + .map(i -> new Pair<>(i, 1)) + // add counting logic to the streams + .reduce((left, right) -> new Pair<>(left.first(), left.second() + right.second())) + // get a stream of word counts + .mergeSubstreams(); + // #word-count + + final CompletionStage>> f = + counts.grouped(10).runWith(Sink.head(), mat); + final Set> result = + f.toCompletableFuture().get(3, TimeUnit.SECONDS).stream().collect(Collectors.toSet()); final Set> expected = new HashSet<>(); expected.add(new Pair<>("hello", 2)); expected.add(new Pair<>("world", 1)); @@ -77,39 +81,45 @@ public class RecipeReduceByKeyTest extends RecipeTest { }; } - //#reduce-by-key-general - static public Flow, NotUsed> reduceByKey( + // #reduce-by-key-general + public static Flow, NotUsed> reduceByKey( int maximumGroupSize, Function groupKey, Function map, Function2 reduce) { - return Flow. create() - .groupBy(maximumGroupSize, groupKey) - .map(i -> new Pair<>(groupKey.apply(i), map.apply(i))) - .reduce((left, right) -> new Pair<>(left.first(), reduce.apply(left.second(), right.second()))) - .mergeSubstreams(); + return Flow.create() + .groupBy(maximumGroupSize, groupKey) + .map(i -> new Pair<>(groupKey.apply(i), map.apply(i))) + .reduce( + (left, right) -> new Pair<>(left.first(), reduce.apply(left.second(), right.second()))) + .mergeSubstreams(); } - //#reduce-by-key-general + // #reduce-by-key-general @Test public void workGeneralised() throws Exception { new TestKit(system) { { - final Source words = Source.from(Arrays.asList("hello", "world", "and", "hello", "akka")); + final Source words = + Source.from(Arrays.asList("hello", "world", "and", "hello", "akka")); - //#reduce-by-key-general2 + // #reduce-by-key-general2 final int MAXIMUM_DISTINCT_WORDS = 1000; - Source, NotUsed> counts = words.via(reduceByKey( - MAXIMUM_DISTINCT_WORDS, - word -> word, - word -> 1, - (left, right) -> left + right)); + Source, NotUsed> counts = + words.via( + reduceByKey( + MAXIMUM_DISTINCT_WORDS, + word -> word, + word -> 1, + (left, right) -> left + right)); - //#reduce-by-key-general2 - final CompletionStage>> f = counts.grouped(10).runWith(Sink.head(), mat); - final Set> result = f.toCompletableFuture().get(3, TimeUnit.SECONDS).stream().collect(Collectors.toSet()); + // #reduce-by-key-general2 + final CompletionStage>> f = + counts.grouped(10).runWith(Sink.head(), mat); + final Set> result = + f.toCompletableFuture().get(3, TimeUnit.SECONDS).stream().collect(Collectors.toSet()); final Set> expected = new HashSet<>(); expected.add(new Pair<>("hello", 2)); expected.add(new Pair<>("world", 1)); @@ -119,5 +129,4 @@ public class RecipeReduceByKeyTest extends RecipeTest { } }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeSeq.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeSeq.java index 630a59a909..a782a8109c 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeSeq.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeSeq.java @@ -23,6 +23,7 @@ import java.util.concurrent.TimeUnit; public class RecipeSeq extends RecipeTest { static ActorSystem system; static Materializer mat; + @BeforeClass public static void setup() { system = ActorSystem.create("RecipeLoggingElements"); @@ -41,10 +42,10 @@ public class RecipeSeq extends RecipeTest { new TestKit(system) { { final Source mySource = Source.from(Arrays.asList("1", "2", "3")); - //#draining-to-list-unsafe + // #draining-to-list-unsafe // Dangerous: might produce a collection with 2 billion elements! final CompletionStage> strings = mySource.runWith(Sink.seq(), mat); - //#draining-to-list-unsafe + // #draining-to-list-unsafe strings.toCompletableFuture().get(3, TimeUnit.SECONDS); } @@ -56,14 +57,14 @@ public class RecipeSeq extends RecipeTest { new TestKit(system) { { final Source mySource = Source.from(Arrays.asList("1", "2", "3")); - //#draining-to-list-safe + // #draining-to-list-safe final int MAX_ALLOWED_SIZE = 100; // OK. Future will fail with a `StreamLimitReachedException` // if the number of incoming elements is larger than max final CompletionStage> strings = - mySource.limit(MAX_ALLOWED_SIZE).runWith(Sink.seq(), mat); - //#draining-to-list-safe + mySource.limit(MAX_ALLOWED_SIZE).runWith(Sink.seq(), mat); + // #draining-to-list-safe strings.toCompletableFuture().get(1, TimeUnit.SECONDS); } @@ -76,12 +77,12 @@ public class RecipeSeq extends RecipeTest { final Source mySource = Source.from(Arrays.asList("1", "2", "3")); final int MAX_ALLOWED_SIZE = 100; - //#draining-to-list-safe - + // #draining-to-list-safe + // OK. Collect up until max-th elements only, then cancel upstream final CompletionStage> strings = - mySource.take(MAX_ALLOWED_SIZE).runWith(Sink.seq(), mat); - //#draining-to-list-safe + mySource.take(MAX_ALLOWED_SIZE).runWith(Sink.seq(), mat); + // #draining-to-list-safe strings.toCompletableFuture().get(1, TimeUnit.SECONDS); } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeSimpleDrop.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeSimpleDrop.java index b770b90a29..9808cdaf17 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeSimpleDrop.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeSimpleDrop.java @@ -45,30 +45,34 @@ public class RecipeSimpleDrop extends RecipeTest { public void work() throws Exception { new TestKit(system) { { - @SuppressWarnings("unused") - //#simple-drop + @SuppressWarnings("unused") + // #simple-drop final Flow droppyStream = - Flow.of(Message.class).conflate((lastMessage, newMessage) -> newMessage); - //#simple-drop - final TestLatch latch = new TestLatch(2, system); + Flow.of(Message.class).conflate((lastMessage, newMessage) -> newMessage); + // #simple-drop + final TestLatch latch = new TestLatch(2, system); final Flow realDroppyStream = - Flow.of(Message.class).conflate((lastMessage, newMessage) -> { latch.countDown(); return newMessage; }); + Flow.of(Message.class) + .conflate( + (lastMessage, newMessage) -> { + latch.countDown(); + return newMessage; + }); - final Pair, TestSubscriber.Probe> pubSub = TestSource - . probe(system) - .via(realDroppyStream) - .toMat(TestSink.probe(system), - (pub, sub) -> new Pair<>(pub, sub)) - .run(mat); + final Pair, TestSubscriber.Probe> pubSub = + TestSource.probe(system) + .via(realDroppyStream) + .toMat(TestSink.probe(system), (pub, sub) -> new Pair<>(pub, sub)) + .run(mat); final TestPublisher.Probe pub = pubSub.first(); final TestSubscriber.Probe sub = pubSub.second(); pub.sendNext(new Message("1")); pub.sendNext(new Message("2")); pub.sendNext(new Message("3")); - + Await.ready(latch, Duration.create(1, TimeUnit.SECONDS)); - + sub.requestNext(new Message("3")); pub.sendComplete(); diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeSourceFromFunction.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeSourceFromFunction.java index eb07993468..295e799452 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeSourceFromFunction.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeSourceFromFunction.java @@ -27,7 +27,11 @@ public class RecipeSourceFromFunction extends RecipeTest { @BeforeClass public static void setup() { - system = ActorSystem.create("RecipeSourceFromFunction", ConfigFactory.parseString("akka.loglevel=DEBUG\nakka.loggers = [akka.testkit.TestEventListener]")); + system = + ActorSystem.create( + "RecipeSourceFromFunction", + ConfigFactory.parseString( + "akka.loglevel=DEBUG\nakka.loggers = [akka.testkit.TestEventListener]")); mat = ActorMaterializer.create(system); } @@ -46,16 +50,13 @@ public class RecipeSourceFromFunction extends RecipeTest { } { - //#source-from-function - final Source source = Source - .repeat(NotUsed.getInstance()) - .map(elem -> builderFunction()); - //#source-from-function + // #source-from-function + final Source source = + Source.repeat(NotUsed.getInstance()).map(elem -> builderFunction()); + // #source-from-function - final List result = source - .take(2) - .runWith(Sink.seq(), mat) - .toCompletableFuture().get(3, TimeUnit.SECONDS); + final List result = + source.take(2).runWith(Sink.seq(), mat).toCompletableFuture().get(3, TimeUnit.SECONDS); Assert.assertEquals(2, result.size()); } diff --git a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeWorkerPool.java b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeWorkerPool.java index d71afd9b80..d4d76413b1 100644 --- a/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeWorkerPool.java +++ b/akka-docs/src/test/java/jdocs/stream/javadsl/cookbook/RecipeWorkerPool.java @@ -38,43 +38,44 @@ public class RecipeWorkerPool extends RecipeTest { mat = null; } - //#worker-pool + // #worker-pool public static Flow balancer( Flow worker, int workerCount) { - return Flow.fromGraph(GraphDSL.create(b -> { - boolean waitForAllDownstreams = true; - final UniformFanOutShape balance = - b.add(Balance.create(workerCount, waitForAllDownstreams)); - final UniformFanInShape merge = - b.add(Merge.create(workerCount)); + return Flow.fromGraph( + GraphDSL.create( + b -> { + boolean waitForAllDownstreams = true; + final UniformFanOutShape balance = + b.add(Balance.create(workerCount, waitForAllDownstreams)); + final UniformFanInShape merge = b.add(Merge.create(workerCount)); - for (int i = 0; i < workerCount; i++) { - b.from(balance.out(i)).via(b.add(worker.async())).toInlet(merge.in(i)); - } + for (int i = 0; i < workerCount; i++) { + b.from(balance.out(i)).via(b.add(worker.async())).toInlet(merge.in(i)); + } - return FlowShape.of(balance.in(), merge.out()); - })); + return FlowShape.of(balance.in(), merge.out()); + })); } - //#worker-pool + // #worker-pool @Test public void workForVersion1() throws Exception { new TestKit(system) { { Source data = - Source - .from(Arrays.asList("1", "2", "3", "4", "5")) - .map(t -> new Message(t)); + Source.from(Arrays.asList("1", "2", "3", "4", "5")).map(t -> new Message(t)); - Flow worker = Flow.of(Message.class).map(m -> new Message(m.msg + " done")); + Flow worker = + Flow.of(Message.class).map(m -> new Message(m.msg + " done")); - //#worker-pool2 + // #worker-pool2 Flow balancer = balancer(worker, 3); Source processedJobs = data.via(balancer); - //#worker-pool2 + // #worker-pool2 FiniteDuration timeout = FiniteDuration.create(200, TimeUnit.MILLISECONDS); - CompletionStage> future = processedJobs.map(m -> m.msg).limit(10).runWith(Sink.seq(), mat); + CompletionStage> future = + processedJobs.map(m -> m.msg).limit(10).runWith(Sink.seq(), mat); List got = future.toCompletableFuture().get(1, TimeUnit.SECONDS); assertTrue(got.contains("1 done")); assertTrue(got.contains("2 done")); @@ -84,5 +85,4 @@ public class RecipeWorkerPool extends RecipeTest { } }; } - } diff --git a/akka-docs/src/test/java/jdocs/stream/operators/SinkDocExamples.java b/akka-docs/src/test/java/jdocs/stream/operators/SinkDocExamples.java index 2cde316370..44c6d1c73f 100644 --- a/akka-docs/src/test/java/jdocs/stream/operators/SinkDocExamples.java +++ b/akka-docs/src/test/java/jdocs/stream/operators/SinkDocExamples.java @@ -11,9 +11,9 @@ import akka.stream.ActorMaterializer; import akka.stream.Materializer; import akka.stream.javadsl.Sink; import akka.stream.javadsl.Source; -//#takeLast-operator-example +// #takeLast-operator-example import akka.japi.Pair; -//#takeLast-operator-example +// #takeLast-operator-example import java.util.*; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; @@ -21,60 +21,68 @@ import java.util.concurrent.TimeoutException; public class SinkDocExamples { - private final static ActorSystem system = ActorSystem.create("SourceFromExample"); - private final static Materializer materializer = ActorMaterializer.create(system); + private static final ActorSystem system = ActorSystem.create("SourceFromExample"); + private static final Materializer materializer = ActorMaterializer.create(system); - static void reduceExample() throws InterruptedException, ExecutionException, TimeoutException { + static void reduceExample() throws InterruptedException, ExecutionException, TimeoutException { - //#reduce-operator-example - Source ints = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); - CompletionStage sum = ints.runWith(Sink.reduce((a, b) -> a + b), materializer); - sum.thenAccept(System.out::println); - // 55 - //#reduce-operator-example - } + // #reduce-operator-example + Source ints = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); + CompletionStage sum = ints.runWith(Sink.reduce((a, b) -> a + b), materializer); + sum.thenAccept(System.out::println); + // 55 + // #reduce-operator-example + } - static void takeLastExample() throws InterruptedException, ExecutionException, TimeoutException { - //#takeLast-operator-example - // pair of (Name, GPA) - List sortedStudents = Arrays.asList(new Pair<>("Benita", 2.1), new Pair<>("Adrian", 3.1), - new Pair<>("Alexis", 4), new Pair<>("Kendra", 4.2), new Pair<>("Jerrie", 4.3), new Pair<>("Alison", 4.7)); + static void takeLastExample() throws InterruptedException, ExecutionException, TimeoutException { + // #takeLast-operator-example + // pair of (Name, GPA) + List sortedStudents = + Arrays.asList( + new Pair<>("Benita", 2.1), + new Pair<>("Adrian", 3.1), + new Pair<>("Alexis", 4), + new Pair<>("Kendra", 4.2), + new Pair<>("Jerrie", 4.3), + new Pair<>("Alison", 4.7)); - Source studentSource = Source.from(sortedStudents); + Source studentSource = Source.from(sortedStudents); - CompletionStage> topThree = studentSource.runWith(Sink.takeLast(3), materializer); + CompletionStage> topThree = studentSource.runWith(Sink.takeLast(3), materializer); - topThree.thenAccept(result -> { - System.out.println("#### Top students ####"); - for (int i = result.size() - 1; i >= 0; i--) { - Pair s = result.get(i); - System.out.println("Name: " + s.first() + ", " + "GPA: " + s.second()); - } + topThree.thenAccept( + result -> { + System.out.println("#### Top students ####"); + for (int i = result.size() - 1; i >= 0; i--) { + Pair s = result.get(i); + System.out.println("Name: " + s.first() + ", " + "GPA: " + s.second()); + } }); - /* - #### Top students #### - Name: Alison, GPA: 4.7 - Name: Jerrie, GPA: 4.3 - Name: Kendra, GPA: 4.2 - */ - //#takeLast-operator-example - } + /* + #### Top students #### + Name: Alison, GPA: 4.7 + Name: Jerrie, GPA: 4.3 + Name: Kendra, GPA: 4.2 + */ + // #takeLast-operator-example + } - static void lastExample() throws InterruptedException, ExecutionException, TimeoutException { - //#last-operator-example - Source source = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); - CompletionStage result = source.runWith(Sink.last(), materializer); - result.thenAccept(System.out::println); - // 10 - //#last-operator-example - } + static void lastExample() throws InterruptedException, ExecutionException, TimeoutException { + // #last-operator-example + Source source = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); + CompletionStage result = source.runWith(Sink.last(), materializer); + result.thenAccept(System.out::println); + // 10 + // #last-operator-example + } - static void lastOptionExample() throws InterruptedException, ExecutionException, TimeoutException { - //#lastOption-operator-example - Source source = Source.empty(); - CompletionStage> result = source.runWith(Sink.lastOption(), materializer); - result.thenAccept(System.out::println); - // Optional.empty - //#lastOption-operator-example - } -} \ No newline at end of file + static void lastOptionExample() + throws InterruptedException, ExecutionException, TimeoutException { + // #lastOption-operator-example + Source source = Source.empty(); + CompletionStage> result = source.runWith(Sink.lastOption(), materializer); + result.thenAccept(System.out::println); + // Optional.empty + // #lastOption-operator-example + } +} diff --git a/akka-docs/src/test/java/jdocs/stream/operators/SourceDocExamples.java b/akka-docs/src/test/java/jdocs/stream/operators/SourceDocExamples.java index b6bdbb4fe3..0dd0e9f5a6 100644 --- a/akka-docs/src/test/java/jdocs/stream/operators/SourceDocExamples.java +++ b/akka-docs/src/test/java/jdocs/stream/operators/SourceDocExamples.java @@ -4,84 +4,84 @@ package jdocs.stream.operators; -//#imports -//#range-imports +// #imports +// #range-imports import akka.NotUsed; import akka.actor.ActorSystem; import akka.stream.ActorMaterializer; import akka.stream.Materializer; import akka.stream.javadsl.Source; -//#range-imports +// #range-imports -//#actor-ref-imports +// #actor-ref-imports import akka.actor.ActorRef; import akka.actor.Status.Success; import akka.stream.OverflowStrategy; import akka.stream.javadsl.Sink; -//#actor-ref-imports +// #actor-ref-imports import java.util.Arrays; -//#imports +// #imports public class SourceDocExamples { - public static void fromExample() { - //#source-from-example - final ActorSystem system = ActorSystem.create("SourceFromExample"); - final Materializer materializer = ActorMaterializer.create(system); + public static void fromExample() { + // #source-from-example + final ActorSystem system = ActorSystem.create("SourceFromExample"); + final Materializer materializer = ActorMaterializer.create(system); - Source ints = Source.from(Arrays.asList(0, 1, 2, 3, 4, 5)); - ints.runForeach(System.out::println, materializer); + Source ints = Source.from(Arrays.asList(0, 1, 2, 3, 4, 5)); + ints.runForeach(System.out::println, materializer); - String text = "Perfection is finally attained not when there is no longer more to add," + - "but when there is no longer anything to take away."; - Source words = Source.from(Arrays.asList(text.split("\\s"))); - words.runForeach(System.out::println, materializer); - //#source-from-example - } + String text = + "Perfection is finally attained not when there is no longer more to add," + + "but when there is no longer anything to take away."; + Source words = Source.from(Arrays.asList(text.split("\\s"))); + words.runForeach(System.out::println, materializer); + // #source-from-example + } - static void rangeExample() { + static void rangeExample() { - final ActorSystem system = ActorSystem.create("Source"); - final Materializer materializer = ActorMaterializer.create(system); + final ActorSystem system = ActorSystem.create("Source"); + final Materializer materializer = ActorMaterializer.create(system); - //#range + // #range - Source source = Source.range(1, 100); + Source source = Source.range(1, 100); - //#range + // #range - //#range - Source sourceStepFive = Source.range(1, 100, 5); + // #range + Source sourceStepFive = Source.range(1, 100, 5); - //#range + // #range - //#range - Source sourceStepNegative = Source.range(100, 1, -1); - //#range + // #range + Source sourceStepNegative = Source.range(100, 1, -1); + // #range - //#run-range - source.runForeach(i -> System.out.println(i), materializer); - //#run-range - } + // #run-range + source.runForeach(i -> System.out.println(i), materializer); + // #run-range + } - static void actorRef() { - //#actor-ref + static void actorRef() { + // #actor-ref - final ActorSystem system = ActorSystem.create(); - final Materializer materializer = ActorMaterializer.create(system); + final ActorSystem system = ActorSystem.create(); + final Materializer materializer = ActorMaterializer.create(system); - int bufferSize = 100; - Source source = Source.actorRef(bufferSize, OverflowStrategy.dropHead()); + int bufferSize = 100; + Source source = Source.actorRef(bufferSize, OverflowStrategy.dropHead()); - ActorRef actorRef = source.to(Sink.foreach(System.out::println)).run(materializer); - actorRef.tell("hello", ActorRef.noSender()); - actorRef.tell("hello", ActorRef.noSender()); - - // The stream completes successfully with the following message - actorRef.tell(new Success("completes stream"), ActorRef.noSender()); - //#actor-ref - } + ActorRef actorRef = source.to(Sink.foreach(System.out::println)).run(materializer); + actorRef.tell("hello", ActorRef.noSender()); + actorRef.tell("hello", ActorRef.noSender()); + // The stream completes successfully with the following message + actorRef.tell(new Success("completes stream"), ActorRef.noSender()); + // #actor-ref + } } diff --git a/akka-docs/src/test/java/jdocs/stream/operators/SourceOrFlow.java b/akka-docs/src/test/java/jdocs/stream/operators/SourceOrFlow.java index 44382be3be..ed8fda7f85 100644 --- a/akka-docs/src/test/java/jdocs/stream/operators/SourceOrFlow.java +++ b/akka-docs/src/test/java/jdocs/stream/operators/SourceOrFlow.java @@ -10,170 +10,171 @@ import akka.stream.javadsl.Flow; import akka.NotUsed; import akka.japi.function.Function2; -//#zip -//#zip-with -//#zip-with-index -//#or-else -//#prepend -//#concat -//#interleave -//#merge -//#merge-sorted +// #zip +// #zip-with +// #zip-with-index +// #or-else +// #prepend +// #concat +// #interleave +// #merge +// #merge-sorted import akka.stream.javadsl.Source; import akka.stream.javadsl.Sink; import java.util.Arrays; -//#merge-sorted -//#merge -//#interleave -//#concat -//#prepend -//#or-else -//#zip-with-index -//#zip-with -//#zip +// #merge-sorted +// #merge +// #interleave +// #concat +// #prepend +// #or-else +// #zip-with-index +// #zip-with +// #zip -//#log +// #log import akka.stream.Attributes; import akka.stream.javadsl.Source; -//#log +// #log import java.time.Duration; import java.util.Arrays; import java.util.Comparator; - class SourceOrFlow { private static Materializer materializer = null; void logExample() { Flow.of(String.class) - //#log + // #log .log("myStream") - .addAttributes(Attributes.createLogLevels( - Attributes.logLevelOff(), // onElement - Attributes.logLevelError(), // onFailure - Attributes.logLevelInfo())) // onFinish - //#log + .addAttributes( + Attributes.createLogLevels( + Attributes.logLevelOff(), // onElement + Attributes.logLevelError(), // onFailure + Attributes.logLevelInfo())) // onFinish + // #log ; } void zipWithIndexExample() { Materializer materializer = null; - //#zip-with-index + // #zip-with-index Source.from(Arrays.asList("apple", "orange", "banana")) - .zipWithIndex() - .runWith(Sink.foreach(System.out::print), materializer); + .zipWithIndex() + .runWith(Sink.foreach(System.out::print), materializer); // this will print ('apple', 0), ('orange', 1), ('banana', 2) - //#zip-with-index + // #zip-with-index } - + void zipExample() { - //#zip + // #zip Source sourceFruits = Source.from(Arrays.asList("apple", "orange", "banana")); Source sourceFirstLetters = Source.from(Arrays.asList("A", "O", "B")); sourceFruits.zip(sourceFirstLetters).runWith(Sink.foreach(System.out::print), materializer); // this will print ('apple', 'A'), ('orange', 'O'), ('banana', 'B') - //#zip + // #zip } void zipWithExample() { - //#zip-with + // #zip-with Source sourceCount = Source.from(Arrays.asList("one", "two", "three")); Source sourceFruits = Source.from(Arrays.asList("apple", "orange", "banana")); - sourceCount.zipWith( + sourceCount + .zipWith( sourceFruits, - (Function2) (countStr, fruitName) -> countStr + " " + fruitName - ).runWith(Sink.foreach(System.out::print), materializer); + (Function2) (countStr, fruitName) -> countStr + " " + fruitName) + .runWith(Sink.foreach(System.out::print), materializer); // this will print 'one apple', 'two orange', 'three banana' - //#zip-with + // #zip-with } void prependExample() { - //#prepend - Source ladies = Source.from(Arrays.asList("Emma", "Emily")); - Source gentlemen = Source.from(Arrays.asList("Liam", "William")); - gentlemen.prepend(ladies).runWith(Sink.foreach(System.out::print), materializer); - // this will print "Emma", "Emily", "Liam", "William" + // #prepend + Source ladies = Source.from(Arrays.asList("Emma", "Emily")); + Source gentlemen = Source.from(Arrays.asList("Liam", "William")); + gentlemen.prepend(ladies).runWith(Sink.foreach(System.out::print), materializer); + // this will print "Emma", "Emily", "Liam", "William" - //#prepend + // #prepend } - void concatExample() { - //#concat - Source sourceA = Source.from(Arrays.asList(1, 2, 3, 4)); - Source sourceB = Source.from(Arrays.asList(10, 20, 30, 40)); - sourceA.concat(sourceB).runWith(Sink.foreach(System.out::print), materializer); - //prints 1, 2, 3, 4, 10, 20, 30, 40 + // #concat + Source sourceA = Source.from(Arrays.asList(1, 2, 3, 4)); + Source sourceB = Source.from(Arrays.asList(10, 20, 30, 40)); + sourceA.concat(sourceB).runWith(Sink.foreach(System.out::print), materializer); + // prints 1, 2, 3, 4, 10, 20, 30, 40 - //#concat + // #concat } - void interleaveExample() { - //#interleave - Source sourceA = Source.from(Arrays.asList(1, 2, 3, 4)); - Source sourceB = Source.from(Arrays.asList(10, 20, 30, 40)); - sourceA.interleave(sourceB, 2).runWith(Sink.foreach(System.out::print), materializer); - //prints 1, 2, 10, 20, 3, 4, 30, 40 + // #interleave + Source sourceA = Source.from(Arrays.asList(1, 2, 3, 4)); + Source sourceB = Source.from(Arrays.asList(10, 20, 30, 40)); + sourceA.interleave(sourceB, 2).runWith(Sink.foreach(System.out::print), materializer); + // prints 1, 2, 10, 20, 3, 4, 30, 40 - //#interleave + // #interleave } - void mergeExample() { - //#merge - Source sourceA = Source.from(Arrays.asList(1, 2, 3, 4)); - Source sourceB = Source.from(Arrays.asList(10, 20, 30, 40)); - sourceA.merge(sourceB).runWith(Sink.foreach(System.out::print), materializer); - // merging is not deterministic, can for example print 1, 2, 3, 4, 10, 20, 30, 40 + // #merge + Source sourceA = Source.from(Arrays.asList(1, 2, 3, 4)); + Source sourceB = Source.from(Arrays.asList(10, 20, 30, 40)); + sourceA.merge(sourceB).runWith(Sink.foreach(System.out::print), materializer); + // merging is not deterministic, can for example print 1, 2, 3, 4, 10, 20, 30, 40 - //#merge + // #merge } - void mergeSortedExample() { - //#merge-sorted - Source sourceA = Source.from(Arrays.asList(1, 3, 5, 7)); - Source sourceB = Source.from(Arrays.asList(2, 4, 6, 8)); - sourceA.mergeSorted(sourceB, Comparator.naturalOrder()).runWith(Sink.foreach(System.out::print), materializer); - //prints 1, 2, 3, 4, 5, 6, 7, 8 + // #merge-sorted + Source sourceA = Source.from(Arrays.asList(1, 3, 5, 7)); + Source sourceB = Source.from(Arrays.asList(2, 4, 6, 8)); + sourceA + .mergeSorted(sourceB, Comparator.naturalOrder()) + .runWith(Sink.foreach(System.out::print), materializer); + // prints 1, 2, 3, 4, 5, 6, 7, 8 - Source sourceC = Source.from(Arrays.asList(20, 1, 1, 1)); - sourceA.mergeSorted(sourceC, Comparator.naturalOrder()).runWith(Sink.foreach(System.out::print), materializer); - //prints 1, 3, 5, 7, 20, 1, 1, 1 - //#merge-sorted + Source sourceC = Source.from(Arrays.asList(20, 1, 1, 1)); + sourceA + .mergeSorted(sourceC, Comparator.naturalOrder()) + .runWith(Sink.foreach(System.out::print), materializer); + // prints 1, 3, 5, 7, 20, 1, 1, 1 + // #merge-sorted } void orElseExample() { - //#or-else - Source source1 = Source.from(Arrays.asList("First source")); - Source source2 = Source.from(Arrays.asList("Second source")); - Source emptySource = Source.empty(); + // #or-else + Source source1 = Source.from(Arrays.asList("First source")); + Source source2 = Source.from(Arrays.asList("Second source")); + Source emptySource = Source.empty(); - source1.orElse(source2).runWith(Sink.foreach(System.out::print), materializer); - // this will print "First source" + source1.orElse(source2).runWith(Sink.foreach(System.out::print), materializer); + // this will print "First source" - emptySource.orElse(source2).runWith(Sink.foreach(System.out::print), materializer); - // this will print "Second source" + emptySource.orElse(source2).runWith(Sink.foreach(System.out::print), materializer); + // this will print "Second source" - //#or-else + // #or-else } void conflateExample() { - //#conflate + // #conflate Source.cycle(() -> Arrays.asList(1, 10, 100).iterator()) .throttle(10, Duration.ofSeconds(1)) // fast upstream .conflate((Integer acc, Integer el) -> acc + el) .throttle(1, Duration.ofSeconds(1)); // slow downstream - //#conflate + // #conflate } void scanExample() { - //#scan + // #scan Source source = Source.range(1, 5); source.scan(0, (acc, x) -> acc + x).runForeach(System.out::println, materializer); // 0 (= 0) @@ -182,10 +183,10 @@ class SourceOrFlow { // 6 (= 0 + 1 + 2 + 3) // 10 (= 0 + 1 + 2 + 3 + 4) // 15 (= 0 + 1 + 2 + 3 + 4 + 5) - //#scan + // #scan } - static //#conflateWithSeed-type + static // #conflateWithSeed-type class Summed { private final Integer el; @@ -198,15 +199,15 @@ class SourceOrFlow { return new Summed(this.el + other.el); } } - //#conflateWithSeed-type + // #conflateWithSeed-type void conflateWithSeedExample() { - //#conflateWithSeed + // #conflateWithSeed Source.cycle(() -> Arrays.asList(1, 10, 100).iterator()) .throttle(10, Duration.ofSeconds(1)) // fast upstream .conflateWithSeed(Summed::new, (Summed acc, Integer el) -> acc.sum(new Summed(el))) .throttle(1, Duration.ofSeconds(1)); // slow downstream - //#conflateWithSeed + // #conflateWithSeed } } diff --git a/akka-docs/src/test/java/jdocs/testkit/ParentChildTest.java b/akka-docs/src/test/java/jdocs/testkit/ParentChildTest.java index 131e840625..b82e8a22b1 100644 --- a/akka-docs/src/test/java/jdocs/testkit/ParentChildTest.java +++ b/akka-docs/src/test/java/jdocs/testkit/ParentChildTest.java @@ -19,13 +19,13 @@ import org.junit.Test; public class ParentChildTest extends AbstractJavaTest { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("TestKitDocTest", - ConfigFactory.parseString("akka.loggers = [akka.testkit.TestEventListener]")); - + new AkkaJUnitActorSystemResource( + "TestKitDocTest", + ConfigFactory.parseString("akka.loggers = [akka.testkit.TestEventListener]")); private final ActorSystem system = actorSystemResource.getSystem(); - //#test-example + // #test-example static class Parent extends AbstractActor { final ActorRef child = getContext().actorOf(Props.create(Child.class), "child"); boolean ponged = false; @@ -33,9 +33,9 @@ public class ParentChildTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("pingit", message -> child.tell("ping", getSelf())) - .matchEquals("pong", message -> ponged = true) - .build(); + .matchEquals("pingit", message -> child.tell("ping", getSelf())) + .matchEquals("pong", message -> ponged = true) + .build(); } } @@ -43,16 +43,18 @@ public class ParentChildTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("ping", message -> { - getContext().getParent().tell("pong", getSelf()); - }) - .build(); + .matchEquals( + "ping", + message -> { + getContext().getParent().tell("pong", getSelf()); + }) + .build(); } } - //#test-example + // #test-example static - //#test-dependentchild + // #test-dependentchild class DependentChild extends AbstractActor { private final ActorRef parent; @@ -63,17 +65,18 @@ public class ParentChildTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("ping", message -> parent.tell("pong", getSelf())) - .build(); + .matchEquals("ping", message -> parent.tell("pong", getSelf())) + .build(); } } - //#test-dependentchild + // #test-dependentchild static - //#test-dependentparent + // #test-dependentparent class DependentParent extends AbstractActor { final ActorRef child; final ActorRef probe; + public DependentParent(Props childProps, ActorRef probe) { child = getContext().actorOf(childProps, "child"); this.probe = probe; @@ -82,33 +85,32 @@ public class ParentChildTest extends AbstractJavaTest { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("pingit", message -> child.tell("ping", getSelf())) - .matchEquals("pong", message -> probe.tell("ponged", getSelf())) - .build(); + .matchEquals("pingit", message -> child.tell("ping", getSelf())) + .matchEquals("pong", message -> probe.tell("ponged", getSelf())) + .build(); } } - //#test-dependentparent + // #test-dependentparent static - //#test-dependentparent-generic + // #test-dependentparent-generic class GenericDependentParent extends AbstractActor { final ActorRef child; boolean ponged = false; - public GenericDependentParent(Function childMaker) - throws Exception { + public GenericDependentParent(Function childMaker) throws Exception { child = childMaker.apply(getContext()); } @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("pingit", message -> child.tell("ping", getSelf())) - .matchEquals("pong", message -> ponged = true) - .build(); + .matchEquals("pingit", message -> child.tell("ping", getSelf())) + .matchEquals("pong", message -> ponged = true) + .build(); } } - //#test-dependentparent-generic + // #test-dependentparent-generic @Test public void testingWithoutParent() { @@ -122,34 +124,34 @@ public class ParentChildTest extends AbstractJavaTest { public void testingWithCustomProps() { final TestProbe probe = new TestProbe(system); final Props childProps = Props.create(MockedChild.class); - final ActorRef parent = system.actorOf(Props.create(DependentParent.class, childProps, probe.ref())); + final ActorRef parent = + system.actorOf(Props.create(DependentParent.class, childProps, probe.ref())); probe.send(parent, "pingit"); probe.expectMsg("ponged"); } - @Test public void testingWithChildProbe() throws Exception { final TestProbe probe = new TestProbe(system); - //#child-maker-test + // #child-maker-test Function maker = param -> probe.ref(); ActorRef parent = system.actorOf(Props.create(GenericDependentParent.class, maker)); - //#child-maker-test + // #child-maker-test probe.send(parent, "pingit"); probe.expectMsg("ping"); } public void exampleProdActorFactoryFunction() throws Exception { - //#child-maker-prod + // #child-maker-prod Function maker = f -> f.actorOf(Props.create(Child.class)); ActorRef parent = system.actorOf(Props.create(GenericDependentParent.class, maker)); - //#child-maker-prod + // #child-maker-prod } static - //#test-fabricated-parent-creator + // #test-fabricated-parent-creator class FabricatedParentCreator implements Creator { private final TestProbe proxy; @@ -157,49 +159,49 @@ public class ParentChildTest extends AbstractJavaTest { this.proxy = proxy; } - @Override public Actor create() throws Exception { + @Override + public Actor create() throws Exception { return new AbstractActor() { final ActorRef child = getContext().actorOf(Props.create(Child.class), "child"); @Override public Receive createReceive() { return receiveBuilder() - .matchAny(message -> { - if (getSender().equals(child)) { - proxy.ref().forward(message, getContext()); - } else { - child.forward(message, getContext()); - } - }) - .build(); - + .matchAny( + message -> { + if (getSender().equals(child)) { + proxy.ref().forward(message, getContext()); + } else { + child.forward(message, getContext()); + } + }) + .build(); } }; } } - //#test-fabricated-parent-creator + // #test-fabricated-parent-creator @Test public void testProbeParentTest() throws Exception { - //#test-TestProbe-parent + // #test-TestProbe-parent TestKit parent = new TestKit(system); ActorRef child = parent.childActorOf(Props.create(Child.class)); - + parent.send(child, "ping"); parent.expectMsgEquals("pong"); - //#test-TestProbe-parent + // #test-TestProbe-parent } - + @Test public void fabricatedParentTestsItsChildResponses() throws Exception { // didn't put final on these in order to make the parent fit in one line in the html docs - //#test-fabricated-parent + // #test-fabricated-parent TestProbe proxy = new TestProbe(system); ActorRef parent = system.actorOf(Props.create(Actor.class, new FabricatedParentCreator(proxy))); proxy.send(parent, "ping"); proxy.expectMsg("pong"); - //#test-fabricated-parent + // #test-fabricated-parent } - } diff --git a/akka-docs/src/test/java/jdocs/testkit/TestKitDocTest.java b/akka-docs/src/test/java/jdocs/testkit/TestKitDocTest.java index 5379bea0d8..2514699fe0 100644 --- a/akka-docs/src/test/java/jdocs/testkit/TestKitDocTest.java +++ b/akka-docs/src/test/java/jdocs/testkit/TestKitDocTest.java @@ -42,25 +42,33 @@ public class TestKitDocTest extends AbstractJavaTest { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("TestKitDocTest", - ConfigFactory.parseString("akka.loggers = [akka.testkit.TestEventListener]")); + new AkkaJUnitActorSystemResource( + "TestKitDocTest", + ConfigFactory.parseString("akka.loggers = [akka.testkit.TestEventListener]")); private final ActorSystem system = actorSystemResource.getSystem(); - //#test-actor-ref + // #test-actor-ref static class MyActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("say42", message -> { - getSender().tell(42, getSelf()); - }) - .match(Exception.class, (Exception ex) -> { - throw ex; - }) - .build(); + .matchEquals( + "say42", + message -> { + getSender().tell(42, getSelf()); + }) + .match( + Exception.class, + (Exception ex) -> { + throw ex; + }) + .build(); + } + + public boolean testMe() { + return true; } - public boolean testMe() { return true; } } @Test @@ -70,44 +78,42 @@ public class TestKitDocTest extends AbstractJavaTest { final MyActor actor = ref.underlyingActor(); assertTrue(actor.testMe()); } - //#test-actor-ref + // #test-actor-ref - //#timer + // #timer static class TestTimerActor extends AbstractActorWithTimers { private static Object SCHED_KEY = "SchedKey"; - static final class TriggerScheduling { - } - static final class ScheduledMessage { - } + + static final class TriggerScheduling {} + + static final class ScheduledMessage {} + @Override public Receive createReceive() { - return receiveBuilder() - .match(TriggerScheduling.class, msg -> triggerScheduling()) - .build(); + return receiveBuilder().match(TriggerScheduling.class, msg -> triggerScheduling()).build(); } + void triggerScheduling() { - getTimers().startSingleTimer( - SCHED_KEY, - new ScheduledMessage(), Duration.ofMillis(500) - ); + getTimers().startSingleTimer(SCHED_KEY, new ScheduledMessage(), Duration.ofMillis(500)); } } - //#timer + // #timer @Test public void demonstrateAsk() throws Exception { - //#test-behavior + // #test-behavior final Props props = Props.create(MyActor.class); final TestActorRef ref = TestActorRef.create(system, props, "testB"); - final CompletableFuture future = Patterns.ask(ref, "say42", Duration.ofMillis(3000)).toCompletableFuture(); + final CompletableFuture future = + Patterns.ask(ref, "say42", Duration.ofMillis(3000)).toCompletableFuture(); assertTrue(future.isDone()); assertEquals(42, future.get()); - //#test-behavior + // #test-behavior } @Test public void demonstrateExceptions() { - //#test-expecting-exceptions + // #test-expecting-exceptions final Props props = Props.create(MyActor.class); final TestActorRef ref = TestActorRef.create(system, props, "myActor"); try { @@ -116,287 +122,345 @@ public class TestKitDocTest extends AbstractJavaTest { } catch (Exception e) { assertEquals("expected", e.getMessage()); } - //#test-expecting-exceptions + // #test-expecting-exceptions } @Test public void demonstrateWithin() { - //#test-within - new TestKit(system) {{ - getRef().tell(42, ActorRef.noSender()); - within(Duration.ZERO, Duration.ofSeconds(1), () -> { - assertEquals((Integer) 42, expectMsgClass(Integer.class)); - return null; - }); - }}; - //#test-within + // #test-within + new TestKit(system) { + { + getRef().tell(42, ActorRef.noSender()); + within( + Duration.ZERO, + Duration.ofSeconds(1), + () -> { + assertEquals((Integer) 42, expectMsgClass(Integer.class)); + return null; + }); + } + }; + // #test-within } @Test public void demonstrateExpectMsg() { - //#test-expectmsg - new TestKit(system) {{ - getRef().tell(42, ActorRef.noSender()); - final String out = expectMsgPF("match hint", in -> { - if (in instanceof Integer) { - return "match"; - } else { - throw JavaPartialFunction.noMatch(); - } - }); - assertEquals("match", out); - }}; - //#test-expectmsg + // #test-expectmsg + new TestKit(system) { + { + getRef().tell(42, ActorRef.noSender()); + final String out = + expectMsgPF( + "match hint", + in -> { + if (in instanceof Integer) { + return "match"; + } else { + throw JavaPartialFunction.noMatch(); + } + }); + assertEquals("match", out); + } + }; + // #test-expectmsg } @Test public void demonstrateReceiveWhile() { - //#test-receivewhile - new TestKit(system) {{ - getRef().tell(42, ActorRef.noSender()); - getRef().tell(43, ActorRef.noSender()); - getRef().tell("hello", ActorRef.noSender()); + // #test-receivewhile + new TestKit(system) { + { + getRef().tell(42, ActorRef.noSender()); + getRef().tell(43, ActorRef.noSender()); + getRef().tell("hello", ActorRef.noSender()); - final List out = receiveWhile(Duration.ofSeconds(1), in -> { - if (in instanceof Integer) { - return in.toString(); - } else { - throw JavaPartialFunction.noMatch(); - } - }); + final List out = + receiveWhile( + Duration.ofSeconds(1), + in -> { + if (in instanceof Integer) { + return in.toString(); + } else { + throw JavaPartialFunction.noMatch(); + } + }); - assertArrayEquals(new String[] {"42", "43"}, out.toArray()); - expectMsgEquals("hello"); - }}; - //#test-receivewhile - new TestKit(system) {{ - //#test-receivewhile-full - receiveWhile(Duration.ofMillis(100), Duration.ofMillis(50), 12, in -> { - //#match-elided - throw JavaPartialFunction.noMatch(); - //#match-elided - }); - //#test-receivewhile-full - }}; + assertArrayEquals(new String[] {"42", "43"}, out.toArray()); + expectMsgEquals("hello"); + } + }; + // #test-receivewhile + new TestKit(system) { + { + // #test-receivewhile-full + receiveWhile( + Duration.ofMillis(100), + Duration.ofMillis(50), + 12, + in -> { + // #match-elided + throw JavaPartialFunction.noMatch(); + // #match-elided + }); + // #test-receivewhile-full + } + }; } @Test public void demonstrateAwaitCond() { - //#test-awaitCond - new TestKit(system) {{ - getRef().tell(42, ActorRef.noSender()); - awaitCond(Duration.ofSeconds(1), Duration.ofMillis(100), this::msgAvailable); - }}; - //#test-awaitCond + // #test-awaitCond + new TestKit(system) { + { + getRef().tell(42, ActorRef.noSender()); + awaitCond(Duration.ofSeconds(1), Duration.ofMillis(100), this::msgAvailable); + } + }; + // #test-awaitCond } @Test public void demonstrateAwaitAssert() { - //#test-awaitAssert - new TestKit(system) {{ - getRef().tell(42, ActorRef.noSender()); - awaitAssert(Duration.ofSeconds(1), Duration.ofMillis(100), () -> { - assertEquals(msgAvailable(), true); - return null; - }); - }}; - //#test-awaitAssert + // #test-awaitAssert + new TestKit(system) { + { + getRef().tell(42, ActorRef.noSender()); + awaitAssert( + Duration.ofSeconds(1), + Duration.ofMillis(100), + () -> { + assertEquals(msgAvailable(), true); + return null; + }); + } + }; + // #test-awaitAssert } @Test - @SuppressWarnings({ "unchecked", "unused" }) // due to generic varargs + @SuppressWarnings({"unchecked", "unused"}) // due to generic varargs public void demonstrateExpect() { - new TestKit(system) {{ - getRef().tell("hello", ActorRef.noSender()); - getRef().tell("hello", ActorRef.noSender()); - getRef().tell("hello", ActorRef.noSender()); - getRef().tell("world", ActorRef.noSender()); - getRef().tell(42, ActorRef.noSender()); - getRef().tell(42, ActorRef.noSender()); - //#test-expect - final String hello = expectMsgEquals("hello"); - final String any = expectMsgAnyOf("hello", "world"); - final List all = expectMsgAllOf("hello", "world"); - final int i = expectMsgClass(Integer.class); - final Number j = expectMsgAnyClassOf(Integer.class, Long.class); - expectNoMessage(); - //#test-expect - getRef().tell("receveN-1", ActorRef.noSender()); - getRef().tell("receveN-2", ActorRef.noSender()); - //#test-expect - final List two = receiveN(2); - //#test-expect - assertEquals("hello", hello); - assertEquals("hello", any); - assertEquals(42, i); - assertEquals(42, j); - assertArrayEquals(new String[] {"hello", "world"}, all.toArray()); - }}; + new TestKit(system) { + { + getRef().tell("hello", ActorRef.noSender()); + getRef().tell("hello", ActorRef.noSender()); + getRef().tell("hello", ActorRef.noSender()); + getRef().tell("world", ActorRef.noSender()); + getRef().tell(42, ActorRef.noSender()); + getRef().tell(42, ActorRef.noSender()); + // #test-expect + final String hello = expectMsgEquals("hello"); + final String any = expectMsgAnyOf("hello", "world"); + final List all = expectMsgAllOf("hello", "world"); + final int i = expectMsgClass(Integer.class); + final Number j = expectMsgAnyClassOf(Integer.class, Long.class); + expectNoMessage(); + // #test-expect + getRef().tell("receveN-1", ActorRef.noSender()); + getRef().tell("receveN-2", ActorRef.noSender()); + // #test-expect + final List two = receiveN(2); + // #test-expect + assertEquals("hello", hello); + assertEquals("hello", any); + assertEquals(42, i); + assertEquals(42, j); + assertArrayEquals(new String[] {"hello", "world"}, all.toArray()); + } + }; } @Test public void demonstrateIgnoreMsg() { - //#test-ignoreMsg - new TestKit(system) {{ - // ignore all Strings - ignoreMsg(msg -> msg instanceof String); - getRef().tell("hello", ActorRef.noSender()); - getRef().tell(42, ActorRef.noSender()); - expectMsgEquals(42); - // remove message filter - ignoreNoMsg(); - getRef().tell("hello", ActorRef.noSender()); - expectMsgEquals("hello"); - }}; - //#test-ignoreMsg + // #test-ignoreMsg + new TestKit(system) { + { + // ignore all Strings + ignoreMsg(msg -> msg instanceof String); + getRef().tell("hello", ActorRef.noSender()); + getRef().tell(42, ActorRef.noSender()); + expectMsgEquals(42); + // remove message filter + ignoreNoMsg(); + getRef().tell("hello", ActorRef.noSender()); + expectMsgEquals("hello"); + } + }; + // #test-ignoreMsg } @Test public void demonstrateDilated() { - //#duration-dilation - new TestKit(system) {{ - final Duration original = Duration.ofSeconds(1); - final Duration stretched = dilated(original); - assertTrue("dilated", stretched.compareTo(original) >= 0); - }}; - //#duration-dilation + // #duration-dilation + new TestKit(system) { + { + final Duration original = Duration.ofSeconds(1); + final Duration stretched = dilated(original); + assertTrue("dilated", stretched.compareTo(original) >= 0); + } + }; + // #duration-dilation } @Test public void demonstrateProbe() { - //#test-probe - new TestKit(system) {{ - // simple actor which only forwards messages - class Forwarder extends AbstractActor { - final ActorRef target; - @SuppressWarnings("unused") - public Forwarder(ActorRef target) { - this.target = target; - } - @Override - public Receive createReceive() { - return receiveBuilder() - .matchAny(message -> target.forward(message, getContext())) - .build(); + // #test-probe + new TestKit(system) { + { + // simple actor which only forwards messages + class Forwarder extends AbstractActor { + final ActorRef target; + + @SuppressWarnings("unused") + public Forwarder(ActorRef target) { + this.target = target; + } + + @Override + public Receive createReceive() { + return receiveBuilder() + .matchAny(message -> target.forward(message, getContext())) + .build(); + } } + + // create a test probe + final TestKit probe = new TestKit(system); + + // create a forwarder, injecting the probe’s testActor + final Props props = Props.create(Forwarder.class, this, probe.getRef()); + final ActorRef forwarder = system.actorOf(props, "forwarder"); + + // verify correct forwarding + forwarder.tell(42, getRef()); + probe.expectMsgEquals(42); + assertEquals(getRef(), probe.getLastSender()); } - - // create a test probe - final TestKit probe = new TestKit(system); - - // create a forwarder, injecting the probe’s testActor - final Props props = Props.create(Forwarder.class, this, probe.getRef()); - final ActorRef forwarder = system.actorOf(props, "forwarder"); - - // verify correct forwarding - forwarder.tell(42, getRef()); - probe.expectMsgEquals(42); - assertEquals(getRef(), probe.getLastSender()); - }}; - //#test-probe + }; + // #test-probe } @Test public void demonstrateTestProbeWithCustomName() { - //#test-probe-with-custom-name - new TestKit(system) {{ - final TestProbe worker = new TestProbe(system, "worker"); - final TestProbe aggregator = new TestProbe(system, "aggregator"); + // #test-probe-with-custom-name + new TestKit(system) { + { + final TestProbe worker = new TestProbe(system, "worker"); + final TestProbe aggregator = new TestProbe(system, "aggregator"); - assertTrue(worker.ref().path().name().startsWith("worker")); - assertTrue(aggregator.ref().path().name().startsWith("aggregator")); - }}; - //#test-probe-with-custom-name + assertTrue(worker.ref().path().name().startsWith("worker")); + assertTrue(aggregator.ref().path().name().startsWith("aggregator")); + } + }; + // #test-probe-with-custom-name } @Test public void demonstrateSpecialProbe() { - //#test-special-probe - new TestKit(system) {{ - class MyProbe extends TestKit { - public MyProbe() { - super(system); - } - public void assertHello() { - expectMsgEquals("hello"); - } - } + // #test-special-probe + new TestKit(system) { + { + class MyProbe extends TestKit { + public MyProbe() { + super(system); + } - final MyProbe probe = new MyProbe(); - probe.getRef().tell("hello", ActorRef.noSender()); - probe.assertHello(); - }}; - //#test-special-probe + public void assertHello() { + expectMsgEquals("hello"); + } + } + + final MyProbe probe = new MyProbe(); + probe.getRef().tell("hello", ActorRef.noSender()); + probe.assertHello(); + } + }; + // #test-special-probe } @Test public void demonstrateWatch() { final ActorRef target = system.actorOf(Props.create(MyActor.class)); - //#test-probe-watch - new TestKit(system) {{ - final TestKit probe = new TestKit(system); - probe.watch(target); - target.tell(PoisonPill.getInstance(), ActorRef.noSender()); - final Terminated msg = probe.expectMsgClass(Terminated.class); - assertEquals(msg.getActor(), target); - }}; - //#test-probe-watch + // #test-probe-watch + new TestKit(system) { + { + final TestKit probe = new TestKit(system); + probe.watch(target); + target.tell(PoisonPill.getInstance(), ActorRef.noSender()); + final Terminated msg = probe.expectMsgClass(Terminated.class); + assertEquals(msg.getActor(), target); + } + }; + // #test-probe-watch } @Test public void demonstrateReply() { - //#test-probe-reply - new TestKit(system) {{ - final TestKit probe = new TestKit(system); - probe.getRef().tell("hello", getRef()); - probe.expectMsgEquals("hello"); - probe.reply("world"); - expectMsgEquals("world"); - assertEquals(probe.getRef(), getLastSender()); - }}; - //#test-probe-reply + // #test-probe-reply + new TestKit(system) { + { + final TestKit probe = new TestKit(system); + probe.getRef().tell("hello", getRef()); + probe.expectMsgEquals("hello"); + probe.reply("world"); + expectMsgEquals("world"); + assertEquals(probe.getRef(), getLastSender()); + } + }; + // #test-probe-reply } @Test public void demonstrateForward() { - //#test-probe-forward - new TestKit(system) {{ - final TestKit probe = new TestKit(system); - probe.getRef().tell("hello", getRef()); - probe.expectMsgEquals("hello"); - probe.forward(getRef()); - expectMsgEquals("hello"); - assertEquals(getRef(), getLastSender()); - }}; - //#test-probe-forward + // #test-probe-forward + new TestKit(system) { + { + final TestKit probe = new TestKit(system); + probe.getRef().tell("hello", getRef()); + probe.expectMsgEquals("hello"); + probe.forward(getRef()); + expectMsgEquals("hello"); + assertEquals(getRef(), getLastSender()); + } + }; + // #test-probe-forward } @Test public void demonstrateUsingInheritenceToTestTimers() { - //#timer-test - new TestKit(system) {{ - final TestKit probe = new TestKit(system); - final ActorRef target = system.actorOf(Props.create(TestTimerActor.class, () -> new TestTimerActor() { - @Override - void triggerScheduling() { - probe.getRef().tell(new ScheduledMessage(), getSelf()); - } - })); - target.tell(new TestTimerActor.TriggerScheduling(), ActorRef.noSender()); - probe.expectMsgClass(TestTimerActor.ScheduledMessage.class); - }}; - //#timer-test + // #timer-test + new TestKit(system) { + { + final TestKit probe = new TestKit(system); + final ActorRef target = + system.actorOf( + Props.create( + TestTimerActor.class, + () -> + new TestTimerActor() { + @Override + void triggerScheduling() { + probe.getRef().tell(new ScheduledMessage(), getSelf()); + } + })); + target.tell(new TestTimerActor.TriggerScheduling(), ActorRef.noSender()); + probe.expectMsgClass(TestTimerActor.ScheduledMessage.class); + } + }; + // #timer-test } @Test public void demonstrateWithinProbe() { try { - //#test-within-probe - new TestKit(system) {{ - final TestKit probe = new TestKit(system); - within(Duration.ofSeconds(1), () -> probe.expectMsgEquals("hello")); - }}; - //#test-within-probe + // #test-within-probe + new TestKit(system) { + { + final TestKit probe = new TestKit(system); + within(Duration.ofSeconds(1), () -> probe.expectMsgEquals("hello")); + } + }; + // #test-within-probe } catch (AssertionError e) { // expected to fail } @@ -404,49 +468,56 @@ public class TestKitDocTest extends AbstractJavaTest { @Test public void demonstrateAutoPilot() { - //#test-auto-pilot - new TestKit(system) {{ - final TestKit probe = new TestKit(system); - // install auto-pilot - probe.setAutoPilot(new TestActor.AutoPilot() { - public AutoPilot run(ActorRef sender, Object msg) { - sender.tell(msg, ActorRef.noSender()); - return noAutoPilot(); - } - }); - // first one is replied to directly ... - probe.getRef().tell("hello", getRef()); - expectMsgEquals("hello"); - // ... but then the auto-pilot switched itself off - probe.getRef().tell("world", getRef()); - expectNoMessage(); - }}; - //#test-auto-pilot + // #test-auto-pilot + new TestKit(system) { + { + final TestKit probe = new TestKit(system); + // install auto-pilot + probe.setAutoPilot( + new TestActor.AutoPilot() { + public AutoPilot run(ActorRef sender, Object msg) { + sender.tell(msg, ActorRef.noSender()); + return noAutoPilot(); + } + }); + // first one is replied to directly ... + probe.getRef().tell("hello", getRef()); + expectMsgEquals("hello"); + // ... but then the auto-pilot switched itself off + probe.getRef().tell("world", getRef()); + expectNoMessage(); + } + }; + // #test-auto-pilot } // only compilation public void demonstrateCTD() { - //#calling-thread-dispatcher - system.actorOf( - Props.create(MyActor.class) - .withDispatcher(CallingThreadDispatcher.Id())); - //#calling-thread-dispatcher + // #calling-thread-dispatcher + system.actorOf(Props.create(MyActor.class).withDispatcher(CallingThreadDispatcher.Id())); + // #calling-thread-dispatcher } @Test public void demonstrateEventFilter() { - //#test-event-filter - new TestKit(system) {{ - assertEquals("TestKitDocTest", system.name()); - final ActorRef victim = system.actorOf(Props.empty(), "victim"); + // #test-event-filter + new TestKit(system) { + { + assertEquals("TestKitDocTest", system.name()); + final ActorRef victim = system.actorOf(Props.empty(), "victim"); - final int result = new EventFilter(ActorKilledException.class, system).from("akka://TestKitDocTest/user/victim").occurrences(1).intercept(() -> { - victim.tell(Kill.getInstance(), ActorRef.noSender()); - return 42; - }); - assertEquals(42, result); - }}; - //#test-event-filter + final int result = + new EventFilter(ActorKilledException.class, system) + .from("akka://TestKitDocTest/user/victim") + .occurrences(1) + .intercept( + () -> { + victim.tell(Kill.getInstance(), ActorRef.noSender()); + return 42; + }); + assertEquals(42, result); + } + }; + // #test-event-filter } - } diff --git a/akka-docs/src/test/java/jdocs/testkit/TestKitSampleTest.java b/akka-docs/src/test/java/jdocs/testkit/TestKitSampleTest.java index c663a73bbb..1087b620e7 100644 --- a/akka-docs/src/test/java/jdocs/testkit/TestKitSampleTest.java +++ b/akka-docs/src/test/java/jdocs/testkit/TestKitSampleTest.java @@ -4,7 +4,7 @@ package jdocs.testkit; -//#fullsample +// #fullsample import jdocs.AbstractJavaTest; import akka.testkit.javadsl.TestKit; import org.junit.AfterClass; @@ -20,32 +20,36 @@ import akka.actor.AbstractActor; import java.time.Duration; public class TestKitSampleTest extends AbstractJavaTest { - + public static class SomeActor extends AbstractActor { ActorRef target = null; @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("hello", message -> { - getSender().tell("world", getSelf()); - if (target != null) target.forward(message, getContext()); - }) - .match(ActorRef.class, actorRef -> { - target = actorRef; - getSender().tell("done", getSelf()); - }) - .build(); + .matchEquals( + "hello", + message -> { + getSender().tell("world", getSelf()); + if (target != null) target.forward(message, getContext()); + }) + .match( + ActorRef.class, + actorRef -> { + target = actorRef; + getSender().tell("done", getSelf()); + }) + .build(); } } - + static ActorSystem system; - + @BeforeClass public static void setup() { system = ActorSystem.create(); } - + @AfterClass public static void teardown() { TestKit.shutdownActorSystem(system); @@ -55,41 +59,44 @@ public class TestKitSampleTest extends AbstractJavaTest { @Test public void testIt() { /* - * Wrap the whole test procedure within a testkit constructor + * Wrap the whole test procedure within a testkit constructor * if you want to receive actor replies or use Within(), etc. */ - new TestKit(system) {{ - final Props props = Props.create(SomeActor.class); - final ActorRef subject = system.actorOf(props); + new TestKit(system) { + { + final Props props = Props.create(SomeActor.class); + final ActorRef subject = system.actorOf(props); - // can also use JavaTestKit “from the outside” - final TestKit probe = new TestKit(system); - // “inject” the probe by passing it to the test subject - // like a real resource would be passed in production - subject.tell(probe.getRef(), getRef()); - // await the correct response - expectMsg(Duration.ofSeconds(1), "done"); - - // the run() method needs to finish within 3 seconds - within(Duration.ofSeconds(3), () -> { - subject.tell("hello", getRef()); + // can also use JavaTestKit “from the outside” + final TestKit probe = new TestKit(system); + // “inject” the probe by passing it to the test subject + // like a real resource would be passed in production + subject.tell(probe.getRef(), getRef()); + // await the correct response + expectMsg(Duration.ofSeconds(1), "done"); - // This is a demo: would normally use expectMsgEquals(). - // Wait time is bounded by 3-second deadline above. - awaitCond(probe::msgAvailable); + // the run() method needs to finish within 3 seconds + within( + Duration.ofSeconds(3), + () -> { + subject.tell("hello", getRef()); - // response must have been enqueued to us before probe - expectMsg(Duration.ZERO, "world"); - // check that the probe we injected earlier got the msg - probe.expectMsg(Duration.ZERO, "hello"); - Assert.assertEquals(getRef(), probe.getLastSender()); + // This is a demo: would normally use expectMsgEquals(). + // Wait time is bounded by 3-second deadline above. + awaitCond(probe::msgAvailable); - // Will wait for the rest of the 3 seconds - expectNoMessage(); - return null; - }); - }}; + // response must have been enqueued to us before probe + expectMsg(Duration.ZERO, "world"); + // check that the probe we injected earlier got the msg + probe.expectMsg(Duration.ZERO, "hello"); + Assert.assertEquals(getRef(), probe.getLastSender()); + + // Will wait for the rest of the 3 seconds + expectNoMessage(); + return null; + }); + } + }; } - } -//#fullsample +// #fullsample diff --git a/akka-docs/src/test/java/jdocs/tutorial_1/ActorHierarchyExperiments.java b/akka-docs/src/test/java/jdocs/tutorial_1/ActorHierarchyExperiments.java index 5cc31f1967..327643d645 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_1/ActorHierarchyExperiments.java +++ b/akka-docs/src/test/java/jdocs/tutorial_1/ActorHierarchyExperiments.java @@ -2,10 +2,10 @@ * Copyright (C) 2018-2019 Lightbend Inc. */ -//#print-refs +// #print-refs package com.example; -//#print-refs +// #print-refs import akka.testkit.javadsl.TestKit; import org.junit.AfterClass; @@ -13,7 +13,7 @@ import org.junit.BeforeClass; import org.junit.Test; import org.scalatest.junit.JUnitSuite; -//#print-refs +// #print-refs import akka.actor.AbstractActor; import akka.actor.AbstractActor.Receive; import akka.actor.ActorRef; @@ -28,16 +28,18 @@ class PrintMyActorRefActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("printit", p -> { - ActorRef secondRef = getContext().actorOf(Props.empty(), "second-actor"); - System.out.println("Second: " + secondRef); - }) + .matchEquals( + "printit", + p -> { + ActorRef secondRef = getContext().actorOf(Props.empty(), "second-actor"); + System.out.println("Second: " + secondRef); + }) .build(); } } -//#print-refs +// #print-refs -//#start-stop +// #start-stop class StartStopActor1 extends AbstractActor { static Props props() { return Props.create(StartStopActor1.class, StartStopActor1::new); @@ -57,9 +59,11 @@ class StartStopActor1 extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("stop", s -> { - getContext().stop(getSelf()); - }) + .matchEquals( + "stop", + s -> { + getContext().stop(getSelf()); + }) .build(); } } @@ -84,13 +88,12 @@ class StartStopActor2 extends AbstractActor { // want to handle any messages in the actor. @Override public Receive createReceive() { - return receiveBuilder() - .build(); + return receiveBuilder().build(); } } -//#start-stop +// #start-stop -//#supervise +// #supervise class SupervisingActor extends AbstractActor { static Props props() { return Props.create(SupervisingActor.class, SupervisingActor::new); @@ -101,9 +104,11 @@ class SupervisingActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("failChild", f -> { - child.tell("fail", getSelf()); - }) + .matchEquals( + "failChild", + f -> { + child.tell("fail", getSelf()); + }) .build(); } } @@ -126,16 +131,18 @@ class SupervisedActor extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .matchEquals("fail", f -> { - System.out.println("supervised actor fails now"); - throw new Exception("I failed!"); - }) + .matchEquals( + "fail", + f -> { + System.out.println("supervised actor fails now"); + throw new Exception("I failed!"); + }) .build(); } } -//#supervise +// #supervise -//#print-refs +// #print-refs public class ActorHierarchyExperiments { public static void main(String[] args) throws java.io.IOException { ActorSystem system = ActorSystem.create("testSystem"); @@ -152,8 +159,7 @@ public class ActorHierarchyExperiments { } } } -//#print-refs - +// #print-refs class ActorHierarchyExperimentsTest extends JUnitSuite { static ActorSystem system; @@ -171,17 +177,17 @@ class ActorHierarchyExperimentsTest extends JUnitSuite { @Test public void testStartAndStopActors() { - //#start-stop-main + // #start-stop-main ActorRef first = system.actorOf(StartStopActor1.props(), "first"); first.tell("stop", ActorRef.noSender()); - //#start-stop-main + // #start-stop-main } @Test public void testSuperviseActors() { - //#supervise-main + // #supervise-main ActorRef supervisingActor = system.actorOf(SupervisingActor.props(), "supervising-actor"); supervisingActor.tell("failChild", ActorRef.noSender()); - //#supervise-main + // #supervise-main } } diff --git a/akka-docs/src/test/java/jdocs/tutorial_2/IotMain.java b/akka-docs/src/test/java/jdocs/tutorial_2/IotMain.java index 5480621d1c..16307167d0 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_2/IotMain.java +++ b/akka-docs/src/test/java/jdocs/tutorial_2/IotMain.java @@ -2,7 +2,7 @@ * Copyright (C) 2009-2019 Lightbend Inc. */ -//#iot-app +// #iot-app package com.example; import java.io.IOException; @@ -25,6 +25,5 @@ public class IotMain { system.terminate(); } } - } -//#iot-app +// #iot-app diff --git a/akka-docs/src/test/java/jdocs/tutorial_2/IotSupervisor.java b/akka-docs/src/test/java/jdocs/tutorial_2/IotSupervisor.java index f147c66213..bddef3aa34 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_2/IotSupervisor.java +++ b/akka-docs/src/test/java/jdocs/tutorial_2/IotSupervisor.java @@ -2,7 +2,7 @@ * Copyright (C) 2009-2019 Lightbend Inc. */ -//#iot-supervisor +// #iot-supervisor package com.example; import akka.actor.AbstractActor; @@ -31,9 +31,7 @@ public class IotSupervisor extends AbstractActor { // No need to handle any messages @Override public Receive createReceive() { - return receiveBuilder() - .build(); + return receiveBuilder().build(); } - } -//#iot-supervisor +// #iot-supervisor diff --git a/akka-docs/src/test/java/jdocs/tutorial_3/Device.java b/akka-docs/src/test/java/jdocs/tutorial_3/Device.java index 04a284b2d9..4096cc79fb 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_3/Device.java +++ b/akka-docs/src/test/java/jdocs/tutorial_3/Device.java @@ -4,7 +4,7 @@ package jdocs.tutorial_3; -//#full-device +// #full-device import java.util.Optional; @@ -81,15 +81,20 @@ public class Device extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(RecordTemperature.class, r -> { + .match( + RecordTemperature.class, + r -> { log.info("Recorded temperature reading {} with {}", r.value, r.requestId); lastTemperatureReading = Optional.of(r.value); getSender().tell(new TemperatureRecorded(r.requestId), getSelf()); }) - .match(ReadTemperature.class, r -> { - getSender().tell(new RespondTemperature(r.requestId, lastTemperatureReading), getSelf()); + .match( + ReadTemperature.class, + r -> { + getSender() + .tell(new RespondTemperature(r.requestId, lastTemperatureReading), getSelf()); }) - .build(); + .build(); } } -//#full-device +// #full-device diff --git a/akka-docs/src/test/java/jdocs/tutorial_3/DeviceInProgress.java b/akka-docs/src/test/java/jdocs/tutorial_3/DeviceInProgress.java index 3102d3e54b..0edbe628ae 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_3/DeviceInProgress.java +++ b/akka-docs/src/test/java/jdocs/tutorial_3/DeviceInProgress.java @@ -13,9 +13,8 @@ import jdocs.tutorial_3.Device.TemperatureRecorded; class DeviceInProgress1 { - //#read-protocol-1 - public static final class ReadTemperature { - } + // #read-protocol-1 + public static final class ReadTemperature {} public static final class RespondTemperature { final Optional value; @@ -24,7 +23,6 @@ class DeviceInProgress1 { this.value = value; } } - //#read-protocol-1 + // #read-protocol-1 } - diff --git a/akka-docs/src/test/java/jdocs/tutorial_3/DeviceInProgress3.java b/akka-docs/src/test/java/jdocs/tutorial_3/DeviceInProgress3.java index 707ce62d10..aa567b4284 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_3/DeviceInProgress3.java +++ b/akka-docs/src/test/java/jdocs/tutorial_3/DeviceInProgress3.java @@ -6,7 +6,7 @@ package jdocs.tutorial_3; class DeviceInProgress3 { - //#write-protocol-1 + // #write-protocol-1 public static final class RecordTemperature { final double value; @@ -14,5 +14,5 @@ class DeviceInProgress3 { this.value = value; } } - //#write-protocol-1 + // #write-protocol-1 } diff --git a/akka-docs/src/test/java/jdocs/tutorial_3/DeviceTest.java b/akka-docs/src/test/java/jdocs/tutorial_3/DeviceTest.java index 1ff9a8a485..db2899a4dc 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_3/DeviceTest.java +++ b/akka-docs/src/test/java/jdocs/tutorial_3/DeviceTest.java @@ -32,7 +32,7 @@ public class DeviceTest extends JUnitSuite { system = null; } - //#device-read-test + // #device-read-test @Test public void testReplyWithEmptyReadingIfNoTemperatureIsKnown() { TestKit probe = new TestKit(system); @@ -42,9 +42,9 @@ public class DeviceTest extends JUnitSuite { assertEquals(42L, response.requestId); assertEquals(Optional.empty(), response.value); } - //#device-read-test + // #device-read-test - //#device-write-read-test + // #device-write-read-test @Test public void testReplyWithLatestTemperatureReading() { TestKit probe = new TestKit(system); @@ -66,6 +66,6 @@ public class DeviceTest extends JUnitSuite { assertEquals(4L, response2.requestId); assertEquals(Optional.of(55.0), response2.value); } - //#device-write-read-test + // #device-write-read-test } diff --git a/akka-docs/src/test/java/jdocs/tutorial_3/inprogress2/DeviceInProgress2.java b/akka-docs/src/test/java/jdocs/tutorial_3/inprogress2/DeviceInProgress2.java index 0a328a107c..8f130f33b7 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_3/inprogress2/DeviceInProgress2.java +++ b/akka-docs/src/test/java/jdocs/tutorial_3/inprogress2/DeviceInProgress2.java @@ -4,7 +4,7 @@ package jdocs.tutorial_3.inprogress2; -//#device-with-read +// #device-with-read import java.util.Optional; @@ -29,7 +29,7 @@ class Device extends AbstractActor { return Props.create(Device.class, () -> new Device(groupId, deviceId)); } - //#read-protocol-2 + // #read-protocol-2 public static final class ReadTemperature { final long requestId; @@ -47,7 +47,7 @@ class Device extends AbstractActor { this.value = value; } } - //#read-protocol-2 + // #read-protocol-2 Optional lastTemperatureReading = Optional.empty(); @@ -64,12 +64,14 @@ class Device extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(ReadTemperature.class, r -> { - getSender().tell(new RespondTemperature(r.requestId, lastTemperatureReading), getSelf()); + .match( + ReadTemperature.class, + r -> { + getSender() + .tell(new RespondTemperature(r.requestId, lastTemperatureReading), getSelf()); }) - .build(); + .build(); } - } -//#device-with-read +// #device-with-read diff --git a/akka-docs/src/test/java/jdocs/tutorial_4/Device.java b/akka-docs/src/test/java/jdocs/tutorial_4/Device.java index 7dd0988171..f3c5331cab 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_4/Device.java +++ b/akka-docs/src/test/java/jdocs/tutorial_4/Device.java @@ -4,7 +4,7 @@ package jdocs.tutorial_4; -//#device-with-register +// #device-with-register import akka.actor.AbstractActor; import akka.actor.Props; @@ -83,25 +83,34 @@ public class Device extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(RequestTrackDevice.class, r -> { + .match( + RequestTrackDevice.class, + r -> { if (this.groupId.equals(r.groupId) && this.deviceId.equals(r.deviceId)) { getSender().tell(new DeviceRegistered(), getSelf()); } else { log.warning( - "Ignoring TrackDevice request for {}-{}.This actor is responsible for {}-{}.", - r.groupId, r.deviceId, this.groupId, this.deviceId - ); + "Ignoring TrackDevice request for {}-{}.This actor is responsible for {}-{}.", + r.groupId, + r.deviceId, + this.groupId, + this.deviceId); } }) - .match(RecordTemperature.class, r -> { + .match( + RecordTemperature.class, + r -> { log.info("Recorded temperature reading {} with {}", r.value, r.requestId); lastTemperatureReading = Optional.of(r.value); getSender().tell(new TemperatureRecorded(r.requestId), getSelf()); }) - .match(ReadTemperature.class, r -> { - getSender().tell(new RespondTemperature(r.requestId, lastTemperatureReading), getSelf()); + .match( + ReadTemperature.class, + r -> { + getSender() + .tell(new RespondTemperature(r.requestId, lastTemperatureReading), getSelf()); }) - .build(); + .build(); } } -//#device-with-register +// #device-with-register diff --git a/akka-docs/src/test/java/jdocs/tutorial_4/DeviceGroup.java b/akka-docs/src/test/java/jdocs/tutorial_4/DeviceGroup.java index 3471b6ff52..4bb63b5849 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_4/DeviceGroup.java +++ b/akka-docs/src/test/java/jdocs/tutorial_4/DeviceGroup.java @@ -18,9 +18,9 @@ import akka.event.LoggingAdapter; import jdocs.tutorial_4.Device; import jdocs.tutorial_4.DeviceManager; -//#device-group-full -//#device-group-remove -//#device-group-register +// #device-group-full +// #device-group-remove +// #device-group-register public class DeviceGroup extends AbstractActor { private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); @@ -33,8 +33,8 @@ public class DeviceGroup extends AbstractActor { public static Props props(String groupId) { return Props.create(DeviceGroup.class, () -> new DeviceGroup(groupId)); } - //#device-group-register - //#device-group-remove + // #device-group-register + // #device-group-remove public static final class RequestDeviceList { final long requestId; @@ -53,13 +53,13 @@ public class DeviceGroup extends AbstractActor { this.ids = ids; } } - //#device-group-remove - //#device-group-register + // #device-group-remove + // #device-group-register final Map deviceIdToActor = new HashMap<>(); - //#device-group-register + // #device-group-register final Map actorToDeviceId = new HashMap<>(); - //#device-group-register + // #device-group-register @Override public void preStart() { @@ -78,28 +78,30 @@ public class DeviceGroup extends AbstractActor { deviceActor.forward(trackMsg, getContext()); } else { log.info("Creating device actor for {}", trackMsg.deviceId); - deviceActor = getContext().actorOf(Device.props(groupId, trackMsg.deviceId), "device-" + trackMsg.deviceId); - //#device-group-register + deviceActor = + getContext() + .actorOf(Device.props(groupId, trackMsg.deviceId), "device-" + trackMsg.deviceId); + // #device-group-register getContext().watch(deviceActor); actorToDeviceId.put(deviceActor, trackMsg.deviceId); - //#device-group-register + // #device-group-register deviceIdToActor.put(trackMsg.deviceId, deviceActor); deviceActor.forward(trackMsg, getContext()); } } else { log.warning( - "Ignoring TrackDevice request for {}. This actor is responsible for {}.", - groupId, this.groupId - ); + "Ignoring TrackDevice request for {}. This actor is responsible for {}.", + groupId, + this.groupId); } } - //#device-group-register - //#device-group-remove + // #device-group-register + // #device-group-remove private void onDeviceList(RequestDeviceList r) { getSender().tell(new ReplyDeviceList(r.requestId, deviceIdToActor.keySet()), getSelf()); } - //#device-group-remove + // #device-group-remove private void onTerminated(Terminated t) { ActorRef deviceActor = t.getActor(); @@ -108,21 +110,21 @@ public class DeviceGroup extends AbstractActor { actorToDeviceId.remove(deviceActor); deviceIdToActor.remove(deviceId); } - //#device-group-register + // #device-group-register @Override public Receive createReceive() { return receiveBuilder() - .match(DeviceManager.RequestTrackDevice.class, this::onTrackDevice) - //#device-group-register - //#device-group-remove - .match(RequestDeviceList.class, this::onDeviceList) - //#device-group-remove - .match(Terminated.class, this::onTerminated) - //#device-group-register - .build(); + .match(DeviceManager.RequestTrackDevice.class, this::onTrackDevice) + // #device-group-register + // #device-group-remove + .match(RequestDeviceList.class, this::onDeviceList) + // #device-group-remove + .match(Terminated.class, this::onTerminated) + // #device-group-register + .build(); } } -//#device-group-register -//#device-group-remove -//#device-group-full +// #device-group-register +// #device-group-remove +// #device-group-full diff --git a/akka-docs/src/test/java/jdocs/tutorial_4/DeviceGroupTest.java b/akka-docs/src/test/java/jdocs/tutorial_4/DeviceGroupTest.java index 942b9ed9d6..b89b37ecf3 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_4/DeviceGroupTest.java +++ b/akka-docs/src/test/java/jdocs/tutorial_4/DeviceGroupTest.java @@ -35,7 +35,7 @@ public class DeviceGroupTest extends JUnitSuite { system = null; } - //#device-group-test-registration + // #device-group-test-registration @Test public void testRegisterDeviceActor() { TestKit probe = new TestKit(system); @@ -65,9 +65,9 @@ public class DeviceGroupTest extends JUnitSuite { groupActor.tell(new DeviceManager.RequestTrackDevice("wrongGroup", "device1"), probe.getRef()); probe.expectNoMessage(); } - //#device-group-test-registration + // #device-group-test-registration - //#device-group-test3 + // #device-group-test3 @Test public void testReturnSameActorForSameDeviceId() { TestKit probe = new TestKit(system); @@ -82,9 +82,9 @@ public class DeviceGroupTest extends JUnitSuite { ActorRef deviceActor2 = probe.getLastSender(); assertEquals(deviceActor1, deviceActor2); } - //#device-group-test3 + // #device-group-test3 - //#device-group-list-terminate-test + // #device-group-list-terminate-test @Test public void testListActiveDevices() { TestKit probe = new TestKit(system); @@ -125,14 +125,14 @@ public class DeviceGroupTest extends JUnitSuite { // using awaitAssert to retry because it might take longer for the groupActor // to see the Terminated, that order is undefined - probe.awaitAssert(() -> { - groupActor.tell(new DeviceGroup.RequestDeviceList(1L), probe.getRef()); - DeviceGroup.ReplyDeviceList r = - probe.expectMsgClass(DeviceGroup.ReplyDeviceList.class); - assertEquals(1L, r.requestId); - assertEquals(Stream.of("device2").collect(Collectors.toSet()), r.ids); - return null; - }); + probe.awaitAssert( + () -> { + groupActor.tell(new DeviceGroup.RequestDeviceList(1L), probe.getRef()); + DeviceGroup.ReplyDeviceList r = probe.expectMsgClass(DeviceGroup.ReplyDeviceList.class); + assertEquals(1L, r.requestId); + assertEquals(Stream.of("device2").collect(Collectors.toSet()), r.ids); + return null; + }); } - //#device-group-list-terminate-test + // #device-group-list-terminate-test } diff --git a/akka-docs/src/test/java/jdocs/tutorial_4/DeviceManager.java b/akka-docs/src/test/java/jdocs/tutorial_4/DeviceManager.java index 88339b2b75..ec52b3ae8d 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_4/DeviceManager.java +++ b/akka-docs/src/test/java/jdocs/tutorial_4/DeviceManager.java @@ -14,7 +14,7 @@ import akka.actor.Terminated; import akka.event.Logging; import akka.event.LoggingAdapter; -//#device-manager-full +// #device-manager-full public class DeviceManager extends AbstractActor { private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); @@ -22,7 +22,7 @@ public class DeviceManager extends AbstractActor { return Props.create(DeviceManager.class, DeviceManager::new); } - //#device-manager-msgs + // #device-manager-msgs public static final class RequestTrackDevice { public final String groupId; public final String deviceId; @@ -33,10 +33,9 @@ public class DeviceManager extends AbstractActor { } } - public static final class DeviceRegistered { - } + public static final class DeviceRegistered {} - //#device-manager-msgs + // #device-manager-msgs final Map groupIdToActor = new HashMap<>(); final Map actorToGroupId = new HashMap<>(); @@ -75,10 +74,9 @@ public class DeviceManager extends AbstractActor { public Receive createReceive() { return receiveBuilder() - .match(RequestTrackDevice.class, this::onTrackDevice) - .match(Terminated.class, this::onTerminated) - .build(); + .match(RequestTrackDevice.class, this::onTrackDevice) + .match(Terminated.class, this::onTerminated) + .build(); } - } -//#device-manager-full +// #device-manager-full diff --git a/akka-docs/src/test/java/jdocs/tutorial_4/DeviceTest.java b/akka-docs/src/test/java/jdocs/tutorial_4/DeviceTest.java index 0a1d3b533f..7f2550d1e5 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_4/DeviceTest.java +++ b/akka-docs/src/test/java/jdocs/tutorial_4/DeviceTest.java @@ -32,7 +32,7 @@ public class DeviceTest extends JUnitSuite { system = null; } - //#device-registration-tests + // #device-registration-tests @Test public void testReplyToRegistrationRequests() { TestKit probe = new TestKit(system); @@ -54,9 +54,9 @@ public class DeviceTest extends JUnitSuite { deviceActor.tell(new DeviceManager.RequestTrackDevice("group", "wrongDevice"), probe.getRef()); probe.expectNoMessage(); } - //#device-registration-tests + // #device-registration-tests - //#device-read-test + // #device-read-test @Test public void testReplyWithEmptyReadingIfNoTemperatureIsKnown() { TestKit probe = new TestKit(system); @@ -66,9 +66,9 @@ public class DeviceTest extends JUnitSuite { assertEquals(42L, response.requestId); assertEquals(Optional.empty(), response.value); } - //#device-read-test + // #device-read-test - //#device-write-read-test + // #device-write-read-test @Test public void testReplyWithLatestTemperatureReading() { TestKit probe = new TestKit(system); @@ -90,6 +90,6 @@ public class DeviceTest extends JUnitSuite { assertEquals(4L, response2.requestId); assertEquals(Optional.of(55.0), response2.value); } - //#device-write-read-test + // #device-write-read-test } diff --git a/akka-docs/src/test/java/jdocs/tutorial_5/Device.java b/akka-docs/src/test/java/jdocs/tutorial_5/Device.java index 38451d2f03..179da5354f 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_5/Device.java +++ b/akka-docs/src/test/java/jdocs/tutorial_5/Device.java @@ -81,24 +81,33 @@ public class Device extends AbstractActor { @Override public Receive createReceive() { return receiveBuilder() - .match(RequestTrackDevice.class, r -> { + .match( + RequestTrackDevice.class, + r -> { if (this.groupId.equals(r.groupId) && this.deviceId.equals(r.deviceId)) { getSender().tell(new DeviceRegistered(), getSelf()); } else { log.warning( - "Ignoring TrackDevice request for {}-{}.This actor is responsible for {}-{}.", - r.groupId, r.deviceId, this.groupId, this.deviceId - ); + "Ignoring TrackDevice request for {}-{}.This actor is responsible for {}-{}.", + r.groupId, + r.deviceId, + this.groupId, + this.deviceId); } }) - .match(RecordTemperature.class, r -> { + .match( + RecordTemperature.class, + r -> { log.info("Recorded temperature reading {} with {}", r.value, r.requestId); lastTemperatureReading = Optional.of(r.value); getSender().tell(new TemperatureRecorded(r.requestId), getSelf()); }) - .match(ReadTemperature.class, r -> { - getSender().tell(new RespondTemperature(r.requestId, lastTemperatureReading), getSelf()); + .match( + ReadTemperature.class, + r -> { + getSender() + .tell(new RespondTemperature(r.requestId, lastTemperatureReading), getSelf()); }) - .build(); + .build(); } } diff --git a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroup.java b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroup.java index 0c7670ebbd..5c1757b780 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroup.java +++ b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroup.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; -//#query-added +// #query-added public class DeviceGroup extends AbstractActor { private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); @@ -49,7 +49,7 @@ public class DeviceGroup extends AbstractActor { } } - //#query-protocol + // #query-protocol public static final class RequestAllTemperatures { final long requestId; @@ -68,8 +68,7 @@ public class DeviceGroup extends AbstractActor { } } - public static interface TemperatureReading { - } + public static interface TemperatureReading {} public static final class Temperature implements TemperatureReading { public final double value; @@ -96,9 +95,7 @@ public class DeviceGroup extends AbstractActor { @Override public String toString() { - return "Temperature{" + - "value=" + value + - '}'; + return "Temperature{" + "value=" + value + '}'; } } @@ -113,8 +110,7 @@ public class DeviceGroup extends AbstractActor { public enum DeviceTimedOut implements TemperatureReading { INSTANCE } - //#query-protocol - + // #query-protocol final Map deviceIdToActor = new HashMap<>(); final Map actorToDeviceId = new HashMap<>(); @@ -129,7 +125,7 @@ public class DeviceGroup extends AbstractActor { log.info("DeviceGroup {} stopped", groupId); } - //#query-added + // #query-added private void onTrackDevice(DeviceManager.RequestTrackDevice trackMsg) { if (this.groupId.equals(trackMsg.groupId)) { ActorRef ref = deviceIdToActor.get(trackMsg.deviceId); @@ -137,7 +133,9 @@ public class DeviceGroup extends AbstractActor { ref.forward(trackMsg, getContext()); } else { log.info("Creating device actor for {}", trackMsg.deviceId); - ActorRef deviceActor = getContext().actorOf(Device.props(groupId, trackMsg.deviceId), "device-" + trackMsg.deviceId); + ActorRef deviceActor = + getContext() + .actorOf(Device.props(groupId, trackMsg.deviceId), "device-" + trackMsg.deviceId); getContext().watch(deviceActor); deviceActor.forward(trackMsg, getContext()); actorToDeviceId.put(deviceActor, trackMsg.deviceId); @@ -145,9 +143,9 @@ public class DeviceGroup extends AbstractActor { } } else { log.warning( - "Ignoring TrackDevice request for {}. This actor is responsible for {}.", - groupId, this.groupId - ); + "Ignoring TrackDevice request for {}. This actor is responsible for {}.", + groupId, + this.groupId); } } @@ -162,30 +160,38 @@ public class DeviceGroup extends AbstractActor { actorToDeviceId.remove(deviceActor); deviceIdToActor.remove(deviceId); } - //#query-added + // #query-added private void onAllTemperatures(RequestAllTemperatures r) { - // since Java collections are mutable, we want to avoid sharing them between actors (since multiple Actors (threads) - // modifying the same mutable data-structure is not safe), and perform a defensive copy of the mutable map: + // since Java collections are mutable, we want to avoid sharing them between actors (since + // multiple Actors (threads) + // modifying the same mutable data-structure is not safe), and perform a defensive copy of the + // mutable map: // - // Feel free to use your favourite immutable data-structures library with Akka in Java applications! + // Feel free to use your favourite immutable data-structures library with Akka in Java + // applications! Map actorToDeviceIdCopy = new HashMap<>(this.actorToDeviceId); - getContext().actorOf(DeviceGroupQuery.props( - actorToDeviceIdCopy, r.requestId, getSender(), new FiniteDuration(3, TimeUnit.SECONDS))); + getContext() + .actorOf( + DeviceGroupQuery.props( + actorToDeviceIdCopy, + r.requestId, + getSender(), + new FiniteDuration(3, TimeUnit.SECONDS))); } @Override public Receive createReceive() { - //#query-added + // #query-added return receiveBuilder() - .match(DeviceManager.RequestTrackDevice.class, this::onTrackDevice) - .match(RequestDeviceList.class, this::onDeviceList) - .match(Terminated.class, this::onTerminated) - //#query-added - // ... other cases omitted - .match(RequestAllTemperatures.class, this::onAllTemperatures) - .build(); + .match(DeviceManager.RequestTrackDevice.class, this::onTrackDevice) + .match(RequestDeviceList.class, this::onDeviceList) + .match(Terminated.class, this::onTerminated) + // #query-added + // ... other cases omitted + .match(RequestAllTemperatures.class, this::onAllTemperatures) + .build(); } } -//#query-added +// #query-added diff --git a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroupQuery.java b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroupQuery.java index c31d78dbd4..86e7268a70 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroupQuery.java +++ b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroupQuery.java @@ -20,11 +20,10 @@ import akka.actor.Terminated; import akka.event.Logging; import akka.event.LoggingAdapter; -//#query-full -//#query-outline +// #query-full +// #query-outline public class DeviceGroupQuery extends AbstractActor { - public static final class CollectionTimeout { - } + public static final class CollectionTimeout {} private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); @@ -34,18 +33,35 @@ public class DeviceGroupQuery extends AbstractActor { Cancellable queryTimeoutTimer; - public DeviceGroupQuery(Map actorToDeviceId, long requestId, ActorRef requester, FiniteDuration timeout) { + public DeviceGroupQuery( + Map actorToDeviceId, + long requestId, + ActorRef requester, + FiniteDuration timeout) { this.actorToDeviceId = actorToDeviceId; this.requestId = requestId; this.requester = requester; - queryTimeoutTimer = getContext().getSystem().scheduler().scheduleOnce( - timeout, getSelf(), new CollectionTimeout(), getContext().getDispatcher(), getSelf() - ); + queryTimeoutTimer = + getContext() + .getSystem() + .scheduler() + .scheduleOnce( + timeout, + getSelf(), + new CollectionTimeout(), + getContext().getDispatcher(), + getSelf()); } - public static Props props(Map actorToDeviceId, long requestId, ActorRef requester, FiniteDuration timeout) { - return Props.create(DeviceGroupQuery.class, () -> new DeviceGroupQuery(actorToDeviceId, requestId, requester, timeout)); + public static Props props( + Map actorToDeviceId, + long requestId, + ActorRef requester, + FiniteDuration timeout) { + return Props.create( + DeviceGroupQuery.class, + () -> new DeviceGroupQuery(actorToDeviceId, requestId, requester, timeout)); } @Override @@ -61,28 +77,38 @@ public class DeviceGroupQuery extends AbstractActor { queryTimeoutTimer.cancel(); } - //#query-outline - //#query-state + // #query-outline + // #query-state @Override public Receive createReceive() { return waitingForReplies(new HashMap<>(), actorToDeviceId.keySet()); } public Receive waitingForReplies( - Map repliesSoFar, - Set stillWaiting) { + Map repliesSoFar, Set stillWaiting) { return receiveBuilder() - .match(Device.RespondTemperature.class, r -> { + .match( + Device.RespondTemperature.class, + r -> { ActorRef deviceActor = getSender(); - DeviceGroup.TemperatureReading reading = r.value + DeviceGroup.TemperatureReading reading = + r.value .map(v -> (DeviceGroup.TemperatureReading) new DeviceGroup.Temperature(v)) .orElse(DeviceGroup.TemperatureNotAvailable.INSTANCE); receivedResponse(deviceActor, reading, stillWaiting, repliesSoFar); }) - .match(Terminated.class, t -> { - receivedResponse(t.getActor(), DeviceGroup.DeviceNotAvailable.INSTANCE, stillWaiting, repliesSoFar); + .match( + Terminated.class, + t -> { + receivedResponse( + t.getActor(), + DeviceGroup.DeviceNotAvailable.INSTANCE, + stillWaiting, + repliesSoFar); }) - .match(CollectionTimeout.class, t -> { + .match( + CollectionTimeout.class, + t -> { Map replies = new HashMap<>(repliesSoFar); for (ActorRef deviceActor : stillWaiting) { String deviceId = actorToDeviceId.get(deviceActor); @@ -91,15 +117,16 @@ public class DeviceGroupQuery extends AbstractActor { requester.tell(new DeviceGroup.RespondAllTemperatures(requestId, replies), getSelf()); getContext().stop(getSelf()); }) - .build(); + .build(); } - //#query-state + // #query-state - //#query-collect-reply - public void receivedResponse(ActorRef deviceActor, - DeviceGroup.TemperatureReading reading, - Set stillWaiting, - Map repliesSoFar) { + // #query-collect-reply + public void receivedResponse( + ActorRef deviceActor, + DeviceGroup.TemperatureReading reading, + Set stillWaiting, + Map repliesSoFar) { getContext().unwatch(deviceActor); String deviceId = actorToDeviceId.get(deviceActor); @@ -115,8 +142,8 @@ public class DeviceGroupQuery extends AbstractActor { getContext().become(waitingForReplies(newRepliesSoFar, newStillWaiting)); } } - //#query-collect-reply - //#query-outline + // #query-collect-reply + // #query-outline } -//#query-outline -//#query-full +// #query-outline +// #query-full diff --git a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroupQueryTest.java b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroupQueryTest.java index d8d2d32f8e..622bbe8f0e 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroupQueryTest.java +++ b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroupQueryTest.java @@ -38,7 +38,7 @@ public class DeviceGroupQueryTest extends JUnitSuite { system = null; } - //#query-test-normal + // #query-test-normal @Test public void testReturnTemperatureValueForWorkingDevices() { TestKit requester = new TestKit(system); @@ -50,11 +50,10 @@ public class DeviceGroupQueryTest extends JUnitSuite { actorToDeviceId.put(device1.getRef(), "device1"); actorToDeviceId.put(device2.getRef(), "device2"); - ActorRef queryActor = system.actorOf(DeviceGroupQuery.props( - actorToDeviceId, - 1L, - requester.getRef(), - new FiniteDuration(3, TimeUnit.SECONDS))); + ActorRef queryActor = + system.actorOf( + DeviceGroupQuery.props( + actorToDeviceId, 1L, requester.getRef(), new FiniteDuration(3, TimeUnit.SECONDS))); assertEquals(0L, device1.expectMsgClass(Device.ReadTemperature.class).requestId); assertEquals(0L, device2.expectMsgClass(Device.ReadTemperature.class).requestId); @@ -62,7 +61,8 @@ public class DeviceGroupQueryTest extends JUnitSuite { queryActor.tell(new Device.RespondTemperature(0L, Optional.of(1.0)), device1.getRef()); queryActor.tell(new Device.RespondTemperature(0L, Optional.of(2.0)), device2.getRef()); - DeviceGroup.RespondAllTemperatures response = requester.expectMsgClass(DeviceGroup.RespondAllTemperatures.class); + DeviceGroup.RespondAllTemperatures response = + requester.expectMsgClass(DeviceGroup.RespondAllTemperatures.class); assertEquals(1L, response.requestId); Map expectedTemperatures = new HashMap<>(); @@ -71,9 +71,9 @@ public class DeviceGroupQueryTest extends JUnitSuite { assertEquals(expectedTemperatures, response.temperatures); } - //#query-test-normal + // #query-test-normal - //#query-test-no-reading + // #query-test-no-reading @Test public void testReturnTemperatureNotAvailableForDevicesWithNoReadings() { TestKit requester = new TestKit(system); @@ -85,11 +85,10 @@ public class DeviceGroupQueryTest extends JUnitSuite { actorToDeviceId.put(device1.getRef(), "device1"); actorToDeviceId.put(device2.getRef(), "device2"); - ActorRef queryActor = system.actorOf(DeviceGroupQuery.props( - actorToDeviceId, - 1L, - requester.getRef(), - new FiniteDuration(3, TimeUnit.SECONDS))); + ActorRef queryActor = + system.actorOf( + DeviceGroupQuery.props( + actorToDeviceId, 1L, requester.getRef(), new FiniteDuration(3, TimeUnit.SECONDS))); assertEquals(0L, device1.expectMsgClass(Device.ReadTemperature.class).requestId); assertEquals(0L, device2.expectMsgClass(Device.ReadTemperature.class).requestId); @@ -97,7 +96,8 @@ public class DeviceGroupQueryTest extends JUnitSuite { queryActor.tell(new Device.RespondTemperature(0L, Optional.empty()), device1.getRef()); queryActor.tell(new Device.RespondTemperature(0L, Optional.of(2.0)), device2.getRef()); - DeviceGroup.RespondAllTemperatures response = requester.expectMsgClass(DeviceGroup.RespondAllTemperatures.class); + DeviceGroup.RespondAllTemperatures response = + requester.expectMsgClass(DeviceGroup.RespondAllTemperatures.class); assertEquals(1L, response.requestId); Map expectedTemperatures = new HashMap<>(); @@ -106,9 +106,9 @@ public class DeviceGroupQueryTest extends JUnitSuite { assertEquals(expectedTemperatures, response.temperatures); } - //#query-test-no-reading + // #query-test-no-reading - //#query-test-stopped + // #query-test-stopped @Test public void testReturnDeviceNotAvailableIfDeviceStopsBeforeAnswering() { TestKit requester = new TestKit(system); @@ -120,11 +120,10 @@ public class DeviceGroupQueryTest extends JUnitSuite { actorToDeviceId.put(device1.getRef(), "device1"); actorToDeviceId.put(device2.getRef(), "device2"); - ActorRef queryActor = system.actorOf(DeviceGroupQuery.props( - actorToDeviceId, - 1L, - requester.getRef(), - new FiniteDuration(3, TimeUnit.SECONDS))); + ActorRef queryActor = + system.actorOf( + DeviceGroupQuery.props( + actorToDeviceId, 1L, requester.getRef(), new FiniteDuration(3, TimeUnit.SECONDS))); assertEquals(0L, device1.expectMsgClass(Device.ReadTemperature.class).requestId); assertEquals(0L, device2.expectMsgClass(Device.ReadTemperature.class).requestId); @@ -132,7 +131,8 @@ public class DeviceGroupQueryTest extends JUnitSuite { queryActor.tell(new Device.RespondTemperature(0L, Optional.of(1.0)), device1.getRef()); device2.getRef().tell(PoisonPill.getInstance(), ActorRef.noSender()); - DeviceGroup.RespondAllTemperatures response = requester.expectMsgClass(DeviceGroup.RespondAllTemperatures.class); + DeviceGroup.RespondAllTemperatures response = + requester.expectMsgClass(DeviceGroup.RespondAllTemperatures.class); assertEquals(1L, response.requestId); Map expectedTemperatures = new HashMap<>(); @@ -141,9 +141,9 @@ public class DeviceGroupQueryTest extends JUnitSuite { assertEquals(expectedTemperatures, response.temperatures); } - //#query-test-stopped + // #query-test-stopped - //#query-test-stopped-later + // #query-test-stopped-later @Test public void testReturnTemperatureReadingEvenIfDeviceStopsAfterAnswering() { TestKit requester = new TestKit(system); @@ -155,11 +155,10 @@ public class DeviceGroupQueryTest extends JUnitSuite { actorToDeviceId.put(device1.getRef(), "device1"); actorToDeviceId.put(device2.getRef(), "device2"); - ActorRef queryActor = system.actorOf(DeviceGroupQuery.props( - actorToDeviceId, - 1L, - requester.getRef(), - new FiniteDuration(3, TimeUnit.SECONDS))); + ActorRef queryActor = + system.actorOf( + DeviceGroupQuery.props( + actorToDeviceId, 1L, requester.getRef(), new FiniteDuration(3, TimeUnit.SECONDS))); assertEquals(0L, device1.expectMsgClass(Device.ReadTemperature.class).requestId); assertEquals(0L, device2.expectMsgClass(Device.ReadTemperature.class).requestId); @@ -168,7 +167,8 @@ public class DeviceGroupQueryTest extends JUnitSuite { queryActor.tell(new Device.RespondTemperature(0L, Optional.of(2.0)), device2.getRef()); device2.getRef().tell(PoisonPill.getInstance(), ActorRef.noSender()); - DeviceGroup.RespondAllTemperatures response = requester.expectMsgClass(DeviceGroup.RespondAllTemperatures.class); + DeviceGroup.RespondAllTemperatures response = + requester.expectMsgClass(DeviceGroup.RespondAllTemperatures.class); assertEquals(1L, response.requestId); Map expectedTemperatures = new HashMap<>(); @@ -177,9 +177,9 @@ public class DeviceGroupQueryTest extends JUnitSuite { assertEquals(expectedTemperatures, response.temperatures); } - //#query-test-stopped-later + // #query-test-stopped-later - //#query-test-timeout + // #query-test-timeout @Test public void testReturnDeviceTimedOutIfDeviceDoesNotAnswerInTime() { TestKit requester = new TestKit(system); @@ -191,20 +191,19 @@ public class DeviceGroupQueryTest extends JUnitSuite { actorToDeviceId.put(device1.getRef(), "device1"); actorToDeviceId.put(device2.getRef(), "device2"); - ActorRef queryActor = system.actorOf(DeviceGroupQuery.props( - actorToDeviceId, - 1L, - requester.getRef(), - new FiniteDuration(1, TimeUnit.SECONDS))); + ActorRef queryActor = + system.actorOf( + DeviceGroupQuery.props( + actorToDeviceId, 1L, requester.getRef(), new FiniteDuration(1, TimeUnit.SECONDS))); assertEquals(0L, device1.expectMsgClass(Device.ReadTemperature.class).requestId); assertEquals(0L, device2.expectMsgClass(Device.ReadTemperature.class).requestId); queryActor.tell(new Device.RespondTemperature(0L, Optional.of(1.0)), device1.getRef()); - DeviceGroup.RespondAllTemperatures response = requester.expectMsgClass( - java.time.Duration.ofSeconds(5), - DeviceGroup.RespondAllTemperatures.class); + DeviceGroup.RespondAllTemperatures response = + requester.expectMsgClass( + java.time.Duration.ofSeconds(5), DeviceGroup.RespondAllTemperatures.class); assertEquals(1L, response.requestId); Map expectedTemperatures = new HashMap<>(); @@ -213,6 +212,6 @@ public class DeviceGroupQueryTest extends JUnitSuite { assertEquals(expectedTemperatures, response.temperatures); } - //#query-test-timeout + // #query-test-timeout } diff --git a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroupTest.java b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroupTest.java index d98c0c9e62..e9a0498a2f 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroupTest.java +++ b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceGroupTest.java @@ -122,17 +122,17 @@ public class DeviceGroupTest extends JUnitSuite { // using awaitAssert to retry because it might take longer for the groupActor // to see the Terminated, that order is undefined - probe.awaitAssert(() -> { - groupActor.tell(new DeviceGroup.RequestDeviceList(1L), probe.getRef()); - DeviceGroup.ReplyDeviceList r = - probe.expectMsgClass(DeviceGroup.ReplyDeviceList.class); - assertEquals(1L, r.requestId); - assertEquals(Stream.of("device2").collect(Collectors.toSet()), r.ids); - return null; - }); + probe.awaitAssert( + () -> { + groupActor.tell(new DeviceGroup.RequestDeviceList(1L), probe.getRef()); + DeviceGroup.ReplyDeviceList r = probe.expectMsgClass(DeviceGroup.ReplyDeviceList.class); + assertEquals(1L, r.requestId); + assertEquals(Stream.of("device2").collect(Collectors.toSet()), r.ids); + return null; + }); } - //#group-query-integration-test + // #group-query-integration-test @Test public void testCollectTemperaturesFromAllActiveDevices() { TestKit probe = new TestKit(system); @@ -158,7 +158,8 @@ public class DeviceGroupTest extends JUnitSuite { // No temperature for device 3 groupActor.tell(new DeviceGroup.RequestAllTemperatures(0L), probe.getRef()); - DeviceGroup.RespondAllTemperatures response = probe.expectMsgClass(DeviceGroup.RespondAllTemperatures.class); + DeviceGroup.RespondAllTemperatures response = + probe.expectMsgClass(DeviceGroup.RespondAllTemperatures.class); assertEquals(0L, response.requestId); Map expectedTemperatures = new HashMap<>(); @@ -168,5 +169,5 @@ public class DeviceGroupTest extends JUnitSuite { assertEquals(expectedTemperatures, response.temperatures); } - //#group-query-integration-test + // #group-query-integration-test } diff --git a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceManager.java b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceManager.java index 3ee0bdb7cd..ac10f86371 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceManager.java +++ b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceManager.java @@ -31,8 +31,7 @@ public class DeviceManager extends AbstractActor { } } - public static final class DeviceRegistered { - } + public static final class DeviceRegistered {} final Map groupIdToActor = new HashMap<>(); final Map actorToGroupId = new HashMap<>(); @@ -72,9 +71,8 @@ public class DeviceManager extends AbstractActor { public Receive createReceive() { return receiveBuilder() - .match(RequestTrackDevice.class, this::onTrackDevice) - .match(Terminated.class, this::onTerminated) - .build(); + .match(RequestTrackDevice.class, this::onTrackDevice) + .match(Terminated.class, this::onTerminated) + .build(); } - } diff --git a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceTest.java b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceTest.java index 7c8c797241..bb02661683 100644 --- a/akka-docs/src/test/java/jdocs/tutorial_5/DeviceTest.java +++ b/akka-docs/src/test/java/jdocs/tutorial_5/DeviceTest.java @@ -85,5 +85,4 @@ public class DeviceTest extends JUnitSuite { assertEquals(4L, response2.requestId); assertEquals(Optional.of(55.0), response2.value); } - } diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_1/ActorHierarchyExperiments.java b/akka-docs/src/test/java/jdocs/typed/tutorial_1/ActorHierarchyExperiments.java index 9ed0ac3c67..bf39fab7cb 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_1/ActorHierarchyExperiments.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_1/ActorHierarchyExperiments.java @@ -13,7 +13,7 @@ import org.scalatest.junit.JUnitSuite; import akka.actor.testkit.typed.javadsl.TestKitJunitResource; import akka.actor.typed.PostStop; -//#print-refs +// #print-refs import akka.actor.typed.ActorRef; import akka.actor.typed.ActorSystem; import akka.actor.typed.Behavior; @@ -36,9 +36,7 @@ class PrintMyActorRefActor extends AbstractBehavior { @Override public Receive createReceive() { - return receiveBuilder() - .onMessageEquals("printit", this::printIt) - .build(); + return receiveBuilder().onMessageEquals("printit", this::printIt).build(); } private Behavior printIt() { @@ -46,11 +44,10 @@ class PrintMyActorRefActor extends AbstractBehavior { System.out.println("Second: " + secondRef); return this; } - } -//#print-refs +// #print-refs -//#start-stop +// #start-stop class StartStopActor1 extends AbstractBehavior { static Behavior createBehavior() { @@ -63,17 +60,16 @@ class StartStopActor1 extends AbstractBehavior { @Override public Receive createReceive() { - return receiveBuilder() - .onMessageEquals("stop", Behaviors::stopped) - .onSignal(PostStop.class, signal -> postStop()) - .build(); + return receiveBuilder() + .onMessageEquals("stop", Behaviors::stopped) + .onSignal(PostStop.class, signal -> postStop()) + .build(); } private Behavior postStop() { System.out.println("first stopped"); return this; } - } class StartStopActor2 extends AbstractBehavior { @@ -88,9 +84,7 @@ class StartStopActor2 extends AbstractBehavior { @Override public Receive createReceive() { - return receiveBuilder() - .onSignal(PostStop.class, signal -> postStop()) - .build(); + return receiveBuilder().onSignal(PostStop.class, signal -> postStop()).build(); } private Behavior postStop() { @@ -98,9 +92,9 @@ class StartStopActor2 extends AbstractBehavior { return this; } } -//#start-stop +// #start-stop -//#supervise +// #supervise class SupervisingActor extends AbstractBehavior { static Behavior createBehavior() { @@ -110,16 +104,16 @@ class SupervisingActor extends AbstractBehavior { private final ActorRef child; private SupervisingActor(ActorContext context) { - child = context.spawn( - Behaviors.supervise(SupervisedActor.createBehavior()).onFailure(SupervisorStrategy.restart()), - "supervised-actor"); + child = + context.spawn( + Behaviors.supervise(SupervisedActor.createBehavior()) + .onFailure(SupervisorStrategy.restart()), + "supervised-actor"); } @Override public Receive createReceive() { - return receiveBuilder() - .onMessageEquals("failChild", this::failChild) - .build(); + return receiveBuilder().onMessageEquals("failChild", this::failChild).build(); } private Behavior failChild() { @@ -141,10 +135,10 @@ class SupervisedActor extends AbstractBehavior { @Override public Receive createReceive() { return receiveBuilder() - .onMessageEquals("fail", this::fail) - .onSignal(PreRestart.class, signal -> preRestart()) - .onSignal(PostStop.class, signal -> postStop()) - .build(); + .onMessageEquals("fail", this::fail) + .onSignal(PreRestart.class, signal -> preRestart()) + .onSignal(PostStop.class, signal -> postStop()) + .build(); } private Behavior fail() { @@ -162,10 +156,9 @@ class SupervisedActor extends AbstractBehavior { return this; } } -//#supervise +// #supervise - -//#print-refs +// #print-refs class Main extends AbstractBehavior { @@ -181,9 +174,7 @@ class Main extends AbstractBehavior { @Override public Receive createReceive() { - return receiveBuilder() - .onMessageEquals("start", this::start) - .build(); + return receiveBuilder().onMessageEquals("start", this::start).build(); } private Behavior start() { @@ -200,28 +191,27 @@ public class ActorHierarchyExperiments { ActorSystem.create(Main.createBehavior(), "testSystem"); } } -//#print-refs - +// #print-refs class ActorHierarchyExperimentsTest extends JUnitSuite { - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(); @Test public void testStartAndStopActors() { - //#start-stop-main + // #start-stop-main ActorRef first = testKit.spawn(StartStopActor1.createBehavior(), "first"); first.tell("stop"); - //#start-stop-main + // #start-stop-main } @Test public void testSuperviseActors() throws Exception { - //#supervise-main - ActorRef supervisingActor = testKit.spawn(SupervisingActor.createBehavior(), "supervising-actor"); + // #supervise-main + ActorRef supervisingActor = + testKit.spawn(SupervisingActor.createBehavior(), "supervising-actor"); supervisingActor.tell("failChild"); - //#supervise-main + // #supervise-main Thread.sleep(200); // allow for the println/logging to complete } } diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_2/IotMain.java b/akka-docs/src/test/java/jdocs/typed/tutorial_2/IotMain.java index 75bdad6d9c..d2e9c7236b 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_2/IotMain.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_2/IotMain.java @@ -4,7 +4,7 @@ package jdocs.typed.tutorial_2; -//#iot-app +// #iot-app import akka.actor.typed.ActorSystem; public class IotMain { @@ -13,6 +13,5 @@ public class IotMain { // Create ActorSystem and top level supervisor ActorSystem.create(IotSupervisor.createBehavior(), "iot-system"); } - } -//#iot-app +// #iot-app diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_2/IotSupervisor.java b/akka-docs/src/test/java/jdocs/typed/tutorial_2/IotSupervisor.java index adc90bc60d..900124410c 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_2/IotSupervisor.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_2/IotSupervisor.java @@ -4,7 +4,7 @@ package jdocs.typed.tutorial_2; -//#iot-supervisor +// #iot-supervisor import akka.actor.typed.Behavior; import akka.actor.typed.PostStop; import akka.actor.typed.javadsl.AbstractBehavior; @@ -28,15 +28,12 @@ public class IotSupervisor extends AbstractBehavior { // No need to handle any messages @Override public Receive createReceive() { - return receiveBuilder() - .onSignal(PostStop.class, signal -> postStop()) - .build(); + return receiveBuilder().onSignal(PostStop.class, signal -> postStop()).build(); } private IotSupervisor postStop() { context.getLog().info("IoT Application stopped"); return this; } - } -//#iot-supervisor +// #iot-supervisor diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_3/Device.java b/akka-docs/src/test/java/jdocs/typed/tutorial_3/Device.java index cb46d6c8fd..5f868ce5ce 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_3/Device.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_3/Device.java @@ -4,7 +4,7 @@ package jdocs.typed.tutorial_3; -//#full-device +// #full-device import java.util.Optional; @@ -15,14 +15,14 @@ import akka.actor.typed.javadsl.ActorContext; import akka.actor.typed.javadsl.Behaviors; import akka.actor.typed.javadsl.Receive; -//#full-device +// #full-device import static jdocs.typed.tutorial_3.DeviceProtocol.*; /* //#full-device import static com.lightbend.akka.sample.DeviceProtocol.*; //#full-device */ -//#full-device +// #full-device public class Device extends AbstractBehavior { @@ -47,10 +47,10 @@ public class Device extends AbstractBehavior { @Override public Receive createReceive() { return receiveBuilder() - .onMessage(RecordTemperature.class, this::recordTemperature) - .onMessage(ReadTemperature.class, this::readTemperature) - .onSignal(PostStop.class, signal -> postStop()) - .build(); + .onMessage(RecordTemperature.class, this::recordTemperature) + .onMessage(ReadTemperature.class, this::readTemperature) + .onSignal(PostStop.class, signal -> postStop()) + .build(); } private Behavior recordTemperature(RecordTemperature r) { @@ -70,4 +70,4 @@ public class Device extends AbstractBehavior { return Behaviors.stopped(); } } -//#full-device +// #full-device diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_3/DeviceProtocol.java b/akka-docs/src/test/java/jdocs/typed/tutorial_3/DeviceProtocol.java index 587dfe65ed..88cf230f76 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_3/DeviceProtocol.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_3/DeviceProtocol.java @@ -14,13 +14,13 @@ abstract class DeviceProtocol { interface DeviceMessage {} - //#write-protocol + // #write-protocol public static final class RecordTemperature implements DeviceMessage { final long requestId; final double value; final ActorRef replyTo; - public RecordTemperature(long requestId, double value, ActorRef replyTo){ + public RecordTemperature(long requestId, double value, ActorRef replyTo) { this.requestId = requestId; this.value = value; this.replyTo = replyTo; @@ -34,7 +34,7 @@ abstract class DeviceProtocol { this.requestId = requestId; } } - //#write-protocol + // #write-protocol public static final class ReadTemperature implements DeviceMessage { final long requestId; @@ -55,5 +55,4 @@ abstract class DeviceProtocol { this.value = value; } } - } diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_3/DeviceTest.java b/akka-docs/src/test/java/jdocs/typed/tutorial_3/DeviceTest.java index b7659f7f6f..ce5d837c9f 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_3/DeviceTest.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_3/DeviceTest.java @@ -4,7 +4,7 @@ package jdocs.typed.tutorial_3; -//#device-read-test +// #device-read-test import akka.actor.testkit.typed.javadsl.TestKitJunitResource; import akka.actor.testkit.typed.javadsl.TestProbe; import akka.actor.typed.ActorRef; @@ -14,7 +14,7 @@ import java.util.Optional; import static org.junit.Assert.assertEquals; -//#device-read-test +// #device-read-test import static jdocs.typed.tutorial_3.DeviceProtocol.*; /* //#device-read-test @@ -24,10 +24,9 @@ public class DeviceTest { //#device-read-test */ public class DeviceTest extends org.scalatest.junit.JUnitSuite { -//#device-read-test + // #device-read-test - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(); @Test public void testReplyWithEmptyReadingIfNoTemperatureIsKnown() { @@ -38,9 +37,9 @@ public class DeviceTest extends org.scalatest.junit.JUnitSuite { assertEquals(42L, response.requestId); assertEquals(Optional.empty(), response.value); } - //#device-read-test + // #device-read-test - //#device-write-read-test + // #device-write-read-test @Test public void testReplyWithLatestTemperatureReading() { TestProbe recordProbe = testKit.createTestProbe(TemperatureRecorded.class); @@ -63,8 +62,8 @@ public class DeviceTest extends org.scalatest.junit.JUnitSuite { assertEquals(4L, response2.requestId); assertEquals(Optional.of(55.0), response2.value); } - //#device-write-read-test + // #device-write-read-test - //#device-read-test + // #device-read-test } -//#device-read-test +// #device-read-test diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress1/DeviceProtocol.java b/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress1/DeviceProtocol.java index 844ab654c3..6edd6f4bc7 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress1/DeviceProtocol.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress1/DeviceProtocol.java @@ -8,11 +8,10 @@ import akka.actor.typed.ActorRef; import java.util.Optional; -//#read-protocol-1 +// #read-protocol-1 abstract class DeviceProtocol { // no instances of DeviceProtocol class - private DeviceProtocol() { - } + private DeviceProtocol() {} interface DeviceMessage {} @@ -31,7 +30,5 @@ abstract class DeviceProtocol { this.value = value; } } - } -//#read-protocol-1 - +// #read-protocol-1 diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress2/Device.java b/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress2/Device.java index a2575e90f5..f4a8631322 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress2/Device.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress2/Device.java @@ -4,7 +4,7 @@ package jdocs.typed.tutorial_3.inprogress2; -//#device-with-read +// #device-with-read import akka.actor.typed.Behavior; import akka.actor.typed.PostStop; @@ -15,14 +15,14 @@ import akka.actor.typed.javadsl.Receive; import java.util.Optional; -//#device-with-read +// #device-with-read import static jdocs.typed.tutorial_3.inprogress2.DeviceProtocol.*; /* //#device-with-read import static com.lightbend.akka.sample.DeviceProtocol.*; //#device-with-read */ -//#device-with-read +// #device-with-read public class Device extends AbstractBehavior { @@ -47,9 +47,9 @@ public class Device extends AbstractBehavior { @Override public Receive createReceive() { return receiveBuilder() - .onMessage(ReadTemperature.class, this::readTemperature) - .onSignal(PostStop.class, signal -> postStop()) - .build(); + .onMessage(ReadTemperature.class, this::readTemperature) + .onSignal(PostStop.class, signal -> postStop()) + .build(); } private Behavior readTemperature(ReadTemperature r) { @@ -61,7 +61,6 @@ public class Device extends AbstractBehavior { context.getLog().info("Device actor {}-{} stopped", groupId, deviceId); return this; } - } -//#device-with-read +// #device-with-read diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress2/DeviceProtocol.java b/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress2/DeviceProtocol.java index 485ab4a489..483ecc0428 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress2/DeviceProtocol.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress2/DeviceProtocol.java @@ -8,11 +8,10 @@ import akka.actor.typed.ActorRef; import java.util.Optional; -//#read-protocol-2 +// #read-protocol-2 abstract class DeviceProtocol { // no instances of DeviceProtocol class - private DeviceProtocol() { - } + private DeviceProtocol() {} interface DeviceMessage {} @@ -35,7 +34,5 @@ abstract class DeviceProtocol { this.value = value; } } - } -//#read-protocol-2 - +// #read-protocol-2 diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress3/DeviceProtocol.java b/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress3/DeviceProtocol.java index e9772a1c50..1dd2dffbc0 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress3/DeviceProtocol.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_3/inprogress3/DeviceProtocol.java @@ -10,12 +10,11 @@ import java.util.Optional; abstract class DeviceProtocol { // no instances of DeviceProtocol class - private DeviceProtocol() { - } + private DeviceProtocol() {} interface DeviceMessage {} - //#write-protocol-1 + // #write-protocol-1 public static final class RecordTemperature implements DeviceMessage { final double value; @@ -23,6 +22,5 @@ abstract class DeviceProtocol { this.value = value; } } - //#write-protocol-1 + // #write-protocol-1 } - diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_4/Device.java b/akka-docs/src/test/java/jdocs/typed/tutorial_4/Device.java index 526a5f11ea..6f78531a7c 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_4/Device.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_4/Device.java @@ -4,7 +4,7 @@ package jdocs.typed.tutorial_4; -//#device-with-passivate +// #device-with-passivate import java.util.Optional; @@ -15,14 +15,14 @@ import akka.actor.typed.javadsl.ActorContext; import akka.actor.typed.javadsl.Behaviors; import akka.actor.typed.javadsl.Receive; -//#device-with-passivate +// #device-with-passivate import static jdocs.typed.tutorial_4.DeviceProtocol.*; /* //#device-with-passivate import static com.lightbend.akka.sample.DeviceProtocol.*; //#device-with-passivate */ -//#device-with-passivate +// #device-with-passivate public class Device extends AbstractBehavior { @@ -47,11 +47,11 @@ public class Device extends AbstractBehavior { @Override public Receive createReceive() { return receiveBuilder() - .onMessage(RecordTemperature.class, this::recordTemperature) - .onMessage(ReadTemperature.class, this::readTemperature) - .onMessage(Passivate.class, m -> Behaviors.stopped()) - .onSignal(PostStop.class, signal -> postStop()) - .build(); + .onMessage(RecordTemperature.class, this::recordTemperature) + .onMessage(ReadTemperature.class, this::readTemperature) + .onMessage(Passivate.class, m -> Behaviors.stopped()) + .onSignal(PostStop.class, signal -> postStop()) + .build(); } private Behavior recordTemperature(RecordTemperature r) { @@ -71,4 +71,4 @@ public class Device extends AbstractBehavior { return Behaviors.stopped(); } } -//#device-with-passivate +// #device-with-passivate diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceGroup.java b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceGroup.java index 0ccb29183e..d90b7768df 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceGroup.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceGroup.java @@ -18,28 +18,29 @@ import java.util.Map; import static jdocs.typed.tutorial_4.DeviceManagerProtocol.*; import static jdocs.typed.tutorial_4.DeviceProtocol.DeviceMessage; -//#device-group-full -//#device-group-remove -//#device-group-register +// #device-group-full +// #device-group-remove +// #device-group-register public class DeviceGroup extends AbstractBehavior { public static Behavior createBehavior(String groupId) { return Behaviors.setup(context -> new DeviceGroup(context, groupId)); } - //#device-terminated - private class DeviceTerminated implements DeviceGroupMessage{ + // #device-terminated + private class DeviceTerminated implements DeviceGroupMessage { public final ActorRef device; public final String groupId; public final String deviceId; - DeviceTerminated(ActorRef device, String groupId, String deviceId) { + DeviceTerminated( + ActorRef device, String groupId, String deviceId) { this.device = device; this.groupId = groupId; this.deviceId = deviceId; } } - //#device-terminated + // #device-terminated private final ActorContext context; private final String groupId; @@ -58,49 +59,54 @@ public class DeviceGroup extends AbstractBehavior { trackMsg.replyTo.tell(new DeviceRegistered(deviceActor)); } else { context.getLog().info("Creating device actor for {}", trackMsg.deviceId); - deviceActor = context.spawn(Device.createBehavior(groupId, trackMsg.deviceId), "device-" + trackMsg.deviceId); - //#device-group-register - context.watchWith(deviceActor, new DeviceTerminated(deviceActor, groupId, trackMsg.deviceId)); - //#device-group-register + deviceActor = + context.spawn( + Device.createBehavior(groupId, trackMsg.deviceId), "device-" + trackMsg.deviceId); + // #device-group-register + context.watchWith( + deviceActor, new DeviceTerminated(deviceActor, groupId, trackMsg.deviceId)); + // #device-group-register deviceIdToActor.put(trackMsg.deviceId, deviceActor); trackMsg.replyTo.tell(new DeviceRegistered(deviceActor)); } } else { - context.getLog().warning( + context + .getLog() + .warning( "Ignoring TrackDevice request for {}. This actor is responsible for {}.", - groupId, this.groupId - ); + groupId, + this.groupId); } return this; } - //#device-group-register - //#device-group-remove + // #device-group-register + // #device-group-remove private DeviceGroup onDeviceList(RequestDeviceList r) { r.replyTo.tell(new ReplyDeviceList(r.requestId, deviceIdToActor.keySet())); return this; } - //#device-group-remove + // #device-group-remove private DeviceGroup onTerminated(DeviceTerminated t) { context.getLog().info("Device actor for {} has been terminated", t.deviceId); deviceIdToActor.remove(t.deviceId); return this; } - //#device-group-register + // #device-group-register @Override public Receive createReceive() { return receiveBuilder() .onMessage(RequestTrackDevice.class, this::onTrackDevice) - //#device-group-register - //#device-group-remove + // #device-group-register + // #device-group-remove .onMessage(RequestDeviceList.class, r -> r.groupId.equals(groupId), this::onDeviceList) - //#device-group-remove + // #device-group-remove .onMessage(DeviceTerminated.class, this::onTerminated) .onSignal(PostStop.class, signal -> postStop()) - //#device-group-register + // #device-group-register .build(); } @@ -109,6 +115,6 @@ public class DeviceGroup extends AbstractBehavior { return this; } } -//#device-group-register -//#device-group-remove -//#device-group-full +// #device-group-register +// #device-group-remove +// #device-group-full diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceGroupTest.java b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceGroupTest.java index 98ca1efe2e..f3a5e2f206 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceGroupTest.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceGroupTest.java @@ -21,10 +21,9 @@ import static jdocs.typed.tutorial_4.DeviceProtocol.*; public class DeviceGroupTest extends JUnitSuite { - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(); - //#device-group-test-registration + // #device-group-test-registration @Test public void testReplyToRegistrationRequests() { TestProbe probe = testKit.createTestProbe(DeviceRegistered.class); @@ -53,9 +52,9 @@ public class DeviceGroupTest extends JUnitSuite { groupActor.tell(new RequestTrackDevice("wrongGroup", "device1", probe.getRef())); probe.expectNoMessage(); } - //#device-group-test-registration + // #device-group-test-registration - //#device-group-test3 + // #device-group-test3 @Test public void testReturnSameActorForSameDeviceId() { TestProbe probe = testKit.createTestProbe(DeviceRegistered.class); @@ -69,9 +68,9 @@ public class DeviceGroupTest extends JUnitSuite { DeviceRegistered registered2 = probe.expectMessageClass(DeviceRegistered.class); assertEquals(registered1.device, registered2.device); } - //#device-group-test3 + // #device-group-test3 - //#device-group-list-terminate-test + // #device-group-list-terminate-test @Test public void testListActiveDevices() { TestProbe registeredProbe = testKit.createTestProbe(DeviceRegistered.class); @@ -116,14 +115,14 @@ public class DeviceGroupTest extends JUnitSuite { // using awaitAssert to retry because it might take longer for the groupActor // to see the Terminated, that order is undefined - registeredProbe.awaitAssert(() -> { - groupActor.tell(new RequestDeviceList(1L, "group", deviceListProbe.getRef())); - ReplyDeviceList r = - deviceListProbe.expectMessageClass(ReplyDeviceList.class); - assertEquals(1L, r.requestId); - assertEquals(Stream.of("device2").collect(Collectors.toSet()), r.ids); - return null; - }); + registeredProbe.awaitAssert( + () -> { + groupActor.tell(new RequestDeviceList(1L, "group", deviceListProbe.getRef())); + ReplyDeviceList r = deviceListProbe.expectMessageClass(ReplyDeviceList.class); + assertEquals(1L, r.requestId); + assertEquals(Stream.of("device2").collect(Collectors.toSet()), r.ids); + return null; + }); } - //#device-group-list-terminate-test + // #device-group-list-terminate-test } diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceManager.java b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceManager.java index 5828159734..de416e5ed8 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceManager.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceManager.java @@ -18,14 +18,14 @@ import java.util.Map; import static jdocs.typed.tutorial_4.DeviceManagerProtocol.*; -//#device-manager-full +// #device-manager-full public class DeviceManager extends AbstractBehavior { public static Behavior createBehavior() { return Behaviors.setup(DeviceManager::new); } - private static class DeviceGroupTerminated implements DeviceManagerMessage{ + private static class DeviceGroupTerminated implements DeviceManagerMessage { public final String groupId; DeviceGroupTerminated(String groupId) { @@ -49,7 +49,7 @@ public class DeviceManager extends AbstractBehavior { } else { context.getLog().info("Creating device group actor for {}", groupId); ActorRef groupActor = - context.spawn(DeviceGroup.createBehavior(groupId), "group-" + groupId); + context.spawn(DeviceGroup.createBehavior(groupId), "group-" + groupId); context.watchWith(groupActor, new DeviceGroupTerminated(groupId)); groupActor.tell(trackMsg); groupIdToActor.put(groupId, groupActor); @@ -86,6 +86,5 @@ public class DeviceManager extends AbstractBehavior { context.getLog().info("DeviceManager stopped"); return this; } - } -//#device-manager-full +// #device-manager-full diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceManagerProtocol.java b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceManagerProtocol.java index a75a3d4244..b9a0628dde 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceManagerProtocol.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceManagerProtocol.java @@ -8,7 +8,7 @@ import akka.actor.typed.ActorRef; import java.util.Set; -//#device-registration-msgs +// #device-registration-msgs abstract class DeviceManagerProtocol { // no instances of DeviceManagerProtocol class private DeviceManagerProtocol() {} @@ -36,9 +36,9 @@ abstract class DeviceManagerProtocol { this.device = device; } } - //#device-registration-msgs + // #device-registration-msgs - //#device-list-msgs + // #device-list-msgs public static final class RequestDeviceList implements DeviceManagerMessage, DeviceGroupMessage { final long requestId; final String groupId; @@ -60,8 +60,8 @@ abstract class DeviceManagerProtocol { this.ids = ids; } } - //#device-list-msgs + // #device-list-msgs - //#device-registration-msgs + // #device-registration-msgs } -//#device-registration-msgs +// #device-registration-msgs diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceManagerTest.java b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceManagerTest.java index fd82444708..b6b69aef47 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceManagerTest.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceManagerTest.java @@ -16,8 +16,7 @@ import static org.junit.Assert.assertNotEquals; public class DeviceManagerTest extends JUnitSuite { - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(); @Test public void testReplyToRegistrationRequests() { @@ -32,5 +31,4 @@ public class DeviceManagerTest extends JUnitSuite { DeviceRegistered registered2 = probe.expectMessageClass(DeviceRegistered.class); assertNotEquals(registered1.device, registered2.device); } - } diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceProtocol.java b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceProtocol.java index 6a6a16ad4c..e760c52d53 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceProtocol.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceProtocol.java @@ -20,7 +20,7 @@ abstract class DeviceProtocol { final double value; final ActorRef replyTo; - public RecordTemperature(long requestId, double value, ActorRef replyTo){ + public RecordTemperature(long requestId, double value, ActorRef replyTo) { this.requestId = requestId; this.value = value; this.replyTo = replyTo; @@ -55,10 +55,10 @@ abstract class DeviceProtocol { } } - //#passivate-msg + // #passivate-msg static enum Passivate implements DeviceMessage { INSTANCE } - //#passivate-msg + // #passivate-msg } diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceTest.java b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceTest.java index 576886e970..2a264baaf6 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceTest.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_4/DeviceTest.java @@ -18,10 +18,9 @@ import static jdocs.typed.tutorial_4.DeviceProtocol.*; public class DeviceTest extends JUnitSuite { - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(); - //#device-read-test + // #device-read-test @Test public void testReplyWithEmptyReadingIfNoTemperatureIsKnown() { TestProbe probe = testKit.createTestProbe(RespondTemperature.class); @@ -31,9 +30,9 @@ public class DeviceTest extends JUnitSuite { assertEquals(42L, response.requestId); assertEquals(Optional.empty(), response.value); } - //#device-read-test + // #device-read-test - //#device-write-read-test + // #device-write-read-test @Test public void testReplyWithLatestTemperatureReading() { TestProbe recordProbe = testKit.createTestProbe(TemperatureRecorded.class); @@ -56,6 +55,6 @@ public class DeviceTest extends JUnitSuite { assertEquals(4L, response2.requestId); assertEquals(Optional.of(55.0), response2.value); } - //#device-write-read-test + // #device-write-read-test } diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_5/Device.java b/akka-docs/src/test/java/jdocs/typed/tutorial_5/Device.java index 6b2235345b..76846d8e63 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_5/Device.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_5/Device.java @@ -38,11 +38,11 @@ public class Device extends AbstractBehavior { @Override public Receive createReceive() { return receiveBuilder() - .onMessage(RecordTemperature.class, this::recordTemperature) - .onMessage(ReadTemperature.class, this::readTemperature) - .onMessage(Passivate.class, m -> Behaviors.stopped()) - .onSignal(PostStop.class, signal -> postStop()) - .build(); + .onMessage(RecordTemperature.class, this::recordTemperature) + .onMessage(ReadTemperature.class, this::readTemperature) + .onMessage(Passivate.class, m -> Behaviors.stopped()) + .onSignal(PostStop.class, signal -> postStop()) + .build(); } private Behavior recordTemperature(RecordTemperature r) { diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroup.java b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroup.java index bd8c0b0009..047830a051 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroup.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroup.java @@ -19,19 +19,20 @@ import java.util.Map; import static jdocs.typed.tutorial_5.DeviceManagerProtocol.*; import static jdocs.typed.tutorial_5.DeviceProtocol.DeviceMessage; -//#query-added +// #query-added public class DeviceGroup extends AbstractBehavior { public static Behavior createBehavior(String groupId) { return Behaviors.setup(context -> new DeviceGroup(context, groupId)); } - private class DeviceTerminated implements DeviceGroupMessage{ + private class DeviceTerminated implements DeviceGroupMessage { public final ActorRef device; public final String groupId; public final String deviceId; - DeviceTerminated(ActorRef device, String groupId, String deviceId) { + DeviceTerminated( + ActorRef device, String groupId, String deviceId) { this.device = device; this.groupId = groupId; this.deviceId = deviceId; @@ -48,7 +49,7 @@ public class DeviceGroup extends AbstractBehavior { context.getLog().info("DeviceGroup {} started", groupId); } - //#query-added + // #query-added private DeviceGroup onTrackDevice(RequestTrackDevice trackMsg) { if (this.groupId.equals(trackMsg.groupId)) { ActorRef deviceActor = deviceIdToActor.get(trackMsg.deviceId); @@ -56,16 +57,21 @@ public class DeviceGroup extends AbstractBehavior { trackMsg.replyTo.tell(new DeviceRegistered(deviceActor)); } else { context.getLog().info("Creating device actor for {}", trackMsg.deviceId); - deviceActor = context.spawn(Device.createBehavior(groupId, trackMsg.deviceId), "device-" + trackMsg.deviceId); - context.watchWith(deviceActor, new DeviceTerminated(deviceActor, groupId, trackMsg.deviceId)); + deviceActor = + context.spawn( + Device.createBehavior(groupId, trackMsg.deviceId), "device-" + trackMsg.deviceId); + context.watchWith( + deviceActor, new DeviceTerminated(deviceActor, groupId, trackMsg.deviceId)); deviceIdToActor.put(trackMsg.deviceId, deviceActor); trackMsg.replyTo.tell(new DeviceRegistered(deviceActor)); } } else { - context.getLog().warning( + context + .getLog() + .warning( "Ignoring TrackDevice request for {}. This actor is responsible for {}.", - groupId, this.groupId - ); + groupId, + this.groupId); } return this; } @@ -86,17 +92,21 @@ public class DeviceGroup extends AbstractBehavior { return this; } - //#query-added + // #query-added private DeviceGroup onAllTemperatures(RequestAllTemperatures r) { - // since Java collections are mutable, we want to avoid sharing them between actors (since multiple Actors (threads) - // modifying the same mutable data-structure is not safe), and perform a defensive copy of the mutable map: + // since Java collections are mutable, we want to avoid sharing them between actors (since + // multiple Actors (threads) + // modifying the same mutable data-structure is not safe), and perform a defensive copy of the + // mutable map: // - // Feel free to use your favourite immutable data-structures library with Akka in Java applications! + // Feel free to use your favourite immutable data-structures library with Akka in Java + // applications! Map> deviceIdToActorCopy = new HashMap<>(this.deviceIdToActor); - context.spawnAnonymous(DeviceGroupQuery.createBehavior( - deviceIdToActorCopy, r.requestId, r.replyTo, Duration.ofSeconds(3))); + context.spawnAnonymous( + DeviceGroupQuery.createBehavior( + deviceIdToActorCopy, r.requestId, r.replyTo, Duration.ofSeconds(3))); return this; } @@ -104,15 +114,16 @@ public class DeviceGroup extends AbstractBehavior { @Override public Receive createReceive() { return receiveBuilder() - //#query-added - .onMessage(RequestTrackDevice.class, this::onTrackDevice) - .onMessage(RequestDeviceList.class, r -> r.groupId.equals(groupId), this::onDeviceList) - .onMessage(DeviceTerminated.class, this::onTerminated) - .onSignal(PostStop.class, signal -> postStop()) - //#query-added - // ... other cases omitted - .onMessage(RequestAllTemperatures.class, r -> r.groupId.equals(groupId), this::onAllTemperatures) - .build(); + // #query-added + .onMessage(RequestTrackDevice.class, this::onTrackDevice) + .onMessage(RequestDeviceList.class, r -> r.groupId.equals(groupId), this::onDeviceList) + .onMessage(DeviceTerminated.class, this::onTerminated) + .onSignal(PostStop.class, signal -> postStop()) + // #query-added + // ... other cases omitted + .onMessage( + RequestAllTemperatures.class, r -> r.groupId.equals(groupId), this::onAllTemperatures) + .build(); } } -//#query-added +// #query-added diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroupQuery.java b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroupQuery.java index 7002ae9ed9..56e2fed6e8 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroupQuery.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroupQuery.java @@ -20,19 +20,21 @@ import java.util.Set; import static jdocs.typed.tutorial_5.DeviceManagerProtocol.*; -//#query-full -//#query-outline +// #query-full +// #query-outline public class DeviceGroupQuery extends AbstractBehavior { public static Behavior createBehavior( - Map> deviceIdToActor, - long requestId, - ActorRef requester, - Duration timeout) { - return - Behaviors.setup(context -> - Behaviors.withTimers(timers -> new DeviceGroupQuery( - deviceIdToActor, requestId, requester, timeout, context, timers))); + Map> deviceIdToActor, + long requestId, + ActorRef requester, + Duration timeout) { + return Behaviors.setup( + context -> + Behaviors.withTimers( + timers -> + new DeviceGroupQuery( + deviceIdToActor, requestId, requester, timeout, context, timers))); } private static enum CollectionTimeout implements DeviceGroupQueryMessage { @@ -57,50 +59,55 @@ public class DeviceGroupQuery extends AbstractBehavior private final long requestId; private final ActorRef requester; - //#query-outline - //#query-state + // #query-outline + // #query-state private Map repliesSoFar = new HashMap<>(); private final Set stillWaiting; - //#query-state - //#query-outline + // #query-state + // #query-outline public DeviceGroupQuery( - Map> deviceIdToActor, - long requestId, - ActorRef requester, - Duration timeout, - ActorContext context, TimerScheduler timers) { + Map> deviceIdToActor, + long requestId, + ActorRef requester, + Duration timeout, + ActorContext context, + TimerScheduler timers) { this.requestId = requestId; this.requester = requester; timers.startSingleTimer(CollectionTimeout.class, CollectionTimeout.INSTANCE, timeout); ActorRef respondTemperatureAdapter = - context.messageAdapter(DeviceProtocol.RespondTemperature.class, WrappedRespondTemperature::new); + context.messageAdapter( + DeviceProtocol.RespondTemperature.class, WrappedRespondTemperature::new); - for (Map.Entry> entry : deviceIdToActor.entrySet()) { + for (Map.Entry> entry : + deviceIdToActor.entrySet()) { context.watchWith(entry.getValue(), new DeviceTerminated(entry.getKey())); entry.getValue().tell(new DeviceProtocol.ReadTemperature(0L, respondTemperatureAdapter)); } stillWaiting = new HashSet<>(deviceIdToActor.keySet()); } - //#query-outline - //#query-state + // #query-outline + // #query-state @Override public Receive createReceive() { return receiveBuilder() - .onMessage(WrappedRespondTemperature.class, this::onRespondTemperature) - .onMessage(DeviceTerminated.class, this::onDeviceTerminated) - .onMessage(CollectionTimeout.class, this::onCollectionTimeout) - .build(); + .onMessage(WrappedRespondTemperature.class, this::onRespondTemperature) + .onMessage(DeviceTerminated.class, this::onDeviceTerminated) + .onMessage(CollectionTimeout.class, this::onCollectionTimeout) + .build(); } private Behavior onRespondTemperature(WrappedRespondTemperature r) { - TemperatureReading reading = r.response.value - .map(v -> (TemperatureReading) new Temperature(v)) - .orElse(TemperatureNotAvailable.INSTANCE); + TemperatureReading reading = + r.response + .value + .map(v -> (TemperatureReading) new Temperature(v)) + .orElse(TemperatureNotAvailable.INSTANCE); String deviceId = r.response.deviceId; repliesSoFar.put(deviceId, reading); @@ -124,9 +131,9 @@ public class DeviceGroupQuery extends AbstractBehavior stillWaiting.clear(); return respondWhenAllCollected(); } - //#query-state + // #query-state - //#query-collect-reply + // #query-collect-reply private Behavior respondWhenAllCollected() { if (stillWaiting.isEmpty()) { requester.tell(new RespondAllTemperatures(requestId, repliesSoFar)); @@ -135,9 +142,9 @@ public class DeviceGroupQuery extends AbstractBehavior return this; } } - //#query-collect-reply - //#query-outline + // #query-collect-reply + // #query-outline } -//#query-outline -//#query-full +// #query-outline +// #query-full diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroupQueryTest.java b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroupQueryTest.java index 4a68f4c392..e254d855a5 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroupQueryTest.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroupQueryTest.java @@ -22,13 +22,13 @@ import static org.junit.Assert.assertEquals; public class DeviceGroupQueryTest extends JUnitSuite { - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(); - //#query-test-normal + // #query-test-normal @Test public void testReturnTemperatureValueForWorkingDevices() { - TestProbe requester = testKit.createTestProbe(RespondAllTemperatures.class); + TestProbe requester = + testKit.createTestProbe(RespondAllTemperatures.class); TestProbe device1 = testKit.createTestProbe(DeviceMessage.class); TestProbe device2 = testKit.createTestProbe(DeviceMessage.class); @@ -36,20 +36,21 @@ public class DeviceGroupQueryTest extends JUnitSuite { deviceIdToActor.put("device1", device1.getRef()); deviceIdToActor.put("device2", device2.getRef()); - ActorRef queryActor = testKit.spawn(DeviceGroupQuery.createBehavior( - deviceIdToActor, - 1L, - requester.getRef(), - Duration.ofSeconds(3))); + ActorRef queryActor = + testKit.spawn( + DeviceGroupQuery.createBehavior( + deviceIdToActor, 1L, requester.getRef(), Duration.ofSeconds(3))); device1.expectMessageClass(ReadTemperature.class); device2.expectMessageClass(ReadTemperature.class); - queryActor.tell(new DeviceGroupQuery.WrappedRespondTemperature( - new RespondTemperature(0L, "device1", Optional.of(1.0)))); + queryActor.tell( + new DeviceGroupQuery.WrappedRespondTemperature( + new RespondTemperature(0L, "device1", Optional.of(1.0)))); - queryActor.tell(new DeviceGroupQuery.WrappedRespondTemperature( - new RespondTemperature(0L, "device2", Optional.of(2.0)))); + queryActor.tell( + new DeviceGroupQuery.WrappedRespondTemperature( + new RespondTemperature(0L, "device2", Optional.of(2.0)))); RespondAllTemperatures response = requester.expectMessageClass(RespondAllTemperatures.class); assertEquals(1L, response.requestId); @@ -60,12 +61,13 @@ public class DeviceGroupQueryTest extends JUnitSuite { assertEquals(expectedTemperatures, response.temperatures); } - //#query-test-normal + // #query-test-normal - //#query-test-no-reading + // #query-test-no-reading @Test public void testReturnTemperatureNotAvailableForDevicesWithNoReadings() { - TestProbe requester = testKit.createTestProbe(RespondAllTemperatures.class); + TestProbe requester = + testKit.createTestProbe(RespondAllTemperatures.class); TestProbe device1 = testKit.createTestProbe(DeviceMessage.class); TestProbe device2 = testKit.createTestProbe(DeviceMessage.class); @@ -73,20 +75,21 @@ public class DeviceGroupQueryTest extends JUnitSuite { deviceIdToActor.put("device1", device1.getRef()); deviceIdToActor.put("device2", device2.getRef()); - ActorRef queryActor = testKit.spawn(DeviceGroupQuery.createBehavior( - deviceIdToActor, - 1L, - requester.getRef(), - Duration.ofSeconds(3))); + ActorRef queryActor = + testKit.spawn( + DeviceGroupQuery.createBehavior( + deviceIdToActor, 1L, requester.getRef(), Duration.ofSeconds(3))); assertEquals(0L, device1.expectMessageClass(ReadTemperature.class).requestId); assertEquals(0L, device2.expectMessageClass(ReadTemperature.class).requestId); - queryActor.tell(new DeviceGroupQuery.WrappedRespondTemperature( - new RespondTemperature(0L, "device1", Optional.empty()))); + queryActor.tell( + new DeviceGroupQuery.WrappedRespondTemperature( + new RespondTemperature(0L, "device1", Optional.empty()))); - queryActor.tell(new DeviceGroupQuery.WrappedRespondTemperature( - new RespondTemperature(0L, "device2", Optional.of(2.0)))); + queryActor.tell( + new DeviceGroupQuery.WrappedRespondTemperature( + new RespondTemperature(0L, "device2", Optional.of(2.0)))); RespondAllTemperatures response = requester.expectMessageClass(RespondAllTemperatures.class); assertEquals(1L, response.requestId); @@ -97,12 +100,13 @@ public class DeviceGroupQueryTest extends JUnitSuite { assertEquals(expectedTemperatures, response.temperatures); } - //#query-test-no-reading + // #query-test-no-reading - //#query-test-stopped + // #query-test-stopped @Test public void testReturnDeviceNotAvailableIfDeviceStopsBeforeAnswering() { - TestProbe requester = testKit.createTestProbe(RespondAllTemperatures.class); + TestProbe requester = + testKit.createTestProbe(RespondAllTemperatures.class); TestProbe device1 = testKit.createTestProbe(DeviceMessage.class); TestProbe device2 = testKit.createTestProbe(DeviceMessage.class); @@ -110,17 +114,17 @@ public class DeviceGroupQueryTest extends JUnitSuite { deviceIdToActor.put("device1", device1.getRef()); deviceIdToActor.put("device2", device2.getRef()); - ActorRef queryActor = testKit.spawn(DeviceGroupQuery.createBehavior( - deviceIdToActor, - 1L, - requester.getRef(), - Duration.ofSeconds(3))); + ActorRef queryActor = + testKit.spawn( + DeviceGroupQuery.createBehavior( + deviceIdToActor, 1L, requester.getRef(), Duration.ofSeconds(3))); assertEquals(0L, device1.expectMessageClass(ReadTemperature.class).requestId); assertEquals(0L, device2.expectMessageClass(ReadTemperature.class).requestId); - queryActor.tell(new DeviceGroupQuery.WrappedRespondTemperature( - new RespondTemperature(0L, "device1", Optional.of(1.0)))); + queryActor.tell( + new DeviceGroupQuery.WrappedRespondTemperature( + new RespondTemperature(0L, "device1", Optional.of(1.0)))); device2.stop(); @@ -133,12 +137,13 @@ public class DeviceGroupQueryTest extends JUnitSuite { assertEquals(expectedTemperatures, response.temperatures); } - //#query-test-stopped + // #query-test-stopped - //#query-test-stopped-later + // #query-test-stopped-later @Test public void testReturnTemperatureReadingEvenIfDeviceStopsAfterAnswering() { - TestProbe requester = testKit.createTestProbe(RespondAllTemperatures.class); + TestProbe requester = + testKit.createTestProbe(RespondAllTemperatures.class); TestProbe device1 = testKit.createTestProbe(DeviceMessage.class); TestProbe device2 = testKit.createTestProbe(DeviceMessage.class); @@ -146,20 +151,21 @@ public class DeviceGroupQueryTest extends JUnitSuite { deviceIdToActor.put("device1", device1.getRef()); deviceIdToActor.put("device2", device2.getRef()); - ActorRef queryActor = testKit.spawn(DeviceGroupQuery.createBehavior( - deviceIdToActor, - 1L, - requester.getRef(), - Duration.ofSeconds(3))); + ActorRef queryActor = + testKit.spawn( + DeviceGroupQuery.createBehavior( + deviceIdToActor, 1L, requester.getRef(), Duration.ofSeconds(3))); assertEquals(0L, device1.expectMessageClass(ReadTemperature.class).requestId); assertEquals(0L, device2.expectMessageClass(ReadTemperature.class).requestId); - queryActor.tell(new DeviceGroupQuery.WrappedRespondTemperature( - new RespondTemperature(0L, "device1", Optional.of(1.0)))); + queryActor.tell( + new DeviceGroupQuery.WrappedRespondTemperature( + new RespondTemperature(0L, "device1", Optional.of(1.0)))); - queryActor.tell(new DeviceGroupQuery.WrappedRespondTemperature( - new RespondTemperature(0L, "device2", Optional.of(2.0)))); + queryActor.tell( + new DeviceGroupQuery.WrappedRespondTemperature( + new RespondTemperature(0L, "device2", Optional.of(2.0)))); device2.stop(); @@ -172,12 +178,13 @@ public class DeviceGroupQueryTest extends JUnitSuite { assertEquals(expectedTemperatures, response.temperatures); } - //#query-test-stopped-later + // #query-test-stopped-later - //#query-test-timeout + // #query-test-timeout @Test public void testReturnDeviceTimedOutIfDeviceDoesNotAnswerInTime() { - TestProbe requester = testKit.createTestProbe(RespondAllTemperatures.class); + TestProbe requester = + testKit.createTestProbe(RespondAllTemperatures.class); TestProbe device1 = testKit.createTestProbe(DeviceMessage.class); TestProbe device2 = testKit.createTestProbe(DeviceMessage.class); @@ -185,17 +192,17 @@ public class DeviceGroupQueryTest extends JUnitSuite { deviceIdToActor.put("device1", device1.getRef()); deviceIdToActor.put("device2", device2.getRef()); - ActorRef queryActor = testKit.spawn(DeviceGroupQuery.createBehavior( - deviceIdToActor, - 1L, - requester.getRef(), - Duration.ofMillis(200))); + ActorRef queryActor = + testKit.spawn( + DeviceGroupQuery.createBehavior( + deviceIdToActor, 1L, requester.getRef(), Duration.ofMillis(200))); assertEquals(0L, device1.expectMessageClass(ReadTemperature.class).requestId); assertEquals(0L, device2.expectMessageClass(ReadTemperature.class).requestId); - queryActor.tell(new DeviceGroupQuery.WrappedRespondTemperature( - new RespondTemperature(0L, "device1", Optional.of(1.0)))); + queryActor.tell( + new DeviceGroupQuery.WrappedRespondTemperature( + new RespondTemperature(0L, "device1", Optional.of(1.0)))); // no reply from device2 @@ -208,5 +215,5 @@ public class DeviceGroupQueryTest extends JUnitSuite { assertEquals(expectedTemperatures, response.temperatures); } - //#query-test-timeout + // #query-test-timeout } diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroupTest.java b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroupTest.java index 3beaa6f412..9be8964a4d 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroupTest.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceGroupTest.java @@ -23,8 +23,7 @@ import static org.junit.Assert.assertNotEquals; public class DeviceGroupTest extends JUnitSuite { - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(); @Test public void testReplyToRegistrationRequests() { @@ -113,30 +112,33 @@ public class DeviceGroupTest extends JUnitSuite { // using awaitAssert to retry because it might take longer for the groupActor // to see the Terminated, that order is undefined - registeredProbe.awaitAssert(() -> { - groupActor.tell(new RequestDeviceList(1L, "group", deviceListProbe.getRef())); - ReplyDeviceList r = - deviceListProbe.expectMessageClass(ReplyDeviceList.class); - assertEquals(1L, r.requestId); - assertEquals(Stream.of("device2").collect(Collectors.toSet()), r.ids); - return null; - }); + registeredProbe.awaitAssert( + () -> { + groupActor.tell(new RequestDeviceList(1L, "group", deviceListProbe.getRef())); + ReplyDeviceList r = deviceListProbe.expectMessageClass(ReplyDeviceList.class); + assertEquals(1L, r.requestId); + assertEquals(Stream.of("device2").collect(Collectors.toSet()), r.ids); + return null; + }); } - //#group-query-integration-test + // #group-query-integration-test @Test public void testCollectTemperaturesFromAllActiveDevices() { TestProbe registeredProbe = testKit.createTestProbe(DeviceRegistered.class); ActorRef groupActor = testKit.spawn(DeviceGroup.createBehavior("group")); groupActor.tell(new RequestTrackDevice("group", "device1", registeredProbe.getRef())); - ActorRef deviceActor1 = registeredProbe.expectMessageClass(DeviceRegistered.class).device; + ActorRef deviceActor1 = + registeredProbe.expectMessageClass(DeviceRegistered.class).device; groupActor.tell(new RequestTrackDevice("group", "device2", registeredProbe.getRef())); - ActorRef deviceActor2 = registeredProbe.expectMessageClass(DeviceRegistered.class).device; + ActorRef deviceActor2 = + registeredProbe.expectMessageClass(DeviceRegistered.class).device; groupActor.tell(new RequestTrackDevice("group", "device3", registeredProbe.getRef())); - ActorRef deviceActor3 = registeredProbe.expectMessageClass(DeviceRegistered.class).device; + ActorRef deviceActor3 = + registeredProbe.expectMessageClass(DeviceRegistered.class).device; // Check that the device actors are working TestProbe recordProbe = testKit.createTestProbe(TemperatureRecorded.class); @@ -146,7 +148,8 @@ public class DeviceGroupTest extends JUnitSuite { assertEquals(1L, recordProbe.expectMessageClass(TemperatureRecorded.class).requestId); // No temperature for device 3 - TestProbe allTempProbe = testKit.createTestProbe(RespondAllTemperatures.class); + TestProbe allTempProbe = + testKit.createTestProbe(RespondAllTemperatures.class); groupActor.tell(new RequestAllTemperatures(0L, "group", allTempProbe.getRef())); RespondAllTemperatures response = allTempProbe.expectMessageClass(RespondAllTemperatures.class); assertEquals(0L, response.requestId); @@ -158,5 +161,5 @@ public class DeviceGroupTest extends JUnitSuite { assertEquals(expectedTemperatures, response.temperatures); } - //#group-query-integration-test + // #group-query-integration-test } diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceManager.java b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceManager.java index 6d10c9898d..a49765835c 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceManager.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceManager.java @@ -24,7 +24,7 @@ public class DeviceManager extends AbstractBehavior { return Behaviors.setup(DeviceManager::new); } - private static class DeviceGroupTerminated implements DeviceManagerMessage{ + private static class DeviceGroupTerminated implements DeviceManagerMessage { public final String groupId; DeviceGroupTerminated(String groupId) { @@ -48,7 +48,7 @@ public class DeviceManager extends AbstractBehavior { } else { context.getLog().info("Creating device group actor for {}", groupId); ActorRef groupActor = - context.spawn(DeviceGroup.createBehavior(groupId), "group-" + groupId); + context.spawn(DeviceGroup.createBehavior(groupId), "group-" + groupId); context.watchWith(groupActor, new DeviceGroupTerminated(groupId)); groupActor.tell(trackMsg); groupIdToActor.put(groupId, groupActor); @@ -96,5 +96,4 @@ public class DeviceManager extends AbstractBehavior { context.getLog().info("DeviceManager stopped"); return this; } - } diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceManagerProtocol.java b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceManagerProtocol.java index 6070a023b9..f337e33e84 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceManagerProtocol.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceManagerProtocol.java @@ -59,17 +59,18 @@ abstract class DeviceManagerProtocol { } } - //#query-protocol + // #query-protocol interface DeviceGroupQueryMessage {} public static final class RequestAllTemperatures - implements DeviceGroupQueryMessage, DeviceGroupMessage, DeviceManagerMessage { + implements DeviceGroupQueryMessage, DeviceGroupMessage, DeviceManagerMessage { final long requestId; final String groupId; final ActorRef replyTo; - public RequestAllTemperatures(long requestId, String groupId, ActorRef replyTo) { + public RequestAllTemperatures( + long requestId, String groupId, ActorRef replyTo) { this.requestId = requestId; this.groupId = groupId; this.replyTo = replyTo; @@ -86,8 +87,7 @@ abstract class DeviceManagerProtocol { } } - public static interface TemperatureReading { - } + public static interface TemperatureReading {} public static final class Temperature implements TemperatureReading { public final double value; @@ -114,9 +114,7 @@ abstract class DeviceManagerProtocol { @Override public String toString() { - return "Temperature{" + - "value=" + value + - '}'; + return "Temperature{" + "value=" + value + '}'; } } @@ -131,6 +129,6 @@ abstract class DeviceManagerProtocol { public enum DeviceTimedOut implements TemperatureReading { INSTANCE } - //#query-protocol + // #query-protocol } diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceManagerTest.java b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceManagerTest.java index f6cd14da8e..132ca562f8 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceManagerTest.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceManagerTest.java @@ -16,8 +16,7 @@ import static org.junit.Assert.assertNotEquals; public class DeviceManagerTest extends JUnitSuite { - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(); @Test public void testReplyToRegistrationRequests() { @@ -32,5 +31,4 @@ public class DeviceManagerTest extends JUnitSuite { DeviceRegistered registered2 = probe.expectMessageClass(DeviceRegistered.class); assertNotEquals(registered1.device, registered2.device); } - } diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceProtocol.java b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceProtocol.java index f58995fa7c..b007008544 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceProtocol.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceProtocol.java @@ -19,7 +19,7 @@ abstract class DeviceProtocol { final double value; final ActorRef replyTo; - public RecordTemperature(long requestId, double value, ActorRef replyTo){ + public RecordTemperature(long requestId, double value, ActorRef replyTo) { this.requestId = requestId; this.value = value; this.replyTo = replyTo; @@ -59,5 +59,4 @@ abstract class DeviceProtocol { static enum Passivate implements DeviceMessage { INSTANCE } - } diff --git a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceTest.java b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceTest.java index ace69989fa..bda8280ce9 100644 --- a/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceTest.java +++ b/akka-docs/src/test/java/jdocs/typed/tutorial_5/DeviceTest.java @@ -20,8 +20,7 @@ import static org.junit.Assert.assertNotEquals; public class DeviceTest extends JUnitSuite { - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(); @Test public void testReplyWithEmptyReadingIfNoTemperatureIsKnown() { @@ -55,5 +54,4 @@ public class DeviceTest extends JUnitSuite { assertEquals(4L, response2.requestId); assertEquals(Optional.of(55.0), response2.value); } - } diff --git a/akka-persistence-query/src/test/java/akka/persistence/query/DummyJavaReadJournal.java b/akka-persistence-query/src/test/java/akka/persistence/query/DummyJavaReadJournal.java index cf720f3268..8353dda626 100644 --- a/akka-persistence-query/src/test/java/akka/persistence/query/DummyJavaReadJournal.java +++ b/akka-persistence-query/src/test/java/akka/persistence/query/DummyJavaReadJournal.java @@ -11,24 +11,26 @@ import akka.persistence.query.javadsl.PersistenceIdsQuery; import akka.persistence.query.javadsl.ReadJournal; import akka.stream.javadsl.Source; -/** - * Use for tests only! - * Emits infinite stream of strings (representing queried for events). - */ +/** Use for tests only! Emits infinite stream of strings (representing queried for events). */ public class DummyJavaReadJournal implements ReadJournal, PersistenceIdsQuery { public static final String Identifier = "akka.persistence.query.journal.dummy-java"; - @Override public Source persistenceIds() { - return Source.fromIterator(() -> new Iterator() { - private int i = 0; - @Override public boolean hasNext() { return true; } + return Source.fromIterator( + () -> + new Iterator() { + private int i = 0; - @Override public String next() { - return "" + (i++); - } - }); + @Override + public boolean hasNext() { + return true; + } + + @Override + public String next() { + return "" + (i++); + } + }); } } - diff --git a/akka-persistence-query/src/test/java/akka/persistence/query/DummyJavaReadJournalForScala.java b/akka-persistence-query/src/test/java/akka/persistence/query/DummyJavaReadJournalForScala.java index cd7cc5c064..4da3a71295 100644 --- a/akka-persistence-query/src/test/java/akka/persistence/query/DummyJavaReadJournalForScala.java +++ b/akka-persistence-query/src/test/java/akka/persistence/query/DummyJavaReadJournalForScala.java @@ -6,12 +6,10 @@ package akka.persistence.query; import akka.NotUsed; -/** - * Use for tests only! - * Emits infinite stream of strings (representing queried for events). - */ -public class DummyJavaReadJournalForScala implements akka.persistence.query.scaladsl.ReadJournal, - akka.persistence.query.scaladsl.PersistenceIdsQuery { +/** Use for tests only! Emits infinite stream of strings (representing queried for events). */ +public class DummyJavaReadJournalForScala + implements akka.persistence.query.scaladsl.ReadJournal, + akka.persistence.query.scaladsl.PersistenceIdsQuery { public static final String Identifier = DummyJavaReadJournal.Identifier; @@ -25,5 +23,4 @@ public class DummyJavaReadJournalForScala implements akka.persistence.query.scal public akka.stream.scaladsl.Source persistenceIds() { return readJournal.persistenceIds().asScala(); } - } diff --git a/akka-persistence-query/src/test/java/akka/persistence/query/DummyJavaReadJournalProvider.java b/akka-persistence-query/src/test/java/akka/persistence/query/DummyJavaReadJournalProvider.java index 946d220f39..4291df0cd2 100644 --- a/akka-persistence-query/src/test/java/akka/persistence/query/DummyJavaReadJournalProvider.java +++ b/akka-persistence-query/src/test/java/akka/persistence/query/DummyJavaReadJournalProvider.java @@ -9,9 +9,14 @@ import com.typesafe.config.ConfigFactory; public class DummyJavaReadJournalProvider implements ReadJournalProvider { - public static final Config config = ConfigFactory.parseString(DummyJavaReadJournal.Identifier + " { \n" - + " class = \"" + DummyJavaReadJournalProvider.class.getCanonicalName() + "\" \n" - + " }\n\n"); + public static final Config config = + ConfigFactory.parseString( + DummyJavaReadJournal.Identifier + + " { \n" + + " class = \"" + + DummyJavaReadJournalProvider.class.getCanonicalName() + + "\" \n" + + " }\n\n"); private final DummyJavaReadJournal readJournal = new DummyJavaReadJournal(); @@ -24,5 +29,4 @@ public class DummyJavaReadJournalProvider implements ReadJournalProvider { public DummyJavaReadJournal javadslReadJournal() { return readJournal; } - } diff --git a/akka-persistence-query/src/test/java/akka/persistence/query/PersistenceQueryTest.java b/akka-persistence-query/src/test/java/akka/persistence/query/PersistenceQueryTest.java index 59c21b5b9c..b933936e9f 100644 --- a/akka-persistence-query/src/test/java/akka/persistence/query/PersistenceQueryTest.java +++ b/akka-persistence-query/src/test/java/akka/persistence/query/PersistenceQueryTest.java @@ -10,20 +10,19 @@ import akka.testkit.AkkaJUnitActorSystemResource; import com.typesafe.config.ConfigFactory; import org.junit.ClassRule; - public class PersistenceQueryTest { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource(PersistenceQueryTest.class.getName()); + new AkkaJUnitActorSystemResource(PersistenceQueryTest.class.getName()); private final ActorSystem system = actorSystemResource.getSystem(); // compile-only test @SuppressWarnings("unused") public void shouldExposeJavaDSLFriendlyQueryJournal() throws Exception { - final DummyJavaReadJournal readJournal = PersistenceQuery.get(system).getReadJournalFor(DummyJavaReadJournal.class, - "noop-journal"); + final DummyJavaReadJournal readJournal = + PersistenceQuery.get(system).getReadJournalFor(DummyJavaReadJournal.class, "noop-journal"); final akka.stream.javadsl.Source ids = readJournal.persistenceIds(); } } diff --git a/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/EventSourcedActorFailureTest.java b/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/EventSourcedActorFailureTest.java index b654400a26..60f56cec94 100644 --- a/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/EventSourcedActorFailureTest.java +++ b/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/EventSourcedActorFailureTest.java @@ -23,92 +23,99 @@ import static akka.persistence.typed.scaladsl.EventSourcedBehaviorFailureSpec.co class FailingEventSourcedActor extends EventSourcedBehavior { - private final ActorRef probe; - private final ActorRef recoveryFailureProbe; + private final ActorRef probe; + private final ActorRef recoveryFailureProbe; - FailingEventSourcedActor(PersistenceId persistenceId, ActorRef probe, ActorRef recoveryFailureProbe) { + FailingEventSourcedActor( + PersistenceId persistenceId, + ActorRef probe, + ActorRef recoveryFailureProbe) { - super(persistenceId, SupervisorStrategy.restartWithBackoff(Duration.ofMillis(1), Duration.ofMillis(5), 0.1)); - this.probe = probe; - this.recoveryFailureProbe = recoveryFailureProbe; - } + super( + persistenceId, + SupervisorStrategy.restartWithBackoff(Duration.ofMillis(1), Duration.ofMillis(5), 0.1)); + this.probe = probe; + this.recoveryFailureProbe = recoveryFailureProbe; + } - @Override - public void onRecoveryCompleted(String s) { - probe.tell("starting"); - } + @Override + public void onRecoveryCompleted(String s) { + probe.tell("starting"); + } - @Override - public void onRecoveryFailure(Throwable failure) { - recoveryFailureProbe.tell(failure); - } + @Override + public void onRecoveryFailure(Throwable failure) { + recoveryFailureProbe.tell(failure); + } - @Override - public String emptyState() { - return ""; - } + @Override + public String emptyState() { + return ""; + } - @Override - public CommandHandler commandHandler() { - return (state, command) -> { - probe.tell("persisting"); - return Effect().persist(command); - }; - } + @Override + public CommandHandler commandHandler() { + return (state, command) -> { + probe.tell("persisting"); + return Effect().persist(command); + }; + } - @Override - public EventHandler eventHandler() { - return (state, event) -> { - probe.tell(event); - return state + event; - }; - } + @Override + public EventHandler eventHandler() { + return (state, event) -> { + probe.tell(event); + return state + event; + }; + } } public class EventSourcedActorFailureTest extends JUnitSuite { - public static final Config config = conf().withFallback(ConfigFactory.load()); + public static final Config config = conf().withFallback(ConfigFactory.load()); - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(config); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(config); - public static Behavior fail(PersistenceId pid, ActorRef probe, ActorRef recoveryFailureProbe) { - return new FailingEventSourcedActor(pid, probe, recoveryFailureProbe); - } - public static Behavior fail(PersistenceId pid, ActorRef probe) { - return fail(pid, probe, testKit.createTestProbe().ref()); - } + public static Behavior fail( + PersistenceId pid, ActorRef probe, ActorRef recoveryFailureProbe) { + return new FailingEventSourcedActor(pid, probe, recoveryFailureProbe); + } - @Test - public void notifyRecoveryFailure() { - TestProbe probe = testKit.createTestProbe(); - TestProbe recoveryFailureProbe = testKit.createTestProbe(); - Behavior p1 = fail(new PersistenceId("fail-recovery-once"), probe.ref(), recoveryFailureProbe.ref()); - testKit.spawn(p1); - recoveryFailureProbe.expectMessageClass(TE.class); - } + public static Behavior fail(PersistenceId pid, ActorRef probe) { + return fail(pid, probe, testKit.createTestProbe().ref()); + } - @Test - public void persistEvents() throws Exception { - TestProbe probe = testKit.createTestProbe(); - Behavior p1 = fail(new PersistenceId("fail-first-2"), probe.ref()); - ActorRef c = testKit.spawn(p1); - probe.expectMessage("starting"); - // fail - c.tell("one"); - probe.expectMessage("persisting"); - probe.expectMessage("one"); - probe.expectMessage("starting"); - // fail - c.tell("two"); - probe.expectMessage("persisting"); - probe.expectMessage("two"); - probe.expectMessage("starting"); - // work - c.tell("three"); - probe.expectMessage("persisting"); - probe.expectMessage("three"); - // no starting as this one did not fail - probe.expectNoMessage(); - } + @Test + public void notifyRecoveryFailure() { + TestProbe probe = testKit.createTestProbe(); + TestProbe recoveryFailureProbe = testKit.createTestProbe(); + Behavior p1 = + fail(new PersistenceId("fail-recovery-once"), probe.ref(), recoveryFailureProbe.ref()); + testKit.spawn(p1); + recoveryFailureProbe.expectMessageClass(TE.class); + } + + @Test + public void persistEvents() throws Exception { + TestProbe probe = testKit.createTestProbe(); + Behavior p1 = fail(new PersistenceId("fail-first-2"), probe.ref()); + ActorRef c = testKit.spawn(p1); + probe.expectMessage("starting"); + // fail + c.tell("one"); + probe.expectMessage("persisting"); + probe.expectMessage("one"); + probe.expectMessage("starting"); + // fail + c.tell("two"); + probe.expectMessage("persisting"); + probe.expectMessage("two"); + probe.expectMessage("starting"); + // work + c.tell("three"); + probe.expectMessage("persisting"); + probe.expectMessage("three"); + // no starting as this one did not fail + probe.expectNoMessage(); + } } diff --git a/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/NullEmptyStateTest.java b/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/NullEmptyStateTest.java index 70cc84aff0..80bb5d1cb2 100644 --- a/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/NullEmptyStateTest.java +++ b/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/NullEmptyStateTest.java @@ -20,11 +20,11 @@ import java.util.Objects; public class NullEmptyStateTest extends JUnitSuite { - private static final Config config = ConfigFactory.parseString( - "akka.persistence.journal.plugin = \"akka.persistence.journal.inmem\" \n"); + private static final Config config = + ConfigFactory.parseString( + "akka.persistence.journal.plugin = \"akka.persistence.journal.inmem\" \n"); - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(config); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(config); static class NullEmptyState extends EventSourcedBehavior { @@ -48,14 +48,14 @@ public class NullEmptyStateTest extends JUnitSuite { @Override public CommandHandler commandHandler() { CommandHandlerBuilder b1 = - commandHandlerBuilder(Objects::isNull) - .matchCommand("stop"::equals, command -> Effect().stop()) - .matchCommand(String.class, this::persistCommand); + commandHandlerBuilder(Objects::isNull) + .matchCommand("stop"::equals, command -> Effect().stop()) + .matchCommand(String.class, this::persistCommand); CommandHandlerBuilder b2 = - commandHandlerBuilder(String.class) - .matchCommand("stop"::equals, command -> Effect().stop()) - .matchCommand(String.class, this::persistCommand); + commandHandlerBuilder(String.class) + .matchCommand("stop"::equals, command -> Effect().stop()) + .matchCommand(String.class, this::persistCommand); return b1.orElse(b2).build(); } @@ -66,24 +66,21 @@ public class NullEmptyStateTest extends JUnitSuite { @Override public EventHandler eventHandler() { - return eventHandlerBuilder() - .matchEvent(String.class, this::applyEvent) - .build(); + return eventHandlerBuilder().matchEvent(String.class, this::applyEvent).build(); } private String applyEvent(String state, String event) { probe.tell("eventHandler:" + state + ":" + event); - if (state == null) - return event; - else - return state + event; + if (state == null) return event; + else return state + event; } } @Test public void handleNullState() throws Exception { TestProbe probe = testKit.createTestProbe(); - Behavior b = Behaviors.setup(ctx -> new NullEmptyState(new PersistenceId("a"), probe.ref())); + Behavior b = + Behaviors.setup(ctx -> new NullEmptyState(new PersistenceId("a"), probe.ref())); ActorRef ref1 = testKit.spawn(b); probe.expectMessage("onRecoveryCompleted:null"); diff --git a/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/PersistentActorCompileOnlyTest.java b/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/PersistentActorCompileOnlyTest.java index b4eaf44fa4..25fead9d9b 100644 --- a/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/PersistentActorCompileOnlyTest.java +++ b/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/PersistentActorCompileOnlyTest.java @@ -22,33 +22,36 @@ import static akka.actor.typed.javadsl.AskPattern.ask; public class PersistentActorCompileOnlyTest { + public abstract static class Simple { - public static abstract class Simple { - - //#event-wrapper + // #event-wrapper public static class Wrapper { private final T t; + public Wrapper(T t) { this.t = t; } + public T getT() { return t; } } - public static class EventAdapterExample extends EventAdapter> { + public static class EventAdapterExample + extends EventAdapter> { @Override public Wrapper toJournal(SimpleEvent simpleEvent) { return new Wrapper<>(simpleEvent); } + @Override public SimpleEvent fromJournal(Wrapper simpleEventWrapper) { return simpleEventWrapper.getT(); } } - //#event-wrapper + // #event-wrapper - //#command + // #command public static class SimpleCommand { public final String data; @@ -56,9 +59,9 @@ public class PersistentActorCompileOnlyTest { this.data = data; } } - //#command + // #command - //#event + // #event static class SimpleEvent { private final String data; @@ -66,9 +69,9 @@ public class PersistentActorCompileOnlyTest { this.data = data; } } - //#event + // #event - //#state + // #state static class SimpleState { private final List events; @@ -80,56 +83,53 @@ public class PersistentActorCompileOnlyTest { this.events = new ArrayList<>(); } - SimpleState addEvent(SimpleEvent event) { List newEvents = new ArrayList<>(events); newEvents.add(event.data); return new SimpleState(newEvents); } } - //#state + // #state - - //#behavior + // #behavior public static EventSourcedBehavior pb = new EventSourcedBehavior(new PersistenceId("p1")) { - @Override - public SimpleState emptyState() { - return new SimpleState(); - } + @Override + public SimpleState emptyState() { + return new SimpleState(); + } - //#command-handler - @Override - public CommandHandler commandHandler() { - return (state, cmd) -> Effect().persist(new SimpleEvent(cmd.data)); - } - //#command-handler + // #command-handler + @Override + public CommandHandler commandHandler() { + return (state, cmd) -> Effect().persist(new SimpleEvent(cmd.data)); + } + // #command-handler - //#event-handler - @Override - public EventHandler eventHandler() { - return (state, event) -> state.addEvent(event); - } - //#event-handler + // #event-handler + @Override + public EventHandler eventHandler() { + return (state, event) -> state.addEvent(event); + } + // #event-handler - //#install-event-adapter - @Override - public EventAdapter> eventAdapter() { - return new EventAdapterExample(); - } - //#install-event-adapter - }; + // #install-event-adapter + @Override + public EventAdapter> eventAdapter() { + return new EventAdapterExample(); + } + // #install-event-adapter + }; - //#behavior + // #behavior } - static abstract class WithAck { - public static class Ack { - } + abstract static class WithAck { + public static class Ack {} + + interface MyCommand {} - interface MyCommand { - } public static class Cmd implements MyCommand { private final String data; private final ActorRef sender; @@ -140,8 +140,8 @@ public class PersistentActorCompileOnlyTest { } } - interface MyEvent { - } + interface MyEvent {} + public static class Evt implements MyEvent { private final String data; @@ -154,49 +154,54 @@ public class PersistentActorCompileOnlyTest { private List events = new ArrayList<>(); } - //#commonChainedEffects + // #commonChainedEffects // Factored out Chained effect - static final SideEffect commonChainedEffect = + static final SideEffect commonChainedEffect = SideEffect.create(s -> System.out.println("Command handled!")); - //#commonChainedEffects + // #commonChainedEffects private EventSourcedBehavior pa = new EventSourcedBehavior(new PersistenceId("pa")) { - @Override - public ExampleState emptyState() { - return new ExampleState(); - } + @Override + public ExampleState emptyState() { + return new ExampleState(); + } - @Override - public CommandHandler commandHandler() { + @Override + public CommandHandler commandHandler() { - //#commonChainedEffects - return commandHandlerBuilder(ExampleState.class) - .matchCommand(Cmd.class, (state, cmd) -> Effect().persist(new Evt(cmd.data)) - .thenRun(() -> cmd.sender.tell(new Ack())) - .andThen(commonChainedEffect) - ) - .build(); - //#commonChainedEffects - } + // #commonChainedEffects + return commandHandlerBuilder(ExampleState.class) + .matchCommand( + Cmd.class, + (state, cmd) -> + Effect() + .persist(new Evt(cmd.data)) + .thenRun(() -> cmd.sender.tell(new Ack())) + .andThen(commonChainedEffect)) + .build(); + // #commonChainedEffects + } - @Override - public EventHandler eventHandler() { - return eventHandlerBuilder() - .matchEvent(Evt.class, (state, event) -> { - state.events.add(event.data); - return state; - }) - .build(); - } - }; + @Override + public EventHandler eventHandler() { + return eventHandlerBuilder() + .matchEvent( + Evt.class, + (state, event) -> { + state.events.add(event.data); + return state; + }) + .build(); + } + }; } - static abstract class RecoveryComplete { - interface Command { - } + abstract static class RecoveryComplete { + interface Command {} + static class DoSideEffect implements Command { final String data; @@ -213,8 +218,7 @@ public class PersistentActorCompileOnlyTest { } } - interface Event { - } + interface Event {} static class IntentRecord implements Event { final int correlationId; @@ -267,10 +271,18 @@ public class PersistentActorCompileOnlyTest { static ActorRef sideEffectProcessor = TestInbox.create().getRef(); static Duration timeout = Duration.ofSeconds(1); - private static void performSideEffect(ActorRef sender, int correlationId, String data, Scheduler scheduler) { - CompletionStage what = ask(sideEffectProcessor, (ActorRef ar) -> new Request(correlationId, data, ar), timeout, scheduler); - what.thenApply(r -> new AcknowledgeSideEffect(r.correlationId)) - .thenAccept(sender::tell); + private static void performSideEffect( + ActorRef sender, + int correlationId, + String data, + Scheduler scheduler) { + CompletionStage what = + ask( + sideEffectProcessor, + (ActorRef ar) -> new Request(correlationId, data, ar), + timeout, + scheduler); + what.thenApply(r -> new AcknowledgeSideEffect(r.correlationId)).thenAccept(sender::tell); } // #actor-context @@ -281,7 +293,8 @@ public class PersistentActorCompileOnlyTest { // #actor-context // #actor-context - class MyPersistentBehavior extends EventSourcedBehavior { + class MyPersistentBehavior + extends EventSourcedBehavior { // this makes the context available to the command handler etc. private final ActorContext ctx; @@ -300,30 +313,45 @@ public class PersistentActorCompileOnlyTest { @Override public CommandHandler commandHandler() { return commandHandlerBuilder(EventsInFlight.class) - .matchCommand(DoSideEffect.class, - (state, cmd) -> Effect().persist(new IntentRecord(state.nextCorrelationId, cmd.data)) - .thenRun(() -> performSideEffect(ctx.getSelf().narrow(), state.nextCorrelationId, cmd.data, ctx.getSystem().scheduler()))) - .matchCommand(AcknowledgeSideEffect.class, (state, command) -> Effect().persist(new SideEffectAcknowledged(command.correlationId))) - .build(); + .matchCommand( + DoSideEffect.class, + (state, cmd) -> + Effect() + .persist(new IntentRecord(state.nextCorrelationId, cmd.data)) + .thenRun( + () -> + performSideEffect( + ctx.getSelf().narrow(), + state.nextCorrelationId, + cmd.data, + ctx.getSystem().scheduler()))) + .matchCommand( + AcknowledgeSideEffect.class, + (state, command) -> + Effect().persist(new SideEffectAcknowledged(command.correlationId))) + .build(); } @Override public EventHandler eventHandler() { return eventHandlerBuilder() - .matchEvent(IntentRecord.class, (state, event) -> { - int nextCorrelationId = event.correlationId; - Map newOutstanding = new HashMap<>(state.dataByCorrelationId); - newOutstanding.put(event.correlationId, event.data); - return new EventsInFlight(nextCorrelationId, newOutstanding); - }) - .matchEvent(SideEffectAcknowledged.class, (state, event) -> { - Map newOutstanding = new HashMap<>(state.dataByCorrelationId); - newOutstanding.remove(event.correlationId); - return new EventsInFlight(state.nextCorrelationId, newOutstanding); - }) - .build(); + .matchEvent( + IntentRecord.class, + (state, event) -> { + int nextCorrelationId = event.correlationId; + Map newOutstanding = new HashMap<>(state.dataByCorrelationId); + newOutstanding.put(event.correlationId, event.data); + return new EventsInFlight(nextCorrelationId, newOutstanding); + }) + .matchEvent( + SideEffectAcknowledged.class, + (state, event) -> { + Map newOutstanding = new HashMap<>(state.dataByCorrelationId); + newOutstanding.remove(event.correlationId); + return new EventsInFlight(state.nextCorrelationId, newOutstanding); + }) + .build(); } } } - } diff --git a/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/PersistentActorJavaDslTest.java b/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/PersistentActorJavaDslTest.java index 09992b368b..dee56281e9 100644 --- a/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/PersistentActorJavaDslTest.java +++ b/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/PersistentActorJavaDslTest.java @@ -44,17 +44,16 @@ public class PersistentActorJavaDslTest extends JUnitSuite { public static final Config config = conf().withFallback(ConfigFactory.load()); - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(config); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(config); + private LeveldbReadJournal queries = + PersistenceQuery.get(Adapter.toUntyped(testKit.system())) + .getReadJournalFor(LeveldbReadJournal.class, LeveldbReadJournal.Identifier()); - private LeveldbReadJournal queries = PersistenceQuery.get(Adapter.toUntyped(testKit.system())) - .getReadJournalFor(LeveldbReadJournal.class, LeveldbReadJournal.Identifier()); + private ActorMaterializer materializer = + ActorMaterializer.create(Adapter.toUntyped(testKit.system())); - private ActorMaterializer materializer = ActorMaterializer.create(Adapter.toUntyped(testKit.system())); - - interface Command extends Serializable { - } + interface Command extends Serializable {} public enum Increment implements Command { INSTANCE @@ -123,9 +122,7 @@ public class PersistentActorJavaDslTest extends JUnitSuite { @Override public String toString() { - return "Incremented{" + - "delta=" + delta + - '}'; + return "Incremented{" + "delta=" + delta + '}'; } @Override @@ -162,10 +159,7 @@ public class PersistentActorJavaDslTest extends JUnitSuite { @Override public String toString() { - return "State{" + - "value=" + value + - ", history=" + history + - '}'; + return "State{" + "value=" + value + ", history=" + history + '}'; } @Override @@ -173,8 +167,7 @@ public class PersistentActorJavaDslTest extends JUnitSuite { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; State state = (State) o; - return value == state.value && - Objects.equals(history, state.history); + return value == state.value && Objects.equals(history, state.history); } @Override @@ -197,7 +190,9 @@ public class PersistentActorJavaDslTest extends JUnitSuite { private final ActorContext ctx; CounterBehavior(PersistenceId persistentId, ActorContext ctx) { - super(persistentId, SupervisorStrategy.restartWithBackoff(Duration.ofMillis(1), Duration.ofMillis(5), 0.1)); + super( + persistentId, + SupervisorStrategy.restartWithBackoff(Duration.ofMillis(1), Duration.ofMillis(5), 0.1)); this.ctx = ctx; } @@ -215,17 +210,15 @@ public class PersistentActorJavaDslTest extends JUnitSuite { .matchCommand(StopThenLog.class, this::stopThenLog) .matchCommand(IncrementTwiceAndLog.class, this::incrementTwiceAndLog) .build(); - } private Effect increment(State state, Increment command) { return Effect().persist(new Incremented(1)); } - private ReplyEffect incrementWithConfirmation(State state, IncrementWithConfirmation command) { - return Effect() - .persist(new Incremented(1)) - .thenReply(command, newState -> done()); + private ReplyEffect incrementWithConfirmation( + State state, IncrementWithConfirmation command) { + return Effect().persist(new Incremented(1)).thenReply(command, newState -> done()); } private ReplyEffect getValue(State state, GetValue command) { @@ -233,10 +226,13 @@ public class PersistentActorJavaDslTest extends JUnitSuite { } private Effect incrementLater(State state, IncrementLater command) { - ActorRef delay = ctx.spawnAnonymous(Behaviors.withTimers(timers -> { - timers.startSingleTimer(Tick.INSTANCE, Tick.INSTANCE, Duration.ofMillis(10)); - return Behaviors.receive((context, o) -> Behaviors.stopped()); - })); + ActorRef delay = + ctx.spawnAnonymous( + Behaviors.withTimers( + timers -> { + timers.startSingleTimer(Tick.INSTANCE, Tick.INSTANCE, Duration.ofMillis(10)); + return Behaviors.receive((context, o) -> Behaviors.stopped()); + })); ctx.watchWith(delay, DelayFinished.INSTANCE); return Effect().none(); } @@ -245,7 +241,8 @@ public class PersistentActorJavaDslTest extends JUnitSuite { return Effect().persist(new Incremented(10)); } - private Effect increment100OnTimeout(State state, Increment100OnTimeout command) { + private Effect increment100OnTimeout( + State state, Increment100OnTimeout command) { ctx.setReceiveTimeout(Duration.ofMillis(10), Timeout.INSTANCE); return Effect().none(); } @@ -254,19 +251,17 @@ public class PersistentActorJavaDslTest extends JUnitSuite { return Effect().persist(new Incremented(100)); } - private Effect emptyEventsListAndThenLog(State state, EmptyEventsListAndThenLog command) { - return Effect() - .persist(Collections.emptyList()) - .thenRun(s -> log()); + private Effect emptyEventsListAndThenLog( + State state, EmptyEventsListAndThenLog command) { + return Effect().persist(Collections.emptyList()).thenRun(s -> log()); } private Effect stopThenLog(State state, StopThenLog command) { - return Effect() - .stop() - .thenRun(s -> log()); + return Effect().stop().thenRun(s -> log()); } - private Effect incrementTwiceAndLog(State state, IncrementTwiceAndLog command) { + private Effect incrementTwiceAndLog( + State state, IncrementTwiceAndLog command) { return Effect() .persist(Arrays.asList(new Incremented(1), new Incremented(1))) .thenRun(s -> log()); @@ -274,9 +269,7 @@ public class PersistentActorJavaDslTest extends JUnitSuite { @Override public EventHandler eventHandler() { - return eventHandlerBuilder() - .matchEvent(Incremented.class, this::applyIncremented) - .build(); + return eventHandlerBuilder().matchEvent(Incremented.class, this::applyIncremented).build(); } @Override @@ -332,34 +325,37 @@ public class PersistentActorJavaDslTest extends JUnitSuite { @Test public void handleTerminatedSignal() { TestProbe> eventHandlerProbe = testKit.createTestProbe(); - Behavior counter = Behaviors.setup(ctx -> - new CounterBehavior(new PersistenceId("c3"), ctx) { - @Override - protected State applyIncremented(State state, Incremented event) { - eventHandlerProbe.ref().tell(Pair.create(state, event)); - return super.applyIncremented(state, event); - } - } - ); + Behavior counter = + Behaviors.setup( + ctx -> + new CounterBehavior(new PersistenceId("c3"), ctx) { + @Override + protected State applyIncremented(State state, Incremented event) { + eventHandlerProbe.ref().tell(Pair.create(state, event)); + return super.applyIncremented(state, event); + } + }); ActorRef c = testKit.spawn(counter); c.tell(Increment.INSTANCE); c.tell(IncrementLater.INSTANCE); eventHandlerProbe.expectMessage(Pair.create(State.EMPTY, new Incremented(1))); - eventHandlerProbe.expectMessage(Pair.create(new State(1, Collections.singletonList(0)), new Incremented(10))); + eventHandlerProbe.expectMessage( + Pair.create(new State(1, Collections.singletonList(0)), new Incremented(10))); } @Test public void handleReceiveTimeout() { TestProbe> eventHandlerProbe = testKit.createTestProbe(); - Behavior counter = Behaviors.setup(ctx -> - new CounterBehavior(new PersistenceId("c4"), ctx) { - @Override - protected State applyIncremented(State state, Incremented event) { - eventHandlerProbe.ref().tell(Pair.create(state, event)); - return super.applyIncremented(state, event); - } - } - ); + Behavior counter = + Behaviors.setup( + ctx -> + new CounterBehavior(new PersistenceId("c4"), ctx) { + @Override + protected State applyIncremented(State state, Incremented event) { + eventHandlerProbe.ref().tell(Pair.create(state, event)); + return super.applyIncremented(state, event); + } + }); ActorRef c = testKit.spawn(counter); c.tell(Increment100OnTimeout.INSTANCE); eventHandlerProbe.expectMessage(Pair.create(State.EMPTY, new Incremented(100))); @@ -368,14 +364,15 @@ public class PersistentActorJavaDslTest extends JUnitSuite { @Test public void chainableSideEffectsWithEvents() { TestProbe loggingProbe = testKit.createTestProbe(); - Behavior counter = Behaviors.setup(ctx -> - new CounterBehavior(new PersistenceId("c5"), ctx) { - @Override - protected void log() { - loggingProbe.ref().tell("logged"); - } - } - ); + Behavior counter = + Behaviors.setup( + ctx -> + new CounterBehavior(new PersistenceId("c5"), ctx) { + @Override + protected void log() { + loggingProbe.ref().tell("logged"); + } + }); ActorRef c = testKit.spawn(counter); c.tell(EmptyEventsListAndThenLog.INSTANCE); loggingProbe.expectMessage("logged"); @@ -383,10 +380,11 @@ public class PersistentActorJavaDslTest extends JUnitSuite { @Test public void workWhenWrappedInOtherBehavior() { - Behavior behavior = Behaviors.supervise(counter(new PersistenceId("c6"))).onFailure( - SupervisorStrategy.restartWithBackoff(Duration.ofSeconds(1), - Duration.ofSeconds(10), 0.1) - ); + Behavior behavior = + Behaviors.supervise(counter(new PersistenceId("c6"))) + .onFailure( + SupervisorStrategy.restartWithBackoff( + Duration.ofSeconds(1), Duration.ofSeconds(10), 0.1)); ActorRef c = testKit.spawn(behavior); TestProbe probe = testKit.createTestProbe(); @@ -399,18 +397,20 @@ public class PersistentActorJavaDslTest extends JUnitSuite { public void snapshot() { TestProbe> snapshotProbe = testKit.createTestProbe(); - Behavior snapshoter = Behaviors.setup(ctx -> - new CounterBehavior(new PersistenceId("snapshot"), ctx) { - @Override - public boolean shouldSnapshot(State state, Incremented event, long sequenceNr) { - return state.value % 2 == 0; - } - @Override - public void onSnapshot(SnapshotMetadata meta, Optional result) { - snapshotProbe.ref().tell(result); - } - } - ); + Behavior snapshoter = + Behaviors.setup( + ctx -> + new CounterBehavior(new PersistenceId("snapshot"), ctx) { + @Override + public boolean shouldSnapshot(State state, Incremented event, long sequenceNr) { + return state.value % 2 == 0; + } + + @Override + public void onSnapshot(SnapshotMetadata meta, Optional result) { + snapshotProbe.ref().tell(result); + } + }); ActorRef c = testKit.spawn(snapshoter); c.tell(Increment.INSTANCE); c.tell(Increment.INSTANCE); @@ -422,18 +422,20 @@ public class PersistentActorJavaDslTest extends JUnitSuite { stateProbe.expectMessage(new State(3, Arrays.asList(0, 1, 2))); TestProbe> eventHandlerProbe = testKit.createTestProbe(); - Behavior recovered = Behaviors.setup(ctx -> - new CounterBehavior(new PersistenceId("snapshot"), ctx) { - @Override - protected State applyIncremented(State state, Incremented event) { - eventHandlerProbe.ref().tell(Pair.create(state, event)); - return super.applyIncremented(state, event); - } - } - ); + Behavior recovered = + Behaviors.setup( + ctx -> + new CounterBehavior(new PersistenceId("snapshot"), ctx) { + @Override + protected State applyIncremented(State state, Incremented event) { + eventHandlerProbe.ref().tell(Pair.create(state, event)); + return super.applyIncremented(state, event); + } + }); ActorRef c2 = testKit.spawn(recovered); // First 2 are snapshot - eventHandlerProbe.expectMessage(Pair.create(new State(2, Arrays.asList(0, 1)), new Incremented(1))); + eventHandlerProbe.expectMessage( + Pair.create(new State(2, Arrays.asList(0, 1)), new Incremented(1))); c2.tell(new GetValue(stateProbe.ref())); stateProbe.expectMessage(new State(3, Arrays.asList(0, 1, 2))); } @@ -450,26 +452,30 @@ public class PersistentActorJavaDslTest extends JUnitSuite { public void tapPersistentActor() { TestProbe interceptProbe = testKit.createTestProbe(); TestProbe signalProbe = testKit.createTestProbe(); - BehaviorInterceptor tap = new BehaviorInterceptor() { + BehaviorInterceptor tap = + new BehaviorInterceptor() { - @Override - public Class interceptMessageType() { - return Command.class; - } + @Override + public Class interceptMessageType() { + return Command.class; + } - @Override - public Behavior aroundReceive(TypedActorContext ctx, Command msg, ReceiveTarget target) { - interceptProbe.ref().tell(msg); - return target.apply(ctx, msg); - } + @Override + public Behavior aroundReceive( + TypedActorContext ctx, Command msg, ReceiveTarget target) { + interceptProbe.ref().tell(msg); + return target.apply(ctx, msg); + } - @Override - public Behavior aroundSignal(TypedActorContext ctx, Signal signal, SignalTarget target) { - signalProbe.ref().tell(signal); - return target.apply(ctx, signal); - } - }; - ActorRef c = testKit.spawn(Behaviors.intercept(tap, counter(new PersistenceId("tap1")))); + @Override + public Behavior aroundSignal( + TypedActorContext ctx, Signal signal, SignalTarget target) { + signalProbe.ref().tell(signal); + return target.apply(ctx, signal); + } + }; + ActorRef c = + testKit.spawn(Behaviors.intercept(tap, counter(new PersistenceId("tap1")))); c.tell(Increment.INSTANCE); interceptProbe.expectMessage(Increment.INSTANCE); signalProbe.expectNoMessage(); @@ -477,14 +483,15 @@ public class PersistentActorJavaDslTest extends JUnitSuite { @Test public void tagEvent() throws Exception { - Behavior tagger = Behaviors.setup(ctx -> - new CounterBehavior(new PersistenceId("tagging"), ctx) { - @Override - public Set tagsFor(Incremented incremented) { - return Sets.newHashSet("tag1", "tag2"); - } - } - ); + Behavior tagger = + Behaviors.setup( + ctx -> + new CounterBehavior(new PersistenceId("tagging"), ctx) { + @Override + public Set tagsFor(Incremented incremented) { + return Sets.newHashSet("tag1", "tag2"); + } + }); ActorRef c = testKit.spawn(tagger); c.tell(Increment.INSTANCE); @@ -493,23 +500,29 @@ public class PersistentActorJavaDslTest extends JUnitSuite { c.tell(new GetValue(stateProbe.ref())); stateProbe.expectMessage(new State(1, Collections.singletonList(0))); - List events = queries.currentEventsByTag("tag1", NoOffset.getInstance()).runWith(Sink.seq(), materializer) - .toCompletableFuture().get(); - assertEquals(Lists.newArrayList( - new EventEnvelope(new Sequence(1), "tagging", 1, new Incremented(1)) - ), events); + List events = + queries + .currentEventsByTag("tag1", NoOffset.getInstance()) + .runWith(Sink.seq(), materializer) + .toCompletableFuture() + .get(); + assertEquals( + Lists.newArrayList(new EventEnvelope(new Sequence(1), "tagging", 1, new Incremented(1))), + events); } @Test public void transformEvent() throws Exception { - Behavior transformer = Behaviors.setup(ctx -> - new CounterBehavior(new PersistenceId("transform"), ctx) { - private final EventAdapter adapter = new WrapperEventAdapter(); - public EventAdapter eventAdapter() { - return adapter; - } - } - ); + Behavior transformer = + Behaviors.setup( + ctx -> + new CounterBehavior(new PersistenceId("transform"), ctx) { + private final EventAdapter adapter = new WrapperEventAdapter(); + + public EventAdapter eventAdapter() { + return adapter; + } + }); ActorRef c = testKit.spawn(transformer); c.tell(Increment.INSTANCE); @@ -518,18 +531,23 @@ public class PersistentActorJavaDslTest extends JUnitSuite { c.tell(new GetValue(stateProbe.ref())); stateProbe.expectMessage(new State(1, Collections.singletonList(0))); - List events = queries.currentEventsByPersistenceId("transform", 0, Long.MAX_VALUE) - .runWith(Sink.seq(), materializer).toCompletableFuture().get(); - assertEquals(Lists.newArrayList( - new EventEnvelope(new Sequence(1), "transform", 1, new Wrapper<>(new Incremented(1))) - ), events); + List events = + queries + .currentEventsByPersistenceId("transform", 0, Long.MAX_VALUE) + .runWith(Sink.seq(), materializer) + .toCompletableFuture() + .get(); + assertEquals( + Lists.newArrayList( + new EventEnvelope(new Sequence(1), "transform", 1, new Wrapper<>(new Incremented(1)))), + events); ActorRef c2 = testKit.spawn(transformer); c2.tell(new GetValue(stateProbe.ref())); stateProbe.expectMessage(new State(1, Collections.singletonList(0))); } - //event-wrapper + // event-wrapper class WrapperEventAdapter extends EventAdapter { @Override public Wrapper toJournal(Incremented incremented) { @@ -541,6 +559,6 @@ public class PersistentActorJavaDslTest extends JUnitSuite { return (Incremented) wrapper.t(); } } - //event-wrapper + // event-wrapper } diff --git a/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/PrimitiveStateTest.java b/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/PrimitiveStateTest.java index 7901880a82..0ee10c636c 100644 --- a/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/PrimitiveStateTest.java +++ b/akka-persistence-typed/src/test/java/akka/persistence/typed/javadsl/PrimitiveStateTest.java @@ -18,11 +18,11 @@ import org.scalatest.junit.JUnitSuite; public class PrimitiveStateTest extends JUnitSuite { - private static final Config config = ConfigFactory.parseString( - "akka.persistence.journal.plugin = \"akka.persistence.journal.inmem\" \n"); + private static final Config config = + ConfigFactory.parseString( + "akka.persistence.journal.plugin = \"akka.persistence.journal.inmem\" \n"); - @ClassRule - public static final TestKitJunitResource testKit = new TestKitJunitResource(config); + @ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource(config); static class PrimitiveState extends EventSourcedBehavior { @@ -46,10 +46,8 @@ public class PrimitiveStateTest extends JUnitSuite { @Override public CommandHandler commandHandler() { return (state, command) -> { - if (command < 0) - return Effect().stop(); - else - return Effect().persist(command); + if (command < 0) return Effect().stop(); + else return Effect().persist(command); }; } @@ -65,7 +63,8 @@ public class PrimitiveStateTest extends JUnitSuite { @Test public void handleIntegerState() throws Exception { TestProbe probe = testKit.createTestProbe(); - Behavior b = Behaviors.setup(ctx -> new PrimitiveState(new PersistenceId("a"), probe.ref())); + Behavior b = + Behaviors.setup(ctx -> new PrimitiveState(new PersistenceId("a"), probe.ref())); ActorRef ref1 = testKit.spawn(b); probe.expectMessage("onRecoveryCompleted:0"); ref1.tell(1); diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/AccountExample.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/AccountExample.java index e4b37d4c9f..dadd629dd3 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/AccountExample.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/AccountExample.java @@ -13,10 +13,14 @@ import akka.persistence.typed.javadsl.CommandHandlerBuilder; import akka.persistence.typed.javadsl.EventHandler; import akka.persistence.typed.javadsl.EventSourcedBehavior; -public class AccountExample extends EventSourcedBehavior { +public class AccountExample + extends EventSourcedBehavior< + AccountExample.AccountCommand, AccountExample.AccountEvent, AccountExample.Account> { interface AccountCommand {} + public static class CreateAccount implements AccountCommand {} + public static class Deposit implements AccountCommand { public final double amount; @@ -24,6 +28,7 @@ public class AccountExample extends EventSourcedBehavior behavior(String accountNumber) { @@ -75,61 +88,65 @@ public class AccountExample extends EventSourcedBehavior initialHandler() { + private CommandHandlerBuilder + initialHandler() { return commandHandlerBuilder(EmptyAccount.class) - .matchCommand(CreateAccount.class, (__, cmd) -> Effect().persist(new AccountCreated())); + .matchCommand(CreateAccount.class, (__, cmd) -> Effect().persist(new AccountCreated())); } - private CommandHandlerBuilder openedAccountHandler() { + private CommandHandlerBuilder + openedAccountHandler() { return commandHandlerBuilder(OpenedAccount.class) - .matchCommand(Deposit.class, (__, cmd) -> Effect().persist(new Deposited(cmd.amount))) - .matchCommand(Withdraw.class, (acc, cmd) -> { - if ((acc.balance - cmd.amount) < 0.0) { - return Effect().unhandled(); // TODO replies are missing in this example - } else { - return Effect().persist(new Withdrawn(cmd.amount)) - .thenRun(acc2 -> { // FIXME in scaladsl it's named thenRun, change javadsl also? - // we know this cast is safe, but somewhat ugly - OpenedAccount openAccount = (OpenedAccount) acc2; - // do some side-effect using balance - System.out.println(openAccount.balance); + .matchCommand(Deposit.class, (__, cmd) -> Effect().persist(new Deposited(cmd.amount))) + .matchCommand( + Withdraw.class, + (acc, cmd) -> { + if ((acc.balance - cmd.amount) < 0.0) { + return Effect().unhandled(); // TODO replies are missing in this example + } else { + return Effect() + .persist(new Withdrawn(cmd.amount)) + .thenRun( + acc2 -> { // FIXME in scaladsl it's named thenRun, change javadsl also? + // we know this cast is safe, but somewhat ugly + OpenedAccount openAccount = (OpenedAccount) acc2; + // do some side-effect using balance + System.out.println(openAccount.balance); + }); + } + }) + .matchCommand( + CloseAccount.class, + (acc, cmd) -> { + if (acc.balance == 0.0) return Effect().persist(new AccountClosed()); + else return Effect().unhandled(); }); - } - }) - .matchCommand(CloseAccount.class, (acc, cmd) -> { - if (acc.balance == 0.0) - return Effect().persist(new AccountClosed()); - else - return Effect().unhandled(); - }); } - private CommandHandlerBuilder closedHandler() { + private CommandHandlerBuilder + closedHandler() { return commandHandlerBuilder(ClosedAccount.class) .matchCommand(AccountCommand.class, (__, ___) -> Effect().unhandled()); } @Override public CommandHandler commandHandler() { - return initialHandler() - .orElse(openedAccountHandler()) - .orElse(closedHandler()) - .build(); + return initialHandler().orElse(openedAccountHandler()).orElse(closedHandler()).build(); } @Override public EventHandler eventHandler() { return eventHandlerBuilder() - .matchEvent(AccountCreated.class, EmptyAccount.class, (__, ___) -> - new OpenedAccount(0.0)) - .matchEvent(Deposited.class, OpenedAccount.class, (acc, cmd) -> - new OpenedAccount(acc.balance + cmd.amount)) - .matchEvent(Withdrawn.class, OpenedAccount.class, (acc, cmd) -> - new OpenedAccount(acc.balance - cmd.amount)) - .matchEvent(AccountClosed.class, OpenedAccount.class, (acc, cmd) -> - new ClosedAccount()) - .build(); + .matchEvent(AccountCreated.class, EmptyAccount.class, (__, ___) -> new OpenedAccount(0.0)) + .matchEvent( + Deposited.class, + OpenedAccount.class, + (acc, cmd) -> new OpenedAccount(acc.balance + cmd.amount)) + .matchEvent( + Withdrawn.class, + OpenedAccount.class, + (acc, cmd) -> new OpenedAccount(acc.balance - cmd.amount)) + .matchEvent(AccountClosed.class, OpenedAccount.class, (acc, cmd) -> new ClosedAccount()) + .build(); } - - } diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/BasicPersistentBehaviorTest.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/BasicPersistentBehaviorTest.java index 7275053da1..853f4017cd 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/BasicPersistentBehaviorTest.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/BasicPersistentBehaviorTest.java @@ -17,17 +17,22 @@ import java.util.Set; public class BasicPersistentBehaviorTest { - //#structure + // #structure public interface Command {} + public interface Event {} + public static class State {} - //#supervision + // #supervision public static class MyPersistentBehavior extends EventSourcedBehavior { public MyPersistentBehavior(PersistenceId persistenceId) { - super(persistenceId, SupervisorStrategy.restartWithBackoff(Duration.ofSeconds(10), Duration.ofSeconds(30), 0.2)); + super( + persistenceId, + SupervisorStrategy.restartWithBackoff( + Duration.ofSeconds(10), Duration.ofSeconds(30), 0.2)); } - //#supervision + // #supervision @Override public State emptyState() { @@ -42,42 +47,44 @@ public class BasicPersistentBehaviorTest { } @Override - public EventHandler eventHandler() { + public EventHandler eventHandler() { return (state, event) -> { throw new RuntimeException("TODO: process the event return the next state"); }; } - //#recovery + // #recovery @Override public void onRecoveryCompleted(State state) { throw new RuntimeException("TODO: add some end-of-recovery side-effect here"); } - //#recovery + // #recovery - //#tagging + // #tagging @Override public Set tagsFor(Event event) { throw new RuntimeException("TODO: inspect the event and return any tags it should have"); } - //#tagging + // #tagging } static EventSourcedBehavior eventSourcedBehavior = new MyPersistentBehavior(new PersistenceId("pid")); - //#structure + // #structure - //#wrapPersistentBehavior - static Behavior debugAlwaysSnapshot = Behaviors.setup((context) -> { + // #wrapPersistentBehavior + static Behavior debugAlwaysSnapshot = + Behaviors.setup( + (context) -> { return new MyPersistentBehavior(new PersistenceId("pid")) { @Override public boolean shouldSnapshot(State state, Event event, long sequenceNr) { - context.getLog().info("Snapshot actor {} => state: {}", - context.getSelf().path().name(), state); + context + .getLog() + .info("Snapshot actor {} => state: {}", context.getSelf().path().name(), state); return true; } }; - } - ); - //#wrapPersistentBehavior + }); + // #wrapPersistentBehavior } diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/BlogPostExample.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/BlogPostExample.java index 5da8a1ab03..d9f8f7322a 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/BlogPostExample.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/BlogPostExample.java @@ -17,9 +17,9 @@ import akka.persistence.typed.javadsl.EventSourcedBehavior; public class BlogPostExample { - //#event - interface BlogEvent { - } + // #event + interface BlogEvent {} + public static class PostAdded implements BlogEvent { private final String postId; private final PostContent content; @@ -47,9 +47,9 @@ public class BlogPostExample { this.postId = postId; } } - //#event + // #event - //#state + // #state interface BlogState {} public enum BlankState implements BlogState { @@ -87,12 +87,11 @@ public class BlogPostExample { return postContent.postId; } } - //#state + // #state - //#commands - public interface BlogCommand { - } - //#reply-command + // #commands + public interface BlogCommand {} + // #reply-command public static class AddPost implements BlogCommand { final PostContent content; final ActorRef replyTo; @@ -102,6 +101,7 @@ public class BlogPostExample { this.replyTo = replyTo; } } + public static class AddPostDone implements BlogCommand { final String postId; @@ -109,7 +109,7 @@ public class BlogPostExample { this.postId = postId; } } - //#reply-command + // #reply-command public static class GetPost implements BlogCommand { final ActorRef replyTo; @@ -117,6 +117,7 @@ public class BlogPostExample { this.replyTo = replyTo; } } + public static class ChangeBody implements BlogCommand { final String newBody; final ActorRef replyTo; @@ -126,6 +127,7 @@ public class BlogPostExample { this.replyTo = replyTo; } } + public static class Publish implements BlogCommand { final ActorRef replyTo; @@ -133,6 +135,7 @@ public class BlogPostExample { this.replyTo = replyTo; } } + public static class PostContent implements BlogCommand { final String postId; final String title; @@ -144,11 +147,11 @@ public class BlogPostExample { this.body = body; } } - //#commands + // #commands - //#behavior + // #behavior public static class BlogBehavior extends EventSourcedBehavior { - //#behavior + // #behavior private final ActorContext ctx; @@ -157,89 +160,114 @@ public class BlogPostExample { this.ctx = ctx; } - //#initial-command-handler - private CommandHandlerBuilder initialCommandHandler() { + // #initial-command-handler + private CommandHandlerBuilder + initialCommandHandler() { return commandHandlerBuilder(BlankState.class) - .matchCommand(AddPost.class, (state, cmd) -> { - //#reply - PostAdded event = new PostAdded(cmd.content.postId, cmd.content); - return Effect().persist(event) - .thenRun(() -> cmd.replyTo.tell(new AddPostDone(cmd.content.postId))); - //#reply - }); + .matchCommand( + AddPost.class, + (state, cmd) -> { + // #reply + PostAdded event = new PostAdded(cmd.content.postId, cmd.content); + return Effect() + .persist(event) + .thenRun(() -> cmd.replyTo.tell(new AddPostDone(cmd.content.postId))); + // #reply + }); } - //#initial-command-handler + // #initial-command-handler - //#post-added-command-handler - private CommandHandlerBuilder draftCommandHandler() { + // #post-added-command-handler + private CommandHandlerBuilder + draftCommandHandler() { return commandHandlerBuilder(DraftState.class) - .matchCommand(ChangeBody.class, (state, cmd) -> { - BodyChanged event = new BodyChanged(state.postId(), cmd.newBody); - return Effect().persist(event).thenRun(() -> cmd.replyTo.tell(Done.getInstance())); - }) - .matchCommand(Publish.class, (state, cmd) -> Effect() - .persist(new Published(state.postId())).thenRun(() -> { - System.out.println("Blog post published: " + state.postId()); - cmd.replyTo.tell(Done.getInstance()); - })) - .matchCommand(GetPost.class, (state, cmd) -> { - cmd.replyTo.tell(state.postContent); - return Effect().none(); - }); + .matchCommand( + ChangeBody.class, + (state, cmd) -> { + BodyChanged event = new BodyChanged(state.postId(), cmd.newBody); + return Effect().persist(event).thenRun(() -> cmd.replyTo.tell(Done.getInstance())); + }) + .matchCommand( + Publish.class, + (state, cmd) -> + Effect() + .persist(new Published(state.postId())) + .thenRun( + () -> { + System.out.println("Blog post published: " + state.postId()); + cmd.replyTo.tell(Done.getInstance()); + })) + .matchCommand( + GetPost.class, + (state, cmd) -> { + cmd.replyTo.tell(state.postContent); + return Effect().none(); + }); } - private CommandHandlerBuilder publishedCommandHandler() { + private CommandHandlerBuilder + publishedCommandHandler() { return commandHandlerBuilder(PublishedState.class) - .matchCommand(ChangeBody.class, (state, cmd) -> { - BodyChanged event = new BodyChanged(state.postId(), cmd.newBody); - return Effect().persist(event).thenRun(() -> cmd.replyTo.tell(Done.getInstance())); - }) - .matchCommand(GetPost.class, (state, cmd) -> { - cmd.replyTo.tell(state.postContent); - return Effect().none(); - }); + .matchCommand( + ChangeBody.class, + (state, cmd) -> { + BodyChanged event = new BodyChanged(state.postId(), cmd.newBody); + return Effect().persist(event).thenRun(() -> cmd.replyTo.tell(Done.getInstance())); + }) + .matchCommand( + GetPost.class, + (state, cmd) -> { + cmd.replyTo.tell(state.postContent); + return Effect().none(); + }); } - private CommandHandlerBuilder commonCommandHandler() { + private CommandHandlerBuilder + commonCommandHandler() { return commandHandlerBuilder(BlogState.class) .matchCommand(AddPost.class, (state, cmd) -> Effect().unhandled()); } - //#post-added-command-handler + // #post-added-command-handler - - //#command-handler + // #command-handler @Override public CommandHandler commandHandler() { - return - initialCommandHandler() - .orElse(draftCommandHandler()) - .orElse(publishedCommandHandler()) - .orElse(commonCommandHandler()) - .build(); + return initialCommandHandler() + .orElse(draftCommandHandler()) + .orElse(publishedCommandHandler()) + .orElse(commonCommandHandler()) + .build(); } - //#command-handler + // #command-handler - //#event-handler + // #event-handler @Override public EventHandler eventHandler() { return eventHandlerBuilder() - .matchEvent(PostAdded.class, (state, event) -> - new DraftState(event.content)) - .matchEvent(BodyChanged.class, DraftState.class, (state, chg) -> - state.withContent(new PostContent(state.postId(), state.postContent.title, chg.newBody))) - .matchEvent(BodyChanged.class, PublishedState.class, (state, chg) -> - state.withContent(new PostContent(state.postId(), state.postContent.title, chg.newBody))) - .matchEvent(Published.class, DraftState.class, (state, event) -> - new PublishedState(state.postContent)) + .matchEvent(PostAdded.class, (state, event) -> new DraftState(event.content)) + .matchEvent( + BodyChanged.class, + DraftState.class, + (state, chg) -> + state.withContent( + new PostContent(state.postId(), state.postContent.title, chg.newBody))) + .matchEvent( + BodyChanged.class, + PublishedState.class, + (state, chg) -> + state.withContent( + new PostContent(state.postId(), state.postContent.title, chg.newBody))) + .matchEvent( + Published.class, + DraftState.class, + (state, event) -> new PublishedState(state.postContent)) .build(); } - //#event-handler + // #event-handler - //#behavior + // #behavior public static Behavior behavior(String entityId) { - return Behaviors.setup(ctx -> - new BlogBehavior(new PersistenceId("Blog-" + entityId), ctx) - ); + return Behaviors.setup(ctx -> new BlogBehavior(new PersistenceId("Blog-" + entityId), ctx)); } @Override @@ -249,5 +277,5 @@ public class BlogPostExample { // commandHandler, eventHandler as in above snippets } - //#behavior + // #behavior } diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/MovieWatchList.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/MovieWatchList.java index f118917a7b..ff9bf05f47 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/MovieWatchList.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/MovieWatchList.java @@ -4,7 +4,6 @@ package jdocs.akka.persistence.typed; - import akka.actor.typed.ActorRef; import akka.actor.typed.Behavior; import akka.persistence.typed.PersistenceId; @@ -16,10 +15,11 @@ import java.util.Collections; import java.util.HashSet; import java.util.Set; -public class MovieWatchList extends EventSourcedBehavior { +public class MovieWatchList + extends EventSourcedBehavior< + MovieWatchList.Command, MovieWatchList.Event, MovieWatchList.MovieList> { - interface Command { - } + interface Command {} public static class AddMovie implements Command { public final String movieId; @@ -37,8 +37,7 @@ public class MovieWatchList extends EventSourcedBehavior newSet = new HashSet<>(movieIds); - newSet.add(movieId); - return new MovieList(newSet); + Set newSet = new HashSet<>(movieIds); + newSet.add(movieId); + return new MovieList(newSet); } public MovieList remove(String movieId) { @@ -100,26 +99,30 @@ public class MovieWatchList extends EventSourcedBehavior commandHandler() { return commandHandlerBuilder(MovieList.class) - .matchCommand(AddMovie.class, (state, cmd) -> { - return Effect().persist(new MovieAdded(cmd.movieId)); - }) - .matchCommand(RemoveMovie.class, (state, cmd) -> { - return Effect().persist(new MovieRemoved(cmd.movieId)); - }) - .matchCommand(GetMovieList.class, (state, cmd) -> { - cmd.replyTo.tell(state); - return Effect().none(); - }) + .matchCommand( + AddMovie.class, + (state, cmd) -> { + return Effect().persist(new MovieAdded(cmd.movieId)); + }) + .matchCommand( + RemoveMovie.class, + (state, cmd) -> { + return Effect().persist(new MovieRemoved(cmd.movieId)); + }) + .matchCommand( + GetMovieList.class, + (state, cmd) -> { + cmd.replyTo.tell(state); + return Effect().none(); + }) .build(); } @Override public EventHandler eventHandler() { return eventHandlerBuilder() - .matchEvent(MovieAdded.class, (state, event) -> state.add(event.movieId)) - .matchEvent(MovieRemoved.class, (state, event) -> state.remove(event.movieId)) - .build(); + .matchEvent(MovieAdded.class, (state, event) -> state.add(event.movieId)) + .matchEvent(MovieRemoved.class, (state, event) -> state.remove(event.movieId)) + .build(); } - - } diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/NullBlogState.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/NullBlogState.java index c8b97371ce..251c940fd8 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/NullBlogState.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/NullBlogState.java @@ -16,8 +16,8 @@ import java.util.Objects; public class NullBlogState { - interface BlogEvent { - } + interface BlogEvent {} + public static class PostAdded implements BlogEvent { private final String postId; private final PostContent content; @@ -64,8 +64,8 @@ public class NullBlogState { } } - public interface BlogCommand { - } + public interface BlogCommand {} + public static class AddPost implements BlogCommand { final PostContent content; final ActorRef replyTo; @@ -75,6 +75,7 @@ public class NullBlogState { this.replyTo = replyTo; } } + public static class AddPostDone implements BlogCommand { final String postId; @@ -82,6 +83,7 @@ public class NullBlogState { this.postId = postId; } } + public static class GetPost implements BlogCommand { final ActorRef replyTo; @@ -89,6 +91,7 @@ public class NullBlogState { this.replyTo = replyTo; } } + public static class ChangeBody implements BlogCommand { final String newBody; final ActorRef replyTo; @@ -98,6 +101,7 @@ public class NullBlogState { this.replyTo = replyTo; } } + public static class Publish implements BlogCommand { final ActorRef replyTo; @@ -105,6 +109,7 @@ public class NullBlogState { this.replyTo = replyTo; } } + public static class PostContent implements BlogCommand { final String postId; final String title; @@ -119,30 +124,44 @@ public class NullBlogState { public static class BlogBehavior extends EventSourcedBehavior { - private CommandHandlerBuilder initialCommandHandler() { + private CommandHandlerBuilder + initialCommandHandler() { return commandHandlerBuilder(Objects::isNull) - .matchCommand(AddPost.class, cmd -> { - PostAdded event = new PostAdded(cmd.content.postId, cmd.content); - return Effect().persist(event) - .thenRun(() -> cmd.replyTo.tell(new AddPostDone(cmd.content.postId))); - }); + .matchCommand( + AddPost.class, + cmd -> { + PostAdded event = new PostAdded(cmd.content.postId, cmd.content); + return Effect() + .persist(event) + .thenRun(() -> cmd.replyTo.tell(new AddPostDone(cmd.content.postId))); + }); } - private CommandHandlerBuilder postCommandHandler() { + private CommandHandlerBuilder + postCommandHandler() { return commandHandlerBuilder(Objects::nonNull) - .matchCommand(ChangeBody.class, (state, cmd) -> { - BodyChanged event = new BodyChanged(state.postId(), cmd.newBody); - return Effect().persist(event).thenRun(() -> cmd.replyTo.tell(Done.getInstance())); - }) - .matchCommand(Publish.class, (state, cmd) -> Effect() - .persist(new Published(state.postId())).thenRun(() -> { - System.out.println("Blog post published: " + state.postId()); - cmd.replyTo.tell(Done.getInstance()); - })) - .matchCommand(GetPost.class, (state, cmd) -> { - cmd.replyTo.tell(state.postContent); - return Effect().none(); - }) + .matchCommand( + ChangeBody.class, + (state, cmd) -> { + BodyChanged event = new BodyChanged(state.postId(), cmd.newBody); + return Effect().persist(event).thenRun(() -> cmd.replyTo.tell(Done.getInstance())); + }) + .matchCommand( + Publish.class, + (state, cmd) -> + Effect() + .persist(new Published(state.postId())) + .thenRun( + () -> { + System.out.println("Blog post published: " + state.postId()); + cmd.replyTo.tell(Done.getInstance()); + })) + .matchCommand( + GetPost.class, + (state, cmd) -> { + cmd.replyTo.tell(state.postContent); + return Effect().none(); + }) .matchCommand(AddPost.class, (state, cmd) -> Effect().unhandled()); } @@ -163,14 +182,14 @@ public class NullBlogState { @Override public EventHandler eventHandler() { return eventHandlerBuilder() - .matchEvent(PostAdded.class, event -> - new BlogState(event.content, false)) - .matchEvent(BodyChanged.class, (state, chg) -> - state.withContent( - new PostContent(state.postId(), state.postContent.title, chg.newBody))) - .matchEvent(Published.class, (state, event) -> - new BlogState(state.postContent, true)) - .build(); + .matchEvent(PostAdded.class, event -> new BlogState(event.content, false)) + .matchEvent( + BodyChanged.class, + (state, chg) -> + state.withContent( + new PostContent(state.postId(), state.postContent.title, chg.newBody))) + .matchEvent(Published.class, (state, event) -> new BlogState(state.postContent, true)) + .build(); } } } diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/OptionalBlogState.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/OptionalBlogState.java index 2eefe5d858..3c353807cb 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/OptionalBlogState.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/OptionalBlogState.java @@ -16,8 +16,8 @@ import java.util.Optional; public class OptionalBlogState { - interface BlogEvent { - } + interface BlogEvent {} + public static class PostAdded implements BlogEvent { private final String postId; private final PostContent content; @@ -64,8 +64,8 @@ public class OptionalBlogState { } } - public interface BlogCommand { - } + public interface BlogCommand {} + public static class AddPost implements BlogCommand { final PostContent content; final ActorRef replyTo; @@ -75,6 +75,7 @@ public class OptionalBlogState { this.replyTo = replyTo; } } + public static class AddPostDone implements BlogCommand { final String postId; @@ -82,6 +83,7 @@ public class OptionalBlogState { this.postId = postId; } } + public static class GetPost implements BlogCommand { final ActorRef replyTo; @@ -89,6 +91,7 @@ public class OptionalBlogState { this.replyTo = replyTo; } } + public static class ChangeBody implements BlogCommand { final String newBody; final ActorRef replyTo; @@ -98,6 +101,7 @@ public class OptionalBlogState { this.replyTo = replyTo; } } + public static class Publish implements BlogCommand { final ActorRef replyTo; @@ -105,6 +109,7 @@ public class OptionalBlogState { this.replyTo = replyTo; } } + public static class PostContent implements BlogCommand { final String postId; final String title; @@ -117,32 +122,47 @@ public class OptionalBlogState { } } - public static class BlogBehavior extends EventSourcedBehavior> { + public static class BlogBehavior + extends EventSourcedBehavior> { - private CommandHandlerBuilder, Optional> initialCommandHandler() { + private CommandHandlerBuilder, Optional> + initialCommandHandler() { return commandHandlerBuilder(state -> !state.isPresent()) - .matchCommand(AddPost.class, (state, cmd) -> { - PostAdded event = new PostAdded(cmd.content.postId, cmd.content); - return Effect().persist(event) - .thenRun(() -> cmd.replyTo.tell(new AddPostDone(cmd.content.postId))); - }); + .matchCommand( + AddPost.class, + (state, cmd) -> { + PostAdded event = new PostAdded(cmd.content.postId, cmd.content); + return Effect() + .persist(event) + .thenRun(() -> cmd.replyTo.tell(new AddPostDone(cmd.content.postId))); + }); } - private CommandHandlerBuilder, Optional> postCommandHandler() { + private CommandHandlerBuilder, Optional> + postCommandHandler() { return commandHandlerBuilder(state -> state.isPresent()) - .matchCommand(ChangeBody.class, (state, cmd) -> { - BodyChanged event = new BodyChanged(state.get().postId(), cmd.newBody); - return Effect().persist(event).thenRun(() -> cmd.replyTo.tell(Done.getInstance())); - }) - .matchCommand(Publish.class, (state, cmd) -> Effect() - .persist(new Published(state.get().postId())).thenRun(() -> { - System.out.println("Blog post published: " + state.get().postId()); - cmd.replyTo.tell(Done.getInstance()); - })) - .matchCommand(GetPost.class, (state, cmd) -> { - cmd.replyTo.tell(state.get().postContent); - return Effect().none(); - }) + .matchCommand( + ChangeBody.class, + (state, cmd) -> { + BodyChanged event = new BodyChanged(state.get().postId(), cmd.newBody); + return Effect().persist(event).thenRun(() -> cmd.replyTo.tell(Done.getInstance())); + }) + .matchCommand( + Publish.class, + (state, cmd) -> + Effect() + .persist(new Published(state.get().postId())) + .thenRun( + () -> { + System.out.println("Blog post published: " + state.get().postId()); + cmd.replyTo.tell(Done.getInstance()); + })) + .matchCommand( + GetPost.class, + (state, cmd) -> { + cmd.replyTo.tell(state.get().postContent); + return Effect().none(); + }) .matchCommand(AddPost.class, (state, cmd) -> Effect().unhandled()); } @@ -163,14 +183,20 @@ public class OptionalBlogState { @Override public EventHandler, BlogEvent> eventHandler() { return eventHandlerBuilder() - .matchEvent(PostAdded.class, (state, event) -> - Optional.of(new BlogState(event.content, false))) - .matchEvent(BodyChanged.class, (state, chg) -> - state.map(blogState -> blogState.withContent( - new PostContent(blogState.postId(), blogState.postContent.title, chg.newBody)))) - .matchEvent(Published.class, (state, event) -> - state.map(blogState -> new BlogState(blogState.postContent, true))) - .build(); + .matchEvent( + PostAdded.class, (state, event) -> Optional.of(new BlogState(event.content, false))) + .matchEvent( + BodyChanged.class, + (state, chg) -> + state.map( + blogState -> + blogState.withContent( + new PostContent( + blogState.postId(), blogState.postContent.title, chg.newBody)))) + .matchEvent( + Published.class, + (state, event) -> state.map(blogState -> new BlogState(blogState.postContent, true))) + .build(); } } } diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/Auction.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/Auction.java index 9dd122b432..99d46ca78b 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/Auction.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/Auction.java @@ -7,36 +7,28 @@ package jdocs.akka.persistence.typed.auction; import java.time.Instant; import java.util.UUID; -/** - * An auction. - */ +/** An auction. */ public final class Auction { - /** - * The item under auction. - */ + /** The item under auction. */ private final UUID itemId; - /** - * The user that created the item. - */ + /** The user that created the item. */ private final UUID creator; - /** - * The reserve price of the auction. - */ + /** The reserve price of the auction. */ private final int reservePrice; - /** - * The minimum increment between bids. - */ + /** The minimum increment between bids. */ private final int increment; - /** - * The time the auction started. - */ + /** The time the auction started. */ private final Instant startTime; - /** - * The time the auction will end. - */ + /** The time the auction will end. */ private final Instant endTime; - public Auction(UUID itemId, UUID creator, int reservePrice, int increment, Instant startTime, Instant endTime) { + public Auction( + UUID itemId, + UUID creator, + int reservePrice, + int increment, + Instant startTime, + Instant endTime) { this.itemId = itemId; this.creator = creator; this.reservePrice = reservePrice; diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionCommand.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionCommand.java index 18d8eb3604..0bf6e411f1 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionCommand.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionCommand.java @@ -10,19 +10,13 @@ import akka.persistence.typed.ExpectingReply; import java.util.UUID; -/** - * An auction command. - */ +/** An auction command. */ public interface AuctionCommand { - /** - * Start the auction. - */ + /** Start the auction. */ final class StartAuction implements AuctionCommand, ExpectingReply { - /** - * The auction to start. - */ + /** The auction to start. */ private final Auction auction; private final ActorRef replyTo; @@ -42,9 +36,7 @@ public interface AuctionCommand { } } - /** - * Cancel the auction. - */ + /** Cancel the auction. */ final class CancelAuction implements AuctionCommand, ExpectingReply { private final ActorRef replyTo; @@ -56,12 +48,9 @@ public interface AuctionCommand { public ActorRef replyTo() { return replyTo; } - } - /** - * Place a bid on the auction. - */ + /** Place a bid on the auction. */ final class PlaceBid implements AuctionCommand, ExpectingReply { private final int bidPrice; @@ -91,37 +80,21 @@ public interface AuctionCommand { interface PlaceBidReply {} - /** - * The status of placing a bid. - */ + /** The status of placing a bid. */ enum PlaceBidStatus { - /** - * The bid was accepted, and is the current highest bid. - */ + /** The bid was accepted, and is the current highest bid. */ ACCEPTED(BidResultStatus.ACCEPTED), - /** - * The bid was accepted, but was outbidded by the maximum bid of the current highest bidder. - */ + /** The bid was accepted, but was outbidded by the maximum bid of the current highest bidder. */ ACCEPTED_OUTBID(BidResultStatus.ACCEPTED_OUTBID), - /** - * The bid was accepted, but is below the reserve. - */ + /** The bid was accepted, but is below the reserve. */ ACCEPTED_BELOW_RESERVE(BidResultStatus.ACCEPTED_BELOW_RESERVE), - /** - * The bid was not at least the current bid plus the increment. - */ + /** The bid was not at least the current bid plus the increment. */ TOO_LOW(BidResultStatus.TOO_LOW), - /** - * The auction hasn't started. - */ + /** The auction hasn't started. */ NOT_STARTED(BidResultStatus.NOT_STARTED), - /** - * The auction has already finished. - */ + /** The auction has already finished. */ FINISHED(BidResultStatus.FINISHED), - /** - * The auction has been cancelled. - */ + /** The auction has been cancelled. */ CANCELLED(BidResultStatus.CANCELLED); public final BidResultStatus bidResultStatus; @@ -152,22 +125,14 @@ public interface AuctionCommand { } } - /** - * The result of placing a bid. - */ + /** The result of placing a bid. */ final class PlaceBidResult implements PlaceBidReply { - /** - * The current price of the auction. - */ + /** The current price of the auction. */ private final int currentPrice; - /** - * The status of the attempt to place a bid. - */ + /** The status of the attempt to place a bid. */ private final PlaceBidStatus status; - /** - * The current winning bidder. - */ + /** The current winning bidder. */ private final UUID currentBidder; public PlaceBidResult(PlaceBidStatus status, int currentPrice, UUID currentBidder) { @@ -201,9 +166,7 @@ public interface AuctionCommand { } } - /** - * Finish bidding. - */ + /** Finish bidding. */ final class FinishBidding implements AuctionCommand, ExpectingReply { private final ActorRef replyTo; @@ -218,9 +181,7 @@ public interface AuctionCommand { } } - /** - * Get the auction. - */ + /** Get the auction. */ final class GetAuction implements AuctionCommand, ExpectingReply { private final ActorRef replyTo; diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionEntity.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionEntity.java index d6a9e2912b..fc29be7b09 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionEntity.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionEntity.java @@ -22,9 +22,11 @@ import java.util.Optional; import java.util.UUID; /** - * Based on https://github.com/lagom/online-auction-java/blob/master/bidding-impl/src/main/java/com/example/auction/bidding/impl/AuctionEntity.java + * Based on + * https://github.com/lagom/online-auction-java/blob/master/bidding-impl/src/main/java/com/example/auction/bidding/impl/AuctionEntity.java */ -public class AuctionEntity extends EventSourcedBehavior { +public class AuctionEntity + extends EventSourcedBehavior { private final UUID entityUUID; @@ -35,64 +37,79 @@ public class AuctionEntity extends EventSourcedBehavior notStartedHandler = - commandHandlerBuilder(state -> state.getStatus() == AuctionStatus.NOT_STARTED) - .matchCommand(StartAuction.class, this::startAuction) - .matchCommand(PlaceBid.class, (state, cmd) -> Effect().reply(cmd, createResult(state, PlaceBidStatus.NOT_STARTED))); + private CommandHandlerBuilder + notStartedHandler = + commandHandlerBuilder(state -> state.getStatus() == AuctionStatus.NOT_STARTED) + .matchCommand(StartAuction.class, this::startAuction) + .matchCommand( + PlaceBid.class, + (state, cmd) -> + Effect().reply(cmd, createResult(state, PlaceBidStatus.NOT_STARTED))); // Command handler for the under auction state. - private CommandHandlerBuilder underAuctionHandler = - commandHandlerBuilder(state -> state.getStatus() == AuctionStatus.UNDER_AUCTION) - .matchCommand(StartAuction.class, (state, cmd) -> alreadyDone(cmd)) - .matchCommand(PlaceBid.class, this::placeBid) - .matchCommand(FinishBidding.class, this::finishBidding); + private CommandHandlerBuilder + underAuctionHandler = + commandHandlerBuilder(state -> state.getStatus() == AuctionStatus.UNDER_AUCTION) + .matchCommand(StartAuction.class, (state, cmd) -> alreadyDone(cmd)) + .matchCommand(PlaceBid.class, this::placeBid) + .matchCommand(FinishBidding.class, this::finishBidding); // Command handler for the completed state. - private CommandHandlerBuilder completedHandler = - commandHandlerBuilder(state -> state.getStatus() == AuctionStatus.COMPLETE) - .matchCommand(StartAuction.class, (state, cmd) -> alreadyDone(cmd)) - .matchCommand(FinishBidding.class, (state, cmd) -> alreadyDone(cmd)) - .matchCommand(PlaceBid.class, (state, cmd) -> Effect().reply(cmd, createResult(state, PlaceBidStatus.FINISHED))); + private CommandHandlerBuilder + completedHandler = + commandHandlerBuilder(state -> state.getStatus() == AuctionStatus.COMPLETE) + .matchCommand(StartAuction.class, (state, cmd) -> alreadyDone(cmd)) + .matchCommand(FinishBidding.class, (state, cmd) -> alreadyDone(cmd)) + .matchCommand( + PlaceBid.class, + (state, cmd) -> + Effect().reply(cmd, createResult(state, PlaceBidStatus.FINISHED))); // Command handler for the cancelled state. - private CommandHandlerBuilder cancelledHandler = - commandHandlerBuilder(state -> state.getStatus() == AuctionStatus.CANCELLED) - .matchCommand(StartAuction.class, (state, cmd) -> alreadyDone(cmd)) - .matchCommand(FinishBidding.class, (state, cmd) -> alreadyDone(cmd)) - .matchCommand(CancelAuction.class, (state, cmd) -> alreadyDone(cmd)) - .matchCommand(PlaceBid.class, (state, cmd) -> Effect().reply(cmd, createResult(state, PlaceBidStatus.CANCELLED))); + private CommandHandlerBuilder + cancelledHandler = + commandHandlerBuilder(state -> state.getStatus() == AuctionStatus.CANCELLED) + .matchCommand(StartAuction.class, (state, cmd) -> alreadyDone(cmd)) + .matchCommand(FinishBidding.class, (state, cmd) -> alreadyDone(cmd)) + .matchCommand(CancelAuction.class, (state, cmd) -> alreadyDone(cmd)) + .matchCommand( + PlaceBid.class, + (state, cmd) -> + Effect().reply(cmd, createResult(state, PlaceBidStatus.CANCELLED))); - private CommandHandlerBuilder getAuctionHandler = - commandHandlerBuilder(AuctionState.class) - .matchCommand(GetAuction.class, (state, cmd) -> Effect().reply(cmd, state)); + private CommandHandlerBuilder + getAuctionHandler = + commandHandlerBuilder(AuctionState.class) + .matchCommand(GetAuction.class, (state, cmd) -> Effect().reply(cmd, state)); - private CommandHandlerBuilder cancelHandler = - commandHandlerBuilder(AuctionState.class) - .matchCommand(CancelAuction.class, this::cancelAuction); + private CommandHandlerBuilder + cancelHandler = + commandHandlerBuilder(AuctionState.class) + .matchCommand(CancelAuction.class, this::cancelAuction); // Note, an item can go from completed to cancelled, since it is the item service that controls // whether an auction is cancelled or not. If it cancels before it receives a bidding finished // event from us, it will ignore the bidding finished event, so we need to update our state // to reflect that. - private Effect startAuction(AuctionState state, StartAuction cmd) { - return Effect().persist(new AuctionStarted(entityUUID, cmd.getAuction())) - .thenReply(cmd, __ -> Done.getInstance()); + return Effect() + .persist(new AuctionStarted(entityUUID, cmd.getAuction())) + .thenReply(cmd, __ -> Done.getInstance()); } private Effect finishBidding(AuctionState state, FinishBidding cmd) { - return Effect().persist(new BiddingFinished(entityUUID)) - .thenReply(cmd, __ -> Done.getInstance()); + return Effect() + .persist(new BiddingFinished(entityUUID)) + .thenReply(cmd, __ -> Done.getInstance()); } private Effect cancelAuction(AuctionState state, CancelAuction cmd) { - return Effect().persist(new AuctionCancelled(entityUUID)) - .thenReply(cmd, __ -> Done.getInstance()); + return Effect() + .persist(new AuctionCancelled(entityUUID)) + .thenReply(cmd, __ -> Done.getInstance()); } - /** - * The main logic for handling of bids. - */ + /** The main logic for handling of bids. */ private Effect placeBid(AuctionState state, PlaceBid bid) { Auction auction = state.getAuction().get(); @@ -104,7 +121,8 @@ public class AuctionEntity extends EventSourcedBehavior currentBid = state.lastBid(); @@ -118,66 +136,85 @@ public class AuctionEntity extends EventSourcedBehavior b.getBidder().equals(bid.getBidder())).isPresent(); + boolean bidderIsCurrentBidder = + currentBid.filter(b -> b.getBidder().equals(bid.getBidder())).isPresent(); if (bidderIsCurrentBidder && bid.getBidPrice() >= currentBidPrice) { // Allow the current bidder to update their bid - if (auction.getReservePrice()>currentBidPrice) { + if (auction.getReservePrice() > currentBidPrice) { int newBidPrice = Math.min(auction.getReservePrice(), bid.getBidPrice()); PlaceBidStatus placeBidStatus; if (newBidPrice == auction.getReservePrice()) { placeBidStatus = PlaceBidStatus.ACCEPTED; - } - else { + } else { placeBidStatus = PlaceBidStatus.ACCEPTED_BELOW_RESERVE; } - return Effect().persist(new BidPlaced(entityUUID, - new Bid(bid.getBidder(), now, newBidPrice, bid.getBidPrice()))) - .thenReply(bid, newState -> new PlaceBidResult(placeBidStatus, newBidPrice, bid.getBidder())); + return Effect() + .persist( + new BidPlaced( + entityUUID, new Bid(bid.getBidder(), now, newBidPrice, bid.getBidPrice()))) + .thenReply( + bid, newState -> new PlaceBidResult(placeBidStatus, newBidPrice, bid.getBidder())); } - return Effect().persist(new BidPlaced(entityUUID, - new Bid(bid.getBidder(), now, currentBidPrice, bid.getBidPrice()))) - .thenReply(bid, newState -> new PlaceBidResult(PlaceBidStatus.ACCEPTED, currentBidPrice, bid.getBidder())); + return Effect() + .persist( + new BidPlaced( + entityUUID, new Bid(bid.getBidder(), now, currentBidPrice, bid.getBidPrice()))) + .thenReply( + bid, + newState -> + new PlaceBidResult(PlaceBidStatus.ACCEPTED, currentBidPrice, bid.getBidder())); } if (bid.getBidPrice() < currentBidPrice + auction.getIncrement()) { return Effect().reply(bid, createResult(state, PlaceBidStatus.TOO_LOW)); } else if (bid.getBidPrice() <= currentBidMaximum) { - return handleAutomaticOutbid(bid, auction, now, currentBid, currentBidPrice, currentBidMaximum); + return handleAutomaticOutbid( + bid, auction, now, currentBid, currentBidPrice, currentBidMaximum); } else { return handleNewWinningBidder(bid, auction, now, currentBidMaximum); } } /** - * Handle the situation where a bid will be accepted, but it will be automatically outbid by the current bidder. + * Handle the situation where a bid will be accepted, but it will be automatically outbid by the + * current bidder. * - * This emits two events, one for the bid currently being replace, and another automatic bid for the current bidder. + *

This emits two events, one for the bid currently being replace, and another automatic bid + * for the current bidder. */ private Effect handleAutomaticOutbid( - PlaceBid bid, Auction auction, Instant now, Optional currentBid, int currentBidPrice, int currentBidMaximum) { - // Adjust the bid so that the increment for the current maximum makes the current maximum a valid bid + PlaceBid bid, + Auction auction, + Instant now, + Optional currentBid, + int currentBidPrice, + int currentBidMaximum) { + // Adjust the bid so that the increment for the current maximum makes the current maximum a + // valid bid int adjustedBidPrice = Math.min(bid.getBidPrice(), currentBidMaximum - auction.getIncrement()); int newBidPrice = adjustedBidPrice + auction.getIncrement(); - return Effect().persist(Arrays.asList( - new BidPlaced(entityUUID, - new Bid(bid.getBidder(), now, adjustedBidPrice, bid.getBidPrice()) - ), - new BidPlaced(entityUUID, - new Bid(currentBid.get().getBidder(), now, newBidPrice, currentBidMaximum) - ) - )) - .thenReply(bid, newState -> new PlaceBidResult(PlaceBidStatus.ACCEPTED_OUTBID, newBidPrice, currentBid.get().getBidder())); + return Effect() + .persist( + Arrays.asList( + new BidPlaced( + entityUUID, new Bid(bid.getBidder(), now, adjustedBidPrice, bid.getBidPrice())), + new BidPlaced( + entityUUID, + new Bid(currentBid.get().getBidder(), now, newBidPrice, currentBidMaximum)))) + .thenReply( + bid, + newState -> + new PlaceBidResult( + PlaceBidStatus.ACCEPTED_OUTBID, newBidPrice, currentBid.get().getBidder())); } - /** - * Handle the situation where a bid will be accepted as the new winning bidder. - */ - private Effect handleNewWinningBidder(PlaceBid bid, - Auction auction, Instant now, int currentBidMaximum) { + /** Handle the situation where a bid will be accepted as the new winning bidder. */ + private Effect handleNewWinningBidder( + PlaceBid bid, Auction auction, Instant now, int currentBidMaximum) { int nextIncrement = Math.min(currentBidMaximum + auction.getIncrement(), bid.getBidPrice()); int newBidPrice; if (nextIncrement < auction.getReservePrice()) { @@ -185,19 +222,21 @@ public class AuctionEntity extends EventSourcedBehavior { - PlaceBidStatus status; - if (newBidPrice < auction.getReservePrice()) { - status = PlaceBidStatus.ACCEPTED_BELOW_RESERVE; - } else { - status = PlaceBidStatus.ACCEPTED; - } - return new PlaceBidResult(status, newBidPrice, bid.getBidder()); - }); + return Effect() + .persist( + new BidPlaced( + entityUUID, new Bid(bid.getBidder(), now, newBidPrice, bid.getBidPrice()))) + .thenReply( + bid, + newState -> { + PlaceBidStatus status; + if (newBidPrice < auction.getReservePrice()) { + status = PlaceBidStatus.ACCEPTED_BELOW_RESERVE; + } else { + status = PlaceBidStatus.ACCEPTED; + } + return new PlaceBidResult(status, newBidPrice, bid.getBidder()); + }); } @Override @@ -221,7 +260,8 @@ public class AuctionEntity extends EventSourcedBehavior AuctionState.start(evt.getAuction())) .matchEvent(BidPlaced.class, (state, evt) -> state.bid(evt.getBid())) .matchEvent(BiddingFinished.class, (state, evt) -> state.withStatus(AuctionStatus.COMPLETE)) - .matchEvent(AuctionCancelled.class, (state, evt) -> state.withStatus(AuctionStatus.CANCELLED)) + .matchEvent( + AuctionCancelled.class, (state, evt) -> state.withStatus(AuctionStatus.CANCELLED)) .build(); } diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionEvent.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionEvent.java index 6b12851fe4..a86c1b9dea 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionEvent.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionEvent.java @@ -6,23 +6,15 @@ package jdocs.akka.persistence.typed.auction; import java.util.UUID; -/** - * A persisted auction event. - */ +/** A persisted auction event. */ public interface AuctionEvent { - /** - * The auction started. - */ + /** The auction started. */ final class AuctionStarted implements AuctionEvent { - /** - * The item that the auction started on. - */ + /** The item that the auction started on. */ private final UUID itemId; - /** - * The auction details. - */ + /** The auction details. */ private final Auction auction; public AuctionStarted(UUID itemId, Auction auction) { @@ -39,18 +31,12 @@ public interface AuctionEvent { } } - /** - * A bid was placed. - */ + /** A bid was placed. */ final class BidPlaced implements AuctionEvent { - /** - * The item that the bid was placed on. - */ + /** The item that the bid was placed on. */ private final UUID itemId; - /** - * The bid. - */ + /** The bid. */ private final Bid bid; public BidPlaced(UUID itemId, Bid bid) { @@ -67,14 +53,10 @@ public interface AuctionEvent { } } - /** - * Bidding finished. - */ + /** Bidding finished. */ final class BiddingFinished implements AuctionEvent { - /** - * The item that bidding finished for. - */ + /** The item that bidding finished for. */ private final UUID itemId; public BiddingFinished(UUID itemId) { @@ -86,14 +68,10 @@ public interface AuctionEvent { } } - /** - * The auction was cancelled. - */ + /** The auction was cancelled. */ final class AuctionCancelled implements AuctionEvent { - /** - * The item that the auction was cancelled for. - */ + /** The item that the auction was cancelled for. */ private final UUID itemId; public AuctionCancelled(UUID itemId) { @@ -104,5 +82,4 @@ public interface AuctionEvent { return itemId; } } - } diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionState.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionState.java index 3f28d9e69d..f040e6f188 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionState.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionState.java @@ -9,22 +9,14 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -/** - * The auction state. - */ +/** The auction state. */ public final class AuctionState { - /** - * The auction details. - */ + /** The auction details. */ private final Optional auction; - /** - * The status of the auction. - */ + /** The status of the auction. */ private final AuctionStatus status; - /** - * The bidding history for the auction. - */ + /** The bidding history for the auction. */ private final List biddingHistory; public AuctionState(Optional auction, AuctionStatus status, List biddingHistory) { @@ -38,7 +30,8 @@ public final class AuctionState { } public static AuctionState start(Auction auction) { - return new AuctionState(Optional.of(auction), AuctionStatus.UNDER_AUCTION, Collections.emptyList()); + return new AuctionState( + Optional.of(auction), AuctionStatus.UNDER_AUCTION, Collections.emptyList()); } public AuctionState withStatus(AuctionStatus status) { diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionStatus.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionStatus.java index 11c967f49a..8b9ce2b375 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionStatus.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/AuctionStatus.java @@ -4,24 +4,14 @@ package jdocs.akka.persistence.typed.auction; -/** - * Auction status. - */ +/** Auction status. */ public enum AuctionStatus { - /** - * The auction hasn't started yet (or doesn't exist). - */ + /** The auction hasn't started yet (or doesn't exist). */ NOT_STARTED, - /** - * The item is under auction. - */ + /** The item is under auction. */ UNDER_AUCTION, - /** - * The auction is complete. - */ + /** The auction is complete. */ COMPLETE, - /** - * The auction is cancelled. - */ + /** The auction is cancelled. */ CANCELLED } diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/Bid.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/Bid.java index 97209ec7fe..991fab88eb 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/Bid.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/Bid.java @@ -7,25 +7,15 @@ package jdocs.akka.persistence.typed.auction; import java.time.Instant; import java.util.UUID; -/** - * A bid. - */ +/** A bid. */ public final class Bid { - /** - * The bidder. - */ + /** The bidder. */ private final UUID bidder; - /** - * The time the bid was placed. - */ + /** The time the bid was placed. */ private final Instant bidTime; - /** - * The bid price. - */ + /** The bid price. */ private final int bidPrice; - /** - * The maximum the bidder is willing to bid. - */ + /** The maximum the bidder is willing to bid. */ private final int maximumBid; public Bid(UUID bidder, Instant bidTime, int bidPrice, int maximumBid) { diff --git a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/BidResultStatus.java b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/BidResultStatus.java index fd1fad9df4..c7366b7334 100644 --- a/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/BidResultStatus.java +++ b/akka-persistence-typed/src/test/java/jdocs/akka/persistence/typed/auction/BidResultStatus.java @@ -4,36 +4,20 @@ package jdocs.akka.persistence.typed.auction; -/** - * The status of the result of placing a bid. - */ +/** The status of the result of placing a bid. */ public enum BidResultStatus { - /** - * The bid was accepted, and is the current highest bid. - */ + /** The bid was accepted, and is the current highest bid. */ ACCEPTED, - /** - * The bid was accepted, but was outbidded by the maximum bid of the current highest bidder. - */ + /** The bid was accepted, but was outbidded by the maximum bid of the current highest bidder. */ ACCEPTED_OUTBID, - /** - * The bid was accepted, but is below the reserve. - */ + /** The bid was accepted, but is below the reserve. */ ACCEPTED_BELOW_RESERVE, - /** - * The bid was not at least the current bid plus the increment. - */ + /** The bid was not at least the current bid plus the increment. */ TOO_LOW, - /** - * The auction hasn't started. - */ + /** The auction hasn't started. */ NOT_STARTED, - /** - * The auction has already finished. - */ + /** The auction has already finished. */ FINISHED, - /** - * The auction has been cancelled. - */ + /** The auction has been cancelled. */ CANCELLED } diff --git a/akka-persistence/src/main/java/akka/persistence/fsm/japi/pf/FSMStateFunctionBuilder.java b/akka-persistence/src/main/java/akka/persistence/fsm/japi/pf/FSMStateFunctionBuilder.java index 606d27fa4f..6871d86e63 100644 --- a/akka-persistence/src/main/java/akka/persistence/fsm/japi/pf/FSMStateFunctionBuilder.java +++ b/akka-persistence/src/main/java/akka/persistence/fsm/japi/pf/FSMStateFunctionBuilder.java @@ -18,74 +18,72 @@ import java.util.List; * @param the state type * @param the data type * @param the domain event type - * */ @SuppressWarnings("rawtypes") public class FSMStateFunctionBuilder { private PFBuilder, PersistentFSM.State> builder = - new PFBuilder, PersistentFSM.State>(); + new PFBuilder, PersistentFSM.State>(); /** - * An erased processing of the event matcher. The compile time checks are enforced - * by the public typed versions. + * An erased processing of the event matcher. The compile time checks are enforced by the public + * typed versions. * - * It works like this. + *

It works like this. * - * If eventOrType or dataOrType is a Class, then we do a isInstance check, - * otherwise we do an equals check. The null value compares true for anything. - * If the predicate is null, it is skipped otherwise the predicate has to match - * as well. + *

If eventOrType or dataOrType is a Class, then we do a isInstance check, otherwise we do an + * equals check. The null value compares true for anything. If the predicate is null, it is + * skipped otherwise the predicate has to match as well. * - * @param eventOrType an event or a type to match against - * @param dataOrType a data instance or a type to match against - * @param predicate a predicate to match against - * @param apply an action to apply to the event and state data if there is a match - * @return the builder with the case statement added + * @param eventOrType an event or a type to match against + * @param dataOrType a data instance or a type to match against + * @param predicate a predicate to match against + * @param apply an action to apply to the event and state data if there is a match + * @return the builder with the case statement added */ - private FSMStateFunctionBuilder erasedEvent(final Object eventOrType, - final Object dataOrType, - final FI.TypedPredicate2 predicate, - final FI.Apply2 apply) { - builder.match(PersistentFSM.Event.class, - new FI.TypedPredicate() { - @Override - public boolean defined(PersistentFSM.Event e) { - boolean res = true; - if (eventOrType != null) { - if (eventOrType instanceof Class) { - Class eventType = (Class) eventOrType; - res = eventType.isInstance(e.event()); + private FSMStateFunctionBuilder erasedEvent( + final Object eventOrType, + final Object dataOrType, + final FI.TypedPredicate2 predicate, + final FI.Apply2 apply) { + builder.match( + PersistentFSM.Event.class, + new FI.TypedPredicate() { + @Override + public boolean defined(PersistentFSM.Event e) { + boolean res = true; + if (eventOrType != null) { + if (eventOrType instanceof Class) { + Class eventType = (Class) eventOrType; + res = eventType.isInstance(e.event()); + } else { + res = eventOrType.equals(e.event()); + } } - else { - res = eventOrType.equals(e.event()); + if (res && dataOrType != null) { + if (dataOrType instanceof Class) { + Class dataType = (Class) dataOrType; + res = dataType.isInstance(e.stateData()); + } else { + res = dataOrType.equals(e.stateData()); + } } + if (res && predicate != null) { + @SuppressWarnings("unchecked") + boolean ures = predicate.defined(e.event(), e.stateData()); + res = ures; + } + return res; } - if (res && dataOrType != null) { - if (dataOrType instanceof Class) { - Class dataType = (Class) dataOrType; - res = dataType.isInstance(e.stateData()); - } - else { - res = dataOrType.equals(e.stateData()); - } - } - if (res && predicate != null) { + }, + new FI.Apply>() { + public PersistentFSM.State apply(PersistentFSM.Event e) throws Exception { @SuppressWarnings("unchecked") - boolean ures = predicate.defined(e.event(), e.stateData()); - res = ures; + PersistentFSM.State res = + (PersistentFSM.State) apply.apply(e.event(), e.stateData()); + return res; } - return res; - } - }, - new FI.Apply>() { - public PersistentFSM.State apply(PersistentFSM.Event e) throws Exception { - @SuppressWarnings("unchecked") - PersistentFSM.State res = (PersistentFSM.State) apply.apply(e.event(), e.stateData()); - return res; - } - } - ); + }); return this; } @@ -93,18 +91,19 @@ public class FSMStateFunctionBuilder { /** * Add a case statement that matches on an event and data type and a predicate. * - * @param eventType the event type to match on - * @param dataType the data type to match on - * @param predicate a predicate to evaluate on the matched types - * @param apply an action to apply to the event and state data if there is a match - * @param

the event type to match on - * @param the data type to match on + * @param eventType the event type to match on + * @param dataType the data type to match on + * @param predicate a predicate to evaluate on the matched types + * @param apply an action to apply to the event and state data if there is a match + * @param

the event type to match on + * @param the data type to match on * @return the builder with the case statement added */ - public final FSMStateFunctionBuilder event(final Class

eventType, - final Class dataType, - final FI.TypedPredicate2 predicate, - final FI.Apply2> apply) { + public final FSMStateFunctionBuilder event( + final Class

eventType, + final Class dataType, + final FI.TypedPredicate2 predicate, + final FI.Apply2> apply) { erasedEvent(eventType, dataType, predicate, apply); return this; } @@ -112,159 +111,164 @@ public class FSMStateFunctionBuilder { /** * Add a case statement that matches on an event and data type. * - * @param eventType the event type to match on - * @param dataType the data type to match on - * @param apply an action to apply to the event and state data if there is a match - * @param

the event type to match on - * @param the data type to match on + * @param eventType the event type to match on + * @param dataType the data type to match on + * @param apply an action to apply to the event and state data if there is a match + * @param

the event type to match on + * @param the data type to match on * @return the builder with the case statement added */ - public FSMStateFunctionBuilder event(final Class

eventType, - final Class dataType, - final FI.Apply2> apply) { + public FSMStateFunctionBuilder event( + final Class

eventType, + final Class dataType, + final FI.Apply2> apply) { return erasedEvent(eventType, dataType, null, apply); } /** * Add a case statement that matches if the event type and predicate matches. * - * @param eventType the event type to match on - * @param predicate a predicate that will be evaluated on the data and the event - * @param apply an action to apply to the event and state data if there is a match + * @param eventType the event type to match on + * @param predicate a predicate that will be evaluated on the data and the event + * @param apply an action to apply to the event and state data if there is a match * @return the builder with the case statement added */ - public

FSMStateFunctionBuilder event(final Class

eventType, - final FI.TypedPredicate2 predicate, - final FI.Apply2> apply) { + public

FSMStateFunctionBuilder event( + final Class

eventType, + final FI.TypedPredicate2 predicate, + final FI.Apply2> apply) { return erasedEvent(eventType, null, predicate, apply); } /** * Add a case statement that matches if the event type and predicate matches. * - * @param eventType the event type to match on - * @param apply an action to apply to the event and state data if there is a match + * @param eventType the event type to match on + * @param apply an action to apply to the event and state data if there is a match * @return the builder with the case statement added */ - public

FSMStateFunctionBuilder event(final Class

eventType, - final FI.Apply2> apply) { + public

FSMStateFunctionBuilder event( + final Class

eventType, final FI.Apply2> apply) { return erasedEvent(eventType, null, null, apply); } /** * Add a case statement that matches if the predicate matches. * - * @param predicate a predicate that will be evaluated on the data and the event - * @param apply an action to apply to the event and state data if there is a match + * @param predicate a predicate that will be evaluated on the data and the event + * @param apply an action to apply to the event and state data if there is a match * @return the builder with the case statement added */ - public FSMStateFunctionBuilder event(final FI.TypedPredicate2 predicate, - final FI.Apply2> apply) { + public FSMStateFunctionBuilder event( + final FI.TypedPredicate2 predicate, + final FI.Apply2> apply) { return erasedEvent(null, null, predicate, apply); } /** - * Add a case statement that matches on the data type and if any of the event types - * in the list match or any of the event instances in the list compares equal. + * Add a case statement that matches on the data type and if any of the event types in the list + * match or any of the event instances in the list compares equal. * - * @param eventMatches a list of types or instances to match against - * @param dataType the data type to match on - * @param apply an action to apply to the event and state data if there is a match - * @param the data type to match on + * @param eventMatches a list of types or instances to match against + * @param dataType the data type to match on + * @param apply an action to apply to the event and state data if there is a match + * @param the data type to match on * @return the builder with the case statement added */ - public FSMStateFunctionBuilder event(final List eventMatches, - final Class dataType, - final FI.Apply2> apply) { - builder.match(PersistentFSM.Event.class, - new FI.TypedPredicate() { - @Override - public boolean defined(PersistentFSM.Event e) { - if (dataType != null && !dataType.isInstance(e.stateData())) - return false; + public FSMStateFunctionBuilder event( + final List eventMatches, + final Class dataType, + final FI.Apply2> apply) { + builder.match( + PersistentFSM.Event.class, + new FI.TypedPredicate() { + @Override + public boolean defined(PersistentFSM.Event e) { + if (dataType != null && !dataType.isInstance(e.stateData())) return false; - boolean emMatch = false; - Object event = e.event(); - for (Object em : eventMatches) { - if (em instanceof Class) { - Class emc = (Class) em; - emMatch = emc.isInstance(event); - } else { - emMatch = event.equals(em); + boolean emMatch = false; + Object event = e.event(); + for (Object em : eventMatches) { + if (em instanceof Class) { + Class emc = (Class) em; + emMatch = emc.isInstance(event); + } else { + emMatch = event.equals(em); + } + if (emMatch) break; } - if (emMatch) - break; + return emMatch; } - return emMatch; - } - }, - new FI.Apply>() { - public PersistentFSM.State apply(PersistentFSM.Event e) throws Exception { - @SuppressWarnings("unchecked") - Q q = (Q) e.stateData(); - return apply.apply(e.event(), q); - } - } - ); + }, + new FI.Apply>() { + public PersistentFSM.State apply(PersistentFSM.Event e) throws Exception { + @SuppressWarnings("unchecked") + Q q = (Q) e.stateData(); + return apply.apply(e.event(), q); + } + }); return this; } /** - * Add a case statement that matches if any of the event types in the list match or - * any of the event instances in the list compares equal. + * Add a case statement that matches if any of the event types in the list match or any of the + * event instances in the list compares equal. * - * @param eventMatches a list of types or instances to match against - * @param apply an action to apply to the event and state data if there is a match + * @param eventMatches a list of types or instances to match against + * @param apply an action to apply to the event and state data if there is a match * @return the builder with the case statement added */ - public FSMStateFunctionBuilder event(final List eventMatches, - final FI.Apply2> apply) { + public FSMStateFunctionBuilder event( + final List eventMatches, + final FI.Apply2> apply) { return event(eventMatches, null, apply); } /** * Add a case statement that matches on the data type and if the event compares equal. * - * @param event an event to compare equal against - * @param dataType the data type to match on - * @param apply an action to apply to the event and state data if there is a match - * @param the data type to match on + * @param event an event to compare equal against + * @param dataType the data type to match on + * @param apply an action to apply to the event and state data if there is a match + * @param the data type to match on * @return the builder with the case statement added */ - public FSMStateFunctionBuilder eventEquals(final P event, - final Class dataType, - final FI.Apply2> apply) { + public FSMStateFunctionBuilder eventEquals( + final P event, + final Class dataType, + final FI.Apply2> apply) { return erasedEvent(event, dataType, null, apply); } /** * Add a case statement that matches if event compares equal. * - * @param event an event to compare equal against - * @param apply an action to apply to the event and state data if there is a match + * @param event an event to compare equal against + * @param apply an action to apply to the event and state data if there is a match * @return the builder with the case statement added */ - public

FSMStateFunctionBuilder eventEquals(final P event, - final FI.Apply2> apply) { + public

FSMStateFunctionBuilder eventEquals( + final P event, final FI.Apply2> apply) { return erasedEvent(event, null, null, apply); } /** * Add a case statement that matches on any type of event. * - * @param apply an action to apply to the event and state data + * @param apply an action to apply to the event and state data * @return the builder with the case statement added */ - public FSMStateFunctionBuilder anyEvent(final FI.Apply2> apply) { + public FSMStateFunctionBuilder anyEvent( + final FI.Apply2> apply) { return erasedEvent(null, null, null, apply); } /** - * Build a {@link scala.PartialFunction} from this builder. - * After this call the builder will be reset. + * Build a {@link scala.PartialFunction} from this builder. After this call the builder will be + * reset. * - * @return a PartialFunction for this builder. + * @return a PartialFunction for this builder. */ public PartialFunction, PersistentFSM.State> build() { return builder.build(); diff --git a/akka-persistence/src/main/java/akka/persistence/fsm/japi/pf/FSMStopBuilder.java b/akka-persistence/src/main/java/akka/persistence/fsm/japi/pf/FSMStopBuilder.java index 27b77c1b53..917ba56246 100644 --- a/akka-persistence/src/main/java/akka/persistence/fsm/japi/pf/FSMStopBuilder.java +++ b/akka-persistence/src/main/java/akka/persistence/fsm/japi/pf/FSMStopBuilder.java @@ -16,39 +16,37 @@ import scala.runtime.BoxedUnit; * * @param the state type * @param the data type - * */ public class FSMStopBuilder { - private UnitPFBuilder> builder = - new UnitPFBuilder<>(); + private UnitPFBuilder> builder = new UnitPFBuilder<>(); /** * Add a case statement that matches on an {@link akka.actor.FSM.Reason}. * - * @param reason the reason for the termination - * @param apply an action to apply to the event and state data if there is a match + * @param reason the reason for the termination + * @param apply an action to apply to the event and state data if there is a match * @return the builder with the case statement added */ - public FSMStopBuilder stop(final PersistentFSM.Reason reason, - final FI.UnitApply2 apply) { - builder.match(PersistentFSM.StopEvent.class, - new FI.TypedPredicate() { - @Override - public boolean defined(PersistentFSM.StopEvent e) { - return reason.equals(e.reason()); - } - }, - new FI.UnitApply() { - public void apply(PersistentFSM.StopEvent e) throws Exception { - @SuppressWarnings("unchecked") - S s = (S) e.currentState(); - @SuppressWarnings("unchecked") - D d = (D) e.stateData(); - apply.apply(s, d); - } - } - ); + public FSMStopBuilder stop( + final PersistentFSM.Reason reason, final FI.UnitApply2 apply) { + builder.match( + PersistentFSM.StopEvent.class, + new FI.TypedPredicate() { + @Override + public boolean defined(PersistentFSM.StopEvent e) { + return reason.equals(e.reason()); + } + }, + new FI.UnitApply() { + public void apply(PersistentFSM.StopEvent e) throws Exception { + @SuppressWarnings("unchecked") + S s = (S) e.currentState(); + @SuppressWarnings("unchecked") + D d = (D) e.stateData(); + apply.apply(s, d); + } + }); return this; } @@ -56,68 +54,71 @@ public class FSMStopBuilder { /** * Add a case statement that matches on a reason type. * - * @param reasonType the reason type to match on - * @param apply an action to apply to the reason, event and state data if there is a match - * @param

the reason type to match on + * @param reasonType the reason type to match on + * @param apply an action to apply to the reason, event and state data if there is a match + * @param

the reason type to match on * @return the builder with the case statement added */ - public

FSMStopBuilder stop(final Class

reasonType, - final FI.UnitApply3 apply) { - return this.stop(reasonType, - new FI.TypedPredicate

() { - @Override - public boolean defined(P p) { - return true; - } - }, apply); + public

FSMStopBuilder stop( + final Class

reasonType, final FI.UnitApply3 apply) { + return this.stop( + reasonType, + new FI.TypedPredicate

() { + @Override + public boolean defined(P p) { + return true; + } + }, + apply); } /** * Add a case statement that matches on a reason type and a predicate. * - * @param reasonType the reason type to match on - * @param apply an action to apply to the reason, event and state data if there is a match - * @param predicate a predicate that will be evaluated on the reason if the type matches - * @param

the reason type to match on + * @param reasonType the reason type to match on + * @param apply an action to apply to the reason, event and state data if there is a match + * @param predicate a predicate that will be evaluated on the reason if the type matches + * @param

the reason type to match on * @return the builder with the case statement added */ - public

FSMStopBuilder stop(final Class

reasonType, - final FI.TypedPredicate

predicate, - final FI.UnitApply3 apply) { - builder.match(PersistentFSM.StopEvent.class, - new FI.TypedPredicate() { - @Override - public boolean defined(PersistentFSM.StopEvent e) { - if (reasonType.isInstance(e.reason())) { + public

FSMStopBuilder stop( + final Class

reasonType, + final FI.TypedPredicate

predicate, + final FI.UnitApply3 apply) { + builder.match( + PersistentFSM.StopEvent.class, + new FI.TypedPredicate() { + @Override + public boolean defined(PersistentFSM.StopEvent e) { + if (reasonType.isInstance(e.reason())) { + @SuppressWarnings("unchecked") + P p = (P) e.reason(); + return predicate.defined(p); + } else { + return false; + } + } + }, + new FI.UnitApply() { + public void apply(PersistentFSM.StopEvent e) throws Exception { @SuppressWarnings("unchecked") P p = (P) e.reason(); - return predicate.defined(p); - } else { - return false; + @SuppressWarnings("unchecked") + S s = (S) e.currentState(); + @SuppressWarnings("unchecked") + D d = (D) e.stateData(); + apply.apply(p, s, d); } - } - }, - new FI.UnitApply() { - public void apply(PersistentFSM.StopEvent e) throws Exception { - @SuppressWarnings("unchecked") - P p = (P) e.reason(); - @SuppressWarnings("unchecked") - S s = (S) e.currentState(); - @SuppressWarnings("unchecked") - D d = (D) e.stateData(); - apply.apply(p, s, d); - } - } - ); + }); return this; } /** - * Build a {@link scala.PartialFunction} from this builder. - * After this call the builder will be reset. + * Build a {@link scala.PartialFunction} from this builder. After this call the builder will be + * reset. * - * @return a PartialFunction for this builder. + * @return a PartialFunction for this builder. */ public PartialFunction, BoxedUnit> build() { return builder.build(); diff --git a/akka-persistence/src/main/java/akka/persistence/journal/japi/AsyncRecoveryPlugin.java b/akka-persistence/src/main/java/akka/persistence/journal/japi/AsyncRecoveryPlugin.java index a0ea383fae..2fa08a7b6b 100644 --- a/akka-persistence/src/main/java/akka/persistence/journal/japi/AsyncRecoveryPlugin.java +++ b/akka-persistence/src/main/java/akka/persistence/journal/japi/AsyncRecoveryPlugin.java @@ -11,49 +11,43 @@ import scala.concurrent.Future; import akka.persistence.PersistentRepr; interface AsyncRecoveryPlugin { - //#async-replay-plugin-api + // #async-replay-plugin-api /** - * Java API, Plugin API: asynchronously replays persistent messages. - * Implementations replay a message by calling `replayCallback`. The returned - * future must be completed when all messages (matching the sequence number - * bounds) have been replayed. The future must be completed with a failure if - * any of the persistent messages could not be replayed. + * Java API, Plugin API: asynchronously replays persistent messages. Implementations replay a + * message by calling `replayCallback`. The returned future must be completed when all messages + * (matching the sequence number bounds) have been replayed. The future must be completed with a + * failure if any of the persistent messages could not be replayed. * - * The `replayCallback` must also be called with messages that have been - * marked as deleted. In this case a replayed message's `deleted` method must - * return `true`. + *

The `replayCallback` must also be called with messages that have been marked as deleted. In + * this case a replayed message's `deleted` method must return `true`. * - * The `toSequenceNr` is the lowest of what was returned by - * {@link #doAsyncReadHighestSequenceNr} and what the user specified as - * recovery {@link akka.persistence.Recovery} parameter. + *

The `toSequenceNr` is the lowest of what was returned by {@link + * #doAsyncReadHighestSequenceNr} and what the user specified as recovery {@link + * akka.persistence.Recovery} parameter. * - * @param persistenceId - * id of the persistent actor. - * @param fromSequenceNr - * sequence number where replay should start (inclusive). - * @param toSequenceNr - * sequence number where replay should end (inclusive). - * @param max - * maximum number of messages to be replayed. - * @param replayCallback - * called to replay a single message. Can be called from any thread. + * @param persistenceId id of the persistent actor. + * @param fromSequenceNr sequence number where replay should start (inclusive). + * @param toSequenceNr sequence number where replay should end (inclusive). + * @param max maximum number of messages to be replayed. + * @param replayCallback called to replay a single message. Can be called from any thread. */ - Future doAsyncReplayMessages(String persistenceId, long fromSequenceNr, - long toSequenceNr, long max, Consumer replayCallback); + Future doAsyncReplayMessages( + String persistenceId, + long fromSequenceNr, + long toSequenceNr, + long max, + Consumer replayCallback); /** - * Java API, Plugin API: asynchronously reads the highest stored sequence - * number for the given `persistenceId`. The persistent actor will use the - * highest sequence number after recovery as the starting point when - * persisting new events. This sequence number is also used as `toSequenceNr` - * in subsequent call to [[#asyncReplayMessages]] unless the user has - * specified a lower `toSequenceNr`. + * Java API, Plugin API: asynchronously reads the highest stored sequence number for the given + * `persistenceId`. The persistent actor will use the highest sequence number after recovery as + * the starting point when persisting new events. This sequence number is also used as + * `toSequenceNr` in subsequent call to [[#asyncReplayMessages]] unless the user has specified a + * lower `toSequenceNr`. * - * @param persistenceId - * id of the persistent actor. - * @param fromSequenceNr - * hint where to start searching for the highest sequence number. + * @param persistenceId id of the persistent actor. + * @param fromSequenceNr hint where to start searching for the highest sequence number. */ Future doAsyncReadHighestSequenceNr(String persistenceId, long fromSequenceNr); - //#async-replay-plugin-api + // #async-replay-plugin-api } diff --git a/akka-persistence/src/main/java/akka/persistence/journal/japi/AsyncWritePlugin.java b/akka-persistence/src/main/java/akka/persistence/journal/japi/AsyncWritePlugin.java index e0696cf594..abbaaf157e 100644 --- a/akka-persistence/src/main/java/akka/persistence/journal/japi/AsyncWritePlugin.java +++ b/akka-persistence/src/main/java/akka/persistence/journal/japi/AsyncWritePlugin.java @@ -11,77 +11,68 @@ import scala.concurrent.Future; import akka.persistence.*; interface AsyncWritePlugin { - //#async-write-plugin-api + // #async-write-plugin-api /** - * Java API, Plugin API: asynchronously writes a batch (`Iterable`) of - * persistent messages to the journal. + * Java API, Plugin API: asynchronously writes a batch (`Iterable`) of persistent messages to the + * journal. * - * The batch is only for performance reasons, i.e. all messages don't have to - * be written atomically. Higher throughput can typically be achieved by using - * batch inserts of many records compared to inserting records one-by-one, but - * this aspect depends on the underlying data store and a journal - * implementation can implement it as efficient as possible. Journals should - * aim to persist events in-order for a given `persistenceId` as otherwise in - * case of a failure, the persistent state may be end up being inconsistent. - * - * Each `AtomicWrite` message contains the single `PersistentRepr` that - * corresponds to the event that was passed to the `persist` method of the - * `PersistentActor`, or it contains several `PersistentRepr` that corresponds - * to the events that were passed to the `persistAll` method of the - * `PersistentActor`. All `PersistentRepr` of the `AtomicWrite` must be - * written to the data store atomically, i.e. all or none must be stored. If - * the journal (data store) cannot support atomic writes of multiple events it - * should reject such writes with an `Optional` with an - * `UnsupportedOperationException` describing the issue. This limitation - * should also be documented by the journal plugin. + *

The batch is only for performance reasons, i.e. all messages don't have to be written + * atomically. Higher throughput can typically be achieved by using batch inserts of many records + * compared to inserting records one-by-one, but this aspect depends on the underlying data store + * and a journal implementation can implement it as efficient as possible. Journals should aim to + * persist events in-order for a given `persistenceId` as otherwise in case of a failure, the + * persistent state may be end up being inconsistent. * - * If there are failures when storing any of the messages in the batch the - * returned `Future` must be completed with failure. The `Future` must only be - * completed with success when all messages in the batch have been confirmed - * to be stored successfully, i.e. they will be readable, and visible, in a - * subsequent replay. If there is uncertainty about if the messages were - * stored or not the `Future` must be completed with failure. + *

Each `AtomicWrite` message contains the single `PersistentRepr` that corresponds to the + * event that was passed to the `persist` method of the `PersistentActor`, or it contains several + * `PersistentRepr` that corresponds to the events that were passed to the `persistAll` method of + * the `PersistentActor`. All `PersistentRepr` of the `AtomicWrite` must be written to the data + * store atomically, i.e. all or none must be stored. If the journal (data store) cannot support + * atomic writes of multiple events it should reject such writes with an `Optional` with an + * `UnsupportedOperationException` describing the issue. This limitation should also be documented + * by the journal plugin. * - * Data store connection problems must be signaled by completing the `Future` - * with failure. + *

If there are failures when storing any of the messages in the batch the returned `Future` + * must be completed with failure. The `Future` must only be completed with success when all + * messages in the batch have been confirmed to be stored successfully, i.e. they will be + * readable, and visible, in a subsequent replay. If there is uncertainty about if the messages + * were stored or not the `Future` must be completed with failure. * - * The journal can also signal that it rejects individual messages - * (`AtomicWrite`) by the returned - * `Iterable<Optional<Exception>>`. The returned `Iterable` must - * have as many elements as the input `messages` `Iterable`. Each `Optional` - * element signals if the corresponding `AtomicWrite` is rejected or not, with - * an exception describing the problem. Rejecting a message means it was not - * stored, i.e. it must not be included in a later replay. Rejecting a message - * is typically done before attempting to store it, e.g. because of + *

Data store connection problems must be signaled by completing the `Future` with failure. + * + *

The journal can also signal that it rejects individual messages (`AtomicWrite`) by the + * returned `Iterable<Optional<Exception>>`. The returned `Iterable` must have as many + * elements as the input `messages` `Iterable`. Each `Optional` element signals if the + * corresponding `AtomicWrite` is rejected or not, with an exception describing the problem. + * Rejecting a message means it was not stored, i.e. it must not be included in a later replay. + * Rejecting a message is typically done before attempting to store it, e.g. because of * serialization error. * - * Data store connection problems must not be signaled as rejections. + *

Data store connection problems must not be signaled as rejections. * - * Note that it is possible to reduce number of allocations by caching some - * result `Iterable` for the happy path, i.e. when no messages are rejected. + *

Note that it is possible to reduce number of allocations by caching some result `Iterable` + * for the happy path, i.e. when no messages are rejected. * - * Calls to this method are serialized by the enclosing journal actor. If you spawn - * work in asynchronous tasks it is alright that they complete the futures in any order, - * but the actual writes for a specific persistenceId should be serialized to avoid - * issues such as events of a later write are visible to consumers (query side, or replay) - * before the events of an earlier write are visible. This can also be done with - * consistent hashing if it is too fine grained to do it on the persistenceId level. - * Normally a `PersistentActor` will only have one outstanding write request to the journal but - * it may emit several write requests when `persistAsync` is used and the max batch size - * is reached. + *

Calls to this method are serialized by the enclosing journal actor. If you spawn work in + * asynchronous tasks it is alright that they complete the futures in any order, but the actual + * writes for a specific persistenceId should be serialized to avoid issues such as events of a + * later write are visible to consumers (query side, or replay) before the events of an earlier + * write are visible. This can also be done with consistent hashing if it is too fine grained to + * do it on the persistenceId level. Normally a `PersistentActor` will only have one outstanding + * write request to the journal but it may emit several write requests when `persistAsync` is used + * and the max batch size is reached. * - * This call is protected with a circuit-breaker. + *

This call is protected with a circuit-breaker. */ Future>> doAsyncWriteMessages(Iterable messages); /** - * Java API, Plugin API: synchronously deletes all persistent messages up to - * `toSequenceNr`. + * Java API, Plugin API: synchronously deletes all persistent messages up to `toSequenceNr`. * - * This call is protected with a circuit-breaker. + *

This call is protected with a circuit-breaker. * * @see AsyncRecoveryPlugin */ Future doAsyncDeleteMessagesTo(String persistenceId, long toSequenceNr); - //#async-write-plugin-api + // #async-write-plugin-api } diff --git a/akka-persistence/src/main/java/akka/persistence/snapshot/japi/SnapshotStorePlugin.java b/akka-persistence/src/main/java/akka/persistence/snapshot/japi/SnapshotStorePlugin.java index b08f571f6d..9cc9938889 100644 --- a/akka-persistence/src/main/java/akka/persistence/snapshot/japi/SnapshotStorePlugin.java +++ b/akka-persistence/src/main/java/akka/persistence/snapshot/japi/SnapshotStorePlugin.java @@ -12,44 +12,37 @@ import scala.concurrent.Future; import java.util.Optional; interface SnapshotStorePlugin { - //#snapshot-store-plugin-api + // #snapshot-store-plugin-api /** * Java API, Plugin API: asynchronously loads a snapshot. * - * @param persistenceId - * id of the persistent actor. - * @param criteria - * selection criteria for loading. + * @param persistenceId id of the persistent actor. + * @param criteria selection criteria for loading. */ - Future> doLoadAsync(String persistenceId, - SnapshotSelectionCriteria criteria); + Future> doLoadAsync( + String persistenceId, SnapshotSelectionCriteria criteria); /** * Java API, Plugin API: asynchronously saves a snapshot. * - * @param metadata - * snapshot metadata. - * @param snapshot - * snapshot. + * @param metadata snapshot metadata. + * @param snapshot snapshot. */ Future doSaveAsync(SnapshotMetadata metadata, Object snapshot); /** * Java API, Plugin API: deletes the snapshot identified by `metadata`. * - * @param metadata - * snapshot metadata. + * @param metadata snapshot metadata. */ Future doDeleteAsync(SnapshotMetadata metadata); /** * Java API, Plugin API: deletes all snapshots matching `criteria`. * - * @param persistenceId - * id of the persistent actor. - * @param criteria - * selection criteria for deleting. + * @param persistenceId id of the persistent actor. + * @param criteria selection criteria for deleting. */ Future doDeleteAsync(String persistenceId, SnapshotSelectionCriteria criteria); - //#snapshot-store-plugin-api + // #snapshot-store-plugin-api } diff --git a/akka-persistence/src/test/java/akka/persistence/fsm/AbstractPersistentFSMTest.java b/akka-persistence/src/test/java/akka/persistence/fsm/AbstractPersistentFSMTest.java index e32e32622b..7cc77580ee 100644 --- a/akka-persistence/src/test/java/akka/persistence/fsm/AbstractPersistentFSMTest.java +++ b/akka-persistence/src/test/java/akka/persistence/fsm/AbstractPersistentFSMTest.java @@ -44,602 +44,669 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class AbstractPersistentFSMTest extends JUnitSuite { - private static Option none = Option.none(); + private static Option none = Option.none(); - @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("PersistentFSMJavaTest", PersistenceSpec.config( - "leveldb", "AbstractPersistentFSMTest", "off", none.asScala())); + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource( + "PersistentFSMJavaTest", + PersistenceSpec.config("leveldb", "AbstractPersistentFSMTest", "off", none.asScala())); - private final ActorSystem system = actorSystemResource.getSystem(); + private final ActorSystem system = actorSystemResource.getSystem(); - //Dummy report actor, for tests that don't need it - private final ActorRef dummyReportActorRef = new TestProbe(system).ref(); + // Dummy report actor, for tests that don't need it + private final ActorRef dummyReportActorRef = new TestProbe(system).ref(); - @Test - public void fsmFunctionalTest() throws Exception { - new TestKit(system) {{ - String persistenceId = generateId(); - ActorRef fsmRef = system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); + @Test + public void fsmFunctionalTest() throws Exception { + new TestKit(system) { + { + String persistenceId = generateId(); + ActorRef fsmRef = + system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); - watch(fsmRef); - fsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); + watch(fsmRef); + fsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); - Item shirt = new Item("1", "Shirt", 19.99F); - Item shoes = new Item("2", "Shoes", 18.99F); - Item coat = new Item("3", "Coat", 119.99F); + Item shirt = new Item("1", "Shirt", 19.99F); + Item shoes = new Item("2", "Shoes", 18.99F); + Item coat = new Item("3", "Coat", 119.99F); - fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); - fsmRef.tell(new AddItem(shirt), getRef()); - fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); - fsmRef.tell(new AddItem(shoes), getRef()); - fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); - fsmRef.tell(new AddItem(coat), getRef()); - fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); - fsmRef.tell(Buy.INSTANCE, getRef()); - fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); - fsmRef.tell(Leave.INSTANCE, getRef()); + fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); + fsmRef.tell(new AddItem(shirt), getRef()); + fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); + fsmRef.tell(new AddItem(shoes), getRef()); + fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); + fsmRef.tell(new AddItem(coat), getRef()); + fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); + fsmRef.tell(Buy.INSTANCE, getRef()); + fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); + fsmRef.tell(Leave.INSTANCE, getRef()); - CurrentState currentState = expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); - assertEquals(currentState.state(), UserState.LOOKING_AROUND); + CurrentState currentState = + expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); + assertEquals(currentState.state(), UserState.LOOKING_AROUND); - ShoppingCart shoppingCart = expectMsgClass(ShoppingCart.class); - assertTrue(shoppingCart.getItems().isEmpty()); + ShoppingCart shoppingCart = expectMsgClass(ShoppingCart.class); + assertTrue(shoppingCart.getItems().isEmpty()); - PersistentFSM.Transition stateTransition = expectMsgClass(PersistentFSM.Transition.class); - assertTransition(stateTransition, fsmRef, UserState.LOOKING_AROUND, UserState.SHOPPING); + PersistentFSM.Transition stateTransition = expectMsgClass(PersistentFSM.Transition.class); + assertTransition(stateTransition, fsmRef, UserState.LOOKING_AROUND, UserState.SHOPPING); - shoppingCart = expectMsgClass(ShoppingCart.class); - assertThat(shoppingCart.getItems(), hasItems(shirt)); + shoppingCart = expectMsgClass(ShoppingCart.class); + assertThat(shoppingCart.getItems(), hasItems(shirt)); - shoppingCart = expectMsgClass(ShoppingCart.class); - assertThat(shoppingCart.getItems(), hasItems(shirt, shoes)); + shoppingCart = expectMsgClass(ShoppingCart.class); + assertThat(shoppingCart.getItems(), hasItems(shirt, shoes)); - shoppingCart = expectMsgClass(ShoppingCart.class); - assertThat(shoppingCart.getItems(), hasItems(shirt, shoes, coat)); + shoppingCart = expectMsgClass(ShoppingCart.class); + assertThat(shoppingCart.getItems(), hasItems(shirt, shoes, coat)); - stateTransition = expectMsgClass(PersistentFSM.Transition.class); - assertTransition(stateTransition, fsmRef, UserState.SHOPPING, UserState.PAID); + stateTransition = expectMsgClass(PersistentFSM.Transition.class); + assertTransition(stateTransition, fsmRef, UserState.SHOPPING, UserState.PAID); - shoppingCart = expectMsgClass(ShoppingCart.class); - assertThat(shoppingCart.getItems(), hasItems(shirt, shoes, coat)); + shoppingCart = expectMsgClass(ShoppingCart.class); + assertThat(shoppingCart.getItems(), hasItems(shirt, shoes, coat)); - Terminated terminated = expectMsgClass(Terminated.class); - assertEquals(fsmRef, terminated.getActor()); - }}; - } + Terminated terminated = expectMsgClass(Terminated.class); + assertEquals(fsmRef, terminated.getActor()); + } + }; + } - @Test - public void fsmTimeoutTest() throws Exception { - new TestKit(system) {{ - String persistenceId = generateId(); - ActorRef fsmRef = system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); + @Test + public void fsmTimeoutTest() throws Exception { + new TestKit(system) { + { + String persistenceId = generateId(); + ActorRef fsmRef = + system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); - watch(fsmRef); - fsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); + watch(fsmRef); + fsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); - Item shirt = new Item("1", "Shirt", 29.99F); + Item shirt = new Item("1", "Shirt", 29.99F); - fsmRef.tell(new AddItem(shirt), getRef()); + fsmRef.tell(new AddItem(shirt), getRef()); - CurrentState currentState = expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); - assertEquals(currentState.state(), UserState.LOOKING_AROUND); + CurrentState currentState = + expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); + assertEquals(currentState.state(), UserState.LOOKING_AROUND); - PersistentFSM.Transition stateTransition = expectMsgClass(PersistentFSM.Transition.class); - assertTransition(stateTransition, fsmRef, UserState.LOOKING_AROUND, UserState.SHOPPING); + PersistentFSM.Transition stateTransition = expectMsgClass(PersistentFSM.Transition.class); + assertTransition(stateTransition, fsmRef, UserState.LOOKING_AROUND, UserState.SHOPPING); - within(Duration.ofMillis(900), getRemainingOrDefault(), () -> { - PersistentFSM.Transition st = expectMsgClass(PersistentFSM.Transition.class); - assertTransition(st, fsmRef, UserState.SHOPPING, UserState.INACTIVE); - return null; + within( + Duration.ofMillis(900), + getRemainingOrDefault(), + () -> { + PersistentFSM.Transition st = expectMsgClass(PersistentFSM.Transition.class); + assertTransition(st, fsmRef, UserState.SHOPPING, UserState.INACTIVE); + return null; }); - within(Duration.ofMillis(1900), getRemainingOrDefault(), () -> expectTerminated(fsmRef)); - }}; - } + within(Duration.ofMillis(1900), getRemainingOrDefault(), () -> expectTerminated(fsmRef)); + } + }; + } - @Test - public void testSuccessfulRecoveryWithCorrectStateData() { - new TestKit(system) {{ - String persistenceId = generateId(); - ActorRef fsmRef = system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); + @Test + public void testSuccessfulRecoveryWithCorrectStateData() { + new TestKit(system) { + { + String persistenceId = generateId(); + ActorRef fsmRef = + system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); - watch(fsmRef); - fsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); + watch(fsmRef); + fsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); - Item shirt = new Item("1", "Shirt", 38.99F); - Item shoes = new Item("2", "Shoes", 39.99F); - Item coat = new Item("3", "Coat", 139.99F); + Item shirt = new Item("1", "Shirt", 38.99F); + Item shoes = new Item("2", "Shoes", 39.99F); + Item coat = new Item("3", "Coat", 139.99F); - fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); - fsmRef.tell(new AddItem(shirt), getRef()); - fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); - fsmRef.tell(new AddItem(shoes), getRef()); - fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); + fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); + fsmRef.tell(new AddItem(shirt), getRef()); + fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); + fsmRef.tell(new AddItem(shoes), getRef()); + fsmRef.tell(GetCurrentCart.INSTANCE, getRef()); - CurrentState currentState = expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); - assertEquals(currentState.state(), UserState.LOOKING_AROUND); + CurrentState currentState = + expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); + assertEquals(currentState.state(), UserState.LOOKING_AROUND); - ShoppingCart shoppingCart = expectMsgClass(ShoppingCart.class); - assertThat(shoppingCart.getItems(), equalTo(Collections.emptyList())); + ShoppingCart shoppingCart = expectMsgClass(ShoppingCart.class); + assertThat(shoppingCart.getItems(), equalTo(Collections.emptyList())); - PersistentFSM.Transition stateTransition = expectMsgClass(PersistentFSM.Transition.class); - assertTransition(stateTransition, fsmRef, UserState.LOOKING_AROUND, UserState.SHOPPING); + PersistentFSM.Transition stateTransition = expectMsgClass(PersistentFSM.Transition.class); + assertTransition(stateTransition, fsmRef, UserState.LOOKING_AROUND, UserState.SHOPPING); - shoppingCart = expectMsgClass(ShoppingCart.class); - assertThat(shoppingCart.getItems(), hasItems(shirt)); + shoppingCart = expectMsgClass(ShoppingCart.class); + assertThat(shoppingCart.getItems(), hasItems(shirt)); - shoppingCart = expectMsgClass(ShoppingCart.class); - assertThat(shoppingCart.getItems(), hasItems(shirt, shoes)); + shoppingCart = expectMsgClass(ShoppingCart.class); + assertThat(shoppingCart.getItems(), hasItems(shirt, shoes)); - fsmRef.tell(PoisonPill.getInstance(), ActorRef.noSender()); - expectTerminated(fsmRef); + fsmRef.tell(PoisonPill.getInstance(), ActorRef.noSender()); + expectTerminated(fsmRef); - ActorRef recoveredFsmRef = system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); - watch(recoveredFsmRef); - recoveredFsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); + ActorRef recoveredFsmRef = + system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); + watch(recoveredFsmRef); + recoveredFsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); - recoveredFsmRef.tell(GetCurrentCart.INSTANCE, getRef()); + recoveredFsmRef.tell(GetCurrentCart.INSTANCE, getRef()); - recoveredFsmRef.tell(new AddItem(coat), getRef()); - recoveredFsmRef.tell(GetCurrentCart.INSTANCE, getRef()); + recoveredFsmRef.tell(new AddItem(coat), getRef()); + recoveredFsmRef.tell(GetCurrentCart.INSTANCE, getRef()); - recoveredFsmRef.tell(Buy.INSTANCE, getRef()); - recoveredFsmRef.tell(GetCurrentCart.INSTANCE, getRef()); - recoveredFsmRef.tell(Leave.INSTANCE, getRef()); + recoveredFsmRef.tell(Buy.INSTANCE, getRef()); + recoveredFsmRef.tell(GetCurrentCart.INSTANCE, getRef()); + recoveredFsmRef.tell(Leave.INSTANCE, getRef()); - currentState = expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); - assertEquals(currentState.state(), UserState.SHOPPING); + currentState = expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); + assertEquals(currentState.state(), UserState.SHOPPING); - shoppingCart = expectMsgClass(ShoppingCart.class); - assertThat(shoppingCart.getItems(), hasItems(shirt, shoes)); + shoppingCart = expectMsgClass(ShoppingCart.class); + assertThat(shoppingCart.getItems(), hasItems(shirt, shoes)); - shoppingCart = expectMsgClass(ShoppingCart.class); - assertThat(shoppingCart.getItems(), hasItems(shirt, shoes, coat)); + shoppingCart = expectMsgClass(ShoppingCart.class); + assertThat(shoppingCart.getItems(), hasItems(shirt, shoes, coat)); - stateTransition = expectMsgClass(PersistentFSM.Transition.class); - assertTransition(stateTransition, recoveredFsmRef, UserState.SHOPPING, UserState.PAID); + stateTransition = expectMsgClass(PersistentFSM.Transition.class); + assertTransition(stateTransition, recoveredFsmRef, UserState.SHOPPING, UserState.PAID); - shoppingCart = expectMsgClass(ShoppingCart.class); - assertThat(shoppingCart.getItems(), hasItems(shirt, shoes, coat)); + shoppingCart = expectMsgClass(ShoppingCart.class); + assertThat(shoppingCart.getItems(), hasItems(shirt, shoes, coat)); - expectTerminated(recoveredFsmRef); - }}; - } + expectTerminated(recoveredFsmRef); + } + }; + } - @Test - public void testExecutionOfDefinedActionsFollowingSuccessfulPersistence() { - new TestKit(system) {{ - String persistenceId = generateId(); + @Test + public void testExecutionOfDefinedActionsFollowingSuccessfulPersistence() { + new TestKit(system) { + { + String persistenceId = generateId(); - TestProbe reportActorProbe = new TestProbe(system); - ActorRef fsmRef = system.actorOf(WebStoreCustomerFSM.props(persistenceId, reportActorProbe.ref())); + TestProbe reportActorProbe = new TestProbe(system); + ActorRef fsmRef = + system.actorOf(WebStoreCustomerFSM.props(persistenceId, reportActorProbe.ref())); - watch(fsmRef); - fsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); + watch(fsmRef); + fsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); - Item shirt = new Item("1", "Shirt", 49.99F); - Item shoes = new Item("2", "Shoes", 49.99F); - Item coat = new Item("3", "Coat", 149.99F); + Item shirt = new Item("1", "Shirt", 49.99F); + Item shoes = new Item("2", "Shoes", 49.99F); + Item coat = new Item("3", "Coat", 149.99F); - fsmRef.tell(new AddItem(shirt), getRef()); - fsmRef.tell(new AddItem(shoes), getRef()); - fsmRef.tell(new AddItem(coat), getRef()); - fsmRef.tell(Buy.INSTANCE, getRef()); - fsmRef.tell(Leave.INSTANCE, getRef()); + fsmRef.tell(new AddItem(shirt), getRef()); + fsmRef.tell(new AddItem(shoes), getRef()); + fsmRef.tell(new AddItem(coat), getRef()); + fsmRef.tell(Buy.INSTANCE, getRef()); + fsmRef.tell(Leave.INSTANCE, getRef()); - CurrentState currentState = expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); - assertEquals(currentState.state(), UserState.LOOKING_AROUND); + CurrentState currentState = + expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); + assertEquals(currentState.state(), UserState.LOOKING_AROUND); - PersistentFSM.Transition stateTransition = expectMsgClass(PersistentFSM.Transition.class); - assertTransition(stateTransition, fsmRef, UserState.LOOKING_AROUND, UserState.SHOPPING); + PersistentFSM.Transition stateTransition = expectMsgClass(PersistentFSM.Transition.class); + assertTransition(stateTransition, fsmRef, UserState.LOOKING_AROUND, UserState.SHOPPING); - stateTransition = expectMsgClass(PersistentFSM.Transition.class); - assertTransition(stateTransition, fsmRef, UserState.SHOPPING, UserState.PAID); + stateTransition = expectMsgClass(PersistentFSM.Transition.class); + assertTransition(stateTransition, fsmRef, UserState.SHOPPING, UserState.PAID); - PurchaseWasMade purchaseWasMade = reportActorProbe.expectMsgClass(PurchaseWasMade.class); - assertThat(purchaseWasMade.getItems(), hasItems(shirt, shoes, coat)); + PurchaseWasMade purchaseWasMade = reportActorProbe.expectMsgClass(PurchaseWasMade.class); + assertThat(purchaseWasMade.getItems(), hasItems(shirt, shoes, coat)); - expectTerminated(fsmRef); - }}; - } + expectTerminated(fsmRef); + } + }; + } - @Test - public void testExecutionOfDefinedActionsFollowingSuccessfulPersistenceOfFSMStop() { - new TestKit(system) {{ - String persistenceId = generateId(); + @Test + public void testExecutionOfDefinedActionsFollowingSuccessfulPersistenceOfFSMStop() { + new TestKit(system) { + { + String persistenceId = generateId(); - TestProbe reportActorProbe = new TestProbe(system); - ActorRef fsmRef = system.actorOf(WebStoreCustomerFSM.props(persistenceId, reportActorProbe.ref())); + TestProbe reportActorProbe = new TestProbe(system); + ActorRef fsmRef = + system.actorOf(WebStoreCustomerFSM.props(persistenceId, reportActorProbe.ref())); - watch(fsmRef); - fsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); + watch(fsmRef); + fsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); - Item shirt = new Item("1", "Shirt", 59.99F); - Item shoes = new Item("2", "Shoes", 58.99F); - Item coat = new Item("3", "Coat", 159.99F); + Item shirt = new Item("1", "Shirt", 59.99F); + Item shoes = new Item("2", "Shoes", 58.99F); + Item coat = new Item("3", "Coat", 159.99F); - fsmRef.tell(new AddItem(shirt), getRef()); - fsmRef.tell(new AddItem(shoes), getRef()); - fsmRef.tell(new AddItem(coat), getRef()); - fsmRef.tell(Leave.INSTANCE, getRef()); + fsmRef.tell(new AddItem(shirt), getRef()); + fsmRef.tell(new AddItem(shoes), getRef()); + fsmRef.tell(new AddItem(coat), getRef()); + fsmRef.tell(Leave.INSTANCE, getRef()); - CurrentState currentState = expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); - assertEquals(currentState.state(), UserState.LOOKING_AROUND); + CurrentState currentState = + expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); + assertEquals(currentState.state(), UserState.LOOKING_AROUND); - PersistentFSM.Transition stateTransition = expectMsgClass(PersistentFSM.Transition.class); - assertTransition(stateTransition, fsmRef, UserState.LOOKING_AROUND, UserState.SHOPPING); + PersistentFSM.Transition stateTransition = expectMsgClass(PersistentFSM.Transition.class); + assertTransition(stateTransition, fsmRef, UserState.LOOKING_AROUND, UserState.SHOPPING); - reportActorProbe.expectMsgClass(ShoppingCardDiscarded.class); + reportActorProbe.expectMsgClass(ShoppingCardDiscarded.class); - expectTerminated(fsmRef); - }}; - } + expectTerminated(fsmRef); + } + }; + } - @Test - public void testCorrectStateTimeoutFollowingRecovery() { - new TestKit(system) {{ - String persistenceId = generateId(); - ActorRef fsmRef = system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); + @Test + public void testCorrectStateTimeoutFollowingRecovery() { + new TestKit(system) { + { + String persistenceId = generateId(); + ActorRef fsmRef = + system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); - watch(fsmRef); - fsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); + watch(fsmRef); + fsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); - Item shirt = new Item("1", "Shirt", 69.99F); + Item shirt = new Item("1", "Shirt", 69.99F); - fsmRef.tell(new AddItem(shirt), getRef()); + fsmRef.tell(new AddItem(shirt), getRef()); - CurrentState currentState = expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); - assertEquals(currentState.state(), UserState.LOOKING_AROUND); + CurrentState currentState = + expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); + assertEquals(currentState.state(), UserState.LOOKING_AROUND); - PersistentFSM.Transition stateTransition = expectMsgClass(PersistentFSM.Transition.class); - assertTransition(stateTransition, fsmRef, UserState.LOOKING_AROUND, UserState.SHOPPING); + PersistentFSM.Transition stateTransition = expectMsgClass(PersistentFSM.Transition.class); + assertTransition(stateTransition, fsmRef, UserState.LOOKING_AROUND, UserState.SHOPPING); - expectNoMessage(Duration.ofMillis(600)); //randomly chosen delay, less than the timeout, before stopping the FSM - fsmRef.tell(PoisonPill.getInstance(), ActorRef.noSender()); - expectTerminated(fsmRef); + expectNoMessage( + Duration.ofMillis( + 600)); // randomly chosen delay, less than the timeout, before stopping the FSM + fsmRef.tell(PoisonPill.getInstance(), ActorRef.noSender()); + expectTerminated(fsmRef); - final ActorRef recoveredFsmRef = system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); - watch(recoveredFsmRef); - recoveredFsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); + final ActorRef recoveredFsmRef = + system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); + watch(recoveredFsmRef); + recoveredFsmRef.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); + currentState = expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); + assertEquals(currentState.state(), UserState.SHOPPING); - currentState = expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); - assertEquals(currentState.state(), UserState.SHOPPING); - - within(Duration.ofMillis(900), getRemainingOrDefault(), () -> { - PersistentFSM.Transition st = expectMsgClass(PersistentFSM.Transition.class); - assertTransition(st, recoveredFsmRef, UserState.SHOPPING, UserState.INACTIVE); - return null; + within( + Duration.ofMillis(900), + getRemainingOrDefault(), + () -> { + PersistentFSM.Transition st = expectMsgClass(PersistentFSM.Transition.class); + assertTransition(st, recoveredFsmRef, UserState.SHOPPING, UserState.INACTIVE); + return null; }); - expectNoMessage(Duration.ofMillis(900)); //randomly chosen delay, less than the timeout, before stopping the FSM - recoveredFsmRef.tell(PoisonPill.getInstance(), ActorRef.noSender()); - expectTerminated(recoveredFsmRef); + expectNoMessage( + Duration.ofMillis( + 900)); // randomly chosen delay, less than the timeout, before stopping the FSM + recoveredFsmRef.tell(PoisonPill.getInstance(), ActorRef.noSender()); + expectTerminated(recoveredFsmRef); - final ActorRef recoveredFsmRef2 = system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); - watch(recoveredFsmRef2); - recoveredFsmRef2.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); + final ActorRef recoveredFsmRef2 = + system.actorOf(WebStoreCustomerFSM.props(persistenceId, dummyReportActorRef)); + watch(recoveredFsmRef2); + recoveredFsmRef2.tell(new PersistentFSM.SubscribeTransitionCallBack(getRef()), getRef()); - currentState = expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); - assertEquals(currentState.state(), UserState.INACTIVE); + currentState = expectMsgClass(akka.persistence.fsm.PersistentFSM.CurrentState.class); + assertEquals(currentState.state(), UserState.INACTIVE); - within(Duration.ofMillis(1900), getRemainingOrDefault(), () -> expectTerminated(recoveredFsmRef2)); + within( + Duration.ofMillis(1900), + getRemainingOrDefault(), + () -> expectTerminated(recoveredFsmRef2)); + } + }; + } - }}; + private static void assertTransition( + PersistentFSM.Transition transition, ActorRef ref, From from, To to) { + assertEquals(ref, transition.fsmRef()); + assertEquals(from, transition.from()); + assertEquals(to, transition.to()); + } + + private static String generateId() { + return UUID.randomUUID().toString(); + } + + public static class WebStoreCustomerFSM + extends AbstractPersistentFSM< + WebStoreCustomerFSM.UserState, + WebStoreCustomerFSM.ShoppingCart, + WebStoreCustomerFSM.DomainEvent> { + + // State name + // #customer-states + enum UserState implements PersistentFSM.FSMState { + LOOKING_AROUND("Looking Around"), + SHOPPING("Shopping"), + INACTIVE("Inactive"), + PAID("Paid"); + + private final String stateIdentifier; + + UserState(String stateIdentifier) { + this.stateIdentifier = stateIdentifier; + } + + @Override + public String identifier() { + return stateIdentifier; + } + } + // #customer-states + + // #customer-states-data + static class ShoppingCart { + private final List items = new ArrayList<>(); + + public List getItems() { + return Collections.unmodifiableList(items); + } + + void addItem(Item item) { + items.add(item); + } + + void empty() { + items.clear(); + } } + static class Item implements Serializable { + private final String id; + private final String name; + private final float price; - private static void assertTransition(PersistentFSM.Transition transition, ActorRef ref, From from, To to) { - assertEquals(ref, transition.fsmRef()); - assertEquals(from, transition.from()); - assertEquals(to, transition.to()); + Item(String id, String name, float price) { + this.id = id; + this.name = name; + this.price = price; + } + + public String getId() { + return id; + } + + public float getPrice() { + return price; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return String.format("Item{id=%s, name=%s, price=%s}", id, price, name); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Item item = (Item) o; + + return item.price == price && id.equals(item.id) && name.equals(item.name); + } + } + // #customer-states-data + + public interface Command {} + + // #customer-commands + public static final class AddItem implements Command { + private final Item item; + + public AddItem(Item item) { + this.item = item; + } + + public Item getItem() { + return item; + } } - private static String generateId() { - return UUID.randomUUID().toString(); + public enum Buy implements Command { + INSTANCE } - - public static class WebStoreCustomerFSM extends AbstractPersistentFSM { - - //State name - //#customer-states - enum UserState implements PersistentFSM.FSMState { - LOOKING_AROUND("Looking Around"), - SHOPPING("Shopping"), - INACTIVE("Inactive"), - PAID("Paid"); - - private final String stateIdentifier; - - UserState(String stateIdentifier) { - this.stateIdentifier = stateIdentifier; - } - - @Override - public String identifier() { - return stateIdentifier; - } - } - //#customer-states - - //#customer-states-data - static class ShoppingCart { - private final List items = new ArrayList<>(); - - public List getItems() { - return Collections.unmodifiableList(items); - } - - void addItem(Item item) { - items.add(item); - } - - void empty() { - items.clear(); - } - } - - static class Item implements Serializable { - private final String id; - private final String name; - private final float price; - - Item(String id, String name, float price) { - this.id = id; - this.name = name; - this.price = price; - } - - public String getId() { - return id; - } - - public float getPrice() { - return price; - } - - public String getName() { - return name; - } - - @Override - public String toString() { - return String.format("Item{id=%s, name=%s, price=%s}", id, price, name); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Item item = (Item) o; - - return item.price == price && id.equals(item.id) && name.equals(item.name); - } - } - //#customer-states-data - - public interface Command { - } - - //#customer-commands - public static final class AddItem implements Command { - private final Item item; - - public AddItem(Item item) { - this.item = item; - } - - public Item getItem() { - return item; - } - } - - public enum Buy implements Command {INSTANCE} - - public enum Leave implements Command {INSTANCE} - - public enum GetCurrentCart implements Command {INSTANCE} - //#customer-commands - - interface DomainEvent extends Serializable { - } - - //#customer-domain-events - public static final class ItemAdded implements DomainEvent { - private final Item item; - - public ItemAdded(Item item) { - this.item = item; - } - - public Item getItem() { - return item; - } - } - - public enum OrderExecuted implements DomainEvent {INSTANCE} - - public enum OrderDiscarded implements DomainEvent {INSTANCE} - //#customer-domain-events - - - //Side effects - report events to be sent to some "Report Actor" - public interface ReportEvent { - } - - public static final class PurchaseWasMade implements ReportEvent { - private final List items; - - public PurchaseWasMade(List items) { - this.items = Collections.unmodifiableList(items); - } - - public List getItems() { - return items; - } - } - - public enum ShoppingCardDiscarded implements ReportEvent {INSTANCE} - - final private String persistenceId; - - @Override - public Class domainEventClass() { - return DomainEvent.class; - } - - @Override - public String persistenceId() { - return persistenceId; - } - - public static Props props(String persistenceId, ActorRef reportActor) { - return Props.create(WebStoreCustomerFSM.class, persistenceId, reportActor); - } - - public WebStoreCustomerFSM(String persistenceId, ActorRef reportActor) { - this.persistenceId = persistenceId; - - //#customer-fsm-body - startWith(UserState.LOOKING_AROUND, new ShoppingCart()); - - when(UserState.LOOKING_AROUND, - matchEvent(AddItem.class, - (event, data) -> - goTo(UserState.SHOPPING).applying(new ItemAdded(event.getItem())) - .forMax(Duration.ofSeconds(1))) - .event(GetCurrentCart.class, (event, data) -> stay().replying(data)) - ); - - when(UserState.SHOPPING, - matchEvent(AddItem.class, - (event, data) -> - stay().applying(new ItemAdded(event.getItem())) - .forMax(Duration.ofSeconds(1))) - .event(Buy.class, - //#customer-andthen-example - (event, data) -> - goTo(UserState.PAID).applying(OrderExecuted.INSTANCE) - .andThen(exec(cart -> { - reportActor.tell(new PurchaseWasMade(cart.getItems()), self()); - //#customer-andthen-example - saveStateSnapshot(); - //#customer-andthen-example - }))) - //#customer-andthen-example - .event(Leave.class, - //#customer-snapshot-example - (event, data) -> - stop().applying(OrderDiscarded.INSTANCE) - .andThen(exec(cart -> { - reportActor.tell(ShoppingCardDiscarded.INSTANCE, self()); - saveStateSnapshot(); - }))) - //#customer-snapshot-example - .event(GetCurrentCart.class, (event, data) -> stay().replying(data)) - .event(StateTimeout$.class, - (event, data) -> - goTo(UserState.INACTIVE).forMax(Duration.ofSeconds(2))) - ); - - - when(UserState.INACTIVE, - matchEvent(AddItem.class, - (event, data) -> - goTo(UserState.SHOPPING).applying(new ItemAdded(event.getItem())) - .forMax(Duration.ofSeconds(1))) - .event(GetCurrentCart.class, (event, data) -> stay().replying(data)) - .event(StateTimeout$.class, - (event, data) -> - stop().applying(OrderDiscarded.INSTANCE) - .andThen(exec(cart -> - reportActor.tell(ShoppingCardDiscarded.INSTANCE, self()) - ))) - ); - - when(UserState.PAID, - matchEvent(Leave.class, (event, data) -> stop()) - .event(GetCurrentCart.class, (event, data) -> stay().replying(data)) - ); - //#customer-fsm-body - } - - /** - * Override this handler to define the action on Domain Event during recovery - * - * @param event domain event to apply - * @param currentData state data of the previous state - */ - //#customer-apply-event - @Override - public ShoppingCart applyEvent(DomainEvent event, ShoppingCart currentData) { - if (event instanceof ItemAdded) { - currentData.addItem(((ItemAdded) event).getItem()); - return currentData; - } else if (event instanceof OrderExecuted) { - return currentData; - } else if (event instanceof OrderDiscarded) { - currentData.empty(); - return currentData; - } - throw new RuntimeException("Unhandled"); - } - //#customer-apply-event + public enum Leave implements Command { + INSTANCE } - enum PFSMState implements FSMState { + public enum GetCurrentCart implements Command { + INSTANCE + } + // #customer-commands - STARTED; + interface DomainEvent extends Serializable {} - @Override - public String identifier() { - return this.name(); - } + // #customer-domain-events + public static final class ItemAdded implements DomainEvent { + private final Item item; + + public ItemAdded(Item item) { + this.item = item; + } + + public Item getItem() { + return item; + } } - public static class PFSMwithLog extends AbstractPersistentFSM { - { - startWith(PFSMState.STARTED, 0); - - when(PFSMState.STARTED, - matchEvent(String.class, (command, currentData) -> { - sender().tell("started", getSelf()); - return stay(); - }) - ); - - onTransition(this::transitionLogger); // this is tested command - } - - private void transitionLogger(PFSMState from, PFSMState to) { - System.out.println("transition from " + from + " to " + to); - } - - @Override - public Class domainEventClass() { - return Integer.class; - } - - @Override - public Integer applyEvent(final Integer domainEvent, final Integer currentData) { - return 0; - } - - @Override - public String persistenceId() { - return "id"; - } + public enum OrderExecuted implements DomainEvent { + INSTANCE } - @Test - public void testCreationOfActorCallingOnTransitionWithVoidFunction() { - new TestKit(system) {{ - ActorRef persistentActor = system.actorOf(Props.create(PFSMwithLog.class)); - persistentActor.tell("check", getRef()); - expectMsg(Duration.ofSeconds(1), "started"); - }}; + public enum OrderDiscarded implements DomainEvent { + INSTANCE } + // #customer-domain-events + + // Side effects - report events to be sent to some "Report Actor" + public interface ReportEvent {} + + public static final class PurchaseWasMade implements ReportEvent { + private final List items; + + public PurchaseWasMade(List items) { + this.items = Collections.unmodifiableList(items); + } + + public List getItems() { + return items; + } + } + + public enum ShoppingCardDiscarded implements ReportEvent { + INSTANCE + } + + private final String persistenceId; + + @Override + public Class domainEventClass() { + return DomainEvent.class; + } + + @Override + public String persistenceId() { + return persistenceId; + } + + public static Props props(String persistenceId, ActorRef reportActor) { + return Props.create(WebStoreCustomerFSM.class, persistenceId, reportActor); + } + + public WebStoreCustomerFSM(String persistenceId, ActorRef reportActor) { + this.persistenceId = persistenceId; + + // #customer-fsm-body + startWith(UserState.LOOKING_AROUND, new ShoppingCart()); + + when( + UserState.LOOKING_AROUND, + matchEvent( + AddItem.class, + (event, data) -> + goTo(UserState.SHOPPING) + .applying(new ItemAdded(event.getItem())) + .forMax(Duration.ofSeconds(1))) + .event(GetCurrentCart.class, (event, data) -> stay().replying(data))); + + when( + UserState.SHOPPING, + matchEvent( + AddItem.class, + (event, data) -> + stay().applying(new ItemAdded(event.getItem())).forMax(Duration.ofSeconds(1))) + .event( + Buy.class, + // #customer-andthen-example + (event, data) -> + goTo(UserState.PAID) + .applying(OrderExecuted.INSTANCE) + .andThen( + exec( + cart -> { + reportActor.tell(new PurchaseWasMade(cart.getItems()), self()); + // #customer-andthen-example + saveStateSnapshot(); + // #customer-andthen-example + }))) + // #customer-andthen-example + .event( + Leave.class, + // #customer-snapshot-example + (event, data) -> + stop() + .applying(OrderDiscarded.INSTANCE) + .andThen( + exec( + cart -> { + reportActor.tell(ShoppingCardDiscarded.INSTANCE, self()); + saveStateSnapshot(); + }))) + // #customer-snapshot-example + .event(GetCurrentCart.class, (event, data) -> stay().replying(data)) + .event( + StateTimeout$.class, + (event, data) -> goTo(UserState.INACTIVE).forMax(Duration.ofSeconds(2)))); + + when( + UserState.INACTIVE, + matchEvent( + AddItem.class, + (event, data) -> + goTo(UserState.SHOPPING) + .applying(new ItemAdded(event.getItem())) + .forMax(Duration.ofSeconds(1))) + .event(GetCurrentCart.class, (event, data) -> stay().replying(data)) + .event( + StateTimeout$.class, + (event, data) -> + stop() + .applying(OrderDiscarded.INSTANCE) + .andThen( + exec( + cart -> + reportActor.tell(ShoppingCardDiscarded.INSTANCE, self()))))); + + when( + UserState.PAID, + matchEvent(Leave.class, (event, data) -> stop()) + .event(GetCurrentCart.class, (event, data) -> stay().replying(data))); + // #customer-fsm-body + } + + /** + * Override this handler to define the action on Domain Event during recovery + * + * @param event domain event to apply + * @param currentData state data of the previous state + */ + // #customer-apply-event + @Override + public ShoppingCart applyEvent(DomainEvent event, ShoppingCart currentData) { + if (event instanceof ItemAdded) { + currentData.addItem(((ItemAdded) event).getItem()); + return currentData; + } else if (event instanceof OrderExecuted) { + return currentData; + } else if (event instanceof OrderDiscarded) { + currentData.empty(); + return currentData; + } + throw new RuntimeException("Unhandled"); + } + // #customer-apply-event + } + + enum PFSMState implements FSMState { + STARTED; + + @Override + public String identifier() { + return this.name(); + } + } + + public static class PFSMwithLog extends AbstractPersistentFSM { + { + startWith(PFSMState.STARTED, 0); + + when( + PFSMState.STARTED, + matchEvent( + String.class, + (command, currentData) -> { + sender().tell("started", getSelf()); + return stay(); + })); + + onTransition(this::transitionLogger); // this is tested command + } + + private void transitionLogger(PFSMState from, PFSMState to) { + System.out.println("transition from " + from + " to " + to); + } + + @Override + public Class domainEventClass() { + return Integer.class; + } + + @Override + public Integer applyEvent(final Integer domainEvent, final Integer currentData) { + return 0; + } + + @Override + public String persistenceId() { + return "id"; + } + } + + @Test + public void testCreationOfActorCallingOnTransitionWithVoidFunction() { + new TestKit(system) { + { + ActorRef persistentActor = system.actorOf(Props.create(PFSMwithLog.class)); + persistentActor.tell("check", getRef()); + expectMsg(Duration.ofSeconds(1), "started"); + } + }; + } } diff --git a/akka-remote/src/main/java/akka/remote/artery/AbstractAssociation.java b/akka-remote/src/main/java/akka/remote/artery/AbstractAssociation.java index 734cbd8d6d..ff5b1667c0 100644 --- a/akka-remote/src/main/java/akka/remote/artery/AbstractAssociation.java +++ b/akka-remote/src/main/java/akka/remote/artery/AbstractAssociation.java @@ -7,13 +7,15 @@ package akka.remote.artery; import akka.util.Unsafe; class AbstractAssociation { - protected final static long sharedStateOffset; + protected static final long sharedStateOffset; - static { - try { - sharedStateOffset = Unsafe.instance.objectFieldOffset(Association.class.getDeclaredField("_sharedStateDoNotCallMeDirectly")); - } catch(Throwable t){ - throw new ExceptionInInitializerError(t); - } + static { + try { + sharedStateOffset = + Unsafe.instance.objectFieldOffset( + Association.class.getDeclaredField("_sharedStateDoNotCallMeDirectly")); + } catch (Throwable t) { + throw new ExceptionInInitializerError(t); } + } } diff --git a/akka-remote/src/main/java/akka/remote/artery/aeron/AeronErrorLog.java b/akka-remote/src/main/java/akka/remote/artery/aeron/AeronErrorLog.java index 9d4233af3e..9f1c678a95 100644 --- a/akka-remote/src/main/java/akka/remote/artery/aeron/AeronErrorLog.java +++ b/akka-remote/src/main/java/akka/remote/artery/aeron/AeronErrorLog.java @@ -31,55 +31,57 @@ import java.nio.MappedByteBuffer; import java.util.concurrent.atomic.AtomicLong; /** - * Application to print out errors recorded in the command-and-control (cnc) file is maintained by media driver in shared - * memory. This application reads the cnc file and prints the distinct errors. Layout of the cnc file is described in - * {@link CncFileDescriptor}. + * Application to print out errors recorded in the command-and-control (cnc) file is maintained by + * media driver in shared memory. This application reads the cnc file and prints the distinct + * errors. Layout of the cnc file is described in {@link CncFileDescriptor}. */ -public class AeronErrorLog -{ - final MappedByteBuffer cncByteBuffer; - final AtomicBuffer buffer; +public class AeronErrorLog { + final MappedByteBuffer cncByteBuffer; + final AtomicBuffer buffer; - @Deprecated - public AeronErrorLog(File cncFile) - { - this(cncFile, NoLogging.getInstance()); + @Deprecated + public AeronErrorLog(File cncFile) { + this(cncFile, NoLogging.getInstance()); + } + + public AeronErrorLog(File cncFile, LoggingAdapter log) { + cncByteBuffer = IoUtil.mapExistingFile(cncFile, "cnc"); + final DirectBuffer cncMetaDataBuffer = CncFileDescriptor.createMetaDataBuffer(cncByteBuffer); + final int cncVersion = cncMetaDataBuffer.getInt(CncFileDescriptor.cncVersionOffset(0)); + buffer = CncFileDescriptor.createErrorLogBuffer(cncByteBuffer, cncMetaDataBuffer); + + if (CncFileDescriptor.CNC_VERSION != cncVersion) { + log.warning( + "Aeron CnC version mismatch: compiled version = {}, file version = {}", + CncFileDescriptor.CNC_VERSION, + cncVersion); } + } - public AeronErrorLog(File cncFile, LoggingAdapter log) - { - cncByteBuffer = IoUtil.mapExistingFile(cncFile, "cnc"); - final DirectBuffer cncMetaDataBuffer = CncFileDescriptor.createMetaDataBuffer(cncByteBuffer); - final int cncVersion = cncMetaDataBuffer.getInt(CncFileDescriptor.cncVersionOffset(0)); - buffer = CncFileDescriptor.createErrorLogBuffer(cncByteBuffer, cncMetaDataBuffer); + public long logErrors(LoggingAdapter log, long sinceTimestamp) { + // using AtomicLong because access from lambda, not because of concurrency + final AtomicLong lastTimestamp = new AtomicLong(sinceTimestamp); - if (CncFileDescriptor.CNC_VERSION != cncVersion) - { - log.warning("Aeron CnC version mismatch: compiled version = {}, file version = {}", - CncFileDescriptor.CNC_VERSION, cncVersion); - } - } + ErrorLogReader.read( + buffer, + (observationCount, + firstObservationTimestamp, + lastObservationTimestamp, + encodedException) -> { + log.error( + String.format( + "Aeron error: %d observations from %s to %s for:%n %s", + observationCount, + Helpers.timestamp(firstObservationTimestamp), + Helpers.timestamp(lastObservationTimestamp), + encodedException)); + lastTimestamp.set(Math.max(lastTimestamp.get(), lastObservationTimestamp)); + }, + sinceTimestamp); + return lastTimestamp.get(); + } - public long logErrors(LoggingAdapter log, long sinceTimestamp) - { - // using AtomicLong because access from lambda, not because of concurrency - final AtomicLong lastTimestamp = new AtomicLong(sinceTimestamp); - - ErrorLogReader.read( - buffer, - (observationCount, firstObservationTimestamp, lastObservationTimestamp, encodedException) -> { - log.error(String.format( - "Aeron error: %d observations from %s to %s for:%n %s", - observationCount, - Helpers.timestamp(firstObservationTimestamp), - Helpers.timestamp(lastObservationTimestamp), - encodedException)); - lastTimestamp.set(Math.max(lastTimestamp.get(), lastObservationTimestamp)); - }, sinceTimestamp); - return lastTimestamp.get(); - } - - public void close() { - IoUtil.unmap(cncByteBuffer); - } + public void close() { + IoUtil.unmap(cncByteBuffer); + } } diff --git a/akka-remote/src/main/java/akka/remote/artery/compress/CountMinSketch.java b/akka-remote/src/main/java/akka/remote/artery/compress/CountMinSketch.java index 79b4c6c508..05f58ed34e 100644 --- a/akka-remote/src/main/java/akka/remote/artery/compress/CountMinSketch.java +++ b/akka-remote/src/main/java/akka/remote/artery/compress/CountMinSketch.java @@ -9,11 +9,12 @@ import akka.actor.ActorRef; /** * INTERNAL API: Count-Min Sketch datastructure. * - * Not thread-safe. + *

Not thread-safe. * - * An Improved Data Stream Summary: The Count-Min Sketch and its Applications + *

An Improved Data Stream Summary: The Count-Min Sketch and its Applications * https://web.archive.org/web/20060907232042/http://www.eecs.harvard.edu/~michaelm/CS222/countmin.pdf - * This implementation is mostly taken and adjusted from the Apache V2 licensed project `stream-lib`, located here: + * This implementation is mostly taken and adjusted from the Apache V2 licensed project + * `stream-lib`, located here: * https://github.com/clearspring/stream-lib/blob/master/src/main/java/com/clearspring/analytics/stream/frequency/CountMinSketch.java */ public class CountMinSketch { @@ -27,10 +28,9 @@ public class CountMinSketch { private int[] recyclableCMSHashBuckets; - public CountMinSketch(int depth, int width, int seed) { - if((width & (width-1)) != 0){ - throw new IllegalArgumentException("width must be a power of 2, was: " + width ); + if ((width & (width - 1)) != 0) { + throw new IllegalArgumentException("width must be a power of 2, was: " + width); } this.depth = depth; this.width = width; @@ -40,14 +40,11 @@ public class CountMinSketch { initTablesWith(depth, width, seed); } - private void initTablesWith(int depth, int width, int seed) { this.table = new long[depth][width]; } - /** - * Referred to as {@code epsilon} in the whitepaper - */ + /** Referred to as {@code epsilon} in the whitepaper */ public double relativeError() { return eps; } @@ -57,8 +54,9 @@ public class CountMinSketch { } /** - * Similar to {@code add}, however we reuse the fact that the hask buckets have to be calculated for {@code add} - * already, and a separate {@code estimateCount} operation would have to calculate them again, so we do it all in one go. + * Similar to {@code add}, however we reuse the fact that the hask buckets have to be calculated + * for {@code add} already, and a separate {@code estimateCount} operation would have to calculate + * them again, so we do it all in one go. */ public long addObjectAndEstimateCount(Object item, long count) { if (count < 0) { @@ -81,8 +79,8 @@ public class CountMinSketch { } /** - * The estimate is correct within {@code 'epsilon' * (total item count)}, - * with probability {@code confidence}. + * The estimate is correct within {@code 'epsilon' * (total item count)}, with probability {@code + * confidence}. */ public long estimateCount(Object item) { Murmur3.hashBuckets(item, recyclableCMSHashBuckets, width); @@ -90,8 +88,8 @@ public class CountMinSketch { } /** - * The estimate is correct within {@code 'epsilon' * (total item count)}, - * with probability {@code confidence}. + * The estimate is correct within {@code 'epsilon' * (total item count)}, with probability {@code + * confidence}. * * @param buckets the "indexes" of buckets from which we want to calculate the count */ @@ -103,20 +101,18 @@ public class CountMinSketch { return res; } - /** * Local implementation of murmur3 hash optimized to used in count min sketch * - * Inspired by scala (scala.util.hashing.MurmurHash3) and C port of MurmurHash3 + *

Inspired by scala (scala.util.hashing.MurmurHash3) and C port of MurmurHash3 * - * scala.util.hashing => https://github.com/scala/scala/blob/2.12.x/src/library/scala/util/hashing/MurmurHash3.scala - * C port of MurmurHash3 => https://github.com/PeterScott/murmur3/blob/master/murmur3.c + *

scala.util.hashing => + * https://github.com/scala/scala/blob/2.12.x/src/library/scala/util/hashing/MurmurHash3.scala C + * port of MurmurHash3 => https://github.com/PeterScott/murmur3/blob/master/murmur3.c */ private static class Murmur3 { - /** - * Force all bits of the hash to avalanche. Used for finalizing the hash. - */ + /** Force all bits of the hash to avalanche. Used for finalizing the hash. */ private static int avalanche(int hash) { int h = hash; @@ -132,14 +128,13 @@ public class CountMinSketch { private static int mixLast(int hash, int data) { int k = data; - k *= 0xcc9e2d51; //c1 + k *= 0xcc9e2d51; // c1 k = Integer.rotateLeft(k, 15); - k *= 0x1b873593; //c2 + k *= 0x1b873593; // c2 return hash ^ k; } - private static int mix(int hash, int data) { int h = mixLast(hash, data); h = Integer.rotateLeft(h, 13); @@ -151,9 +146,11 @@ public class CountMinSketch { return 0; } if (o instanceof ActorRef) { // TODO possibly scary optimisation - // ActorRef hashcode is the ActorPath#uid, which is a random number assigned at its creation, + // ActorRef hashcode is the ActorPath#uid, which is a random number assigned at its + // creation, // thus no hashing happens here - the value is already cached. - // TODO it should be thought over if this preciseness (just a random number, and not hashing) is good enough here? + // TODO it should be thought over if this preciseness (just a random number, and not + // hashing) is good enough here? // this is not cryptographic one, anything which is stable and random is good enough return o.hashCode(); } @@ -219,8 +216,9 @@ public class CountMinSketch { /** * Hash item using pair independent hash functions. * - * Implemetation based on "Less Hashing, Same Performance: Building a - * Better Bloom Filter" https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf + *

Implemetation based on "Less Hashing, Same Performance: Building a Better Bloom Filter" + * https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf + * * @param item what should be hashed * @param hashBuckets where hashes should be placed * @param limit value to shrink result @@ -231,10 +229,12 @@ public class CountMinSketch { final int depth = hashBuckets.length; final int mask = limit - 1; for (int i = 0; i < depth; i++) { - hashBuckets[i] = Math.abs((hash1 + i * hash2) & mask); //shrink done by AND instead MOD. Assume limit is power of 2 + hashBuckets[i] = + Math.abs( + (hash1 + i * hash2) + & mask); // shrink done by AND instead MOD. Assume limit is power of 2 } } - } private int[] preallocateHashBucketsArray(int depth) { @@ -243,11 +243,15 @@ public class CountMinSketch { @Override public String toString() { - return "CountMinSketch{" + - "confidence=" + confidence + - ", size=" + size + - ", depth=" + depth + - ", width=" + width + - '}'; + return "CountMinSketch{" + + "confidence=" + + confidence + + ", size=" + + size + + ", depth=" + + depth + + ", width=" + + width + + '}'; } } diff --git a/akka-remote/src/test/java/akka/remote/artery/RateReporter.java b/akka-remote/src/test/java/akka/remote/artery/RateReporter.java index 05fd8170c2..aa0fdf0cf5 100644 --- a/akka-remote/src/test/java/akka/remote/artery/RateReporter.java +++ b/akka-remote/src/test/java/akka/remote/artery/RateReporter.java @@ -21,96 +21,85 @@ import java.util.concurrent.locks.LockSupport; /** * Tracker and reporter of rates. * - * Uses volatile semantics for counters. + *

Uses volatile semantics for counters. */ -public class RateReporter implements Runnable -{ +public class RateReporter implements Runnable { + /** Interface for reporting of rate information */ + @FunctionalInterface + public interface Reporter { /** - * Interface for reporting of rate information - */ - @FunctionalInterface - public interface Reporter - { - /** - * Called for a rate report. - * - * @param messagesPerSec since last report - * @param bytesPerSec since last report - * @param totalMessages since beginning of reporting - * @param totalBytes since beginning of reporting - */ - void onReport(double messagesPerSec, double bytesPerSec, long totalMessages, long totalBytes); - } - - private final long reportIntervalNs; - private final long parkNs; - private final Reporter reportingFunc; - - private volatile boolean halt = false; - private volatile long totalBytes; - private volatile long totalMessages; - private long lastTotalBytes; - private long lastTotalMessages; - private long lastTimestamp; - - /** - * Create a rate reporter with the given report interval in nanoseconds and the reporting function. + * Called for a rate report. * - * @param reportInterval in nanoseconds - * @param reportingFunc to call for reporting rates + * @param messagesPerSec since last report + * @param bytesPerSec since last report + * @param totalMessages since beginning of reporting + * @param totalBytes since beginning of reporting */ - public RateReporter(final long reportInterval, final Reporter reportingFunc) - { - this.reportIntervalNs = reportInterval; - this.parkNs = reportInterval; - this.reportingFunc = reportingFunc; - lastTimestamp = System.nanoTime(); - } + void onReport(double messagesPerSec, double bytesPerSec, long totalMessages, long totalBytes); + } - /** - * Run loop for the rate reporter - */ - @Override - public void run() - { - do - { - LockSupport.parkNanos(parkNs); + private final long reportIntervalNs; + private final long parkNs; + private final Reporter reportingFunc; - final long currentTotalMessages = totalMessages; - final long currentTotalBytes = totalBytes; - final long currentTimestamp = System.nanoTime(); + private volatile boolean halt = false; + private volatile long totalBytes; + private volatile long totalMessages; + private long lastTotalBytes; + private long lastTotalMessages; + private long lastTimestamp; - final long timeSpanNs = currentTimestamp - lastTimestamp; - final double messagesPerSec = ((currentTotalMessages - lastTotalMessages) * reportIntervalNs) / (double)timeSpanNs; - final double bytesPerSec = ((currentTotalBytes - lastTotalBytes) * reportIntervalNs) / (double)timeSpanNs; + /** + * Create a rate reporter with the given report interval in nanoseconds and the reporting + * function. + * + * @param reportInterval in nanoseconds + * @param reportingFunc to call for reporting rates + */ + public RateReporter(final long reportInterval, final Reporter reportingFunc) { + this.reportIntervalNs = reportInterval; + this.parkNs = reportInterval; + this.reportingFunc = reportingFunc; + lastTimestamp = System.nanoTime(); + } - reportingFunc.onReport(messagesPerSec, bytesPerSec, currentTotalMessages, currentTotalBytes); + /** Run loop for the rate reporter */ + @Override + public void run() { + do { + LockSupport.parkNanos(parkNs); - lastTotalBytes = currentTotalBytes; - lastTotalMessages = currentTotalMessages; - lastTimestamp = currentTimestamp; - } - while (!halt); - } + final long currentTotalMessages = totalMessages; + final long currentTotalBytes = totalBytes; + final long currentTimestamp = System.nanoTime(); - /** - * Signal the run loop to exit. Does not block. - */ - public void halt() - { - halt = true; - } + final long timeSpanNs = currentTimestamp - lastTimestamp; + final double messagesPerSec = + ((currentTotalMessages - lastTotalMessages) * reportIntervalNs) / (double) timeSpanNs; + final double bytesPerSec = + ((currentTotalBytes - lastTotalBytes) * reportIntervalNs) / (double) timeSpanNs; - /** - * Tell rate reporter of number of messages and bytes received, sent, etc. - * - * @param messages received, sent, etc. - * @param bytes received, sent, etc. - */ - public void onMessage(final long messages, final long bytes) - { - totalBytes += bytes; - totalMessages += messages; - } -} \ No newline at end of file + reportingFunc.onReport(messagesPerSec, bytesPerSec, currentTotalMessages, currentTotalBytes); + + lastTotalBytes = currentTotalBytes; + lastTotalMessages = currentTotalMessages; + lastTimestamp = currentTimestamp; + } while (!halt); + } + + /** Signal the run loop to exit. Does not block. */ + public void halt() { + halt = true; + } + + /** + * Tell rate reporter of number of messages and bytes received, sent, etc. + * + * @param messages received, sent, etc. + * @param bytes received, sent, etc. + */ + public void onMessage(final long messages, final long bytes) { + totalBytes += bytes; + totalMessages += messages; + } +} diff --git a/akka-remote/src/test/java/akka/remote/artery/aeron/AeronStat.java b/akka-remote/src/test/java/akka/remote/artery/aeron/AeronStat.java index a7f9d81218..eae061a5c5 100644 --- a/akka-remote/src/test/java/akka/remote/artery/aeron/AeronStat.java +++ b/akka-remote/src/test/java/akka/remote/artery/aeron/AeronStat.java @@ -42,261 +42,230 @@ import static io.aeron.driver.status.StreamPositionCounter.*; import static io.aeron.driver.status.SystemCounterDescriptor.SYSTEM_COUNTER_TYPE_ID; /** - * Tool for printing out Aeron counters. A command-and-control (cnc) file is maintained by media driver - * in shared memory. This application reads the cnc file and prints the counters. Layout of the cnc file is - * described in {@link CncFileDescriptor}. - * - * This tool accepts filters on the command line, e.g. for connections only see example below: + * Tool for printing out Aeron counters. A command-and-control (cnc) file is maintained by media + * driver in shared memory. This application reads the cnc file and prints the counters. Layout of + * the cnc file is described in {@link CncFileDescriptor}. * + *

This tool accepts filters on the command line, e.g. for connections only see example below: * * java -cp aeron-samples/build/libs/samples.jar io.aeron.samples.AeronStat type=[1-4] identity=12345 * */ -public class AeronStat -{ - /** - * Types of the counters. - *

    - *
  • 0: System Counters
  • - *
  • 1 - 4: Stream Positions
  • - *
- */ - private static final String COUNTER_TYPE_ID = "type"; +public class AeronStat { + /** + * Types of the counters. + * + *
    + *
  • 0: System Counters + *
  • 1 - 4: Stream Positions + *
+ */ + private static final String COUNTER_TYPE_ID = "type"; - /** - * The identity of each counter that can either be the system counter id or registration id for positions. - */ - private static final String COUNTER_IDENTITY = "identity"; + /** + * The identity of each counter that can either be the system counter id or registration id for + * positions. + */ + private static final String COUNTER_IDENTITY = "identity"; - /** - * Session id filter to be used for position counters. - */ - private static final String COUNTER_SESSION_ID = "session"; + /** Session id filter to be used for position counters. */ + private static final String COUNTER_SESSION_ID = "session"; - /** - * Stream id filter to be used for position counters. - */ - private static final String COUNTER_STREAM_ID = "stream"; + /** Stream id filter to be used for position counters. */ + private static final String COUNTER_STREAM_ID = "stream"; - /** - * Channel filter to be used for position counters. - */ - private static final String COUNTER_CHANNEL = "channel"; + /** Channel filter to be used for position counters. */ + private static final String COUNTER_CHANNEL = "channel"; - private static final int ONE_SECOND = 1_000; + private static final int ONE_SECOND = 1_000; - private final CountersReader counters; - private final Pattern typeFilter; - private final Pattern identityFilter; - private final Pattern sessionFilter; - private final Pattern streamFilter; - private final Pattern channelFilter; + private final CountersReader counters; + private final Pattern typeFilter; + private final Pattern identityFilter; + private final Pattern sessionFilter; + private final Pattern streamFilter; + private final Pattern channelFilter; - public AeronStat( - final CountersReader counters, - final Pattern typeFilter, - final Pattern identityFilter, - final Pattern sessionFilter, - final Pattern streamFilter, - final Pattern channelFilter) - { - this.counters = counters; - this.typeFilter = typeFilter; - this.identityFilter = identityFilter; - this.sessionFilter = sessionFilter; - this.streamFilter = streamFilter; - this.channelFilter = channelFilter; + public AeronStat( + final CountersReader counters, + final Pattern typeFilter, + final Pattern identityFilter, + final Pattern sessionFilter, + final Pattern streamFilter, + final Pattern channelFilter) { + this.counters = counters; + this.typeFilter = typeFilter; + this.identityFilter = identityFilter; + this.sessionFilter = sessionFilter; + this.streamFilter = streamFilter; + this.channelFilter = channelFilter; + } + + public AeronStat(final CountersReader counters) { + this.counters = counters; + this.typeFilter = null; + this.identityFilter = null; + this.sessionFilter = null; + this.streamFilter = null; + this.channelFilter = null; + } + + public static CountersReader mapCounters() { + return mapCounters(CommonContext.newDefaultCncFile()); + } + + public static CountersReader mapCounters(final MappedByteBuffer cncByteBuffer) { + final DirectBuffer cncMetaData = createMetaDataBuffer(cncByteBuffer); + final int cncVersion = cncMetaData.getInt(cncVersionOffset(0)); + + if (CncFileDescriptor.CNC_VERSION != cncVersion) { + throw new IllegalStateException( + "Aeron CnC version does not match: version=" + cncVersion + " required=" + CNC_VERSION); } - public AeronStat(final CountersReader counters) - { - this.counters = counters; - this.typeFilter = null; - this.identityFilter = null; - this.sessionFilter = null; - this.streamFilter = null; - this.channelFilter = null; + return new CountersReader( + createCountersMetaDataBuffer(cncByteBuffer, cncMetaData), + createCountersValuesBuffer(cncByteBuffer, cncMetaData)); + } + + public static CountersReader mapCounters(final File cncFile) { + System.out.println("Command `n Control file " + cncFile); + + final MappedByteBuffer cncByteBuffer = IoUtil.mapExistingFile(cncFile, "cnc"); + final DirectBuffer cncMetaData = createMetaDataBuffer(cncByteBuffer); + final int cncVersion = cncMetaData.getInt(cncVersionOffset(0)); + + if (CncFileDescriptor.CNC_VERSION != cncVersion) { + throw new IllegalStateException( + "Aeron CnC version does not match: version=" + cncVersion + " required=" + CNC_VERSION); } - public static CountersReader mapCounters() - { - return mapCounters(CommonContext.newDefaultCncFile()); - } + return new CountersReader( + createCountersMetaDataBuffer(cncByteBuffer, cncMetaData), + createCountersValuesBuffer(cncByteBuffer, cncMetaData)); + } - public static CountersReader mapCounters(final MappedByteBuffer cncByteBuffer) - { - final DirectBuffer cncMetaData = createMetaDataBuffer(cncByteBuffer); - final int cncVersion = cncMetaData.getInt(cncVersionOffset(0)); + public static void main(final String[] args) throws Exception { + Pattern typeFilter = null; + Pattern identityFilter = null; + Pattern sessionFilter = null; + Pattern streamFilter = null; + Pattern channelFilter = null; - if (CncFileDescriptor.CNC_VERSION != cncVersion) - { - throw new IllegalStateException( - "Aeron CnC version does not match: version=" + cncVersion + " required=" + CNC_VERSION); + if (0 != args.length) { + checkForHelp(args); + + for (final String arg : args) { + final int equalsIndex = arg.indexOf('='); + if (-1 == equalsIndex) { + System.out.println("Arguments must be in name=pattern format: Invalid '" + arg + "'"); + return; } - return new CountersReader( - createCountersMetaDataBuffer(cncByteBuffer, cncMetaData), - createCountersValuesBuffer(cncByteBuffer, cncMetaData)); + final String argName = arg.substring(0, equalsIndex); + final String argValue = arg.substring(equalsIndex + 1); + + switch (argName) { + case COUNTER_TYPE_ID: + typeFilter = Pattern.compile(argValue); + break; + + case COUNTER_IDENTITY: + identityFilter = Pattern.compile(argValue); + break; + + case COUNTER_SESSION_ID: + sessionFilter = Pattern.compile(argValue); + break; + + case COUNTER_STREAM_ID: + streamFilter = Pattern.compile(argValue); + break; + + case COUNTER_CHANNEL: + channelFilter = Pattern.compile(argValue); + break; + + default: + System.out.println("Unrecognised argument: '" + arg + "'"); + return; + } + } } - public static CountersReader mapCounters(final File cncFile) - { - System.out.println("Command `n Control file " + cncFile); - - final MappedByteBuffer cncByteBuffer = IoUtil.mapExistingFile(cncFile, "cnc"); - final DirectBuffer cncMetaData = createMetaDataBuffer(cncByteBuffer); - final int cncVersion = cncMetaData.getInt(cncVersionOffset(0)); - - if (CncFileDescriptor.CNC_VERSION != cncVersion) - { - throw new IllegalStateException( - "Aeron CnC version does not match: version=" + cncVersion + " required=" + CNC_VERSION); - } - - return new CountersReader( - createCountersMetaDataBuffer(cncByteBuffer, cncMetaData), - createCountersValuesBuffer(cncByteBuffer, cncMetaData)); - } - - public static void main(final String[] args) throws Exception - { - Pattern typeFilter = null; - Pattern identityFilter = null; - Pattern sessionFilter = null; - Pattern streamFilter = null; - Pattern channelFilter = null; - - if (0 != args.length) - { - checkForHelp(args); - - for (final String arg : args) - { - final int equalsIndex = arg.indexOf('='); - if (-1 == equalsIndex) - { - System.out.println("Arguments must be in name=pattern format: Invalid '" + arg + "'"); - return; - } - - final String argName = arg.substring(0, equalsIndex); - final String argValue = arg.substring(equalsIndex + 1); - - switch (argName) - { - case COUNTER_TYPE_ID: - typeFilter = Pattern.compile(argValue); - break; - - case COUNTER_IDENTITY: - identityFilter = Pattern.compile(argValue); - break; - - case COUNTER_SESSION_ID: - sessionFilter = Pattern.compile(argValue); - break; - - case COUNTER_STREAM_ID: - streamFilter = Pattern.compile(argValue); - break; - - case COUNTER_CHANNEL: - channelFilter = Pattern.compile(argValue); - break; - - default: - System.out.println("Unrecognised argument: '" + arg + "'"); - return; - } - } - } - - final AeronStat aeronStat = new AeronStat( + final AeronStat aeronStat = + new AeronStat( mapCounters(), typeFilter, identityFilter, sessionFilter, streamFilter, channelFilter); - final AtomicBoolean running = new AtomicBoolean(true); - SigInt.register(() -> running.set(false)); + final AtomicBoolean running = new AtomicBoolean(true); + SigInt.register(() -> running.set(false)); - while (running.get()) - { - System.out.print("\033[H\033[2J"); + while (running.get()) { + System.out.print("\033[H\033[2J"); - System.out.format("%1$tH:%1$tM:%1$tS - Aeron Stat%n", new Date()); - System.out.println("========================="); + System.out.format("%1$tH:%1$tM:%1$tS - Aeron Stat%n", new Date()); + System.out.println("========================="); - aeronStat.print(System.out); - System.out.println("--"); + aeronStat.print(System.out); + System.out.println("--"); - Thread.sleep(ONE_SECOND); - } + Thread.sleep(ONE_SECOND); + } + } + + public void print(final PrintStream out) { + counters.forEach( + (counterId, typeId, keyBuffer, label) -> { + if (filter(typeId, keyBuffer)) { + final long value = counters.getCounterValue(counterId); + out.format("%3d: %,20d - %s%n", counterId, value, label); + } + }); + } + + private static void checkForHelp(final String[] args) { + for (final String arg : args) { + if ("-?".equals(arg) || "-h".equals(arg) || "-help".equals(arg)) { + System.out.format( + "Usage: [-Daeron.dir=] AeronStat%n" + + "\tfilter by optional regex patterns:%n" + + "\t[type=]%n" + + "\t[identity=]%n" + + "\t[sessionId=]%n" + + "\t[streamId=]%n" + + "\t[channel=]%n"); + + System.exit(0); + } + } + } + + private boolean filter(final int typeId, final DirectBuffer keyBuffer) { + if (!match(typeFilter, () -> Integer.toString(typeId))) { + return false; } - public void print(final PrintStream out) - { - counters.forEach( - (counterId, typeId, keyBuffer, label) -> - { - if (filter(typeId, keyBuffer)) - { - final long value = counters.getCounterValue(counterId); - out.format("%3d: %,20d - %s%n", counterId, value, label); - } - }); + if (SYSTEM_COUNTER_TYPE_ID == typeId + && !match(identityFilter, () -> Integer.toString(keyBuffer.getInt(0)))) { + return false; + } else if ((typeId >= PUBLISHER_LIMIT_TYPE_ID && typeId <= RECEIVER_POS_TYPE_ID) + || typeId == PER_IMAGE_TYPE_ID) { + if (!match(identityFilter, () -> Long.toString(keyBuffer.getLong(REGISTRATION_ID_OFFSET))) + || !match(sessionFilter, () -> Integer.toString(keyBuffer.getInt(SESSION_ID_OFFSET))) + || !match(streamFilter, () -> Integer.toString(keyBuffer.getInt(STREAM_ID_OFFSET))) + || !match(channelFilter, () -> keyBuffer.getStringUtf8(CHANNEL_OFFSET))) { + return false; + } + } else if (typeId >= SEND_CHANNEL_STATUS_TYPE_ID && typeId <= RECEIVE_CHANNEL_STATUS_TYPE_ID) { + if (!match( + channelFilter, () -> keyBuffer.getStringUtf8(ChannelEndpointStatus.CHANNEL_OFFSET))) { + return false; + } } - private static void checkForHelp(final String[] args) - { - for (final String arg : args) - { - if ("-?".equals(arg) || "-h".equals(arg) || "-help".equals(arg)) - { - System.out.format( - "Usage: [-Daeron.dir=] AeronStat%n" + - "\tfilter by optional regex patterns:%n" + - "\t[type=]%n" + - "\t[identity=]%n" + - "\t[sessionId=]%n" + - "\t[streamId=]%n" + - "\t[channel=]%n"); + return true; + } - System.exit(0); - } - } - } - - private boolean filter(final int typeId, final DirectBuffer keyBuffer) - { - if (!match(typeFilter, () -> Integer.toString(typeId))) - { - return false; - } - - if (SYSTEM_COUNTER_TYPE_ID == typeId && !match(identityFilter, () -> Integer.toString(keyBuffer.getInt(0)))) - { - return false; - } - else if ((typeId >= PUBLISHER_LIMIT_TYPE_ID && typeId <= RECEIVER_POS_TYPE_ID) || typeId == PER_IMAGE_TYPE_ID) - { - if (!match(identityFilter, () -> Long.toString(keyBuffer.getLong(REGISTRATION_ID_OFFSET))) || - !match(sessionFilter, () -> Integer.toString(keyBuffer.getInt(SESSION_ID_OFFSET))) || - !match(streamFilter, () -> Integer.toString(keyBuffer.getInt(STREAM_ID_OFFSET))) || - !match(channelFilter, () -> keyBuffer.getStringUtf8(CHANNEL_OFFSET))) - { - return false; - } - } - else if (typeId >= SEND_CHANNEL_STATUS_TYPE_ID && typeId <= RECEIVE_CHANNEL_STATUS_TYPE_ID) - { - if (!match(channelFilter, () -> keyBuffer.getStringUtf8(ChannelEndpointStatus.CHANNEL_OFFSET))) - { - return false; - } - } - - return true; - } - - private static boolean match(final Pattern pattern, final Supplier supplier) - { - return null == pattern || pattern.matcher(supplier.get()).find(); - } + private static boolean match(final Pattern pattern, final Supplier supplier) { + return null == pattern || pattern.matcher(supplier.get()).find(); + } } diff --git a/akka-remote/src/test/java/akka/remote/transport/ThrottlerTransportAdapterTest.java b/akka-remote/src/test/java/akka/remote/transport/ThrottlerTransportAdapterTest.java index 5779d09c2c..53e4b13986 100644 --- a/akka-remote/src/test/java/akka/remote/transport/ThrottlerTransportAdapterTest.java +++ b/akka-remote/src/test/java/akka/remote/transport/ThrottlerTransportAdapterTest.java @@ -7,20 +7,19 @@ package akka.remote.transport; // compile only; verify java interop public class ThrottlerTransportAdapterTest { - public void compileThrottlerTransportAdapterDirections() { - acceptDirection(ThrottlerTransportAdapter.bothDirection()); - acceptDirection(ThrottlerTransportAdapter.receiveDirection()); - acceptDirection(ThrottlerTransportAdapter.sendDirection()); - } + public void compileThrottlerTransportAdapterDirections() { + acceptDirection(ThrottlerTransportAdapter.bothDirection()); + acceptDirection(ThrottlerTransportAdapter.receiveDirection()); + acceptDirection(ThrottlerTransportAdapter.sendDirection()); + } - public void compleThrottleMode() { - acceptThrottleMode(ThrottlerTransportAdapter.unthrottledThrottleMode()); - acceptThrottleMode(ThrottlerTransportAdapter.blackholeThrottleMode()); - acceptThrottleMode(new ThrottlerTransportAdapter.TokenBucket(0, 0.0, 0, 0)); - } + public void compleThrottleMode() { + acceptThrottleMode(ThrottlerTransportAdapter.unthrottledThrottleMode()); + acceptThrottleMode(ThrottlerTransportAdapter.blackholeThrottleMode()); + acceptThrottleMode(new ThrottlerTransportAdapter.TokenBucket(0, 0.0, 0, 0)); + } - void acceptDirection(ThrottlerTransportAdapter.Direction dir) {} - - void acceptThrottleMode(ThrottlerTransportAdapter.ThrottleMode mode) {} + void acceptDirection(ThrottlerTransportAdapter.Direction dir) {} + void acceptThrottleMode(ThrottlerTransportAdapter.ThrottleMode mode) {} } diff --git a/akka-stream-tests/src/test/java/akka/stream/StreamTest.java b/akka-stream-tests/src/test/java/akka/stream/StreamTest.java index d6a96b4a53..9cee0fdaeb 100644 --- a/akka-stream-tests/src/test/java/akka/stream/StreamTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/StreamTest.java @@ -13,24 +13,24 @@ import akka.actor.ActorSystem; import akka.testkit.AkkaJUnitActorSystemResource; public abstract class StreamTest extends JUnitSuite { - final protected ActorSystem system; - final private ActorMaterializerSettings settings; + protected final ActorSystem system; + private final ActorMaterializerSettings settings; - protected ActorMaterializer materializer; + protected ActorMaterializer materializer; - protected StreamTest(AkkaJUnitActorSystemResource actorSystemResource) { - system = actorSystemResource.getSystem(); - settings = ActorMaterializerSettings.create(system); - } + protected StreamTest(AkkaJUnitActorSystemResource actorSystemResource) { + system = actorSystemResource.getSystem(); + settings = ActorMaterializerSettings.create(system); + } - @Before - public void setUp() { - materializer = ActorMaterializer.create(settings, system); - } + @Before + public void setUp() { + materializer = ActorMaterializer.create(settings, system); + } - @After - public void tearDown() { - StreamTestKit.assertAllStagesStopped(materializer); - materializer.shutdown(); - } + @After + public void tearDown() { + StreamTestKit.assertAllStagesStopped(materializer); + materializer.shutdown(); + } } diff --git a/akka-stream-tests/src/test/java/akka/stream/actor/ActorPublisherTest.java b/akka-stream-tests/src/test/java/akka/stream/actor/ActorPublisherTest.java index 629e634146..76edc7baad 100644 --- a/akka-stream-tests/src/test/java/akka/stream/actor/ActorPublisherTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/actor/ActorPublisherTest.java @@ -23,9 +23,10 @@ public class ActorPublisherTest extends StreamTest { } @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("ActorPublisherTest", AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("ActorPublisherTest", AkkaSpec.testConf()); - public static class TestPublisher extends UntypedActorPublisher { + public static class TestPublisher extends UntypedActorPublisher { @Override public void onReceive(Object msg) { @@ -43,18 +44,21 @@ public class ActorPublisherTest extends StreamTest { @Test public void mustHaveJavaAPI() { final TestKit probe = new TestKit(system); - final ActorRef ref = system - .actorOf(Props.create(TestPublisher.class).withDispatcher("akka.test.stream-dispatcher")); + final ActorRef ref = + system.actorOf( + Props.create(TestPublisher.class).withDispatcher("akka.test.stream-dispatcher")); final Publisher publisher = UntypedActorPublisher.create(ref); Source.fromPublisher(publisher) - .runForeach(new akka.japi.function.Procedure() { - private static final long serialVersionUID = 1L; - @Override - public void apply(Integer elem) throws Exception { - probe.getRef().tell(elem, ActorRef.noSender()); - } - }, materializer); + .runForeach( + new akka.japi.function.Procedure() { + private static final long serialVersionUID = 1L; + + @Override + public void apply(Integer elem) throws Exception { + probe.getRef().tell(elem, ActorRef.noSender()); + } + }, + materializer); probe.expectMsgEquals(1); } - } diff --git a/akka-stream-tests/src/test/java/akka/stream/actor/ActorSubscriberTest.java b/akka-stream-tests/src/test/java/akka/stream/actor/ActorSubscriberTest.java index 691acf2531..738acf9046 100644 --- a/akka-stream-tests/src/test/java/akka/stream/actor/ActorSubscriberTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/actor/ActorSubscriberTest.java @@ -27,7 +27,8 @@ public class ActorSubscriberTest extends StreamTest { } @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("FlowTest", AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("FlowTest", AkkaSpec.testConf()); public static class TestSubscriber extends UntypedActorSubscriber { @@ -63,7 +64,10 @@ public class ActorSubscriberTest extends StreamTest { @Test public void mustHaveJavaAPI() { final TestKit probe = new TestKit(system); - final ActorRef ref = system.actorOf(Props.create(TestSubscriber.class, probe.getRef()).withDispatcher("akka.test.stream-dispatcher")); + final ActorRef ref = + system.actorOf( + Props.create(TestSubscriber.class, probe.getRef()) + .withDispatcher("akka.test.stream-dispatcher")); final Subscriber subscriber = UntypedActorSubscriber.create(ref); final java.lang.Iterable input = Arrays.asList(1, 2, 3); @@ -75,5 +79,4 @@ public class ActorSubscriberTest extends StreamTest { probe.expectMsgEquals(3); probe.expectMsgEquals("done"); } - } diff --git a/akka-stream-tests/src/test/java/akka/stream/io/InputStreamSinkTest.java b/akka-stream-tests/src/test/java/akka/stream/io/InputStreamSinkTest.java index f7a74aac35..3f0de81105 100644 --- a/akka-stream-tests/src/test/java/akka/stream/io/InputStreamSinkTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/io/InputStreamSinkTest.java @@ -26,25 +26,25 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertTrue; -public class InputStreamSinkTest extends StreamTest { - public InputStreamSinkTest() { - super(actorSystemResource); - } +public class InputStreamSinkTest extends StreamTest { + public InputStreamSinkTest() { + super(actorSystemResource); + } - @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("InputStreamSink", - Utils.UnboundedMailboxConfig()); - @Test - public void mustReadEventViaInputStream() throws Exception { - final FiniteDuration timeout = FiniteDuration.create(300, TimeUnit.MILLISECONDS); + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("InputStreamSink", Utils.UnboundedMailboxConfig()); - final Sink sink = StreamConverters.asInputStream(timeout); - final List list = Collections.singletonList(ByteString.fromString("a")); - final InputStream stream = Source.from(list).runWith(sink, materializer); + @Test + public void mustReadEventViaInputStream() throws Exception { + final FiniteDuration timeout = FiniteDuration.create(300, TimeUnit.MILLISECONDS); - byte[] a = new byte[1]; - stream.read(a); - assertTrue(Arrays.equals("a".getBytes(), a)); - } + final Sink sink = StreamConverters.asInputStream(timeout); + final List list = Collections.singletonList(ByteString.fromString("a")); + final InputStream stream = Source.from(list).runWith(sink, materializer); + byte[] a = new byte[1]; + stream.read(a); + assertTrue(Arrays.equals("a".getBytes(), a)); + } } diff --git a/akka-stream-tests/src/test/java/akka/stream/io/OutputStreamSinkTest.java b/akka-stream-tests/src/test/java/akka/stream/io/OutputStreamSinkTest.java index a836506744..82128ffc68 100644 --- a/akka-stream-tests/src/test/java/akka/stream/io/OutputStreamSinkTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/io/OutputStreamSinkTest.java @@ -24,31 +24,35 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; -public class OutputStreamSinkTest extends StreamTest { - public OutputStreamSinkTest() { - super(actorSystemResource); - } +public class OutputStreamSinkTest extends StreamTest { + public OutputStreamSinkTest() { + super(actorSystemResource); + } - @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("OutputStreamSinkTest", - Utils.UnboundedMailboxConfig()); - @Test - public void mustSignalFailureViaIoResult() throws Exception { + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("OutputStreamSinkTest", Utils.UnboundedMailboxConfig()); - final OutputStream os = new OutputStream() { - volatile int left = 3; - public void write(int data) { - if (left == 0) { - throw new RuntimeException("Can't accept more data."); + @Test + public void mustSignalFailureViaIoResult() throws Exception { + + final OutputStream os = + new OutputStream() { + volatile int left = 3; + + public void write(int data) { + if (left == 0) { + throw new RuntimeException("Can't accept more data."); + } + left -= 1; } - left -= 1; - } - }; - final CompletionStage resultFuture = Source.single(ByteString.fromString("123456")).runWith(StreamConverters.fromOutputStream(() -> os), materializer); - final IOResult result = resultFuture.toCompletableFuture().get(3, TimeUnit.SECONDS); - - assertFalse(result.wasSuccessful()); - assertTrue(result.getError().getMessage().equals("Can't accept more data.")); - } + }; + final CompletionStage resultFuture = + Source.single(ByteString.fromString("123456")) + .runWith(StreamConverters.fromOutputStream(() -> os), materializer); + final IOResult result = resultFuture.toCompletableFuture().get(3, TimeUnit.SECONDS); + assertFalse(result.wasSuccessful()); + assertTrue(result.getError().getMessage().equals("Can't accept more data.")); + } } diff --git a/akka-stream-tests/src/test/java/akka/stream/io/OutputStreamSourceTest.java b/akka-stream-tests/src/test/java/akka/stream/io/OutputStreamSourceTest.java index b7038f4d59..94aabc2786 100644 --- a/akka-stream-tests/src/test/java/akka/stream/io/OutputStreamSourceTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/io/OutputStreamSourceTest.java @@ -24,32 +24,36 @@ import akka.stream.testkit.Utils; import akka.util.ByteString; public class OutputStreamSourceTest extends StreamTest { - public OutputStreamSourceTest() { - super(actorSystemResource); - } + public OutputStreamSourceTest() { + super(actorSystemResource); + } - @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("OutputStreamSourceTest2", - Utils.UnboundedMailboxConfig()); - @Test - public void mustSendEventsViaOutputStream() throws Exception { - final TestKit probe = new TestKit(system); - final Duration timeout = Duration.ofSeconds(3); + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("OutputStreamSourceTest2", Utils.UnboundedMailboxConfig()); - final Source source = StreamConverters.asOutputStream(timeout); - final OutputStream s = source.to(Sink.foreach(new Procedure() { - private static final long serialVersionUID = 1L; - public void apply(ByteString elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - })).run(materializer); + @Test + public void mustSendEventsViaOutputStream() throws Exception { + final TestKit probe = new TestKit(system); + final Duration timeout = Duration.ofSeconds(3); - s.write("a".getBytes()); - - - assertEquals(ByteString.fromString("a"), probe.receiveOne(timeout)); - s.close(); + final Source source = StreamConverters.asOutputStream(timeout); + final OutputStream s = + source + .to( + Sink.foreach( + new Procedure() { + private static final long serialVersionUID = 1L; - } + public void apply(ByteString elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + })) + .run(materializer); + s.write("a".getBytes()); + + assertEquals(ByteString.fromString("a"), probe.receiveOne(timeout)); + s.close(); + } } diff --git a/akka-stream-tests/src/test/java/akka/stream/io/SinkAsJavaSourceTest.java b/akka-stream-tests/src/test/java/akka/stream/io/SinkAsJavaSourceTest.java index 47d33d9a4d..8cd3c0641c 100644 --- a/akka-stream-tests/src/test/java/akka/stream/io/SinkAsJavaSourceTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/io/SinkAsJavaSourceTest.java @@ -4,7 +4,6 @@ package akka.stream.io; - import akka.stream.StreamTest; import akka.testkit.AkkaJUnitActorSystemResource; import akka.stream.javadsl.Sink; @@ -22,19 +21,20 @@ import java.util.stream.Stream; import static org.junit.Assert.assertEquals; public class SinkAsJavaSourceTest extends StreamTest { - public SinkAsJavaSourceTest() { - super(actorSystemResource); - } + public SinkAsJavaSourceTest() { + super(actorSystemResource); + } - @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("OutputStreamSource", - Utils.UnboundedMailboxConfig()); + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("OutputStreamSource", Utils.UnboundedMailboxConfig()); - @Test - public void mustBeAbleToUseAsJavaStream() throws Exception { - final List list = Arrays.asList(1, 2, 3); - final Sink> streamSink = StreamConverters.asJavaStream(); - java.util.stream.Stream javaStream= Source.from(list).runWith(streamSink, materializer); - assertEquals(list, javaStream.collect(Collectors.toList())); - } + @Test + public void mustBeAbleToUseAsJavaStream() throws Exception { + final List list = Arrays.asList(1, 2, 3); + final Sink> streamSink = StreamConverters.asJavaStream(); + java.util.stream.Stream javaStream = + Source.from(list).runWith(streamSink, materializer); + assertEquals(list, javaStream.collect(Collectors.toList())); + } } diff --git a/akka-stream-tests/src/test/java/akka/stream/javadsl/AttributesTest.java b/akka-stream-tests/src/test/java/akka/stream/javadsl/AttributesTest.java index c65d94a726..b8a8321498 100644 --- a/akka-stream-tests/src/test/java/akka/stream/javadsl/AttributesTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/javadsl/AttributesTest.java @@ -25,19 +25,17 @@ public class AttributesTest extends StreamTest { } @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("AttributesTest", - AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("AttributesTest", AkkaSpec.testConf()); final Attributes attributes = - Attributes.name("a") - .and(Attributes.name("b")) - .and(Attributes.inputBuffer(1, 2)); + Attributes.name("a").and(Attributes.name("b")).and(Attributes.inputBuffer(1, 2)); @Test public void mustGetAttributesByClass() { assertEquals( - Arrays.asList(new Attributes.Name("b"), new Attributes.Name("a")), - attributes.getAttributeList(Attributes.Name.class)); + Arrays.asList(new Attributes.Name("b"), new Attributes.Name("a")), + attributes.getAttributeList(Attributes.Name.class)); assertEquals( Collections.singletonList(new Attributes.InputBuffer(1, 2)), attributes.getAttributeList(Attributes.InputBuffer.class)); @@ -46,36 +44,29 @@ public class AttributesTest extends StreamTest { @Test public void mustGetAttributeByClass() { assertEquals( - new Attributes.Name("b"), - attributes.getAttribute(Attributes.Name.class, new Attributes.Name("default"))); + new Attributes.Name("b"), + attributes.getAttribute(Attributes.Name.class, new Attributes.Name("default"))); } @Test public void mustGetMissingAttributeByClass() { - assertEquals( - Optional.empty(), - attributes.getAttribute(Attributes.LogLevels.class)); + assertEquals(Optional.empty(), attributes.getAttribute(Attributes.LogLevels.class)); } @Test public void mustGetPossiblyMissingAttributeByClass() { assertEquals( - Optional.of(new Attributes.Name("b")), - attributes.getAttribute(Attributes.Name.class)); + Optional.of(new Attributes.Name("b")), attributes.getAttribute(Attributes.Name.class)); } @Test public void mustGetPossiblyMissingFirstAttributeByClass() { assertEquals( - Optional.of(new Attributes.Name("a")), - attributes.getFirstAttribute(Attributes.Name.class)); + Optional.of(new Attributes.Name("a")), attributes.getFirstAttribute(Attributes.Name.class)); } @Test public void mustGetMissingFirstAttributeByClass() { - assertEquals( - Optional.empty(), - attributes.getFirstAttribute(Attributes.LogLevels.class)); + assertEquals(Optional.empty(), attributes.getFirstAttribute(Attributes.LogLevels.class)); } - } diff --git a/akka-stream-tests/src/test/java/akka/stream/javadsl/FlowTest.java b/akka-stream-tests/src/test/java/akka/stream/javadsl/FlowTest.java index deb6940034..e2cd937305 100644 --- a/akka-stream-tests/src/test/java/akka/stream/javadsl/FlowTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/javadsl/FlowTest.java @@ -45,11 +45,13 @@ public class FlowTest extends StreamTest { } @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("FlowTest", - AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("FlowTest", AkkaSpec.testConf()); interface Fruit {} + static class Apple implements Fruit {}; + static class Orange implements Fruit {}; public void compileOnlyUpcast() { @@ -62,35 +64,46 @@ public class FlowTest extends StreamTest { @Test public void mustBeAbleToUseSimpleOperators() { final TestKit probe = new TestKit(system); - final String[] lookup = { "a", "b", "c", "d", "e", "f" }; + final String[] lookup = {"a", "b", "c", "d", "e", "f"}; final java.lang.Iterable input = Arrays.asList(0, 1, 2, 3, 4, 5); final Source ints = Source.from(input); - final Flow flow1 = Flow.of(Integer.class).drop(2).take(3 - ).takeWithin(Duration.ofSeconds(10 - )).map(new Function() { - public String apply(Integer elem) { - return lookup[elem]; - } - }).filter(new Predicate() { - public boolean test(String elem) { - return !elem.equals("c"); - } - }); - final Flow flow2 = Flow.of(String.class).grouped(2 - ).mapConcat(new Function, java.lang.Iterable>() { - public java.util.List apply(java.util.List elem) { - return elem; - } - }).groupedWithin(100, Duration.ofMillis(50) - ).mapConcat(new Function, java.lang.Iterable>() { - public java.util.List apply(java.util.List elem) { - return elem; - } - }); + final Flow flow1 = + Flow.of(Integer.class) + .drop(2) + .take(3) + .takeWithin(Duration.ofSeconds(10)) + .map( + new Function() { + public String apply(Integer elem) { + return lookup[elem]; + } + }) + .filter( + new Predicate() { + public boolean test(String elem) { + return !elem.equals("c"); + } + }); + final Flow flow2 = + Flow.of(String.class) + .grouped(2) + .mapConcat( + new Function, java.lang.Iterable>() { + public java.util.List apply(java.util.List elem) { + return elem; + } + }) + .groupedWithin(100, Duration.ofMillis(50)) + .mapConcat( + new Function, java.lang.Iterable>() { + public java.util.List apply(java.util.List elem) { + return elem; + } + }); ints.via(flow1.via(flow2)) - .runFold("", (acc, elem) -> acc + elem, materializer) - .thenAccept(elem -> probe.getRef().tell(elem, ActorRef.noSender())); + .runFold("", (acc, elem) -> acc + elem, materializer) + .thenAccept(elem -> probe.getRef().tell(elem, ActorRef.noSender())); probe.expectMsgEquals("de"); } @@ -99,11 +112,13 @@ public class FlowTest extends StreamTest { public void mustBeAbleToUseDropWhile() throws Exception { final TestKit probe = new TestKit(system); final Source source = Source.from(Arrays.asList(0, 1, 2, 3)); - final Flow flow = - Flow.of(Integer.class).dropWhile(elem -> elem < 2); + final Flow flow = Flow.of(Integer.class).dropWhile(elem -> elem < 2); final CompletionStage future = - source.via(flow).runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + source + .via(flow) + .runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); probe.expectMsgEquals(2); probe.expectMsgEquals(3); @@ -115,19 +130,21 @@ public class FlowTest extends StreamTest { final TestKit probe = new TestKit(system); final java.lang.Iterable input = Arrays.asList(1, 2, 3, 4, 5); final Source ints = Source.from(input); - final Flow flow = Flow.of(Integer.class).statefulMapConcat( - () -> { - int[] state = new int[] {0}; - return (elem) -> { - List list = new ArrayList<>(Collections.nCopies(state[0], elem)); - state[0] = elem; - return list; - }; - }); + final Flow flow = + Flow.of(Integer.class) + .statefulMapConcat( + () -> { + int[] state = new int[] {0}; + return (elem) -> { + List list = new ArrayList<>(Collections.nCopies(state[0], elem)); + state[0] = elem; + return list; + }; + }); ints.via(flow) - .runFold("", (acc, elem) -> acc + elem, materializer) - .thenAccept(elem -> probe.getRef().tell(elem, ActorRef.noSender())); + .runFold("", (acc, elem) -> acc + elem, materializer) + .thenAccept(elem -> probe.getRef().tell(elem, ActorRef.noSender())); probe.expectMsgEquals("2334445555"); } @@ -139,7 +156,10 @@ public class FlowTest extends StreamTest { final Flow flow = Flow.of(String.class).intersperse("[", ",", "]"); final CompletionStage future = - source.via(flow).runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + source + .via(flow) + .runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); probe.expectMsgEquals("["); probe.expectMsgEquals("0"); @@ -160,7 +180,10 @@ public class FlowTest extends StreamTest { final Flow flow = Flow.of(String.class).intersperse(","); final CompletionStage future = - Source.single(">> ").concat(source.via(flow)).runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + Source.single(">> ") + .concat(source.via(flow)) + .runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); probe.expectMsgEquals(">> "); probe.expectMsgEquals("0"); @@ -177,15 +200,20 @@ public class FlowTest extends StreamTest { public void mustBeAbleToUseTakeWhile() throws Exception { final TestKit probe = new TestKit(system); final Source source = Source.from(Arrays.asList(0, 1, 2, 3)); - final Flow flow = Flow.of(Integer.class).takeWhile - (new Predicate() { - public boolean test(Integer elem) { - return elem < 2; - } - }); + final Flow flow = + Flow.of(Integer.class) + .takeWhile( + new Predicate() { + public boolean test(Integer elem) { + return elem < 2; + } + }); final CompletionStage future = - source.via(flow).runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + source + .via(flow) + .runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); probe.expectMsgEquals(0); probe.expectMsgEquals(1); @@ -193,56 +221,67 @@ public class FlowTest extends StreamTest { future.toCompletableFuture().get(3, TimeUnit.SECONDS); } - @Test public void mustBeAbleToUseVia() { final TestKit probe = new TestKit(system); final Iterable input = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7); // duplicate each element, stop after 4 elements, and emit sum to the end - final Flow flow = Flow.of(Integer.class).via(new GraphStage>() { + final Flow flow = + Flow.of(Integer.class) + .via( + new GraphStage>() { - public final Inlet in = Inlet.create("in"); - public final Outlet out = Outlet.create("out"); + public final Inlet in = Inlet.create("in"); + public final Outlet out = Outlet.create("out"); - @Override - public GraphStageLogic createLogic(Attributes inheritedAttributes) throws Exception { - return new GraphStageLogic(shape()) { - int sum = 0; - int count = 0; + @Override + public GraphStageLogic createLogic(Attributes inheritedAttributes) + throws Exception { + return new GraphStageLogic(shape()) { + int sum = 0; + int count = 0; - { - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() throws Exception { - final Integer element = grab(in); - sum += element; - count += 1; - if (count == 4) { - emitMultiple(out, Arrays.asList(element, element, sum).iterator(), () -> completeStage()); - } else { - emitMultiple(out, Arrays.asList(element, element).iterator()); - } + { + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() throws Exception { + final Integer element = grab(in); + sum += element; + count += 1; + if (count == 4) { + emitMultiple( + out, + Arrays.asList(element, element, sum).iterator(), + () -> completeStage()); + } else { + emitMultiple(out, Arrays.asList(element, element).iterator()); + } + } + }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + pull(in); + } + }); + } + }; + } - } - }); - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - pull(in); - } - }); - } - }; - } - - @Override - public FlowShape shape() { - return FlowShape.of(in, out); - } - } - ); - Source.from(input).via(flow).runForeach((Procedure) elem -> - probe.getRef().tell(elem, ActorRef.noSender()), materializer); + @Override + public FlowShape shape() { + return FlowShape.of(in, out); + } + }); + Source.from(input) + .via(flow) + .runForeach( + (Procedure) elem -> probe.getRef().tell(elem, ActorRef.noSender()), + materializer); probe.expectMsgEquals(0); probe.expectMsgEquals(0); @@ -259,67 +298,85 @@ public class FlowTest extends StreamTest { @Test public void mustBeAbleToUseGroupBy() throws Exception { final Iterable input = Arrays.asList("Aaa", "Abb", "Bcc", "Cdd", "Cee"); - final Flow, NotUsed> flow = Flow - .of(String.class) - .groupBy(3, new Function() { - public String apply(String elem) { - return elem.substring(0, 1); - } - }) - .grouped(10) - .mergeSubstreams(); + final Flow, NotUsed> flow = + Flow.of(String.class) + .groupBy( + 3, + new Function() { + public String apply(String elem) { + return elem.substring(0, 1); + } + }) + .grouped(10) + .mergeSubstreams(); final CompletionStage>> future = - Source.from(input).via(flow).limit(10).runWith(Sink.> seq(), materializer); + Source.from(input).via(flow).limit(10).runWith(Sink.>seq(), materializer); final Object[] result = future.toCompletableFuture().get(1, TimeUnit.SECONDS).toArray(); - Arrays.sort(result, (Comparator)(Object) new Comparator>() { - @Override - public int compare(List o1, List o2) { - return o1.get(0).charAt(0) - o2.get(0).charAt(0); - } - }); + Arrays.sort( + result, + (Comparator) + (Object) + new Comparator>() { + @Override + public int compare(List o1, List o2) { + return o1.get(0).charAt(0) - o2.get(0).charAt(0); + } + }); - assertArrayEquals(new Object[] { Arrays.asList("Aaa", "Abb"), Arrays.asList("Bcc"), Arrays.asList("Cdd", "Cee") }, result); + assertArrayEquals( + new Object[] { + Arrays.asList("Aaa", "Abb"), Arrays.asList("Bcc"), Arrays.asList("Cdd", "Cee") + }, + result); } @Test public void mustBeAbleToUseSplitWhen() throws Exception { final Iterable input = Arrays.asList("A", "B", "C", ".", "D", ".", "E", "F"); - final Flow, NotUsed> flow = Flow - .of(String.class) - .splitWhen(new Predicate() { - public boolean test(String elem) { - return elem.equals("."); - } - }) - .grouped(10) - .concatSubstreams(); + final Flow, NotUsed> flow = + Flow.of(String.class) + .splitWhen( + new Predicate() { + public boolean test(String elem) { + return elem.equals("."); + } + }) + .grouped(10) + .concatSubstreams(); final CompletionStage>> future = - Source.from(input).via(flow).limit(10).runWith(Sink.> seq(), materializer); + Source.from(input).via(flow).limit(10).runWith(Sink.>seq(), materializer); final List> result = future.toCompletableFuture().get(1, TimeUnit.SECONDS); - assertEquals(Arrays.asList(Arrays.asList("A", "B", "C"), Arrays.asList(".", "D"), Arrays.asList(".", "E", "F")), result); + assertEquals( + Arrays.asList( + Arrays.asList("A", "B", "C"), Arrays.asList(".", "D"), Arrays.asList(".", "E", "F")), + result); } @Test public void mustBeAbleToUseSplitAfter() throws Exception { - final Iterable input = Arrays.asList("A", "B", "C", ".", "D", ".", "E", "F"); - final Flow, NotUsed> flow = Flow - .of(String.class) - .splitAfter(new Predicate() { - public boolean test(String elem) { - return elem.equals("."); - } - }) - .grouped(10) - .concatSubstreams(); + final Iterable input = Arrays.asList("A", "B", "C", ".", "D", ".", "E", "F"); + final Flow, NotUsed> flow = + Flow.of(String.class) + .splitAfter( + new Predicate() { + public boolean test(String elem) { + return elem.equals("."); + } + }) + .grouped(10) + .concatSubstreams(); final CompletionStage>> future = - Source.from(input).via(flow).limit(10).runWith(Sink.> seq(), materializer); + Source.from(input).via(flow).limit(10).runWith(Sink.>seq(), materializer); final List> result = future.toCompletableFuture().get(1, TimeUnit.SECONDS); - assertEquals(Arrays.asList(Arrays.asList("A", "B", "C", "."), Arrays.asList("D", "."), Arrays.asList("E", "F")), result); + assertEquals( + Arrays.asList( + Arrays.asList("A", "B", "C", "."), Arrays.asList("D", "."), Arrays.asList("E", "F")), + result); } public GraphStage> op() { @@ -331,18 +388,22 @@ public class FlowTest extends StreamTest { public GraphStageLogic createLogic(Attributes inheritedAttributes) throws Exception { return new GraphStageLogic(shape()) { { - setHandler(in, new AbstractInHandler() { - @Override - public void onPush() throws Exception { - push(out, grab(in)); - } - }); - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - pull(in); - } - }); + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() throws Exception { + push(out, grab(in)); + } + }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + pull(in); + } + }); } }; } @@ -369,72 +430,81 @@ public class FlowTest extends StreamTest { final Sink> publisher = Sink.asPublisher(AsPublisher.WITHOUT_FANOUT); - final Source source = Source.fromGraph( - GraphDSL.create(new Function, SourceShape>() { - @Override - public SourceShape apply(Builder b) throws Exception { - final UniformFanInShape merge = b.add(Merge.create(2)); - b.from(b.add(in1)).via(b.add(f1)).toInlet(merge.in(0)); - b.from(b.add(in2)).via(b.add(f2)).toInlet(merge.in(1)); - return new SourceShape(merge.out()); - } - })); + final Source source = + Source.fromGraph( + GraphDSL.create( + new Function, SourceShape>() { + @Override + public SourceShape apply(Builder b) throws Exception { + final UniformFanInShape merge = b.add(Merge.create(2)); + b.from(b.add(in1)).via(b.add(f1)).toInlet(merge.in(0)); + b.from(b.add(in2)).via(b.add(f2)).toInlet(merge.in(1)); + return new SourceShape(merge.out()); + } + })); // collecting final Publisher pub = source.runWith(publisher, materializer); - final CompletionStage> all = Source.fromPublisher(pub).limit(100).runWith(Sink.seq(), materializer); + final CompletionStage> all = + Source.fromPublisher(pub).limit(100).runWith(Sink.seq(), materializer); final List result = all.toCompletableFuture().get(3, TimeUnit.SECONDS); - assertEquals(new HashSet(Arrays.asList("a", "b", "c", "d", "e", "f")), new HashSet(result)); + assertEquals( + new HashSet(Arrays.asList("a", "b", "c", "d", "e", "f")), + new HashSet(result)); } @Test public void mustBeAbleToUsefromSourceCompletionStage() throws Exception { final Flow f1 = - Flow.of(String.class).via(FlowTest.this. op()).named("f1"); + Flow.of(String.class).via(FlowTest.this.op()).named("f1"); final Flow f2 = - Flow.of(String.class).via(FlowTest.this. op()).named("f2"); + Flow.of(String.class).via(FlowTest.this.op()).named("f2"); @SuppressWarnings("unused") final Flow f3 = - Flow.of(String.class).via(FlowTest.this. op()).named("f3"); + Flow.of(String.class).via(FlowTest.this.op()).named("f3"); final Source in1 = Source.from(Arrays.asList("a", "b", "c")); final Source in2 = Source.from(Arrays.asList("d", "e", "f")); final Sink> publisher = Sink.asPublisher(AsPublisher.WITHOUT_FANOUT); - final Graph, NotUsed> graph = Source.fromGraph( - GraphDSL.create(new Function, SourceShape>() { - @Override - public SourceShape apply(Builder b) - throws Exception { - final UniformFanInShape merge = - b.add(Merge.create(2)); - b.from(b.add(in1)).via(b.add(f1)).toInlet(merge.in(0)); - b.from(b.add(in2)).via(b.add(f2)).toInlet(merge.in(1)); - return new SourceShape(merge.out()); - } + final Graph, NotUsed> graph = + Source.fromGraph( + GraphDSL.create( + new Function, SourceShape>() { + @Override + public SourceShape apply(Builder b) throws Exception { + final UniformFanInShape merge = b.add(Merge.create(2)); + b.from(b.add(in1)).via(b.add(f1)).toInlet(merge.in(0)); + b.from(b.add(in2)).via(b.add(f2)).toInlet(merge.in(1)); + return new SourceShape(merge.out()); + } })); final Supplier, NotUsed>> fn = new Supplier, NotUsed>>() { - public Graph, NotUsed> get() { return graph; } + public Graph, NotUsed> get() { + return graph; + } }; final CompletionStage, NotUsed>> stage = CompletableFuture.supplyAsync(fn); - final Source> source = - Source.fromSourceCompletionStage(stage); + final Source> source = Source.fromSourceCompletionStage(stage); // collecting final Publisher pub = source.runWith(publisher, materializer); - final CompletionStage> all = Source.fromPublisher(pub).limit(100).runWith(Sink.seq(), materializer); + final CompletionStage> all = + Source.fromPublisher(pub).limit(100).runWith(Sink.seq(), materializer); final List result = all.toCompletableFuture().get(3, TimeUnit.SECONDS); - assertEquals(new HashSet(Arrays.asList("a", "b", "c", "d", "e", "f")), new HashSet(result)); + assertEquals( + new HashSet(Arrays.asList("a", "b", "c", "d", "e", "f")), + new HashSet(result)); } @Test @@ -443,29 +513,38 @@ public class FlowTest extends StreamTest { final Iterable input1 = Arrays.asList("A", "B", "C"); final Iterable input2 = Arrays.asList(1, 2, 3); - RunnableGraph.fromGraph(GraphDSL.create(new Function, ClosedShape>(){ - public ClosedShape apply(Builder b) { - final Outlet in1 = b.add(Source.from(input1)).out(); - final Outlet in2 = b.add(Source.from(input2)).out(); - final FanInShape2> zip = b.add(Zip.create()); - final SinkShape> out = - b.add(Sink.foreach(new Procedure>() { - @Override - public void apply(Pair param) throws Exception { - probe.getRef().tell(param, ActorRef.noSender()); - } - })); + RunnableGraph.fromGraph( + GraphDSL.create( + new Function, ClosedShape>() { + public ClosedShape apply(Builder b) { + final Outlet in1 = b.add(Source.from(input1)).out(); + final Outlet in2 = b.add(Source.from(input2)).out(); + final FanInShape2> zip = + b.add(Zip.create()); + final SinkShape> out = + b.add( + Sink.foreach( + new Procedure>() { + @Override + public void apply(Pair param) throws Exception { + probe.getRef().tell(param, ActorRef.noSender()); + } + })); - b.from(in1).toInlet(zip.in0()); - b.from(in2).toInlet(zip.in1()); - b.from(zip.out()).to(out); - return ClosedShape.getInstance(); - } - })).run(materializer); + b.from(in1).toInlet(zip.in0()); + b.from(in2).toInlet(zip.in1()); + b.from(zip.out()).to(out); + return ClosedShape.getInstance(); + } + })) + .run(materializer); List output = probe.receiveN(3); - List> expected = Arrays.asList(new Pair("A", 1), new Pair( - "B", 2), new Pair("C", 3)); + List> expected = + Arrays.asList( + new Pair("A", 1), + new Pair("B", 2), + new Pair("C", 3)); assertEquals(expected, output); } @@ -478,11 +557,14 @@ public class FlowTest extends StreamTest { final Source in1 = Source.from(input1); final Source in2 = Source.from(input2); final Flow flow = Flow.of(String.class); - in1.via(flow.concat(in2)).runForeach(new Procedure() { - public void apply(String elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - }, materializer); + in1.via(flow.concat(in2)) + .runForeach( + new Procedure() { + public void apply(String elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + }, + materializer); List output = probe.receiveN(6); assertEquals(Arrays.asList("A", "B", "C", "D", "E", "F"), output); @@ -497,11 +579,14 @@ public class FlowTest extends StreamTest { final Source in1 = Source.from(input1); final Source in2 = Source.from(input2); final Flow flow = Flow.of(String.class); - in2.via(flow.prepend(in1)).runForeach(new Procedure() { - public void apply(String elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - }, materializer); + in2.via(flow.prepend(in1)) + .runForeach( + new Procedure() { + public void apply(String elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + }, + materializer); List output = probe.receiveN(6); assertEquals(Arrays.asList("A", "B", "C", "D", "E", "F"), output); @@ -511,13 +596,18 @@ public class FlowTest extends StreamTest { public void mustBeAbleToUsePrefixAndTail() throws Exception { final TestKit probe = new TestKit(system); final Iterable input = Arrays.asList(1, 2, 3, 4, 5, 6); - final Flow, Source>, NotUsed> flow = Flow.of(Integer.class).prefixAndTail(3); + final Flow, Source>, NotUsed> flow = + Flow.of(Integer.class).prefixAndTail(3); CompletionStage, Source>> future = - Source.from(input).via(flow).runWith(Sink., Source>>head(), materializer); - Pair, Source> result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); + Source.from(input) + .via(flow) + .runWith(Sink., Source>>head(), materializer); + Pair, Source> result = + future.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals(Arrays.asList(1, 2, 3), result.first()); - CompletionStage> tailFuture = result.second().limit(4).runWith(Sink.seq(), materializer); + CompletionStage> tailFuture = + result.second().limit(4).runWith(Sink.seq(), materializer); List tailResult = tailFuture.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals(Arrays.asList(4, 5, 6), tailResult); } @@ -528,14 +618,16 @@ public class FlowTest extends StreamTest { final Iterable input1 = Arrays.asList(1, 2, 3); final Iterable input2 = Arrays.asList(4, 5); - final List> mainInputs = new ArrayList>(); + final List> mainInputs = new ArrayList>(); mainInputs.add(Source.from(input1)); mainInputs.add(Source.from(input2)); - final Flow, List, NotUsed> flow = Flow.>create(). - flatMapConcat(ConstantFun.>javaIdentityFunction()).grouped(6); - CompletionStage> future = Source.from(mainInputs).via(flow) - .runWith(Sink.>head(), materializer); + final Flow, List, NotUsed> flow = + Flow.>create() + .flatMapConcat(ConstantFun.>javaIdentityFunction()) + .grouped(6); + CompletionStage> future = + Source.from(mainInputs).via(flow).runWith(Sink.>head(), materializer); List result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); @@ -550,20 +642,22 @@ public class FlowTest extends StreamTest { final Iterable input3 = Arrays.asList(20, 21, 22, 23, 24, 25, 26, 27, 28, 29); final Iterable input4 = Arrays.asList(30, 31, 32, 33, 34, 35, 36, 37, 38, 39); - final List> mainInputs = new ArrayList>(); + final List> mainInputs = new ArrayList>(); mainInputs.add(Source.from(input1)); mainInputs.add(Source.from(input2)); mainInputs.add(Source.from(input3)); mainInputs.add(Source.from(input4)); - final Flow, List, NotUsed> flow = Flow.>create(). - flatMapMerge(3, ConstantFun.>javaIdentityFunction()).grouped(60); - CompletionStage> future = Source.from(mainInputs).via(flow) - .runWith(Sink.>head(), materializer); + final Flow, List, NotUsed> flow = + Flow.>create() + .flatMapMerge(3, ConstantFun.>javaIdentityFunction()) + .grouped(60); + CompletionStage> future = + Source.from(mainInputs).via(flow).runWith(Sink.>head(), materializer); List result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); final Set set = new HashSet(); - for (Integer i: result) { + for (Integer i : result) { set.add(i); } final Set expected = new HashSet(); @@ -578,9 +672,10 @@ public class FlowTest extends StreamTest { public void mustBeAbleToUseBuffer() throws Exception { final TestKit probe = new TestKit(system); final List input = Arrays.asList("A", "B", "C"); - final Flow, NotUsed> flow = Flow.of(String.class).buffer(2, OverflowStrategy.backpressure()).grouped(4); - final CompletionStage> future = Source.from(input).via(flow) - .runWith(Sink.>head(), materializer); + final Flow, NotUsed> flow = + Flow.of(String.class).buffer(2, OverflowStrategy.backpressure()).grouped(4); + final CompletionStage> future = + Source.from(input).via(flow).runWith(Sink.>head(), materializer); List result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals(input, result); @@ -589,9 +684,8 @@ public class FlowTest extends StreamTest { @Test public void mustBeAbleToUseWatchTermination() throws Exception { final List input = Arrays.asList("A", "B", "C"); - CompletionStage future = Source.from(input) - .watchTermination(Keep.right()) - .to(Sink.ignore()).run(materializer); + CompletionStage future = + Source.from(input).watchTermination(Keep.right()).to(Sink.ignore()).run(materializer); assertEquals(done(), future.toCompletableFuture().get(3, TimeUnit.SECONDS)); } @@ -600,24 +694,30 @@ public class FlowTest extends StreamTest { public void mustBeAbleToUseConflate() throws Exception { final TestKit probe = new TestKit(system); final List input = Arrays.asList("A", "B", "C"); - final Flow flow = Flow.of(String.class).conflateWithSeed(new Function() { - @Override - public String apply(String s) throws Exception { - return s; - } - }, new Function2() { - @Override - public String apply(String aggr, String in) throws Exception { - return aggr + in; - } - }); - CompletionStage future = Source.from(input).via(flow).runFold("", (aggr, in) -> aggr + in, materializer); + final Flow flow = + Flow.of(String.class) + .conflateWithSeed( + new Function() { + @Override + public String apply(String s) throws Exception { + return s; + } + }, + new Function2() { + @Override + public String apply(String aggr, String in) throws Exception { + return aggr + in; + } + }); + CompletionStage future = + Source.from(input).via(flow).runFold("", (aggr, in) -> aggr + in, materializer); String result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals("ABC", result); final Flow flow2 = Flow.of(String.class).conflate((a, b) -> a + b); - CompletionStage future2 = Source.from(input).via(flow2).runFold("", (a, b) -> a + b, materializer); + CompletionStage future2 = + Source.from(input).via(flow2).runFold("", (a, b) -> a + b, materializer); String result2 = future2.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals("ABC", result2); } @@ -626,18 +726,24 @@ public class FlowTest extends StreamTest { public void mustBeAbleToUseBatch() throws Exception { final TestKit probe = new TestKit(system); final List input = Arrays.asList("A", "B", "C"); - final Flow flow = Flow.of(String.class).batch(3L, new Function() { - @Override - public String apply(String s) throws Exception { - return s; - } - }, new Function2() { - @Override - public String apply(String aggr, String in) throws Exception { - return aggr + in; - } - }); - CompletionStage future = Source.from(input).via(flow).runFold("", (aggr, in) -> aggr + in, materializer); + final Flow flow = + Flow.of(String.class) + .batch( + 3L, + new Function() { + @Override + public String apply(String s) throws Exception { + return s; + } + }, + new Function2() { + @Override + public String apply(String aggr, String in) throws Exception { + return aggr + in; + } + }); + CompletionStage future = + Source.from(input).via(flow).runFold("", (aggr, in) -> aggr + in, materializer); String result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals("ABC", result); } @@ -646,23 +752,30 @@ public class FlowTest extends StreamTest { public void mustBeAbleToUseBatchWeighted() throws Exception { final TestKit probe = new TestKit(system); final List input = Arrays.asList("A", "B", "C"); - final Flow flow = Flow.of(String.class).batchWeighted(3L, new Function() { - @Override - public java.lang.Long apply(String s) throws Exception { - return 1L; - } - }, new Function() { - @Override - public String apply(String s) throws Exception { - return s; - } - }, new Function2() { - @Override - public String apply(String aggr, String in) throws Exception { - return aggr + in; - } - }); - CompletionStage future = Source.from(input).via(flow).runFold("", (aggr, in) -> aggr + in, materializer); + final Flow flow = + Flow.of(String.class) + .batchWeighted( + 3L, + new Function() { + @Override + public java.lang.Long apply(String s) throws Exception { + return 1L; + } + }, + new Function() { + @Override + public String apply(String s) throws Exception { + return s; + } + }, + new Function2() { + @Override + public String apply(String aggr, String in) throws Exception { + return aggr + in; + } + }); + CompletionStage future = + Source.from(input).via(flow).runFold("", (aggr, in) -> aggr + in, materializer); String result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals("ABC", result); } @@ -671,7 +784,8 @@ public class FlowTest extends StreamTest { public void mustBeAbleToUseExpand() throws Exception { final TestKit probe = new TestKit(system); final List input = Arrays.asList("A", "B", "C"); - final Flow flow = Flow.of(String.class).expand(in -> Stream.iterate(in, i -> i).iterator()); + final Flow flow = + Flow.of(String.class).expand(in -> Stream.iterate(in, i -> i).iterator()); final Sink> sink = Sink.head(); CompletionStage future = Source.from(input).via(flow).runWith(sink, materializer); String result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); @@ -682,12 +796,18 @@ public class FlowTest extends StreamTest { public void mustBeAbleToUseMapAsync() throws Exception { final TestKit probe = new TestKit(system); final Iterable input = Arrays.asList("a", "b", "c"); - final Flow flow = Flow.of(String.class).mapAsync(4, elem -> CompletableFuture.completedFuture(elem.toUpperCase())); - Source.from(input).via(flow).runForeach(new Procedure() { - public void apply(String elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - }, materializer); + final Flow flow = + Flow.of(String.class) + .mapAsync(4, elem -> CompletableFuture.completedFuture(elem.toUpperCase())); + Source.from(input) + .via(flow) + .runForeach( + new Procedure() { + public void apply(String elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + }, + materializer); probe.expectMsgEquals("A"); probe.expectMsgEquals("B"); probe.expectMsgEquals("C"); @@ -696,33 +816,42 @@ public class FlowTest extends StreamTest { @Test public void mustBeAbleToUseCollectType() throws Exception { final TestKit probe = new TestKit(system); - final Iterable input = Arrays.asList(new FlowSpec.Apple(), new FlowSpec.Orange()); + final Iterable input = + Arrays.asList(new FlowSpec.Apple(), new FlowSpec.Orange()); - Source.from(input).via(Flow.of(FlowSpec.Fruit.class).collectType(FlowSpec.Apple.class)) + Source.from(input) + .via(Flow.of(FlowSpec.Fruit.class).collectType(FlowSpec.Apple.class)) .runForeach((apple) -> probe.getRef().tell(apple, ActorRef.noSender()), materializer); probe.expectMsgAnyClassOf(FlowSpec.Apple.class); } @Test public void mustBeAbleToRecover() throws Exception { - final TestPublisher.ManualProbe publisherProbe = TestPublisher.manualProbe(true,system); + final TestPublisher.ManualProbe publisherProbe = + TestPublisher.manualProbe(true, system); final TestKit probe = new TestKit(system); final Source source = Source.fromPublisher(publisherProbe); - final Flow flow = Flow.of(Integer.class) - .map(elem -> { - if (elem == 2) throw new RuntimeException("ex"); - else return elem; - }) - .recover(new JavaPartialFunction() { - public Integer apply(Throwable elem, boolean isCheck) { - if (isCheck) return null; - return 0; - } - }); + final Flow flow = + Flow.of(Integer.class) + .map( + elem -> { + if (elem == 2) throw new RuntimeException("ex"); + else return elem; + }) + .recover( + new JavaPartialFunction() { + public Integer apply(Throwable elem, boolean isCheck) { + if (isCheck) return null; + return 0; + } + }); final CompletionStage future = - source.via(flow).runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + source + .via(flow) + .runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); final PublisherProbeSubscription s = publisherProbe.expectSubscription(); @@ -737,22 +866,25 @@ public class FlowTest extends StreamTest { @Test public void mustBeAbleToRecoverClass() throws Exception { - final TestPublisher.ManualProbe publisherProbe = TestPublisher.manualProbe(true,system); + final TestPublisher.ManualProbe publisherProbe = + TestPublisher.manualProbe(true, system); final TestKit probe = new TestKit(system); final Source source = Source.fromPublisher(publisherProbe); - final Flow flow = Flow.of(Integer.class) - .map(elem -> { - if (elem == 2) throw new RuntimeException("ex"); - else return elem; - }) - .recover( - RuntimeException.class, - () -> 0 - ); + final Flow flow = + Flow.of(Integer.class) + .map( + elem -> { + if (elem == 2) throw new RuntimeException("ex"); + else return elem; + }) + .recover(RuntimeException.class, () -> 0); final CompletionStage future = - source.via(flow).runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + source + .via(flow) + .runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); final PublisherProbeSubscription s = publisherProbe.expectSubscription(); @@ -767,25 +899,32 @@ public class FlowTest extends StreamTest { @Test public void mustBeAbleToRecoverWithSource() throws Exception { - final TestPublisher.ManualProbe publisherProbe = TestPublisher.manualProbe(true,system); + final TestPublisher.ManualProbe publisherProbe = + TestPublisher.manualProbe(true, system); final TestKit probe = new TestKit(system); final Iterable recover = Arrays.asList(55, 0); final Source source = Source.fromPublisher(publisherProbe); - final Flow flow = Flow.of(Integer.class) - .map(elem -> { - if (elem == 2) throw new RuntimeException("ex"); - else return elem; - }) - .recoverWith(new JavaPartialFunction>() { - public Source apply(Throwable elem, boolean isCheck) { - if (isCheck) return null; - return Source.from(recover); - } - }); + final Flow flow = + Flow.of(Integer.class) + .map( + elem -> { + if (elem == 2) throw new RuntimeException("ex"); + else return elem; + }) + .recoverWith( + new JavaPartialFunction>() { + public Source apply(Throwable elem, boolean isCheck) { + if (isCheck) return null; + return Source.from(recover); + } + }); final CompletionStage future = - source.via(flow).runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + source + .via(flow) + .runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); final PublisherProbeSubscription s = publisherProbe.expectSubscription(); @@ -801,22 +940,26 @@ public class FlowTest extends StreamTest { @Test public void mustBeAbleToRecoverWithClass() throws Exception { - final TestPublisher.ManualProbe publisherProbe = TestPublisher.manualProbe(true,system); + final TestPublisher.ManualProbe publisherProbe = + TestPublisher.manualProbe(true, system); final TestKit probe = new TestKit(system); final Iterable recover = Arrays.asList(55, 0); final Source source = Source.fromPublisher(publisherProbe); - final Flow flow = Flow.of(Integer.class) - .map(elem -> { - if (elem == 2) throw new RuntimeException("ex"); - else return elem; - }) - .recoverWith( - RuntimeException.class, - () -> Source.from(recover)); + final Flow flow = + Flow.of(Integer.class) + .map( + elem -> { + if (elem == 2) throw new RuntimeException("ex"); + else return elem; + }) + .recoverWith(RuntimeException.class, () -> Source.from(recover)); final CompletionStage future = - source.via(flow).runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + source + .via(flow) + .runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); final PublisherProbeSubscription s = publisherProbe.expectSubscription(); @@ -832,24 +975,28 @@ public class FlowTest extends StreamTest { @Test public void mustBeAbleToRecoverWithRetries() throws Exception { - final TestPublisher.ManualProbe publisherProbe = TestPublisher.manualProbe(true,system); + final TestPublisher.ManualProbe publisherProbe = + TestPublisher.manualProbe(true, system); final TestKit probe = new TestKit(system); final Iterable recover = Arrays.asList(55, 0); final Source source = Source.fromPublisher(publisherProbe); - final Flow flow = Flow.of(Integer.class) - .map(elem -> { - if (elem == 2) throw new RuntimeException("ex"); - else return elem; - }) - .recoverWithRetries( - 3, - new PFBuilder() - .match(RuntimeException.class, ex -> Source.from(recover)) - .build()); + final Flow flow = + Flow.of(Integer.class) + .map( + elem -> { + if (elem == 2) throw new RuntimeException("ex"); + else return elem; + }) + .recoverWithRetries( + 3, + new PFBuilder().match(RuntimeException.class, ex -> Source.from(recover)).build()); final CompletionStage future = - source.via(flow).runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + source + .via(flow) + .runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); final PublisherProbeSubscription s = publisherProbe.expectSubscription(); @@ -863,85 +1010,101 @@ public class FlowTest extends StreamTest { future.toCompletableFuture().get(3, TimeUnit.SECONDS); } - @Test - public void mustBeAbleToRecoverWithRetriesClass() throws Exception { - final TestPublisher.ManualProbe publisherProbe = TestPublisher.manualProbe(true,system); - final TestKit probe = new TestKit(system); - final Iterable recover = Arrays.asList(55, 0); + @Test + public void mustBeAbleToRecoverWithRetriesClass() throws Exception { + final TestPublisher.ManualProbe publisherProbe = + TestPublisher.manualProbe(true, system); + final TestKit probe = new TestKit(system); + final Iterable recover = Arrays.asList(55, 0); - final Source source = Source.fromPublisher(publisherProbe); - final Flow flow = Flow.of(Integer.class) - .map(elem -> { - if (elem == 2) throw new RuntimeException("ex"); - else return elem; - }) - .recoverWithRetries( - 3, - RuntimeException.class, - () -> Source.from(recover)); + final Source source = Source.fromPublisher(publisherProbe); + final Flow flow = + Flow.of(Integer.class) + .map( + elem -> { + if (elem == 2) throw new RuntimeException("ex"); + else return elem; + }) + .recoverWithRetries(3, RuntimeException.class, () -> Source.from(recover)); - final CompletionStage future = - source.via(flow).runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + final CompletionStage future = + source + .via(flow) + .runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); - final PublisherProbeSubscription s = publisherProbe.expectSubscription(); + final PublisherProbeSubscription s = publisherProbe.expectSubscription(); - s.sendNext(0); - probe.expectMsgEquals(0); - s.sendNext(1); - probe.expectMsgEquals(1); - s.sendNext(2); - probe.expectMsgEquals(55); - probe.expectMsgEquals(0); - future.toCompletableFuture().get(3, TimeUnit.SECONDS); - } + s.sendNext(0); + probe.expectMsgEquals(0); + s.sendNext(1); + probe.expectMsgEquals(1); + s.sendNext(2); + probe.expectMsgEquals(55); + probe.expectMsgEquals(0); + future.toCompletableFuture().get(3, TimeUnit.SECONDS); + } @Test public void mustBeAbleToMaterializeIdentityWithJavaFlow() throws Exception { final TestKit probe = new TestKit(system); final List input = Arrays.asList("A", "B", "C"); - Flow otherFlow = Flow.of(String.class); + Flow otherFlow = Flow.of(String.class); - Flow myFlow = Flow.of(String.class).via(otherFlow); - Source.from(input).via(myFlow).runWith(Sink.foreach(new Procedure() { // Scala Future - public void apply(String elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - }), materializer); + Flow myFlow = Flow.of(String.class).via(otherFlow); + Source.from(input) + .via(myFlow) + .runWith( + Sink.foreach( + new Procedure() { // Scala Future + public void apply(String elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + }), + materializer); - probe.expectMsgAllOf("A","B","C"); + probe.expectMsgAllOf("A", "B", "C"); } @Test public void mustBeAbleToMaterializeIdentityToJavaSink() throws Exception { final TestKit probe = new TestKit(system); final List input = Arrays.asList("A", "B", "C"); - Flow otherFlow = Flow.of(String.class); + Flow otherFlow = Flow.of(String.class); - Sink sink = Flow.of(String.class).to(otherFlow.to(Sink.foreach(new Procedure() { // Scala Future - public void apply(String elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - }))); + Sink sink = + Flow.of(String.class) + .to( + otherFlow.to( + Sink.foreach( + new Procedure() { // Scala Future + public void apply(String elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + }))); Source.from(input).to(sink).run(materializer); - probe.expectMsgAllOf("A","B","C"); + probe.expectMsgAllOf("A", "B", "C"); } @Test public void mustBeAbleToBroadcastEagerCancel() throws Exception { - final Sink sink = Sink.fromGraph( - GraphDSL.create(new Function, SinkShape>() { - @Override - public SinkShape apply(Builder b) throws Exception { - final UniformFanOutShape broadcast = b.add(Broadcast.create(2, true)); - final SinkShape out1 = b.add(Sink.cancelled()); - final SinkShape out2 = b.add(Sink.ignore()); - b.from(broadcast.out(0)).to(out1); - b.from(broadcast.out(1)).to(out2); - return new SinkShape(broadcast.in()); - } - })); + final Sink sink = + Sink.fromGraph( + GraphDSL.create( + new Function, SinkShape>() { + @Override + public SinkShape apply(Builder b) throws Exception { + final UniformFanOutShape broadcast = + b.add(Broadcast.create(2, true)); + final SinkShape out1 = b.add(Sink.cancelled()); + final SinkShape out2 = b.add(Sink.ignore()); + b.from(broadcast.out(0)).to(out1); + b.from(broadcast.out(1)).to(out2); + return new SinkShape(broadcast.in()); + } + })); final TestKit probe = new TestKit(system); Source source = Source.actorRef(1, OverflowStrategy.dropNew()); @@ -950,22 +1113,29 @@ public class FlowTest extends StreamTest { probe.expectTerminated(actor); } - @Test public void mustBeAbleToUseZipWith() throws Exception { final TestKit probe = new TestKit(system); final Iterable input1 = Arrays.asList("A", "B", "C"); final Iterable input2 = Arrays.asList("D", "E", "F"); - Source.from(input1).via(Flow.of(String.class).zipWith(Source.from(input2), new Function2() { - public String apply(String s1, String s2) { - return s1 + "-" + s2; - } - })).runForeach(new Procedure() { - public void apply(String elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - }, materializer); + Source.from(input1) + .via( + Flow.of(String.class) + .zipWith( + Source.from(input2), + new Function2() { + public String apply(String s1, String s2) { + return s1 + "-" + s2; + } + })) + .runForeach( + new Procedure() { + public void apply(String elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + }, + materializer); probe.expectMsgEquals("A-D"); probe.expectMsgEquals("B-E"); @@ -978,16 +1148,19 @@ public class FlowTest extends StreamTest { final Iterable input1 = Arrays.asList("A", "B", "C"); final Iterable input2 = Arrays.asList("D", "E", "F"); - Source.from(input1).via(Flow.of(String.class).zip(Source.from(input2))) - .runForeach(new Procedure>() { + Source.from(input1) + .via(Flow.of(String.class).zip(Source.from(input2))) + .runForeach( + new Procedure>() { public void apply(Pair elem) { probe.getRef().tell(elem, ActorRef.noSender()); } - }, materializer); + }, + materializer); - probe.expectMsgEquals(new Pair("A", "D")); - probe.expectMsgEquals(new Pair("B", "E")); - probe.expectMsgEquals(new Pair("C", "F")); + probe.expectMsgEquals(new Pair("A", "D")); + probe.expectMsgEquals(new Pair("B", "E")); + probe.expectMsgEquals(new Pair("C", "F")); } @Test @@ -996,12 +1169,15 @@ public class FlowTest extends StreamTest { final Iterable input1 = Arrays.asList("A", "B", "C"); final Iterable input2 = Arrays.asList("D", "E", "F"); - Source.from(input1).via(Flow.of(String.class).merge(Source.from(input2))) - .runForeach(new Procedure() { + Source.from(input1) + .via(Flow.of(String.class).merge(Source.from(input2))) + .runForeach( + new Procedure() { public void apply(String elem) { probe.getRef().tell(elem, ActorRef.noSender()); } - }, materializer); + }, + materializer); probe.expectMsgAllOf("A", "B", "C", "D", "E", "F"); } @@ -1010,8 +1186,11 @@ public class FlowTest extends StreamTest { public void mustBeAbleToUseInitialTimeout() throws Throwable { try { try { - Source. maybe().via(Flow.of(Integer.class).initialTimeout(Duration.ofSeconds(1))) - .runWith(Sink. head(), materializer).toCompletableFuture().get(3, TimeUnit.SECONDS); + Source.maybe() + .via(Flow.of(Integer.class).initialTimeout(Duration.ofSeconds(1))) + .runWith(Sink.head(), materializer) + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); org.junit.Assert.fail("A TimeoutException was expected"); } catch (ExecutionException e) { throw e.getCause(); @@ -1021,13 +1200,15 @@ public class FlowTest extends StreamTest { } } - @Test public void mustBeAbleToUseCompletionTimeout() throws Throwable { try { try { - Source. maybe().via(Flow.of(Integer.class).completionTimeout(Duration.ofSeconds(1))) - .runWith(Sink. head(), materializer).toCompletableFuture().get(3, TimeUnit.SECONDS); + Source.maybe() + .via(Flow.of(Integer.class).completionTimeout(Duration.ofSeconds(1))) + .runWith(Sink.head(), materializer) + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); org.junit.Assert.fail("A TimeoutException was expected"); } catch (ExecutionException e) { throw e.getCause(); @@ -1041,8 +1222,11 @@ public class FlowTest extends StreamTest { public void mustBeAbleToUseIdleTimeout() throws Throwable { try { try { - Source. maybe().via(Flow.of(Integer.class).idleTimeout(Duration.ofSeconds(1))) - .runWith(Sink. head(), materializer).toCompletableFuture().get(3, TimeUnit.SECONDS); + Source.maybe() + .via(Flow.of(Integer.class).idleTimeout(Duration.ofSeconds(1))) + .runWith(Sink.head(), materializer) + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); org.junit.Assert.fail("A TimeoutException was expected"); } catch (ExecutionException e) { throw e.getCause(); @@ -1056,53 +1240,64 @@ public class FlowTest extends StreamTest { public void mustBeAbleToUseKeepAlive() throws Exception { Integer result = Source.maybe() - .via(Flow.of(Integer.class) - .keepAlive(Duration.ofSeconds(1), (Creator) () -> 0) - ) + .via( + Flow.of(Integer.class).keepAlive(Duration.ofSeconds(1), (Creator) () -> 0)) .takeWithin(Duration.ofMillis(1500)) .runWith(Sink.head(), materializer) - .toCompletableFuture().get(3, TimeUnit.SECONDS); + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); assertEquals((Object) 0, result); } @Test public void shouldBePossibleToCreateFromFunction() throws Exception { - List out = Source.range(0, 2).via(Flow.fromFunction((Integer x) -> x + 1)) - .runWith(Sink.seq(), materializer).toCompletableFuture().get(3, TimeUnit.SECONDS); + List out = + Source.range(0, 2) + .via(Flow.fromFunction((Integer x) -> x + 1)) + .runWith(Sink.seq(), materializer) + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); assertEquals(Arrays.asList(1, 2, 3), out); - } @Test public void mustSuitablyOverrideAttributeHandlingMethods() { @SuppressWarnings("unused") final Flow f = - Flow.of(Integer.class).withAttributes(Attributes.name("")).addAttributes(Attributes.asyncBoundary()).named(""); + Flow.of(Integer.class) + .withAttributes(Attributes.name("")) + .addAttributes(Attributes.asyncBoundary()) + .named(""); } @Test public void mustBeAbleToUseAlsoTo() { final Flow f = Flow.of(Integer.class).alsoTo(Sink.ignore()); - final Flow f2 = Flow.of(Integer.class).alsoToMat(Sink.ignore(), (i, n) -> "foo"); + final Flow f2 = + Flow.of(Integer.class).alsoToMat(Sink.ignore(), (i, n) -> "foo"); } @Test public void mustBeAbleToUseDivertTo() { - final Flow f = Flow.of(Integer.class).divertTo(Sink.ignore(), e -> true); - final Flow f2 = Flow.of(Integer.class).divertToMat(Sink.ignore(), e -> true, (i, n) -> "foo"); + final Flow f = + Flow.of(Integer.class).divertTo(Sink.ignore(), e -> true); + final Flow f2 = + Flow.of(Integer.class).divertToMat(Sink.ignore(), e -> true, (i, n) -> "foo"); } @Test public void mustBeAbleToUseLazyInit() throws Exception { - final CompletionStage> future = new CompletableFuture>(); + final CompletionStage> future = + new CompletableFuture>(); future.toCompletableFuture().complete(Flow.fromFunction((id) -> id)); Integer result = - Source.range(1, 10) - .via(Flow.lazyInitAsync(() -> future)) - .runWith(Sink.head(), materializer) - .toCompletableFuture().get(3, TimeUnit.SECONDS); + Source.range(1, 10) + .via(Flow.lazyInitAsync(() -> future)) + .runWith(Sink.head(), materializer) + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); assertEquals((Object) 1, result); } diff --git a/akka-stream-tests/src/test/java/akka/stream/javadsl/FlowThrottleTest.java b/akka-stream-tests/src/test/java/akka/stream/javadsl/FlowThrottleTest.java index 82e833fce5..ff88d44230 100644 --- a/akka-stream-tests/src/test/java/akka/stream/javadsl/FlowThrottleTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/javadsl/FlowThrottleTest.java @@ -20,31 +20,33 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; public class FlowThrottleTest extends StreamTest { - public FlowThrottleTest() { - super(actorSystemResource); - } + public FlowThrottleTest() { + super(actorSystemResource); + } - @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("ThrottleTest", AkkaSpec.testConf()); + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("ThrottleTest", AkkaSpec.testConf()); - @Test - public void mustWorksForTwoStreams() throws Exception { - final Flow sharedThrottle = - Flow.of(Integer.class) - .throttle(1,java.time.Duration.ofDays(1), 1, ThrottleMode.enforcing()); + @Test + public void mustWorksForTwoStreams() throws Exception { + final Flow sharedThrottle = + Flow.of(Integer.class) + .throttle(1, java.time.Duration.ofDays(1), 1, ThrottleMode.enforcing()); - CompletionStage> result1 = - Source.single(1).via(sharedThrottle).via(sharedThrottle).runWith(Sink.seq(), materializer); + CompletionStage> result1 = + Source.single(1).via(sharedThrottle).via(sharedThrottle).runWith(Sink.seq(), materializer); - // If there is accidental shared state then we would not be able to pass through the single element - assertEquals(result1.toCompletableFuture().get(3, TimeUnit.SECONDS), Collections.singletonList(1)); + // If there is accidental shared state then we would not be able to pass through the single + // element + assertEquals( + result1.toCompletableFuture().get(3, TimeUnit.SECONDS), Collections.singletonList(1)); - // It works with a new stream, too - CompletionStage> result2 = - Source.single(1).via(sharedThrottle).via(sharedThrottle).runWith(Sink.seq(), materializer); - - assertEquals(result2.toCompletableFuture().get(3, TimeUnit.SECONDS), Collections.singletonList(1)); - } + // It works with a new stream, too + CompletionStage> result2 = + Source.single(1).via(sharedThrottle).via(sharedThrottle).runWith(Sink.seq(), materializer); + assertEquals( + result2.toCompletableFuture().get(3, TimeUnit.SECONDS), Collections.singletonList(1)); + } } diff --git a/akka-stream-tests/src/test/java/akka/stream/javadsl/FramingTest.java b/akka-stream-tests/src/test/java/akka/stream/javadsl/FramingTest.java index 33f2461600..68d9259654 100644 --- a/akka-stream-tests/src/test/java/akka/stream/javadsl/FramingTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/javadsl/FramingTest.java @@ -19,13 +19,14 @@ public class FramingTest extends StreamTest { @ClassRule public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("FramingTest", AkkaSpec.testConf()); + new AkkaJUnitActorSystemResource("FramingTest", AkkaSpec.testConf()); @Test public void mustBeAbleToUseFraming() throws Exception { final Source in = Source.single(ByteString.fromString("1,3,4,5")); - in.via(Framing.delimiter(ByteString.fromString(","), Integer.MAX_VALUE, FramingTruncation.ALLOW)) - .runWith(Sink.ignore(), materializer); + in.via( + Framing.delimiter( + ByteString.fromString(","), Integer.MAX_VALUE, FramingTruncation.ALLOW)) + .runWith(Sink.ignore(), materializer); } - } diff --git a/akka-stream-tests/src/test/java/akka/stream/javadsl/GraphDslTest.java b/akka-stream-tests/src/test/java/akka/stream/javadsl/GraphDslTest.java index 7b4257085c..a10f1f394a 100644 --- a/akka-stream-tests/src/test/java/akka/stream/javadsl/GraphDslTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/javadsl/GraphDslTest.java @@ -30,12 +30,12 @@ public class GraphDslTest extends StreamTest { } @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("GraphDslTest", - AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("GraphDslTest", AkkaSpec.testConf()); @Test public void demonstrateBuildSimpleGraph() throws Exception { - //#simple-graph-dsl + // #simple-graph-dsl final Source in = Source.from(Arrays.asList(1, 2, 3, 4, 5)); final Sink, CompletionStage>> sink = Sink.head(); final Flow f1 = Flow.of(Integer.class).map(elem -> elem + 10); @@ -44,48 +44,59 @@ public class GraphDslTest extends StreamTest { final Flow f4 = Flow.of(Integer.class).map(elem -> elem + 30); final RunnableGraph>> result = - RunnableGraph.fromGraph( - GraphDSL // create() function binds sink, out which is sink's out port and builder DSL - .create( // we need to reference out's shape in the builder DSL below (in to() function) - sink, // previously created sink (Sink) - (builder, out) -> { // variables: builder (GraphDSL.Builder) and out (SinkShape) - final UniformFanOutShape bcast = builder.add(Broadcast.create(2)); - final UniformFanInShape merge = builder.add(Merge.create(2)); + RunnableGraph.fromGraph( + GraphDSL // create() function binds sink, out which is sink's out port and builder DSL + .create( // we need to reference out's shape in the builder DSL below (in to() + // function) + sink, // previously created sink (Sink) + (builder, out) -> { // variables: builder (GraphDSL.Builder) and out (SinkShape) + final UniformFanOutShape bcast = + builder.add(Broadcast.create(2)); + final UniformFanInShape merge = builder.add(Merge.create(2)); - final Outlet source = builder.add(in).out(); - builder.from(source).via(builder.add(f1)) - .viaFanOut(bcast).via(builder.add(f2)).viaFanIn(merge) - .via(builder.add(f3.grouped(1000))).to(out); // to() expects a SinkShape - builder.from(bcast).via(builder.add(f4)).toFanIn(merge); - return ClosedShape.getInstance(); - })); - //#simple-graph-dsl - final List list = result.run(materializer).toCompletableFuture().get(3, TimeUnit.SECONDS); - final String[] res = list.toArray(new String[]{}); + final Outlet source = builder.add(in).out(); + builder + .from(source) + .via(builder.add(f1)) + .viaFanOut(bcast) + .via(builder.add(f2)) + .viaFanIn(merge) + .via(builder.add(f3.grouped(1000))) + .to(out); // to() expects a SinkShape + builder.from(bcast).via(builder.add(f4)).toFanIn(merge); + return ClosedShape.getInstance(); + })); + // #simple-graph-dsl + final List list = + result.run(materializer).toCompletableFuture().get(3, TimeUnit.SECONDS); + final String[] res = list.toArray(new String[] {}); Arrays.sort(res, null); - assertArrayEquals(new String[]{"31", "32", "33", "34", "35", "41", "42", "43", "44", "45"}, res); + assertArrayEquals( + new String[] {"31", "32", "33", "34", "35", "41", "42", "43", "44", "45"}, res); } @Test @SuppressWarnings("unused") public void demonstrateConnectErrors() { try { - //#simple-graph + // #simple-graph final RunnableGraph g = - RunnableGraph.fromGraph( - GraphDSL - .create((b) -> { - final SourceShape source1 = b.add(Source.from(Arrays.asList(1, 2, 3, 4, 5))); - final SourceShape source2 = b.add(Source.from(Arrays.asList(1, 2, 3, 4, 5))); - final FanInShape2> zip = b.add(Zip.create()); - b.from(source1).toInlet(zip.in0()); - b.from(source2).toInlet(zip.in1()); - return ClosedShape.getInstance(); - } - ) - ); - // unconnected zip.out (!) => "The inlets [] and outlets [] must correspond to the inlets [] and outlets [ZipWith2.out]" - //#simple-graph + RunnableGraph.fromGraph( + GraphDSL.create( + (b) -> { + final SourceShape source1 = + b.add(Source.from(Arrays.asList(1, 2, 3, 4, 5))); + final SourceShape source2 = + b.add(Source.from(Arrays.asList(1, 2, 3, 4, 5))); + final FanInShape2> zip = + b.add(Zip.create()); + b.from(source1).toInlet(zip.in0()); + b.from(source2).toInlet(zip.in1()); + return ClosedShape.getInstance(); + })); + // unconnected zip.out (!) => "The inlets [] and outlets [] must correspond to the inlets [] + // and outlets [ZipWith2.out]" + // #simple-graph org.junit.Assert.fail("expected IllegalArgumentException"); } catch (IllegalStateException e) { assertTrue(e != null && e.getMessage() != null && e.getMessage().contains("ZipWith2.out")); @@ -94,29 +105,29 @@ public class GraphDslTest extends StreamTest { @Test public void demonstrateReusingFlowInGraph() throws Exception { - //#graph-dsl-reusing-a-flow + // #graph-dsl-reusing-a-flow final Sink> topHeadSink = Sink.head(); final Sink> bottomHeadSink = Sink.head(); - final Flow sharedDoubler = Flow.of(Integer.class).map(elem -> elem * 2); + final Flow sharedDoubler = + Flow.of(Integer.class).map(elem -> elem * 2); final RunnableGraph, CompletionStage>> g = - RunnableGraph., CompletionStage>>fromGraph( - GraphDSL.create( - topHeadSink, // import this sink into the graph - bottomHeadSink, // and this as well - Keep.both(), - (b, top, bottom) -> { - final UniformFanOutShape bcast = - b.add(Broadcast.create(2)); + RunnableGraph., CompletionStage>>fromGraph( + GraphDSL.create( + topHeadSink, // import this sink into the graph + bottomHeadSink, // and this as well + Keep.both(), + (b, top, bottom) -> { + final UniformFanOutShape bcast = b.add(Broadcast.create(2)); - b.from(b.add(Source.single(1))).viaFanOut(bcast) - .via(b.add(sharedDoubler)).to(top); - b.from(bcast).via(b.add(sharedDoubler)).to(bottom); - return ClosedShape.getInstance(); - } - ) - ); - //#graph-dsl-reusing-a-flow + b.from(b.add(Source.single(1))) + .viaFanOut(bcast) + .via(b.add(sharedDoubler)) + .to(top); + b.from(bcast).via(b.add(sharedDoubler)).to(bottom); + return ClosedShape.getInstance(); + })); + // #graph-dsl-reusing-a-flow final Pair, CompletionStage> pair = g.run(materializer); assertEquals(Integer.valueOf(2), pair.first().toCompletableFuture().get(3, TimeUnit.SECONDS)); assertEquals(Integer.valueOf(2), pair.second().toCompletableFuture().get(3, TimeUnit.SECONDS)); @@ -124,78 +135,86 @@ public class GraphDslTest extends StreamTest { @Test public void demonstrateMatValue() throws Exception { - //#graph-dsl-matvalue - final Sink> foldSink = Sink.fold(0, (a, b) -> { - return a + b; - }); + // #graph-dsl-matvalue + final Sink> foldSink = + Sink.fold( + 0, + (a, b) -> { + return a + b; + }); final Flow, Integer, NotUsed> flatten = - Flow.>create().mapAsync(4, x -> x); + Flow.>create().mapAsync(4, x -> x); - final Flow> foldingFlow = Flow.fromGraph( - GraphDSL.create(foldSink, - (b, fold) -> { - return FlowShape.of( - fold.in(), - b.from(b.materializedValue()).via(b.add(flatten)).out()); - })); - //#graph-dsl-matvalue + final Flow> foldingFlow = + Flow.fromGraph( + GraphDSL.create( + foldSink, + (b, fold) -> { + return FlowShape.of( + fold.in(), b.from(b.materializedValue()).via(b.add(flatten)).out()); + })); + // #graph-dsl-matvalue - //#graph-dsl-matvalue-cycle + // #graph-dsl-matvalue-cycle // This cannot produce any value: - final Source> cyclicSource = Source.fromGraph( - GraphDSL.create(foldSink, - (b, fold) -> { - // - Fold cannot complete until its upstream mapAsync completes - // - mapAsync cannot complete until the materialized Future produced by - // fold completes - // As a result this Source will never emit anything, and its materialited - // Future will never complete - b.from(b.materializedValue()).via(b.add(flatten)).to(fold); - return SourceShape.of(b.from(b.materializedValue()).via(b.add(flatten)).out()); - })); + final Source> cyclicSource = + Source.fromGraph( + GraphDSL.create( + foldSink, + (b, fold) -> { + // - Fold cannot complete until its upstream mapAsync completes + // - mapAsync cannot complete until the materialized Future produced by + // fold completes + // As a result this Source will never emit anything, and its materialited + // Future will never complete + b.from(b.materializedValue()).via(b.add(flatten)).to(fold); + return SourceShape.of(b.from(b.materializedValue()).via(b.add(flatten)).out()); + })); - //#graph-dsl-matvalue-cycle + // #graph-dsl-matvalue-cycle } @Test public void beAbleToConstructClosedGraphFromList() throws Exception { - //#graph-from-list - //create the source + // #graph-from-list + // create the source final Source in = Source.from(Arrays.asList("ax", "bx", "cx")); - //generate the sinks from code + // generate the sinks from code List prefixes = Arrays.asList("a", "b", "c"); final List>> list = new ArrayList<>(); for (String prefix : prefixes) { final Sink> sink = - Flow.of(String.class).filter(str -> str.startsWith(prefix)).toMat(Sink.head(), Keep.right()); + Flow.of(String.class) + .filter(str -> str.startsWith(prefix)) + .toMat(Sink.head(), Keep.right()); list.add(sink); } - final RunnableGraph>> g = RunnableGraph.fromGraph( + final RunnableGraph>> g = + RunnableGraph.fromGraph( GraphDSL.create( - list, - (GraphDSL.Builder>> builder, List> outs) -> { - final UniformFanOutShape bcast = builder.add(Broadcast.create(outs.size())); + list, + (GraphDSL.Builder>> builder, + List> outs) -> { + final UniformFanOutShape bcast = + builder.add(Broadcast.create(outs.size())); - final Outlet source = builder.add(in).out(); - builder.from(source).viaFanOut(bcast); + final Outlet source = builder.add(in).out(); + builder.from(source).viaFanOut(bcast); - for (SinkShape sink : outs) { - builder.from(bcast).to(sink); - } + for (SinkShape sink : outs) { + builder.from(bcast).to(sink); + } - return ClosedShape.getInstance(); - })); + return ClosedShape.getInstance(); + })); List> result = g.run(materializer); - //#graph-from-list + // #graph-from-list assertEquals(3, result.size()); assertEquals("ax", result.get(0).toCompletableFuture().get(1, TimeUnit.SECONDS)); assertEquals("bx", result.get(1).toCompletableFuture().get(1, TimeUnit.SECONDS)); assertEquals("cx", result.get(2).toCompletableFuture().get(1, TimeUnit.SECONDS)); - - } - } diff --git a/akka-stream-tests/src/test/java/akka/stream/javadsl/JsonFramingTest.java b/akka-stream-tests/src/test/java/akka/stream/javadsl/JsonFramingTest.java index 15b43e741b..d616b42edc 100644 --- a/akka-stream-tests/src/test/java/akka/stream/javadsl/JsonFramingTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/javadsl/JsonFramingTest.java @@ -21,29 +21,35 @@ import java.util.concurrent.TimeoutException; import static org.junit.Assert.assertEquals; public class JsonFramingTest extends StreamTest { - public JsonFramingTest() { - super(actorSystemResource); - } + public JsonFramingTest() { + super(actorSystemResource); + } - @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = - new AkkaJUnitActorSystemResource("JsonFramingTest", AkkaSpec.testConf()); + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("JsonFramingTest", AkkaSpec.testConf()); - @Test - public void mustBeAbleToParseJsonArray() throws InterruptedException, ExecutionException, TimeoutException { - // #using-json-framing - String input = "[{ \"name\" : \"john\" }, { \"name\" : \"Ég get etið gler án þess að meiða mig\" }, { \"name\" : \"jack\" }]"; - CompletionStage> result = Source.single(ByteString.fromString(input)) - .via(JsonFraming.objectScanner(Integer.MAX_VALUE)) - .runFold(new ArrayList(), (acc, entry) -> { - acc.add(entry.utf8String()); - return acc; - }, materializer); - // #using-json-framing + @Test + public void mustBeAbleToParseJsonArray() + throws InterruptedException, ExecutionException, TimeoutException { + // #using-json-framing + String input = + "[{ \"name\" : \"john\" }, { \"name\" : \"Ég get etið gler án þess að meiða mig\" }, { \"name\" : \"jack\" }]"; + CompletionStage> result = + Source.single(ByteString.fromString(input)) + .via(JsonFraming.objectScanner(Integer.MAX_VALUE)) + .runFold( + new ArrayList(), + (acc, entry) -> { + acc.add(entry.utf8String()); + return acc; + }, + materializer); + // #using-json-framing - List frames = result.toCompletableFuture().get(5, TimeUnit.SECONDS); - assertEquals("{ \"name\" : \"john\" }", frames.get(0)); - assertEquals("{ \"name\" : \"Ég get etið gler án þess að meiða mig\" }", frames.get(1)); - assertEquals("{ \"name\" : \"jack\" }", frames.get(2)); - } + List frames = result.toCompletableFuture().get(5, TimeUnit.SECONDS); + assertEquals("{ \"name\" : \"john\" }", frames.get(0)); + assertEquals("{ \"name\" : \"Ég get etið gler án þess að meiða mig\" }", frames.get(1)); + assertEquals("{ \"name\" : \"jack\" }", frames.get(2)); + } } diff --git a/akka-stream-tests/src/test/java/akka/stream/javadsl/KillSwitchTest.java b/akka-stream-tests/src/test/java/akka/stream/javadsl/KillSwitchTest.java index e0eb3b1f68..f4b2b76c40 100644 --- a/akka-stream-tests/src/test/java/akka/stream/javadsl/KillSwitchTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/javadsl/KillSwitchTest.java @@ -26,8 +26,8 @@ public class KillSwitchTest extends StreamTest { } @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("FlowTest", - AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("FlowTest", AkkaSpec.testConf()); @Test public void beAbleToUseKillSwitch() throws Exception { @@ -36,14 +36,13 @@ public class KillSwitchTest extends StreamTest { final SharedKillSwitch killSwitch = KillSwitches.shared("testSwitch"); final SharedKillSwitch k = - Source.fromPublisher(upstream) - .viaMat(killSwitch.flow(), Keep.right()) - .to(Sink.fromSubscriber(downstream)).run(materializer); + Source.fromPublisher(upstream) + .viaMat(killSwitch.flow(), Keep.right()) + .to(Sink.fromSubscriber(downstream)) + .run(materializer); final CompletionStage completionStage = - Source.single(1) - .via(killSwitch.flow()) - .runWith(Sink.ignore(), materializer); + Source.single(1).via(killSwitch.flow()).runWith(Sink.ignore(), materializer); downstream.request(1); upstream.sendNext(1); @@ -66,8 +65,8 @@ public class KillSwitchTest extends StreamTest { final SharedKillSwitch killSwitch = KillSwitches.shared("testSwitch"); Source.fromPublisher(upstream) - .viaMat(killSwitch.flow(), Keep.right()) - .runWith(Sink.fromSubscriber(downstream), materializer); + .viaMat(killSwitch.flow(), Keep.right()) + .runWith(Sink.fromSubscriber(downstream), materializer); downstream.request(1); upstream.sendNext(1); @@ -82,18 +81,18 @@ public class KillSwitchTest extends StreamTest { assertEquals(te, te2); } - @Test public void beAbleToUseSingleKillSwitch() throws Exception { final TestPublisher.Probe upstream = TestPublisher.probe(0, system); final TestSubscriber.Probe downstream = TestSubscriber.probe(system); - final Graph, UniqueKillSwitch> killSwitchFlow = KillSwitches.single(); + final Graph, UniqueKillSwitch> killSwitchFlow = + KillSwitches.single(); final UniqueKillSwitch killSwitch = - Source.fromPublisher(upstream) - .viaMat(killSwitchFlow, Keep.right()) - .to(Sink.fromSubscriber(downstream)).run(materializer); - + Source.fromPublisher(upstream) + .viaMat(killSwitchFlow, Keep.right()) + .to(Sink.fromSubscriber(downstream)) + .run(materializer); downstream.request(1); upstream.sendNext(1); @@ -104,5 +103,4 @@ public class KillSwitchTest extends StreamTest { upstream.expectCancellation(); downstream.expectComplete(); } - } diff --git a/akka-stream-tests/src/test/java/akka/stream/javadsl/SinkTest.java b/akka-stream-tests/src/test/java/akka/stream/javadsl/SinkTest.java index 7601142eed..3502420adf 100644 --- a/akka-stream-tests/src/test/java/akka/stream/javadsl/SinkTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/javadsl/SinkTest.java @@ -33,14 +33,15 @@ public class SinkTest extends StreamTest { } @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("FlowTest", - AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("FlowTest", AkkaSpec.testConf()); @Test public void mustBeAbleToUseFanoutPublisher() throws Exception { final Sink> pubSink = Sink.asPublisher(AsPublisher.WITH_FANOUT); @SuppressWarnings("unused") - final Publisher publisher = Source.from(new ArrayList()).runWith(pubSink, materializer); + final Publisher publisher = + Source.from(new ArrayList()).runWith(pubSink, materializer); } @Test @@ -55,7 +56,8 @@ public class SinkTest extends StreamTest { public void mustBeAbleToUseFold() throws Exception { Sink> foldSink = Sink.fold(0, (arg1, arg2) -> arg1 + arg2); @SuppressWarnings("unused") - CompletionStage integerFuture = Source.from(new ArrayList()).runWith(foldSink, materializer); + CompletionStage integerFuture = + Source.from(new ArrayList()).runWith(foldSink, materializer); } @Test @@ -72,7 +74,8 @@ public class SinkTest extends StreamTest { @Test public void mustBeAbleToUseCollector() throws Exception { final List list = Arrays.asList(1, 2, 3); - final Sink>> collectorSink = StreamConverters.javaCollector(Collectors::toList); + final Sink>> collectorSink = + StreamConverters.javaCollector(Collectors::toList); CompletionStage> result = Source.from(list).runWith(collectorSink, materializer); assertEquals(list, result.toCompletableFuture().get(1, TimeUnit.SECONDS)); } @@ -85,13 +88,16 @@ public class SinkTest extends StreamTest { final Sink sink1 = Sink.actorRef(probe1.getRef(), "done1"); final Sink sink2 = Sink.actorRef(probe2.getRef(), "done2"); - final Sink sink = Sink.combine(sink1, sink2, new ArrayList>(), + final Sink sink = + Sink.combine( + sink1, + sink2, + new ArrayList>(), new Function, NotUsed>>() { public Graph, NotUsed> apply(Integer elem) { return Broadcast.create(elem); } - } - ); + }); Source.from(Arrays.asList(0, 1)).runWith(sink, materializer); @@ -106,15 +112,20 @@ public class SinkTest extends StreamTest { @Test public void mustBeAbleToUseContramap() throws Exception { - List out = Source.range(0, 2).toMat(Sink.seq().contramap(x -> x + 1), Keep.right()) - .run(materializer).toCompletableFuture().get(3, TimeUnit.SECONDS); + List out = + Source.range(0, 2) + .toMat(Sink.seq().contramap(x -> x + 1), Keep.right()) + .run(materializer) + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); assertEquals(Arrays.asList(1, 2, 3), out); } @Test public void mustBeAbleToUsePreMaterialize() throws Exception { - Pair, Sink> pair = Sink.head().preMaterialize(materializer); + Pair, Sink> pair = + Sink.head().preMaterialize(materializer); CompletableFuture future = pair.first().toCompletableFuture(); assertEquals(false, future.isDone()); // not yet, only once actually source attached @@ -122,7 +133,7 @@ public class SinkTest extends StreamTest { String element = "element"; Source.single(element).runWith(pair.second(), materializer); - String got = future.get(3, TimeUnit.SECONDS);// should complete nicely + String got = future.get(3, TimeUnit.SECONDS); // should complete nicely assertEquals(element, got); assertEquals(true, future.isDone()); } @@ -130,6 +141,9 @@ public class SinkTest extends StreamTest { public void mustSuitablyOverrideAttributeHandlingMethods() { @SuppressWarnings("unused") final Sink> s = - Sink. head().withAttributes(Attributes.name("")).addAttributes(Attributes.asyncBoundary()).named(""); + Sink.head() + .withAttributes(Attributes.name("")) + .addAttributes(Attributes.asyncBoundary()) + .named(""); } } diff --git a/akka-stream-tests/src/test/java/akka/stream/javadsl/SourceTest.java b/akka-stream-tests/src/test/java/akka/stream/javadsl/SourceTest.java index 6501f91165..94d43dd8ec 100644 --- a/akka-stream-tests/src/test/java/akka/stream/javadsl/SourceTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/javadsl/SourceTest.java @@ -12,10 +12,10 @@ import akka.actor.Status; import akka.japi.Pair; import akka.japi.function.*; import akka.japi.pf.PFBuilder; -//#imports +// #imports import akka.stream.*; -//#imports +// #imports import akka.stream.scaladsl.FlowSpec; import akka.util.ConstantFun; import akka.stream.stage.*; @@ -50,12 +50,13 @@ public class SourceTest extends StreamTest { } @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("SourceTest", - AkkaSpec.testConf()); - + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("SourceTest", AkkaSpec.testConf()); interface Fruit {} + static class Apple implements Fruit {}; + static class Orange implements Fruit {}; public void compileOnlyUpcast() { @@ -74,18 +75,17 @@ public class SourceTest extends StreamTest { final java.lang.Iterable input = Arrays.asList(0, 1, 2, 3, 4, 5); final Source ints = Source.from(input); - ints - .drop(2) - .take(3) - .takeWithin(Duration.ofSeconds(10)) - .map(elem -> lookup[elem]) - .filter(elem -> !elem.equals("c")) - .grouped(2) - .mapConcat(elem -> elem) - .groupedWithin(100, Duration.ofMillis(50)) - .mapConcat(elem -> elem) - .runFold("", (acc, elem) -> acc + elem, materializer) - .thenAccept(elem -> probe.getRef().tell(elem, ActorRef.noSender())); + ints.drop(2) + .take(3) + .takeWithin(Duration.ofSeconds(10)) + .map(elem -> lookup[elem]) + .filter(elem -> !elem.equals("c")) + .grouped(2) + .mapConcat(elem -> elem) + .groupedWithin(100, Duration.ofMillis(50)) + .mapConcat(elem -> elem) + .runFold("", (acc, elem) -> acc + elem, materializer) + .thenAccept(elem -> probe.getRef().tell(elem, ActorRef.noSender())); probe.expectMsgEquals("de"); } @@ -96,7 +96,8 @@ public class SourceTest extends StreamTest { final java.lang.Iterable input = Arrays.asList("a", "b", "c"); Source ints = Source.from(input); - final CompletionStage completion = ints.runForeach(elem -> probe.getRef().tell(elem, ActorRef.noSender()), materializer); + final CompletionStage completion = + ints.runForeach(elem -> probe.getRef().tell(elem, ActorRef.noSender()), materializer); completion.thenAccept(elem -> probe.getRef().tell(String.valueOf(elem), ActorRef.noSender())); @@ -111,46 +112,57 @@ public class SourceTest extends StreamTest { final TestKit probe = new TestKit(system); final Iterable input = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7); // duplicate each element, stop after 4 elements, and emit sum to the end - Source.from(input).via(new GraphStage>() { - public final Inlet in = Inlet.create("in"); - public final Outlet out = Outlet.create("out"); + Source.from(input) + .via( + new GraphStage>() { + public final Inlet in = Inlet.create("in"); + public final Outlet out = Outlet.create("out"); - @Override - public GraphStageLogic createLogic(Attributes inheritedAttributes) throws Exception { - return new GraphStageLogic(shape()) { - int sum = 0; - int count = 0; - - { - setHandler(in, new AbstractInHandler() { @Override - public void onPush() { - final Integer element = grab(in); - sum += element; - count += 1; - if (count == 4) { - emitMultiple(out, Arrays.asList(element, element, sum).iterator(), () -> completeStage()); - } else { - emitMultiple(out, Arrays.asList(element, element).iterator()); - } - } - }); - setHandler(out, new AbstractOutHandler() { - @Override - public void onPull() throws Exception { - pull(in); - } - }); - } - }; - } + public GraphStageLogic createLogic(Attributes inheritedAttributes) throws Exception { + return new GraphStageLogic(shape()) { + int sum = 0; + int count = 0; - @Override - public FlowShape shape() { - return FlowShape.of(in, out); - } - }).runForeach((Procedure) elem -> - probe.getRef().tell(elem, ActorRef.noSender()), materializer); + { + setHandler( + in, + new AbstractInHandler() { + @Override + public void onPush() { + final Integer element = grab(in); + sum += element; + count += 1; + if (count == 4) { + emitMultiple( + out, + Arrays.asList(element, element, sum).iterator(), + () -> completeStage()); + } else { + emitMultiple(out, Arrays.asList(element, element).iterator()); + } + } + }); + setHandler( + out, + new AbstractOutHandler() { + @Override + public void onPull() throws Exception { + pull(in); + } + }); + } + }; + } + + @Override + public FlowShape shape() { + return FlowShape.of(in, out); + } + }) + .runForeach( + (Procedure) elem -> probe.getRef().tell(elem, ActorRef.noSender()), + materializer); probe.expectMsgEquals(0); probe.expectMsgEquals(0); @@ -167,67 +179,85 @@ public class SourceTest extends StreamTest { @Test public void mustBeAbleToUseGroupBy() throws Exception { final Iterable input = Arrays.asList("Aaa", "Abb", "Bcc", "Cdd", "Cee"); - final Source, NotUsed> source = Source - .from(input) - .groupBy(3, new Function() { - public String apply(String elem) { - return elem.substring(0, 1); - } - }) - .grouped(10) - .mergeSubstreams(); + final Source, NotUsed> source = + Source.from(input) + .groupBy( + 3, + new Function() { + public String apply(String elem) { + return elem.substring(0, 1); + } + }) + .grouped(10) + .mergeSubstreams(); final CompletionStage>> future = - source.grouped(10).runWith(Sink.>> head(), materializer); + source.grouped(10).runWith(Sink.>>head(), materializer); final Object[] result = future.toCompletableFuture().get(1, TimeUnit.SECONDS).toArray(); - Arrays.sort(result, (Comparator)(Object) new Comparator>() { - @Override - public int compare(List o1, List o2) { - return o1.get(0).charAt(0) - o2.get(0).charAt(0); - } - }); + Arrays.sort( + result, + (Comparator) + (Object) + new Comparator>() { + @Override + public int compare(List o1, List o2) { + return o1.get(0).charAt(0) - o2.get(0).charAt(0); + } + }); - assertArrayEquals(new Object[] { Arrays.asList("Aaa", "Abb"), Arrays.asList("Bcc"), Arrays.asList("Cdd", "Cee") }, result); + assertArrayEquals( + new Object[] { + Arrays.asList("Aaa", "Abb"), Arrays.asList("Bcc"), Arrays.asList("Cdd", "Cee") + }, + result); } @Test public void mustBeAbleToUseSplitWhen() throws Exception { final Iterable input = Arrays.asList("A", "B", "C", ".", "D", ".", "E", "F"); - final Source, NotUsed> source = Source - .from(input) - .splitWhen(new Predicate() { - public boolean test(String elem) { - return elem.equals("."); - } - }) - .grouped(10) - .concatSubstreams(); + final Source, NotUsed> source = + Source.from(input) + .splitWhen( + new Predicate() { + public boolean test(String elem) { + return elem.equals("."); + } + }) + .grouped(10) + .concatSubstreams(); final CompletionStage>> future = - source.grouped(10).runWith(Sink.>> head(), materializer); + source.grouped(10).runWith(Sink.>>head(), materializer); final List> result = future.toCompletableFuture().get(1, TimeUnit.SECONDS); - assertEquals(Arrays.asList(Arrays.asList("A", "B", "C"), Arrays.asList(".", "D"), Arrays.asList(".", "E", "F")), result); + assertEquals( + Arrays.asList( + Arrays.asList("A", "B", "C"), Arrays.asList(".", "D"), Arrays.asList(".", "E", "F")), + result); } @Test public void mustBeAbleToUseSplitAfter() throws Exception { - final Iterable input = Arrays.asList("A", "B", "C", ".", "D", ".", "E", "F"); - final Source, NotUsed> source = Source - .from(input) - .splitAfter(new Predicate() { - public boolean test(String elem) { - return elem.equals("."); - } - }) - .grouped(10) - .concatSubstreams(); + final Iterable input = Arrays.asList("A", "B", "C", ".", "D", ".", "E", "F"); + final Source, NotUsed> source = + Source.from(input) + .splitAfter( + new Predicate() { + public boolean test(String elem) { + return elem.equals("."); + } + }) + .grouped(10) + .concatSubstreams(); final CompletionStage>> future = - source.grouped(10).runWith(Sink.>> head(), materializer); + source.grouped(10).runWith(Sink.>>head(), materializer); final List> result = future.toCompletableFuture().get(1, TimeUnit.SECONDS); - assertEquals(Arrays.asList(Arrays.asList("A", "B", "C", "."), Arrays.asList("D", "."), Arrays.asList("E", "F")), result); + assertEquals( + Arrays.asList( + Arrays.asList("A", "B", "C", "."), Arrays.asList("D", "."), Arrays.asList("E", "F")), + result); } @Test @@ -239,11 +269,14 @@ public class SourceTest extends StreamTest { final Source in1 = Source.from(input1); final Source in2 = Source.from(input2); - in1.concat(in2).runForeach(new Procedure() { - public void apply(String elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - }, materializer); + in1.concat(in2) + .runForeach( + new Procedure() { + public void apply(String elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + }, + materializer); List output = probe.receiveN(6); assertEquals(Arrays.asList("A", "B", "C", "D", "E", "F"), output); @@ -258,11 +291,14 @@ public class SourceTest extends StreamTest { final Source in1 = Source.from(input1); final Source in2 = Source.from(input2); - in2.prepend(in1).runForeach(new Procedure() { - public void apply(String elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - }, materializer); + in2.prepend(in1) + .runForeach( + new Procedure() { + public void apply(String elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + }, + materializer); List output = probe.receiveN(6); assertEquals(Arrays.asList("A", "B", "C", "D", "E", "F"), output); @@ -272,17 +308,21 @@ public class SourceTest extends StreamTest { public void mustBeAbleToUseCallableInput() { final TestKit probe = new TestKit(system); final Iterable input1 = Arrays.asList(4, 3, 2, 1, 0); - final Creator> input = new Creator>() { - @Override - public Iterator create() { - return input1.iterator(); - } - }; - Source.fromIterator(input).runForeach(new Procedure() { - public void apply(Integer elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - }, materializer); + final Creator> input = + new Creator>() { + @Override + public Iterator create() { + return input1.iterator(); + } + }; + Source.fromIterator(input) + .runForeach( + new Procedure() { + public void apply(Integer elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + }, + materializer); List output = probe.receiveN(5); assertEquals(Arrays.asList(4, 3, 2, 1, 0), output); @@ -294,12 +334,16 @@ public class SourceTest extends StreamTest { final TestKit probe = new TestKit(system); final Iterable input = Arrays.asList("A", "B", "C"); - Source.from(input).runWith(Sink.onComplete(new Procedure>() { - @Override - public void apply(Try param) throws Exception { - probe.getRef().tell(param.get(), ActorRef.noSender()); - } - }), materializer); + Source.from(input) + .runWith( + Sink.onComplete( + new Procedure>() { + @Override + public void apply(Try param) throws Exception { + probe.getRef().tell(param.get(), ActorRef.noSender()); + } + }), + materializer); probe.expectMsgClass(Done.class); } @@ -310,15 +354,19 @@ public class SourceTest extends StreamTest { final Iterable input = Arrays.asList("A", "B", "C"); Source.from(input) - . map(in -> { throw new RuntimeException("simulated err"); }) - .runWith(Sink.head(), materializer) - .whenComplete((s, ex) -> { - if (ex == null) { - probe.getRef().tell("done", ActorRef.noSender()); - } else { - probe.getRef().tell(ex.getMessage(), ActorRef.noSender()); - } - }); + .map( + in -> { + throw new RuntimeException("simulated err"); + }) + .runWith(Sink.head(), materializer) + .whenComplete( + (s, ex) -> { + if (ex == null) { + probe.getRef().tell("done", ActorRef.noSender()); + } else { + probe.getRef().tell(ex.getMessage(), ActorRef.noSender()); + } + }); probe.expectMsgEquals("simulated err"); } @@ -334,30 +382,33 @@ public class SourceTest extends StreamTest { @Test public void mustBeAbleToUseSingle() throws Exception { - //#source-single + // #source-single CompletionStage> future = Source.single("A").runWith(Sink.seq(), materializer); CompletableFuture> completableFuture = future.toCompletableFuture(); completableFuture.thenAccept(result -> System.out.printf("collected elements: %s\n", result)); // result list will contain exactly one element "A" - //#source-single + // #source-single // DO NOT use get() directly in your production code! List result = completableFuture.get(); assertEquals(1, result.size()); assertEquals("A", result.get(0)); - } @Test public void mustBeAbleToUsePrefixAndTail() throws Exception { final TestKit probe = new TestKit(system); final Iterable input = Arrays.asList(1, 2, 3, 4, 5, 6); - CompletionStage, Source>> future = Source.from(input).prefixAndTail(3) - .runWith(Sink., Source>>head(), materializer); - Pair, Source> result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); + CompletionStage, Source>> future = + Source.from(input) + .prefixAndTail(3) + .runWith(Sink., Source>>head(), materializer); + Pair, Source> result = + future.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals(Arrays.asList(1, 2, 3), result.first()); - CompletionStage> tailFuture = result.second().limit(4).runWith(Sink.seq(), materializer); + CompletionStage> tailFuture = + result.second().limit(4).runWith(Sink.seq(), materializer); List tailResult = tailFuture.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals(Arrays.asList(4, 5, 6), tailResult); } @@ -368,14 +419,16 @@ public class SourceTest extends StreamTest { final Iterable input1 = Arrays.asList(1, 2, 3); final Iterable input2 = Arrays.asList(4, 5); - final List> mainInputs = new ArrayList>(); + final List> mainInputs = new ArrayList>(); mainInputs.add(Source.from(input1)); mainInputs.add(Source.from(input2)); - CompletionStage> future = Source.from(mainInputs) - .flatMapConcat(ConstantFun.>javaIdentityFunction()) - .grouped(6) - .runWith(Sink.>head(), materializer); + CompletionStage> future = + Source.from(mainInputs) + .flatMapConcat( + ConstantFun.>javaIdentityFunction()) + .grouped(6) + .runWith(Sink.>head(), materializer); List result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); @@ -390,19 +443,21 @@ public class SourceTest extends StreamTest { final Iterable input3 = Arrays.asList(20, 21, 22, 23, 24, 25, 26, 27, 28, 29); final Iterable input4 = Arrays.asList(30, 31, 32, 33, 34, 35, 36, 37, 38, 39); - final List> mainInputs = new ArrayList>(); + final List> mainInputs = new ArrayList>(); mainInputs.add(Source.from(input1)); mainInputs.add(Source.from(input2)); mainInputs.add(Source.from(input3)); mainInputs.add(Source.from(input4)); - CompletionStage> future = Source.from(mainInputs) - .flatMapMerge(3, ConstantFun.>javaIdentityFunction()).grouped(60) - .runWith(Sink.>head(), materializer); + CompletionStage> future = + Source.from(mainInputs) + .flatMapMerge(3, ConstantFun.>javaIdentityFunction()) + .grouped(60) + .runWith(Sink.>head(), materializer); List result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); final Set set = new HashSet(); - for (Integer i: result) { + for (Integer i : result) { set.add(i); } final Set expected = new HashSet(); @@ -417,8 +472,11 @@ public class SourceTest extends StreamTest { public void mustBeAbleToUseBuffer() throws Exception { final TestKit probe = new TestKit(system); final List input = Arrays.asList("A", "B", "C"); - final CompletionStage> future = Source.from(input).buffer(2, OverflowStrategy.backpressure()).grouped(4) - .runWith(Sink.>head(), materializer); + final CompletionStage> future = + Source.from(input) + .buffer(2, OverflowStrategy.backpressure()) + .grouped(4) + .runWith(Sink.>head(), materializer); List result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals(input, result); @@ -428,16 +486,19 @@ public class SourceTest extends StreamTest { public void mustBeAbleToUseConflate() throws Exception { final TestKit probe = new TestKit(system); final List input = Arrays.asList("A", "B", "C"); - CompletionStage future = Source.from(input) - .conflateWithSeed(s -> s, (aggr, in) -> aggr + in) - .runFold("", (aggr, in) -> aggr + in, materializer); + CompletionStage future = + Source.from(input) + .conflateWithSeed(s -> s, (aggr, in) -> aggr + in) + .runFold("", (aggr, in) -> aggr + in, materializer); String result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals("ABC", result); - final Flow flow2 = Flow.of(String.class).conflate((a, b) -> a + b); - CompletionStage future2 = Source.from(input).conflate((String a, String b) -> a + b).runFold("", (a, b) -> a + b, materializer); + CompletionStage future2 = + Source.from(input) + .conflate((String a, String b) -> a + b) + .runFold("", (a, b) -> a + b, materializer); String result2 = future2.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals("ABC", result2); } @@ -446,7 +507,10 @@ public class SourceTest extends StreamTest { public void mustBeAbleToUseExpand() throws Exception { final TestKit probe = new TestKit(system); final List input = Arrays.asList("A", "B", "C"); - CompletionStage future = Source.from(input).expand(in -> Stream.iterate(in, i -> i).iterator()).runWith(Sink.head(), materializer); + CompletionStage future = + Source.from(input) + .expand(in -> Stream.iterate(in, i -> i).iterator()) + .runWith(Sink.head(), materializer); String result = future.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals("A", result); } @@ -454,14 +518,19 @@ public class SourceTest extends StreamTest { @Test public void mustProduceTicks() throws Exception { final TestKit probe = new TestKit(system); - Source tickSource = Source.tick(Duration.ofSeconds(1), - Duration.ofMillis(500), "tick"); + Source tickSource = + Source.tick(Duration.ofSeconds(1), Duration.ofMillis(500), "tick"); @SuppressWarnings("unused") - Cancellable cancellable = tickSource.to(Sink.foreach(new Procedure() { - public void apply(String elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - })).run(materializer); + Cancellable cancellable = + tickSource + .to( + Sink.foreach( + new Procedure() { + public void apply(String elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + })) + .run(materializer); probe.expectNoMessage(Duration.ofMillis(600)); probe.expectMsgEquals("tick"); probe.expectNoMessage(Duration.ofMillis(200)); @@ -473,8 +542,8 @@ public class SourceTest extends StreamTest { @Test @SuppressWarnings("unused") public void mustCompileMethodsWithJavaDuration() { - Source tickSource = Source.tick(Duration.ofSeconds(1), - Duration.ofMillis(500), notUsed()); + Source tickSource = + Source.tick(Duration.ofSeconds(1), Duration.ofMillis(500), notUsed()); } @Test @@ -482,23 +551,27 @@ public class SourceTest extends StreamTest { final TestKit probe = new TestKit(system); final Iterable input = Arrays.asList("a", "b", "c"); Source.from(input) - .mapAsync(4, elem -> CompletableFuture.completedFuture(elem.toUpperCase())) - .runForeach(elem -> probe.getRef().tell(elem, ActorRef.noSender()), materializer); + .mapAsync(4, elem -> CompletableFuture.completedFuture(elem.toUpperCase())) + .runForeach(elem -> probe.getRef().tell(elem, ActorRef.noSender()), materializer); probe.expectMsgEquals("A"); probe.expectMsgEquals("B"); probe.expectMsgEquals("C"); } @Test - public void mustBeAbleToUseCollectType() throws Exception{ + public void mustBeAbleToUseCollectType() throws Exception { final TestKit probe = new TestKit(system); final Iterable input = Collections.singletonList(new FlowSpec.Apple()); - final Source appleSource = Source.from(input); - final Source fruitSource = appleSource.collectType(FlowSpec.Fruit.class); - fruitSource.collectType(FlowSpec.Apple.class).collectType(FlowSpec.Apple.class) - .runForeach((elem) -> { - probe.getRef().tell(elem,ActorRef.noSender()); - },materializer); + final Source appleSource = Source.from(input); + final Source fruitSource = appleSource.collectType(FlowSpec.Fruit.class); + fruitSource + .collectType(FlowSpec.Apple.class) + .collectType(FlowSpec.Apple.class) + .runForeach( + (elem) -> { + probe.getRef().tell(elem, ActorRef.noSender()); + }, + materializer); probe.expectMsgAnyClassOf(FlowSpec.Apple.class); } @@ -506,65 +579,72 @@ public class SourceTest extends StreamTest { public void mustWorkFromFuture() throws Exception { final Iterable input = Arrays.asList("A", "B", "C"); CompletionStage future1 = Source.from(input).runWith(Sink.head(), materializer); - CompletionStage future2 = Source.fromCompletionStage(future1).runWith(Sink.head(), materializer); + CompletionStage future2 = + Source.fromCompletionStage(future1).runWith(Sink.head(), materializer); String result = future2.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals("A", result); } @Test public void mustWorkFromRange() throws Exception { - CompletionStage> f = Source.range(0, 10).grouped(20).runWith(Sink.> head(), materializer); + CompletionStage> f = + Source.range(0, 10).grouped(20).runWith(Sink.>head(), materializer); final List result = f.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals(11, result.size()); Integer counter = 0; - for (Integer i: result) - assertEquals(i, counter++); + for (Integer i : result) assertEquals(i, counter++); } @Test public void mustWorkFromRangeWithStep() throws Exception { - CompletionStage> f = Source.range(0, 10, 2).grouped(20).runWith(Sink.> head(), materializer); + CompletionStage> f = + Source.range(0, 10, 2).grouped(20).runWith(Sink.>head(), materializer); final List result = f.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals(6, result.size()); Integer counter = 0; - for (Integer i: result) { + for (Integer i : result) { assertEquals(i, counter); - counter+=2; + counter += 2; } } @Test public void mustRepeat() throws Exception { - final CompletionStage> f = Source.repeat(42).grouped(10000).runWith(Sink.> head(), materializer); + final CompletionStage> f = + Source.repeat(42).grouped(10000).runWith(Sink.>head(), materializer); final List result = f.toCompletableFuture().get(3, TimeUnit.SECONDS); assertEquals(result.size(), 10000); - for (Integer i: result) assertEquals(i, (Integer) 42); + for (Integer i : result) assertEquals(i, (Integer) 42); } - + @Test public void mustBeAbleToUseQueue() throws Exception { - final Pair, CompletionStage>> x = - Flow.of(String.class).runWith( - Source.queue(2, OverflowStrategy.fail()), - Sink.seq(), materializer); + final Pair, CompletionStage>> x = + Flow.of(String.class) + .runWith(Source.queue(2, OverflowStrategy.fail()), Sink.seq(), materializer); final SourceQueueWithComplete source = x.first(); final CompletionStage> result = x.second(); source.offer("hello"); source.offer("world"); source.complete(); - assertEquals(result.toCompletableFuture().get(3, TimeUnit.SECONDS), - Arrays.asList("hello", "world")); + assertEquals( + result.toCompletableFuture().get(3, TimeUnit.SECONDS), Arrays.asList("hello", "world")); } @Test public void mustBeAbleToUseActorRefSource() throws Exception { final TestKit probe = new TestKit(system); final Source actorRefSource = Source.actorRef(10, OverflowStrategy.fail()); - final ActorRef ref = actorRefSource.to(Sink.foreach(new Procedure() { - public void apply(Integer elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - })).run(materializer); + final ActorRef ref = + actorRefSource + .to( + Sink.foreach( + new Procedure() { + public void apply(Integer elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + })) + .run(materializer); ref.tell(1, ActorRef.noSender()); probe.expectMsgEquals(1); ref.tell(2, ActorRef.noSender()); @@ -576,19 +656,20 @@ public class SourceTest extends StreamTest { public void mustBeAbleToUseStatefulMaponcat() throws Exception { final TestKit probe = new TestKit(system); final java.lang.Iterable input = Arrays.asList(1, 2, 3, 4, 5); - final Source ints = Source.from(input).statefulMapConcat( - () -> { - int[] state = new int[] {0}; - return (elem) -> { - List list = new ArrayList<>(Collections.nCopies(state[0], elem)); - state[0] = elem; - return list; - }; - }); + final Source ints = + Source.from(input) + .statefulMapConcat( + () -> { + int[] state = new int[] {0}; + return (elem) -> { + List list = new ArrayList<>(Collections.nCopies(state[0], elem)); + state[0] = elem; + return list; + }; + }); - ints - .runFold("", (acc, elem) -> acc + elem, materializer) - .thenAccept(elem -> probe.getRef().tell(elem, ActorRef.noSender())); + ints.runFold("", (acc, elem) -> acc + elem, materializer) + .thenAccept(elem -> probe.getRef().tell(elem, ActorRef.noSender())); probe.expectMsgEquals("2334445555"); } @@ -596,11 +677,12 @@ public class SourceTest extends StreamTest { @Test public void mustBeAbleToUseIntersperse() throws Exception { final TestKit probe = new TestKit(system); - final Source source = Source.from(Arrays.asList("0", "1", "2", "3")) - .intersperse("[", ",", "]"); + final Source source = + Source.from(Arrays.asList("0", "1", "2", "3")).intersperse("[", ",", "]"); final CompletionStage future = - source.runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + source.runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); probe.expectMsgEquals("["); probe.expectMsgEquals("0"); @@ -617,11 +699,14 @@ public class SourceTest extends StreamTest { @Test public void mustBeAbleToUseIntersperseAndConcat() throws Exception { final TestKit probe = new TestKit(system); - final Source source = Source.from(Arrays.asList("0", "1", "2", "3")) - .intersperse(","); + final Source source = + Source.from(Arrays.asList("0", "1", "2", "3")).intersperse(","); final CompletionStage future = - Source.single(">> ").concat(source).runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + Source.single(">> ") + .concat(source) + .runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); probe.expectMsgEquals(">> "); probe.expectMsgEquals("0"); @@ -637,14 +722,18 @@ public class SourceTest extends StreamTest { @Test public void mustBeAbleToUseDropWhile() throws Exception { final TestKit probe = new TestKit(system); - final Source source = Source.from(Arrays.asList(0, 1, 2, 3)).dropWhile - (new Predicate() { - public boolean test(Integer elem) { - return elem < 2; - } - }); + final Source source = + Source.from(Arrays.asList(0, 1, 2, 3)) + .dropWhile( + new Predicate() { + public boolean test(Integer elem) { + return elem < 2; + } + }); - final CompletionStage future = source.runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + final CompletionStage future = + source.runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); probe.expectMsgEquals(2); probe.expectMsgEquals(3); @@ -654,14 +743,18 @@ public class SourceTest extends StreamTest { @Test public void mustBeAbleToUseTakeWhile() throws Exception { final TestKit probe = new TestKit(system); - final Source source = Source.from(Arrays.asList(0, 1, 2, 3)).takeWhile - (new Predicate() { - public boolean test(Integer elem) { - return elem < 2; - } - }); + final Source source = + Source.from(Arrays.asList(0, 1, 2, 3)) + .takeWhile( + new Predicate() { + public boolean test(Integer elem) { + return elem < 2; + } + }); - final CompletionStage future = source.runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + final CompletionStage future = + source.runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); probe.expectMsgEquals(0); probe.expectMsgEquals(1); @@ -674,20 +767,21 @@ public class SourceTest extends StreamTest { @Test public void mustBeAbleToRecover() throws Exception { - final ManualProbe publisherProbe = TestPublisher.manualProbe(true,system); + final ManualProbe publisherProbe = TestPublisher.manualProbe(true, system); final TestKit probe = new TestKit(system); final Source source = Source.fromPublisher(publisherProbe) - .map(elem -> { - if (elem == 1) throw new RuntimeException("ex"); - else return elem; - }) - .recover(new PFBuilder() - .matchAny(ex -> 0) - .build()); + .map( + elem -> { + if (elem == 1) throw new RuntimeException("ex"); + else return elem; + }) + .recover(new PFBuilder().matchAny(ex -> 0).build()); - final CompletionStage future = source.runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + final CompletionStage future = + source.runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); final PublisherProbeSubscription s = publisherProbe.expectSubscription(); s.sendNext(0); probe.expectMsgEquals(0); @@ -703,11 +797,16 @@ public class SourceTest extends StreamTest { final Source source1 = Source.from(Arrays.asList(0, 1)); final Source source2 = Source.from(Arrays.asList(2, 3)); - final Source source = Source.combine( - source1, source2, new ArrayList>(), - width -> Merge. create(width)); + final Source source = + Source.combine( + source1, + source2, + new ArrayList>(), + width -> Merge.create(width)); - final CompletionStage future = source.runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + final CompletionStage future = + source.runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); probe.expectMsgAllOf(0, 1, 2, 3); @@ -717,22 +816,32 @@ public class SourceTest extends StreamTest { @Test public void mustBeAbleToCombineMat() throws Exception { final TestKit probe = new TestKit(system); - final Source> source1 = Source.queue(1, OverflowStrategy.dropNew()); + final Source> source1 = + Source.queue(1, OverflowStrategy.dropNew()); final Source source2 = Source.from(Arrays.asList(2, 3)); - // compiler to check the correct materialized value of type = SourceQueueWithComplete available - final Source> combined = Source.combineMat( - source1, source2, width -> Concat. create(width), Keep.left()); //Keep.left() (i.e. preserve queueSource's materialized value) + // compiler to check the correct materialized value of type = SourceQueueWithComplete + // available + final Source> combined = + Source.combineMat( + source1, + source2, + width -> Concat.create(width), + Keep.left()); // Keep.left() (i.e. preserve queueSource's materialized value) - SourceQueueWithComplete queue = combined - .toMat(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), Keep.left()) - .run(materializer); + SourceQueueWithComplete queue = + combined + .toMat( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), Keep.left()) + .run(materializer); queue.offer(0); queue.offer(1); - queue.complete(); //complete queueSource so that combined with `Concat` pulls elements from queueSource + queue.complete(); // complete queueSource so that combined with `Concat` pulls elements from + // queueSource - // elements from source1 (i.e. first of combined source) come first, then source2 elements, due to `Concat` + // elements from source1 (i.e. first of combined source) come first, then source2 elements, due + // to `Concat` probe.expectMsgAllOf(0, 1, 2, 3); } @@ -746,7 +855,9 @@ public class SourceTest extends StreamTest { final Source, ?> source = Source.zipN(sources); - final CompletionStage future = source.runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + final CompletionStage future = + source.runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); probe.expectMsgAllOf(Arrays.asList(0, 2), Arrays.asList(1, 3)); @@ -761,9 +872,12 @@ public class SourceTest extends StreamTest { final List> sources = Arrays.asList(source1, source2); - final Source source = Source.zipWithN(list -> new Boolean(list.contains(0)), sources); + final Source source = + Source.zipWithN(list -> new Boolean(list.contains(0)), sources); - final CompletionStage future = source.runWith(Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); + final CompletionStage future = + source.runWith( + Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer); probe.expectMsgAllOf(Boolean.TRUE, Boolean.FALSE); @@ -772,33 +886,33 @@ public class SourceTest extends StreamTest { @Test public void createEmptySource() throws Exception { - List actual = Source.empty(Integer.class) - .runWith(Sink.seq(), materializer) - .toCompletableFuture().get(); - assertThat(actual, is(Collections.emptyList())); + List actual = + Source.empty(Integer.class).runWith(Sink.seq(), materializer).toCompletableFuture().get(); + assertThat(actual, is(Collections.emptyList())); } @Test public void cycleSourceMustGenerateSameSequenceInRepeatedFashion() throws Exception { - //#cycle + // #cycle final Source source = Source.cycle(() -> Arrays.asList(1, 2, 3).iterator()); CompletionStage> result = source.grouped(9).runWith(Sink.head(), materializer); List emittedValues = result.toCompletableFuture().get(); assertThat(emittedValues, is(Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3))); - //#cycle + // #cycle } @Test(expected = IllegalArgumentException.class) public void cycleSourceMustThrow() throws Throwable { try { - //#cycle-error + // #cycle-error Iterator emptyIterator = Collections.emptyList().iterator(); Source.cycle(() -> emptyIterator) - .runWith(Sink.head(), materializer) - // stream will be terminated with IllegalArgumentException - //#cycle-error - .toCompletableFuture().get(); + .runWith(Sink.head(), materializer) + // stream will be terminated with IllegalArgumentException + // #cycle-error + .toCompletableFuture() + .get(); } catch (ExecutionException e) { throw e.getCause(); } @@ -810,11 +924,15 @@ public class SourceTest extends StreamTest { final Iterable input1 = Arrays.asList("A", "B", "C"); final Iterable input2 = Arrays.asList("D", "E", "F"); - Source.from(input1).merge(Source.from(input2)).runForeach(new Procedure() { - public void apply(String elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - }, materializer); + Source.from(input1) + .merge(Source.from(input2)) + .runForeach( + new Procedure() { + public void apply(String elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + }, + materializer); probe.expectMsgAllOf("A", "B", "C", "D", "E", "F"); } @@ -825,15 +943,21 @@ public class SourceTest extends StreamTest { final Iterable input1 = Arrays.asList("A", "B", "C"); final Iterable input2 = Arrays.asList("D", "E", "F"); - Source.from(input1).zipWith(Source.from(input2),new Function2(){ - public String apply(String s1,String s2){ - return s1+"-"+s2; - } - }).runForeach(new Procedure() { - public void apply(String elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - }, materializer); + Source.from(input1) + .zipWith( + Source.from(input2), + new Function2() { + public String apply(String s1, String s2) { + return s1 + "-" + s2; + } + }) + .runForeach( + new Procedure() { + public void apply(String elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + }, + materializer); probe.expectMsgEquals("A-D"); probe.expectMsgEquals("B-E"); @@ -846,39 +970,49 @@ public class SourceTest extends StreamTest { final Iterable input1 = Arrays.asList("A", "B", "C"); final Iterable input2 = Arrays.asList("D", "E", "F"); - Source.from(input1).zip(Source.from(input2)).runForeach(new Procedure>() { - public void apply(Pair elem) { - probe.getRef().tell(elem, ActorRef.noSender()); - } - }, materializer); + Source.from(input1) + .zip(Source.from(input2)) + .runForeach( + new Procedure>() { + public void apply(Pair elem) { + probe.getRef().tell(elem, ActorRef.noSender()); + } + }, + materializer); - probe.expectMsgEquals(new Pair("A", "D")); - probe.expectMsgEquals(new Pair("B", "E")); - probe.expectMsgEquals(new Pair("C", "F")); + probe.expectMsgEquals(new Pair("A", "D")); + probe.expectMsgEquals(new Pair("B", "E")); + probe.expectMsgEquals(new Pair("C", "F")); } + @Test public void mustBeAbleToUseMerge2() { final TestKit probe = new TestKit(system); final Iterable input1 = Arrays.asList("A", "B", "C"); final Iterable input2 = Arrays.asList("D", "E", "F"); - Source.from(input1).merge(Source.from(input2)) - .runForeach(new Procedure() { + Source.from(input1) + .merge(Source.from(input2)) + .runForeach( + new Procedure() { public void apply(String elem) { probe.getRef().tell(elem, ActorRef.noSender()); } - }, materializer); + }, + materializer); probe.expectMsgAllOf("A", "B", "C", "D", "E", "F"); } - @Test public void mustBeAbleToUseInitialTimeout() throws Throwable { try { try { - Source.maybe().initialTimeout(Duration.ofSeconds(1)).runWith(Sink.head(), materializer) - .toCompletableFuture().get(3, TimeUnit.SECONDS); + Source.maybe() + .initialTimeout(Duration.ofSeconds(1)) + .runWith(Sink.head(), materializer) + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); org.junit.Assert.fail("A TimeoutException was expected"); } catch (ExecutionException e) { throw e.getCause(); @@ -892,8 +1026,11 @@ public class SourceTest extends StreamTest { public void mustBeAbleToUseCompletionTimeout() throws Throwable { try { try { - Source.maybe().completionTimeout(Duration.ofSeconds(1)).runWith(Sink.head(), materializer) - .toCompletableFuture().get(3, TimeUnit.SECONDS); + Source.maybe() + .completionTimeout(Duration.ofSeconds(1)) + .runWith(Sink.head(), materializer) + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); org.junit.Assert.fail("A TimeoutException was expected"); } catch (ExecutionException e) { throw e.getCause(); @@ -907,8 +1044,11 @@ public class SourceTest extends StreamTest { public void mustBeAbleToUseIdleTimeout() throws Throwable { try { try { - Source.maybe().idleTimeout(Duration.ofSeconds(1)).runWith(Sink.head(), materializer) - .toCompletableFuture().get(3, TimeUnit.SECONDS); + Source.maybe() + .idleTimeout(Duration.ofSeconds(1)) + .runWith(Sink.head(), materializer) + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); org.junit.Assert.fail("A TimeoutException was expected"); } catch (ExecutionException e) { throw e.getCause(); @@ -925,7 +1065,8 @@ public class SourceTest extends StreamTest { .keepAlive(Duration.ofSeconds(1), () -> 0) .takeWithin(Duration.ofMillis(1500)) .runWith(Sink.head(), materializer) - .toCompletableFuture().get(3, TimeUnit.SECONDS); + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); assertEquals((Object) 0, result); } @@ -933,7 +1074,10 @@ public class SourceTest extends StreamTest { public void mustSuitablyOverrideAttributeHandlingMethods() { @SuppressWarnings("unused") final Source f = - Source.single(42).withAttributes(Attributes.name("")).addAttributes(Attributes.asyncBoundary()).named(""); + Source.single(42) + .withAttributes(Attributes.name("")) + .addAttributes(Attributes.asyncBoundary()) + .named(""); } @Test @@ -943,7 +1087,8 @@ public class SourceTest extends StreamTest { .throttle(10, Duration.ofSeconds(1), 10, ThrottleMode.shaping()) .throttle(10, Duration.ofSeconds(1), 10, ThrottleMode.enforcing()) .runWith(Sink.head(), materializer) - .toCompletableFuture().get(3, TimeUnit.SECONDS); + .toCompletableFuture() + .get(3, TimeUnit.SECONDS); assertEquals((Object) 0, result); } @@ -951,17 +1096,20 @@ public class SourceTest extends StreamTest { @Test public void mustBeAbleToUseAlsoTo() { final Source f = Source.empty().alsoTo(Sink.ignore()); - final Source f2 = Source.empty().alsoToMat(Sink.ignore(), (i, n) -> "foo"); + final Source f2 = + Source.empty().alsoToMat(Sink.ignore(), (i, n) -> "foo"); } @Test public void mustBeAbleToUseDivertTo() { final Source f = Source.empty().divertTo(Sink.ignore(), e -> true); - final Source f2 = Source.empty().divertToMat(Sink.ignore(), e -> true, (i, n) -> "foo"); + final Source f2 = + Source.empty().divertToMat(Sink.ignore(), e -> true, (i, n) -> "foo"); } @Test public void mustBeAbleToUsePreMaterialize() { - final Pair> p = Source.empty().preMaterialize(materializer); + final Pair> p = + Source.empty().preMaterialize(materializer); } } diff --git a/akka-stream-tests/src/test/java/akka/stream/javadsl/TcpTest.java b/akka-stream-tests/src/test/java/akka/stream/javadsl/TcpTest.java index 98683362b1..82ae95798a 100644 --- a/akka-stream-tests/src/test/java/akka/stream/javadsl/TcpTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/javadsl/TcpTest.java @@ -49,17 +49,19 @@ public class TcpTest extends StreamTest { } @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("TcpTest", - AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("TcpTest", AkkaSpec.testConf()); final Sink> echoHandler = - Sink.foreach(new Procedure() { - public void apply(IncomingConnection conn) { - conn.handleWith(Flow.of(ByteString.class), materializer); - } - }); + Sink.foreach( + new Procedure() { + public void apply(IncomingConnection conn) { + conn.handleWith(Flow.of(ByteString.class), materializer); + } + }); final List testInput = new ArrayList(); + { for (char c = 'a'; c <= 'z'; c++) { testInput.add(ByteString.fromString(String.valueOf(c))); @@ -68,26 +70,31 @@ public class TcpTest extends StreamTest { @Test public void mustWorkInHappyCase() throws Exception { - final InetSocketAddress serverAddress = SocketUtil.temporaryServerAddress(SocketUtil.RANDOM_LOOPBACK_ADDRESS(), false); - final Source> binding = Tcp.get(system) - .bind(serverAddress.getHostString(), serverAddress.getPort()); + final InetSocketAddress serverAddress = + SocketUtil.temporaryServerAddress(SocketUtil.RANDOM_LOOPBACK_ADDRESS(), false); + final Source> binding = + Tcp.get(system).bind(serverAddress.getHostString(), serverAddress.getPort()); final CompletionStage future = binding.to(echoHandler).run(materializer); final ServerBinding b = future.toCompletableFuture().get(5, TimeUnit.SECONDS); assertEquals(b.localAddress().getPort(), serverAddress.getPort()); - final CompletionStage resultFuture = Source - .from(testInput) - .via(Tcp.get(system).outgoingConnection(serverAddress.getHostString(), serverAddress.getPort())) - .runFold(ByteString.empty(), - new Function2() { - public ByteString apply(ByteString acc, ByteString elem) { - return acc.concat(elem); - } - }, materializer); + final CompletionStage resultFuture = + Source.from(testInput) + .via( + Tcp.get(system) + .outgoingConnection(serverAddress.getHostString(), serverAddress.getPort())) + .runFold( + ByteString.empty(), + new Function2() { + public ByteString apply(ByteString acc, ByteString elem) { + return acc.concat(elem); + } + }, + materializer); final byte[] result = resultFuture.toCompletableFuture().get(5, TimeUnit.SECONDS).toArray(); - for (int i = 0; i < testInput.size(); i ++) { + for (int i = 0; i < testInput.size(); i++) { assertEquals(testInput.get(i).head(), result[i]); } @@ -96,30 +103,41 @@ public class TcpTest extends StreamTest { @Test public void mustReportServerBindFailure() throws Exception { - final InetSocketAddress serverAddress = SocketUtil.temporaryServerAddress(SocketUtil.RANDOM_LOOPBACK_ADDRESS(), false); - final Source> binding = Tcp.get(system) - .bind(serverAddress.getHostString(), serverAddress.getPort()); + final InetSocketAddress serverAddress = + SocketUtil.temporaryServerAddress(SocketUtil.RANDOM_LOOPBACK_ADDRESS(), false); + final Source> binding = + Tcp.get(system).bind(serverAddress.getHostString(), serverAddress.getPort()); final CompletionStage future = binding.to(echoHandler).run(materializer); final ServerBinding b = future.toCompletableFuture().get(5, TimeUnit.SECONDS); assertEquals(b.localAddress().getPort(), serverAddress.getPort()); - new TestKit(system) {{ - new EventFilter(BindException.class, system).occurrences(1).intercept(() -> { - try { - binding.to(echoHandler).run(materializer).toCompletableFuture().get(5, TimeUnit.SECONDS); - assertTrue("Expected BindFailedException, but nothing was reported", false); - } catch (ExecutionException e) { - if (e.getCause() instanceof BindFailedException) {} // all good - else throw new AssertionError("failed", e); - // expected - b.unbind(); - } catch (Exception e) { - throw new AssertionError("failed", e); - } - return null; - }); - }}; + new TestKit(system) { + { + new EventFilter(BindException.class, system) + .occurrences(1) + .intercept( + () -> { + try { + binding + .to(echoHandler) + .run(materializer) + .toCompletableFuture() + .get(5, TimeUnit.SECONDS); + assertTrue("Expected BindFailedException, but nothing was reported", false); + } catch (ExecutionException e) { + if (e.getCause() instanceof BindFailedException) { + } // all good + else throw new AssertionError("failed", e); + // expected + b.unbind(); + } catch (Exception e) { + throw new AssertionError("failed", e); + } + return null; + }); + } + }; } @Test @@ -128,9 +146,14 @@ public class TcpTest extends StreamTest { try { try { Source.from(testInput) - .viaMat(Tcp.get(system).outgoingConnection(serverAddress.getHostString(), serverAddress.getPort()), + .viaMat( + Tcp.get(system) + .outgoingConnection(serverAddress.getHostString(), serverAddress.getPort()), Keep.right()) - .to(Sink. ignore()).run(materializer).toCompletableFuture().get(5, TimeUnit.SECONDS); + .to(Sink.ignore()) + .run(materializer) + .toCompletableFuture() + .get(5, TimeUnit.SECONDS); assertTrue("Expected StreamTcpException, but nothing was reported", false); } catch (ExecutionException e) { throw e.getCause(); @@ -178,13 +201,13 @@ public class TcpTest extends StreamTest { String[] cipherSuites = sslConfig.configureCipherSuites(defaultCiphers, sslConfig.config()); defaultParams.setCipherSuites(cipherSuites); - TLSProtocol.NegotiateNewSession negotiateNewSession = TLSProtocol.negotiateNewSession() - .withCipherSuites(cipherSuites) - .withProtocols(protocols) - .withParameters(defaultParams) - .withClientAuth(TLSClientAuth.none()); + TLSProtocol.NegotiateNewSession negotiateNewSession = + TLSProtocol.negotiateNewSession() + .withCipherSuites(cipherSuites) + .withProtocols(protocols) + .withParameters(defaultParams) + .withClientAuth(TLSClientAuth.none()); // #setting-up-ssl-context } - } diff --git a/akka-stream-tests/src/test/java/akka/stream/stage/JavaIdentityStage.java b/akka-stream-tests/src/test/java/akka/stream/stage/JavaIdentityStage.java index 659f187b37..0f03f3472f 100644 --- a/akka-stream-tests/src/test/java/akka/stream/stage/JavaIdentityStage.java +++ b/akka-stream-tests/src/test/java/akka/stream/stage/JavaIdentityStage.java @@ -14,32 +14,37 @@ public class JavaIdentityStage extends GraphStage> { private Outlet _out = Outlet.create("Identity.out"); private FlowShape _shape = FlowShape.of(_in, _out); - public Inlet in() { return _in; } - public Outlet out() { return _out; } + public Inlet in() { + return _in; + } + public Outlet out() { + return _out; + } @Override public GraphStageLogic createLogic(Attributes inheritedAttributes) { return new GraphStageLogic(shape()) { { - setHandler(in(), new AbstractInHandler() { - @Override - public void onPush() { - push(out(), grab(in())); - } - - }); - - setHandler(out(), new AbstractOutHandler() { - @Override - public void onPull() { - pull(in()); - } - }); + setHandler( + in(), + new AbstractInHandler() { + @Override + public void onPush() { + push(out(), grab(in())); + } + }); + setHandler( + out(), + new AbstractOutHandler() { + @Override + public void onPull() { + pull(in()); + } + }); } - }; } diff --git a/akka-stream-tests/src/test/java/akka/stream/stage/StageTest.java b/akka-stream-tests/src/test/java/akka/stream/stage/StageTest.java index 6fae7bf112..8a35fbf812 100644 --- a/akka-stream-tests/src/test/java/akka/stream/stage/StageTest.java +++ b/akka-stream-tests/src/test/java/akka/stream/stage/StageTest.java @@ -26,8 +26,8 @@ public class StageTest extends StreamTest { } @ClassRule - public static AkkaJUnitActorSystemResource actorSystemResource = new AkkaJUnitActorSystemResource("FlowTest", - AkkaSpec.testConf()); + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("FlowTest", AkkaSpec.testConf()); @Test public void javaStageUsage() throws Exception { @@ -36,12 +36,12 @@ public class StageTest extends StreamTest { final JavaIdentityStage identity = new JavaIdentityStage(); final CompletionStage> result = - ints - .via(identity) - .via(identity) - .grouped(1000) - .runWith(Sink.>head(), materializer); + ints.via(identity) + .via(identity) + .grouped(1000) + .runWith(Sink.>head(), materializer); - assertEquals(Arrays.asList(0, 1, 2, 3, 4, 5), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); + assertEquals( + Arrays.asList(0, 1, 2, 3, 4, 5), result.toCompletableFuture().get(3, TimeUnit.SECONDS)); } } diff --git a/akka-stream-typed/src/test/java/akka/stream/typed/javadsl/ActorFlowCompileTest.java b/akka-stream-typed/src/test/java/akka/stream/typed/javadsl/ActorFlowCompileTest.java index 8179833418..5f2839fa26 100644 --- a/akka-stream-typed/src/test/java/akka/stream/typed/javadsl/ActorFlowCompileTest.java +++ b/akka-stream-typed/src/test/java/akka/stream/typed/javadsl/ActorFlowCompileTest.java @@ -16,9 +16,13 @@ import java.time.temporal.ChronoUnit; public class ActorFlowCompileTest { interface Protocol {} + class Init implements Protocol {} + class Msg implements Protocol {} + class Complete implements Protocol {} + class Failure implements Protocol { public Exception ex; } @@ -29,7 +33,7 @@ public class ActorFlowCompileTest { } static - //#ask-actor + // #ask-actor class AskMe { final String payload; final ActorRef replyTo; @@ -40,22 +44,21 @@ public class ActorFlowCompileTest { } } - //#ask-actor + // #ask-actor { final ActorRef ref = null; - //#ask + // #ask Duration timeout = Duration.of(1, ChronoUnit.SECONDS); - Source.repeat("hello") - .via(ActorFlow.ask(ref, timeout, AskMe::new)) - .to(Sink.ignore()); + Source.repeat("hello").via(ActorFlow.ask(ref, timeout, AskMe::new)).to(Sink.ignore()); Source.repeat("hello") - .via(ActorFlow.ask(ref, timeout, (msg, replyTo) -> new AskMe(msg, replyTo))) - .to(Sink.ignore()); - //#ask + .via( + ActorFlow.ask( + ref, timeout, (msg, replyTo) -> new AskMe(msg, replyTo))) + .to(Sink.ignore()); + // #ask } - } diff --git a/akka-stream-typed/src/test/java/akka/stream/typed/javadsl/ActorSourceSinkCompileTest.java b/akka-stream-typed/src/test/java/akka/stream/typed/javadsl/ActorSourceSinkCompileTest.java index 90f732e2f9..cec92321d2 100644 --- a/akka-stream-typed/src/test/java/akka/stream/typed/javadsl/ActorSourceSinkCompileTest.java +++ b/akka-stream-typed/src/test/java/akka/stream/typed/javadsl/ActorSourceSinkCompileTest.java @@ -15,9 +15,13 @@ import akka.stream.javadsl.Source; public class ActorSourceSinkCompileTest { interface Protocol {} + class Init implements Protocol {} + class Msg implements Protocol {} + class Complete implements Protocol {} + class Failure implements Protocol { public Exception ex; } @@ -31,57 +35,52 @@ public class ActorSourceSinkCompileTest { final ActorRef ref = null; Source.queue(10, OverflowStrategy.dropBuffer()) - .map(s -> s + "!") - .to(ActorSink.actorRef(ref, "DONE", ex -> "FAILED: " + ex.getMessage())); + .map(s -> s + "!") + .to(ActorSink.actorRef(ref, "DONE", ex -> "FAILED: " + ex.getMessage())); } { final ActorRef ref = null; Source.queue(10, OverflowStrategy.dropBuffer()) - .to(ActorSink.actorRefWithAck( - ref, - (sender, msg) -> new Init(), - (sender) -> new Msg(), - "ACK", - new Complete(), - (f) -> new Failure())); + .to( + ActorSink.actorRefWithAck( + ref, + (sender, msg) -> new Init(), + (sender) -> new Msg(), + "ACK", + new Complete(), + (f) -> new Failure())); } { - ActorSource - .actorRef( - (m) -> m == "complete", - new JavaPartialFunction() { + ActorSource.actorRef( + (m) -> m == "complete", + new JavaPartialFunction() { + @Override + public Throwable apply(String x, boolean isCheck) throws Exception { + throw noMatch(); + } + }, + 10, + OverflowStrategy.dropBuffer()) + .to(Sink.seq()); + } + + { + final JavaPartialFunction failureMatcher = + new JavaPartialFunction() { @Override - public Throwable apply(String x, boolean isCheck) throws Exception { - throw noMatch(); + public Throwable apply(Protocol p, boolean isCheck) throws Exception { + if (p instanceof Failure) { + return ((Failure) p).ex; + } else { + throw noMatch(); + } } - }, - 10, - OverflowStrategy.dropBuffer()) - .to(Sink.seq()); + }; + + ActorSource.actorRef((m) -> false, failureMatcher, 10, OverflowStrategy.dropBuffer()) + .to(Sink.seq()); } - - { - final JavaPartialFunction failureMatcher = new JavaPartialFunction() { - @Override - public Throwable apply(Protocol p, boolean isCheck) throws Exception { - if (p instanceof Failure) { - return ((Failure)p).ex; - } - else { - throw noMatch(); - } - } - }; - - ActorSource - .actorRef( - (m) -> false, - failureMatcher, 10, - OverflowStrategy.dropBuffer()) - .to(Sink.seq()); - } - } diff --git a/akka-stream-typed/src/test/java/docs/akka/stream/typed/ActorSinkExample.java b/akka-stream-typed/src/test/java/docs/akka/stream/typed/ActorSinkExample.java index 327d57bf38..bfc2c5c50d 100644 --- a/akka-stream-typed/src/test/java/docs/akka/stream/typed/ActorSinkExample.java +++ b/akka-stream-typed/src/test/java/docs/akka/stream/typed/ActorSinkExample.java @@ -18,15 +18,20 @@ public class ActorSinkExample { // #actor-sink-ref interface Protocol {} + class Message implements Protocol { private final String msg; + public Message(String msg) { this.msg = msg; } } + class Complete implements Protocol {} + class Fail implements Protocol { private final Throwable ex; + public Fail(Throwable ex) { this.ex = ex; } @@ -40,14 +45,9 @@ public class ActorSinkExample { final ActorRef actor = null; - final Sink sink = ActorSink.actorRef( - actor, - new Complete(), - Fail::new - ); + final Sink sink = ActorSink.actorRef(actor, new Complete(), Fail::new); Source.single(new Message("msg1")).runWith(sink, mat); // #actor-sink-ref } - } diff --git a/akka-stream-typed/src/test/java/docs/akka/stream/typed/ActorSinkWithAckExample.java b/akka-stream-typed/src/test/java/docs/akka/stream/typed/ActorSinkWithAckExample.java index 56fdc89909..b928f76af8 100644 --- a/akka-stream-typed/src/test/java/docs/akka/stream/typed/ActorSinkWithAckExample.java +++ b/akka-stream-typed/src/test/java/docs/akka/stream/typed/ActorSinkWithAckExample.java @@ -20,23 +20,30 @@ public class ActorSinkWithAckExample { class Ack {} interface Protocol {} + class Init implements Protocol { private final ActorRef ack; + public Init(ActorRef ack) { this.ack = ack; } } + class Message implements Protocol { private final ActorRef ackTo; private final String msg; + public Message(ActorRef ackTo, String msg) { this.ackTo = ackTo; this.msg = msg; } } + class Complete implements Protocol {} + class Fail implements Protocol { private final Throwable ex; + public Fail(Throwable ex) { this.ex = ex; } @@ -50,17 +57,11 @@ public class ActorSinkWithAckExample { final ActorRef actor = null; - final Sink sink = ActorSink.actorRefWithAck( - actor, - Message::new, - Init::new, - new Ack(), - new Complete(), - Fail::new - ); + final Sink sink = + ActorSink.actorRefWithAck( + actor, Message::new, Init::new, new Ack(), new Complete(), Fail::new); Source.single("msg1").runWith(sink, mat); // #actor-sink-ref-with-ack } - } diff --git a/akka-stream-typed/src/test/java/docs/akka/stream/typed/ActorSourceExample.java b/akka-stream-typed/src/test/java/docs/akka/stream/typed/ActorSourceExample.java index 512d72a68c..d099faabab 100644 --- a/akka-stream-typed/src/test/java/docs/akka/stream/typed/ActorSourceExample.java +++ b/akka-stream-typed/src/test/java/docs/akka/stream/typed/ActorSourceExample.java @@ -19,15 +19,20 @@ public class ActorSourceExample { // #actor-source-ref interface Protocol {} + class Message implements Protocol { private final String msg; + public Message(String msg) { this.msg = msg; } } + class Complete implements Protocol {} + class Fail implements Protocol { private final Exception ex; + public Fail(Exception ex) { this.ex = ex; } @@ -40,35 +45,37 @@ public class ActorSourceExample { // #actor-source-ref final JavaPartialFunction failureMatcher = - new JavaPartialFunction() { - public Throwable apply(Protocol p, boolean isCheck) { - if (p instanceof Fail) { - return ((Fail)p).ex; - } else { - throw noMatch(); + new JavaPartialFunction() { + public Throwable apply(Protocol p, boolean isCheck) { + if (p instanceof Fail) { + return ((Fail) p).ex; + } else { + throw noMatch(); + } } - } - }; + }; - final Source> source = ActorSource.actorRef( - (m) -> m instanceof Complete, - failureMatcher, - 8, - OverflowStrategy.fail() - ); + final Source> source = + ActorSource.actorRef( + (m) -> m instanceof Complete, failureMatcher, 8, OverflowStrategy.fail()); - final ActorRef ref = source.collect(new JavaPartialFunction() { - public String apply(Protocol p, boolean isCheck) { - if (p instanceof Message) { - return ((Message)p).msg; - } else { - throw noMatch(); - } - } - }).to(Sink.foreach(System.out::println)).run(mat); + final ActorRef ref = + source + .collect( + new JavaPartialFunction() { + public String apply(Protocol p, boolean isCheck) { + if (p instanceof Message) { + return ((Message) p).msg; + } else { + throw noMatch(); + } + } + }) + .to(Sink.foreach(System.out::println)) + .run(mat); ref.tell(new Message("msg1")); // ref.tell("msg2"); Does not compile // #actor-source-ref } -} \ No newline at end of file +} diff --git a/akka-stream/src/main/java/akka/stream/javadsl/AsPublisher.java b/akka-stream/src/main/java/akka/stream/javadsl/AsPublisher.java index c0eb5ed9f2..ade23e41a7 100644 --- a/akka-stream/src/main/java/akka/stream/javadsl/AsPublisher.java +++ b/akka-stream/src/main/java/akka/stream/javadsl/AsPublisher.java @@ -5,5 +5,6 @@ package akka.stream.javadsl; public enum AsPublisher { - WITH_FANOUT, WITHOUT_FANOUT + WITH_FANOUT, + WITHOUT_FANOUT } diff --git a/akka-stream/src/main/java/akka/stream/javadsl/FramingTruncation.java b/akka-stream/src/main/java/akka/stream/javadsl/FramingTruncation.java index 5b88509c0c..9b29cc61a1 100644 --- a/akka-stream/src/main/java/akka/stream/javadsl/FramingTruncation.java +++ b/akka-stream/src/main/java/akka/stream/javadsl/FramingTruncation.java @@ -6,5 +6,6 @@ package akka.stream.javadsl; /** Determines mode in which [[Framing]] operates. */ public enum FramingTruncation { - ALLOW, DISALLOW + ALLOW, + DISALLOW } diff --git a/akka-testkit/src/main/java/akka/testkit/JavaTestKit.java b/akka-testkit/src/main/java/akka/testkit/JavaTestKit.java index c5ce944133..f5d792e944 100644 --- a/akka-testkit/src/main/java/akka/testkit/JavaTestKit.java +++ b/akka-testkit/src/main/java/akka/testkit/JavaTestKit.java @@ -20,53 +20,50 @@ import scala.concurrent.duration.FiniteDuration; import java.util.concurrent.TimeUnit; /** - * Java API: Test kit for testing actors. Inheriting from this class enables - * reception of replies from actors, which are queued by an internal actor and - * can be examined using the expectMsg... methods. Assertions and - * bounds concerning timing are available in the form of Within - * blocks. - *

+ * Java API: Test kit for testing actors. Inheriting from this class enables reception of replies + * from actors, which are queued by an internal actor and can be examined using the + * expectMsg... methods. Assertions and bounds concerning timing are available in the form of + * Within blocks. + * + *

Beware of two points: * - * Beware of two points: *

* *

    - *
  • the ActorSystem passed into the constructor needs to be shutdown, - * otherwise thread pools and memory will be leaked - this trait is not - * thread-safe (only one actor with one queue, one stack of Within - * blocks); take care not to run tests within a single test class instance in - * parallel.
  • - * - *
  • It should be noted that for CI servers and the like all maximum Durations - * are scaled using the dilated method, which uses the - * TestKitExtension.Settings.TestTimeFactor settable via akka.conf entry - * "akka.test.timefactor".
  • + *
  • the ActorSystem passed into the constructor needs to be shutdown, otherwise thread pools + * and memory will be leaked - this trait is not thread-safe (only one actor with one queue, + * one stack of Within blocks); take care not to run tests within a single test + * class instance in parallel. + *
  • It should be noted that for CI servers and the like all maximum Durations are scaled using + * the dilated method, which uses the TestKitExtension.Settings.TestTimeFactor + * settable via akka.conf entry "akka.test.timefactor". *
* * @deprecated Use {@link akka.testkit.javadsl.TestKit} instead, since 2.5.0 - * */ @Deprecated public class JavaTestKit { /** - * Shut down an actor system and wait for termination. - * On failure debug output will be logged about the remaining actors in the system. - *

+ * Shut down an actor system and wait for termination. On failure debug output will be logged + * about the remaining actors in the system. * - * If verifySystemShutdown is true, then an exception will be thrown on failure. + *

If verifySystemShutdown is true, then an exception will be thrown on failure. */ - public static void shutdownActorSystem(ActorSystem actorSystem, Duration duration, Boolean verifySystemShutdown) { - boolean vss = verifySystemShutdown != null ? verifySystemShutdown : false; - Duration dur = duration != null ? duration : FiniteDuration.create(10, TimeUnit.SECONDS); + public static void shutdownActorSystem( + ActorSystem actorSystem, Duration duration, Boolean verifySystemShutdown) { + boolean vss = verifySystemShutdown != null ? verifySystemShutdown : false; + Duration dur = duration != null ? duration : FiniteDuration.create(10, TimeUnit.SECONDS); TestKit.shutdownActorSystem(actorSystem, dur, vss); } public static void shutdownActorSystem(ActorSystem actorSystem) { shutdownActorSystem(actorSystem, null, null); } + public static void shutdownActorSystem(ActorSystem actorSystem, Duration duration) { shutdownActorSystem(actorSystem, duration, null); } + public static void shutdownActorSystem(ActorSystem actorSystem, Boolean verifySystemShutdown) { shutdownActorSystem(actorSystem, null, verifySystemShutdown); } @@ -78,16 +75,13 @@ public class JavaTestKit { } /** - * ActorRef of the test actor. Access is provided to enable e.g. registration - * as message target. + * ActorRef of the test actor. Access is provided to enable e.g. registration as message target. */ public ActorRef getTestActor() { return p.testActor(); } - /** - * Shorthand to get the testActor. - */ + /** Shorthand to get the testActor. */ public ActorRef getRef() { return getTestActor(); } @@ -96,21 +90,19 @@ public class JavaTestKit { return p.system(); } - static public FiniteDuration duration(String s) { + public static FiniteDuration duration(String s) { final Duration ret = Duration.apply(s); - if (ret instanceof FiniteDuration) - return (FiniteDuration) ret; + if (ret instanceof FiniteDuration) return (FiniteDuration) ret; else - throw new IllegalArgumentException("duration() is only for finite durations, use Duration.Inf() and friends"); + throw new IllegalArgumentException( + "duration() is only for finite durations, use Duration.Inf() and friends"); } public Duration dilated(Duration d) { return d.mul(TestKitExtension.get(getSystem()).TestTimeFactor()); } - /** - * Query queue status. - */ + /** Query queue status. */ public boolean msgAvailable() { return p.msgAvailable(); } @@ -139,58 +131,47 @@ public class JavaTestKit { return p.remainingOr(def); } - /** - * Have the testActor watch someone (i.e. - * getContext().getWatch(...) ). - */ + /** Have the testActor watch someone (i.e. getContext().getWatch(...) ). */ public ActorRef watch(ActorRef ref) { return p.watch(ref); } - /** - * Have the testActor stop watching someone (i.e. - * getContext.unwatch(...)). - */ + /** Have the testActor stop watching someone (i.e. getContext.unwatch(...)). */ public ActorRef unwatch(ActorRef ref) { return p.unwatch(ref); } - /** - * Ignore all messages in the test actor for which the given function returns - * true. - */ + /** Ignore all messages in the test actor for which the given function returns true. */ public abstract class IgnoreMsg { - abstract protected boolean ignore(Object msg); + protected abstract boolean ignore(Object msg); public IgnoreMsg() { - p.ignoreMsg(new JavaPartialFunction() { - public Boolean apply(Object in, boolean isCheck) { - return ignore(in); - } - }); + p.ignoreMsg( + new JavaPartialFunction() { + public Boolean apply(Object in, boolean isCheck) { + return ignore(in); + } + }); } } - /** - * Stop ignoring messages in the test actor. - */ + /** Stop ignoring messages in the test actor. */ public void ignoreNoMsg() { p.ignoreNoMsg(); } /** - * Install an AutoPilot to drive the testActor: the AutoPilot will be run for - * each received message and can be used to send or forward messages, etc. - * Each invocation must return the AutoPilot for the next round. + * Install an AutoPilot to drive the testActor: the AutoPilot will be run for each received + * message and can be used to send or forward messages, etc. Each invocation must return the + * AutoPilot for the next round. */ public void setAutoPilot(TestActor.AutoPilot pilot) { p.setAutoPilot(pilot); } /** - * Obtain time remaining for execution of the innermost enclosing - * Within block or missing that it returns the properly dilated - * default for this case from settings (key + * Obtain time remaining for execution of the innermost enclosing Within block or + * missing that it returns the properly dilated default for this case from settings (key * "akka.test.single-expect-default"). */ public FiniteDuration remaining() { @@ -198,17 +179,16 @@ public class JavaTestKit { } /** - * Obtain time remaining for execution of the innermost enclosing - * Within block or missing that it returns the given duration. + * Obtain time remaining for execution of the innermost enclosing Within block or + * missing that it returns the given duration. */ public FiniteDuration remainingOr(FiniteDuration duration) { return p.remainingOr(duration); } /** - * Obtain time remaining for execution of the innermost enclosing - * Within block or missing that it returns the properly dilated - * default for this case from settings (key + * Obtain time remaining for execution of the innermost enclosing Within block or + * missing that it returns the properly dilated default for this case from settings (key * "akka.test.single-expect-default"). */ public FiniteDuration remainingOrDefault() { @@ -216,15 +196,14 @@ public class JavaTestKit { } /** - * Execute code block while bounding its execution time between - * min and max. Within blocks may be - * nested. All methods in this trait which take maximum wait times are - * available in a version which implicitly uses the remaining time governed by - * the innermost enclosing Within block. - *

+ * Execute code block while bounding its execution time between min and max + * . Within blocks may be nested. All methods in this trait which take maximum + * wait times are available in a version which implicitly uses the remaining time governed by the + * innermost enclosing Within block. + * + *

Note that the timeout is scaled using dilated, which uses the configuration + * entry "akka.test.timefactor", while the min Duration is not. * - * Note that the timeout is scaled using dilated, which uses the - * configuration entry "akka.test.timefactor", while the min Duration is not. *

* *

@@ -242,37 +221,39 @@ public class JavaTestKit {
     protected abstract void run();
 
     public Within(FiniteDuration max) {
-      p.within(max, new AbstractFunction0() {
-        @Override
-        public Object apply() {
-          run();
-          return null;
-        }
-      });
+      p.within(
+          max,
+          new AbstractFunction0() {
+            @Override
+            public Object apply() {
+              run();
+              return null;
+            }
+          });
     }
 
     public Within(FiniteDuration min, FiniteDuration max) {
-      p.within(min, max, new AbstractFunction0() {
-        @Override
-        public Object apply() {
-          run();
-          return null;
-        }
-      });
+      p.within(
+          min,
+          max,
+          new AbstractFunction0() {
+            @Override
+            public Object apply() {
+              run();
+              return null;
+            }
+          });
     }
   }
 
   /**
-   * Await until the given condition evaluates to true or the
-   * timeout expires, whichever comes first.
-   * 

+ * Await until the given condition evaluates to true or the timeout expires, + * whichever comes first. * - * If no timeout is given, take it from the innermost enclosing - * Within block. - *

+ *

If no timeout is given, take it from the innermost enclosing Within block. * - * Note that the timeout is scaled using Duration.dilated, which uses the - * configuration entry "akka.test.timefactor". + *

Note that the timeout is scaled using Duration.dilated, which uses the configuration entry + * "akka.test.timefactor". */ public abstract class AwaitCond { protected abstract boolean cond(); @@ -286,36 +267,40 @@ public class JavaTestKit { } public AwaitCond(Duration max, Duration interval) { - p.awaitCond(new AbstractFunction0() { - @Override - public Object apply() { - return cond(); - } - }, max, interval, p.awaitCond$default$4()); + p.awaitCond( + new AbstractFunction0() { + @Override + public Object apply() { + return cond(); + } + }, + max, + interval, + p.awaitCond$default$4()); } public AwaitCond(Duration max, Duration interval, String message) { - p.awaitCond(new AbstractFunction0() { - @Override - public Object apply() { - return cond(); - } - }, max, interval, message); + p.awaitCond( + new AbstractFunction0() { + @Override + public Object apply() { + return cond(); + } + }, + max, + interval, + message); } } /** - * Await until the given assert does not throw an exception or the timeout - * expires, whichever comes first. If the timeout expires the last exception - * is thrown. - *

+ * Await until the given assert does not throw an exception or the timeout expires, whichever + * comes first. If the timeout expires the last exception is thrown. * - * If no timeout is given, take it from the innermost enclosing - * Within block. - *

+ *

If no timeout is given, take it from the innermost enclosing Within block. * - * Note that the timeout is scaled using Duration.dilated, which uses the - * configuration entry "akka.test.timefactor". + *

Note that the timeout is scaled using Duration.dilated, which uses the configuration entry + * "akka.test.timefactor". */ public abstract class AwaitAssert { protected abstract void check(); @@ -329,25 +314,29 @@ public class JavaTestKit { } public AwaitAssert(Duration max, Duration interval) { - p.awaitAssert(new AbstractFunction0() { - @Override - public Object apply() { - check(); - return null; - } - }, max, interval); + p.awaitAssert( + new AbstractFunction0() { + @Override + public Object apply() { + check(); + return null; + } + }, + max, + interval); } } /** - * Receive one message from the test actor and assert that the given matching - * function accepts it. Wait time is bounded by the given duration, with an - * AssertionFailure being thrown in case of timeout. - *

- * The received object as transformed by the matching function can be - * retrieved with the get method. + * Receive one message from the test actor and assert that the given matching function accepts it. + * Wait time is bounded by the given duration, with an AssertionFailure being thrown in case of + * timeout. + * + *

The received object as transformed by the matching function can be retrieved with the + * get method. + * + *

Use this variant to implement more complicated or conditional processing. * - * Use this variant to implement more complicated or conditional processing. *

* *

@@ -379,7 +368,7 @@ public class JavaTestKit {
       }
     }
 
-    abstract protected T match(Object msg);
+    protected abstract T match(Object msg);
 
     protected RuntimeException noMatch() {
       throw JavaPartialFunction.noMatch();
@@ -391,17 +380,16 @@ public class JavaTestKit {
   }
 
   /**
-   * Same as expectMsgEquals(remainingOrDefault(), obj), but correctly
-   * treating the timeFactor.
+   * Same as expectMsgEquals(remainingOrDefault(), obj), but correctly treating the
+   * timeFactor.
    */
   public  T expectMsgEquals(T msg) {
     return p.expectMsg(msg);
   }
 
   /**
-   * Receive one message from the test actor and assert that it equals the given
-   * object. Wait time is bounded by the given duration, with an
-   * AssertionFailure being thrown in case of timeout.
+   * Receive one message from the test actor and assert that it equals the given object. Wait time
+   * is bounded by the given duration, with an AssertionFailure being thrown in case of timeout.
    *
    * @return the received object
    */
@@ -410,17 +398,17 @@ public class JavaTestKit {
   }
 
   /**
-   * Same as expectMsgClass(remainingOrDefault(), clazz), but correctly
-   * treating the timeFactor.
+   * Same as expectMsgClass(remainingOrDefault(), clazz), but correctly treating the
+   * timeFactor.
    */
   public  T expectMsgClass(Class clazz) {
     return p.expectMsgClass(clazz);
   }
 
   /**
-   * Receive one message from the test actor and assert that it conforms to the
-   * given class. Wait time is bounded by the given duration, with an
-   * AssertionFailure being thrown in case of timeout.
+   * Receive one message from the test actor and assert that it conforms to the given class. Wait
+   * time is bounded by the given duration, with an AssertionFailure being thrown in case of
+   * timeout.
    *
    * @return the received object
    */
@@ -429,17 +417,17 @@ public class JavaTestKit {
   }
 
   /**
-   * Same as expectMsgAnyOf(remainingOrDefault(), obj...), but correctly
-   * treating the timeFactor.
+   * Same as expectMsgAnyOf(remainingOrDefault(), obj...), but correctly treating the
+   * timeFactor.
    */
   public Object expectMsgAnyOf(Object... msgs) {
     return p.expectMsgAnyOf(Util.immutableSeq(msgs));
   }
 
   /**
-   * Receive one message from the test actor and assert that it equals one of
-   * the given objects. Wait time is bounded by the given duration, with an
-   * AssertionFailure being thrown in case of timeout.
+   * Receive one message from the test actor and assert that it equals one of the given objects.
+   * Wait time is bounded by the given duration, with an AssertionFailure being thrown in case of
+   * timeout.
    *
    * @return the received object
    */
@@ -448,27 +436,28 @@ public class JavaTestKit {
   }
 
   /**
-   * Same as expectMsgAllOf(remainingOrDefault(), obj...), but correctly
-   * treating the timeFactor.
+   * Same as expectMsgAllOf(remainingOrDefault(), obj...), but correctly treating the
+   * timeFactor.
    */
   public Object[] expectMsgAllOf(Object... msgs) {
-    return (Object[]) p.expectMsgAllOf(Util.immutableSeq(msgs)).toArray(Util.classTag(Object.class));
+    return (Object[])
+        p.expectMsgAllOf(Util.immutableSeq(msgs)).toArray(Util.classTag(Object.class));
   }
 
   /**
-   * Receive a number of messages from the test actor matching the given number
-   * of objects and assert that for each given object one is received which
-   * equals it and vice versa. This construct is useful when the order in which
-   * the objects are received is not fixed. Wait time is bounded by the given
-   * duration, with an AssertionFailure being thrown in case of timeout.
+   * Receive a number of messages from the test actor matching the given number of objects and
+   * assert that for each given object one is received which equals it and vice versa. This
+   * construct is useful when the order in which the objects are received is not fixed. Wait time is
+   * bounded by the given duration, with an AssertionFailure being thrown in case of timeout.
    */
   public Object[] expectMsgAllOf(FiniteDuration max, Object... msgs) {
-    return (Object[]) p.expectMsgAllOf(max, Util.immutableSeq(msgs)).toArray(Util.classTag(Object.class));
+    return (Object[])
+        p.expectMsgAllOf(max, Util.immutableSeq(msgs)).toArray(Util.classTag(Object.class));
   }
 
   /**
-   * Same as expectMsgAnyClassOf(remainingOrDefault(), obj...), but
-   * correctly treating the timeFactor.
+   * Same as expectMsgAnyClassOf(remainingOrDefault(), obj...), but correctly treating
+   * the timeFactor.
    */
   @SuppressWarnings("unchecked")
   public  T expectMsgAnyClassOf(Class... classes) {
@@ -477,9 +466,9 @@ public class JavaTestKit {
   }
 
   /**
-   * Receive one message from the test actor and assert that it conforms to one
-   * of the given classes. Wait time is bounded by the given duration, with an
-   * AssertionFailure being thrown in case of timeout.
+   * Receive one message from the test actor and assert that it conforms to one of the given
+   * classes. Wait time is bounded by the given duration, with an AssertionFailure being thrown in
+   * case of timeout.
    *
    * @return the received object
    */
@@ -488,81 +477,65 @@ public class JavaTestKit {
   }
 
   /**
-   * Same as expectNoMsg(remainingOrDefault()), but correctly treating the
-   * timeFactor.
+   * Same as expectNoMsg(remainingOrDefault()), but correctly treating the timeFactor.
    */
   public void expectNoMsg() {
     p.expectNoMsg();
   }
 
-  /**
-   * Assert that no message is received for the specified time.
-   */
+  /** Assert that no message is received for the specified time. */
   public void expectNoMsg(FiniteDuration max) {
     p.expectNoMsg(max);
   }
 
-
   /**
-   * Assert that the given ActorRef is Terminated within the specified time.
-   * Don't forget to 'watch' it first!
+   * Assert that the given ActorRef is Terminated within the specified time. Don't forget to 'watch'
+   * it first!
    */
   public Terminated expectTerminated(Duration max, ActorRef target) {
-      return p.expectTerminated(target, max);
+    return p.expectTerminated(target, max);
   }
 
   /**
-   * Same as expectTerminated(remainingOrDefault(), target),
-   * but correctly treating the timeFactor.
-   * Don't forget to 'watch' it first!
+   * Same as expectTerminated(remainingOrDefault(), target), but correctly treating the
+   * timeFactor. Don't forget to 'watch' it first!
    */
   public Terminated expectTerminated(ActorRef target) {
-      return expectTerminated(Duration.Undefined(), target);
+    return expectTerminated(Duration.Undefined(), target);
   }
 
-  /**
-   * Same as receiveN(n, remaining()), but correctly treating the
-   * timeFactor.
-   */
-
+  /** Same as receiveN(n, remaining()), but correctly treating the timeFactor. */
   public Object[] receiveN(int n) {
     return (Object[]) p.receiveN(n).toArray(Util.classTag(Object.class));
   }
 
-  /**
-   * Receive N messages in a row before the given deadline.
-   */
+  /** Receive N messages in a row before the given deadline. */
   public Object[] receiveN(int n, FiniteDuration max) {
     return (Object[]) p.receiveN(n, max).toArray(Util.classTag(Object.class));
   }
 
   /**
-   * Receive one message from the internal queue of the TestActor. If the given
-   * duration is zero, the queue is polled (non-blocking).
-   * 

+ * Receive one message from the internal queue of the TestActor. If the given duration is zero, + * the queue is polled (non-blocking). * - * This method does NOT automatically scale its Duration parameter! + *

This method does NOT automatically scale its Duration parameter! */ public Object receiveOne(Duration max) { return p.receiveOne(max); } /** - * Receive a series of messages until one does not match the given - * match function or the idle timeout is met (disabled by - * default) or the overall maximum duration is elapsed. Returns the sequence - * of messages. - *

+ * Receive a series of messages until one does not match the given match function or + * the idle timeout is met (disabled by default) or the overall maximum duration is elapsed. + * Returns the sequence of messages. * - * Note that it is not an error to hit the max duration in this - * case. - *

+ *

Note that it is not an error to hit the max duration in this case. * - * One possible use of this method is for testing whether messages of certain - * characteristics are generated at a certain rate. + *

One possible use of this method is for testing whether messages of certain characteristics + * are generated at a certain rate. */ public abstract class ReceiveWhile { - abstract protected T match(Object msg) throws Exception; + protected abstract T match(Object msg) throws Exception; private Object results; @@ -580,11 +553,17 @@ public class JavaTestKit { @SuppressWarnings("all") public ReceiveWhile(Class clazz, Duration max, Duration idle, int messages) { - results = p.receiveWhile(max, idle, messages, new CachingPartialFunction() { - public T match(Object msg) throws Exception { - return ReceiveWhile.this.match(msg); - } - }).toArray(Util.classTag(clazz)); + results = + p.receiveWhile( + max, + idle, + messages, + new CachingPartialFunction() { + public T match(Object msg) throws Exception { + return ReceiveWhile.this.match(msg); + } + }) + .toArray(Util.classTag(clazz)); } protected RuntimeException noMatch() { @@ -598,16 +577,14 @@ public class JavaTestKit { } /** - * Facilities for selectively filtering out expected events from logging so - * that you can keep your test run’s console output clean and do not miss real - * error messages. - *

+ * Facilities for selectively filtering out expected events from logging so that you can keep your + * test run’s console output clean and do not miss real error messages. * - * If the occurrences is set to Integer.MAX_VALUE, - * no tracking is done. + *

If the occurrences is set to Integer.MAX_VALUE, no tracking is + * done. */ public abstract class EventFilter { - abstract protected T run(); + protected abstract T run(); private final Class clazz; @@ -627,14 +604,12 @@ public class JavaTestKit { this.clazz = (Class) clazz; } else throw new IllegalArgumentException("supplied class must either be LogEvent or Throwable"); - } public T exec() { akka.testkit.EventFilter filter; if (clazz == Logging.Error.class) { - if (exceptionType == null) - exceptionType = Logging.noCause().getClass(); + if (exceptionType == null) exceptionType = Logging.noCause().getClass(); filter = new ErrorFilter(exceptionType, source, message, pattern, complete, occurrences); } else if (clazz == Logging.Warning.class) { filter = new WarningFilter(source, message, pattern, complete, occurrences); @@ -642,14 +617,15 @@ public class JavaTestKit { filter = new InfoFilter(source, message, pattern, complete, occurrences); } else if (clazz == Logging.Debug.class) { filter = new DebugFilter(source, message, pattern, complete, occurrences); - } else - throw new IllegalArgumentException("unknown LogLevel " + clazz); - return filter.intercept(new AbstractFunction0() { - @Override - public T apply() { - return run(); - } - }, p.system()); + } else throw new IllegalArgumentException("unknown LogLevel " + clazz); + return filter.intercept( + new AbstractFunction0() { + @Override + public T apply() { + return run(); + } + }, + p.system()); } public EventFilter message(String msg) { @@ -684,65 +660,74 @@ public class JavaTestKit { } /** - * Shut down an actor system and wait for termination. - * On failure debug output will be logged about the remaining actors in the system. - *

+ * Shut down an actor system and wait for termination. On failure debug output will be logged + * about the remaining actors in the system. * - * If verifySystemShutdown is true, then an exception will be thrown on failure. + *

If verifySystemShutdown is true, then an exception will be thrown on failure. */ public void shutdown(ActorSystem actorSystem, Duration duration, Boolean verifySystemShutdown) { boolean vss = verifySystemShutdown != null ? verifySystemShutdown : false; - Duration dur = duration != null ? duration : - dilated(FiniteDuration.create(5, TimeUnit.SECONDS)).min(FiniteDuration.create(10, TimeUnit.SECONDS)); + Duration dur = + duration != null + ? duration + : dilated(FiniteDuration.create(5, TimeUnit.SECONDS)) + .min(FiniteDuration.create(10, TimeUnit.SECONDS)); JavaTestKit.shutdownActorSystem(actorSystem, dur, vss); } public void shutdown(ActorSystem actorSystem) { - shutdown(actorSystem, null, null); + shutdown(actorSystem, null, null); } + public void shutdown(ActorSystem actorSystem, Duration duration) { - shutdown(actorSystem, duration, null); + shutdown(actorSystem, duration, null); } + public void shutdown(ActorSystem actorSystem, Boolean verifySystemShutdown) { - shutdown(actorSystem, null, verifySystemShutdown); + shutdown(actorSystem, null, verifySystemShutdown); } /** * Spawns an actor as a child of this test actor, and returns the child's ActorRef. + * * @param props Props to create the child actor * @param name Actor name for the child actor * @param supervisorStrategy Strategy should decide what to do with failures in the actor. */ public ActorRef childActorOf(Props props, String name, SupervisorStrategy supervisorStrategy) { - return p.childActorOf(props, name, supervisorStrategy); + return p.childActorOf(props, name, supervisorStrategy); } /** - * Spawns an actor as a child of this test actor, and returns the child's ActorRef. - * The actor will have an auto-generated name. + * Spawns an actor as a child of this test actor, and returns the child's ActorRef. The actor will + * have an auto-generated name. + * * @param props Props to create the child actor * @param supervisorStrategy Strategy should decide what to do with failures in the actor. */ public ActorRef childActorOf(Props props, SupervisorStrategy supervisorStrategy) { - return p.childActorOf(props, supervisorStrategy); + return p.childActorOf(props, supervisorStrategy); } /** - * Spawns an actor as a child of this test actor, and returns the child's ActorRef. - * The actor will be supervised using {@link SupervisorStrategy.stoppingStrategy}. + * Spawns an actor as a child of this test actor, and returns the child's ActorRef. The actor will + * be supervised using {@link SupervisorStrategy.stoppingStrategy}. + * * @param props Props to create the child actor * @param name Actor name for the child actor */ public ActorRef childActorOf(Props props, String name) { - return p.childActorOf(props, name); + return p.childActorOf(props, name); } /** - * Spawns an actor as a child of this test actor, and returns the child's ActorRef. - * The actor will have an auto-generated name and will be supervised using {@link SupervisorStrategy.stoppingStrategy}. + * Spawns an actor as a child of this test actor, and returns the child's ActorRef. The actor will + * have an auto-generated name and will be supervised using {@link + * SupervisorStrategy.stoppingStrategy}. + * * @param props Props to create the child actor */ public ActorRef childActorOf(Props props) { - return p.childActorOf(props); + return p.childActorOf(props); } } diff --git a/akka-testkit/src/test/java/akka/testkit/AkkaJUnitActorSystemResource.java b/akka-testkit/src/test/java/akka/testkit/AkkaJUnitActorSystemResource.java index 18189bce61..7595e7fc62 100644 --- a/akka-testkit/src/test/java/akka/testkit/AkkaJUnitActorSystemResource.java +++ b/akka-testkit/src/test/java/akka/testkit/AkkaJUnitActorSystemResource.java @@ -11,23 +11,15 @@ import com.typesafe.config.Config; import org.junit.rules.ExternalResource; /** - * This is a resource for creating an actor system before test start and shut it - * down afterwards. + * This is a resource for creating an actor system before test start and shut it down afterwards. * - * To use it on a class level add this to your test class: - * - * + *

To use it on a class level add this to your test class: * @ClassRule * public static AkkaJUnitActorSystemResource actorSystemResource = * new AkkaJUnitActorSystemResource(name, config); * * private final ActorSystem system = actorSystemResource.getSystem(); - * - * - * - * To use it on a per test level add this to your test class: - * - * + * To use it on a per test level add this to your test class: * @Rule * public AkkaJUnitActorSystemResource actorSystemResource = * new AkkaJUnitActorSystemResource(name, config); @@ -38,14 +30,10 @@ import org.junit.rules.ExternalResource; * public void beforeEach() { * system = actorSystemResource.getSystem(); * } - * - * - * Note that it is important to not use getSystem from the - * constructor of the test, because some test runners may create an - * instance of the class without actually using it later, resulting in - * memory leaks because of not shutting down the actor system. + * Note that it is important to not use getSystem from the constructor of the + * test, because some test runners may create an instance of the class without actually using it + * later, resulting in memory leaks because of not shutting down the actor system. */ - public class AkkaJUnitActorSystemResource extends ExternalResource { private ActorSystem system = null; private final String name; @@ -53,12 +41,9 @@ public class AkkaJUnitActorSystemResource extends ExternalResource { private ActorSystem createSystem(String name, Config config) { try { - if (config == null) - return ActorSystem.create(name); - else - return ActorSystem.create(name, config); - } - catch (Exception e) { + if (config == null) return ActorSystem.create(name); + else return ActorSystem.create(name, config); + } catch (Exception e) { e.printStackTrace(); return null; } diff --git a/akka-testkit/src/test/java/akka/testkit/TestActorRefJavaCompile.java b/akka-testkit/src/test/java/akka/testkit/TestActorRefJavaCompile.java index c60cebd0e4..9b3fbff59c 100644 --- a/akka-testkit/src/test/java/akka/testkit/TestActorRefJavaCompile.java +++ b/akka-testkit/src/test/java/akka/testkit/TestActorRefJavaCompile.java @@ -10,14 +10,15 @@ import akka.actor.Props; public class TestActorRefJavaCompile { public void shouldBeAbleToCompileWhenUsingApply() { - //Just dummy calls to make sure it compiles + // Just dummy calls to make sure it compiles TestActorRef ref = TestActorRef.create(null, Props.empty()); ref.toString(); TestActorRef namedRef = TestActorRef.create(null, Props.empty(), "namedActor"); namedRef.toString(); TestActorRef supervisedRef = TestActorRef.create(null, Props.empty(), ref); supervisedRef.toString(); - TestActorRef namedSupervisedRef = TestActorRef.create(null, Props.empty(), ref, "namedActor"); + TestActorRef namedSupervisedRef = + TestActorRef.create(null, Props.empty(), ref, "namedActor"); namedSupervisedRef.toString(); } }