Beispiel #1
0
    public void testSchedule(
        final JavaTestKit probe,
        Props props,
        FiniteDuration startDuration,
        FiniteDuration afterRestartDuration) {
      Iterable<akka.testkit.EventFilter> filter =
          Arrays.asList(
              new akka.testkit.EventFilter[] {
                (akka.testkit.EventFilter) new ErrorFilter(ArithmeticException.class)
              });
      try {
        system.eventStream().publish(new Mute(filter));

        final ActorRef actor = system.actorOf(props);
        new Within(startDuration) {
          protected void run() {
            probe.expectMsgEquals("tick");
            probe.expectMsgEquals("tick");
            probe.expectMsgEquals("tick");
          }
        };
        actor.tell("restart", getRef());
        new Within(afterRestartDuration) {
          protected void run() {
            probe.expectMsgEquals("tick");
            probe.expectMsgEquals("tick");
          }
        };
        system.stop(actor);
      } finally {
        system.eventStream().publish(new UnMute(filter));
      }
    }
 public static void startFrontend(Address joinAddress) {
   ActorSystem system = ActorSystem.create(systemName);
   Cluster.get(system).join(joinAddress);
   ActorRef frontend = system.actorOf(Props.create(Frontend.class), "frontend");
   system.actorOf(Props.create(WorkProducer.class, frontend), "producer");
   system.actorOf(Props.create(WorkResultConsumer.class), "consumer");
 }
  @Test
  public void demonstrateTheProgrammaticAPI() {
    // #programmatic
    ActorSystem system = ActorSystem.create("example");

    // Get the Serialization Extension
    Serialization serialization = SerializationExtension.get(system);

    // Have something to serialize
    String original = "woohoo";

    // Find the Serializer for it
    Serializer serializer = serialization.findSerializerFor(original);

    // Turn it into bytes
    byte[] bytes = serializer.toBinary(original);

    // Turn it back into an object,
    // the nulls are for the class manifest and for the classloader
    String back = (String) serializer.fromBinary(bytes);

    // Voilá!
    assertEquals(original, back);

    // #programmatic
    system.shutdown();
  }
Beispiel #4
0
 @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 serializeActorRefs() {
    final ActorSystem theActorSystem = ActorSystem.create("whatever");
    final ActorRef theActorRef = theActorSystem.deadLetters(); // Of course this should be you

    // #actorref-serializer
    // Serialize
    // (beneath toBinary)
    final Address transportAddress = Serialization.currentTransportAddress().value();
    String identifier;

    // If there is no transportAddress,
    // it means that either this Serializer isn't called
    // within a piece of code that sets it,
    // so either you need to supply your own,
    // or simply use the local path.
    if (transportAddress == null) identifier = theActorRef.path().toString();
    else identifier = theActorRef.path().toStringWithAddress(transportAddress);
    // Then just serialize the identifier however you like

    // Deserialize
    // (beneath fromBinary)
    final ActorRef deserializedActorRef = theActorSystem.actorFor(identifier);
    // Then just use the ActorRef
    // #actorref-serializer
    theActorSystem.shutdown();
  }
 public static void startWorker(Address contactAddress) {
   ActorSystem system = ActorSystem.create(systemName);
   Set<ActorSelection> initialContacts = new HashSet<ActorSelection>();
   initialContacts.add(system.actorSelection(contactAddress + "/user/receptionist"));
   ActorRef clusterClient =
       system.actorOf(ClusterClient.defaultProps(initialContacts), "clusterClient");
   system.actorOf(Worker.props(clusterClient, Props.create(WorkExecutor.class)), "worker");
 }
Beispiel #7
0
 @Test
 public void useAskWithActorSelection() throws Exception {
   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), Duration.create(3, "seconds"));
   assertEquals("Ask (Identify) should return the proper ActorIdentity", testActor, id.getRef());
 }
  public static Address startBackend(Address joinAddress, String role) {
    Config conf =
        ConfigFactory.parseString("akka.cluster.roles=[" + role + "]")
            .withFallback(ConfigFactory.load());
    ActorSystem system = ActorSystem.create(systemName, conf);
    Address realJoinAddress =
        (joinAddress == null) ? Cluster.get(system).selfAddress() : joinAddress;
    Cluster.get(system).join(realJoinAddress);

    system.actorOf(
        ClusterSingletonManager.defaultProps(
            Master.props(workTimeout), "active", PoisonPill.getInstance(), role),
        "master");

    return realJoinAddress;
  }
Beispiel #9
0
 @Test
 public void testingWithoutParent() {
   TestProbe probe = new TestProbe(system);
   ActorRef child = system.actorOf(Props.create(DependentChild.class, probe.ref()));
   probe.send(child, "ping");
   probe.expectMsg("pong");
 }
Beispiel #10
0
 @Test
 public void useAsk() throws Exception {
   ActorRef testActor = system.actorOf(Props.create(JavaAPITestActor.class), "test");
   assertEquals(
       "Ask should return expected answer",
       JavaAPITestActor.ANSWER,
       Await.result(ask(testActor, "hey!", 3000), Duration.create(3, "seconds")));
 }
 public void demonstrateDefaultAddress() {
   // this is not meant to be run, only to be compiled
   final ActorSystem system = ActorSystem.create();
   final Address remoteAddr = new Address("", "");
   // #external-address-default
   final Address addr = DefaultAddress.ID.get(system).getAddress();
   // #external-address-default
 }
Beispiel #12
0
  @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
    TestProbe proxy = new TestProbe(system);
    ActorRef parent = system.actorOf(Props.create(new FabricatedParentCreator(proxy)));

    proxy.send(parent, "ping");
    proxy.expectMsg("pong");
    // #test-fabricated-parent
  }
Beispiel #13
0
 public void exampleProdActorFactoryFunction() throws Exception {
   // #child-maker-prod
   Function<ActorRefFactory, ActorRef> maker =
       new Function<ActorRefFactory, ActorRef>() {
         @Override
         public ActorRef apply(ActorRefFactory f) throws Exception {
           return f.actorOf(Props.create(Child.class));
         }
       };
   ActorRef parent = system.actorOf(Props.create(GenericDependentParent.class, maker));
   // #child-maker-prod
 }
Beispiel #14
0
 @Test
 public void shouldImplementComparable() {
   ActorRef ref1 = system.actorOf(TrivialActor.class);
   ActorRef ref2 = system.actorOf(TrivialActor.class);
   Assert.assertNotEquals(
       "Two references must appear as different using the compareTo method",
       0,
       ref1.compareTo(ref2));
   Assert.assertEquals(
       "A reference must be equal to itself according to compareTo method",
       0,
       ref1.compareTo(ref1));
 }
 @Test
 public void proxyAnyActorRef() {
   try {
     final ActorRef actorRefToRemoteActor = system.deadLetters();
     // #typed-actor-remote
     Squarer typedActor =
         TypedActor.get(system)
             .typedActorOf(new TypedProps<Squarer>(Squarer.class), actorRefToRemoteActor);
     // Use "typedActor" as a FooBar
     // #typed-actor-remote
   } catch (Exception e) {
     // dun care
   }
 }
  public static void main(String[] args) {

    if (args.length != 6) {
      System.err.println("Incorrect input args");
      System.exit(-1);
    }

    final String fileName = args[0];
    final int minId = Integer.valueOf(args[1]);
    final int maxId = Integer.valueOf(args[2]);
    final double minAmount = Double.parseDouble(args[3]);
    final double maxAmount = Double.parseDouble(args[4]);
    final int recordsAmount = Integer.parseInt(args[5]);

    final ActorSystem system = ActorSystem.create("FileGeneration");
    ActorRef detailsFileWriter =
        system.actorOf(Props.create(RandomInformationFileWriter.class), "detailsFileWriter");
    system.actorOf(Props.create(Terminator.class, detailsFileWriter), "terminator");

    RandomInformationFileWriter.Details details =
        new RandomInformationFileWriter.Details(
            fileName, minId, maxId, minAmount, maxAmount, recordsAmount);
    detailsFileWriter.tell(details, null);
  }
  // #crTest
  @Test
  public void countVotesAsIntendedNotAsInFlorida() {
    ActorRef routedActor = system.actorOf(new Props().withRouter(new VoteCountRouter()));
    routedActor.tell(DemocratVote);
    routedActor.tell(DemocratVote);
    routedActor.tell(RepublicanVote);
    routedActor.tell(DemocratVote);
    routedActor.tell(RepublicanVote);
    Timeout timeout = new Timeout(Duration.parse("1 seconds"));
    Future<Object> democratsResult = routedActor.ask(DemocratCountResult, timeout);
    Future<Object> republicansResult = routedActor.ask(RepublicanCountResult, timeout);

    assertEquals(3, Await.result(democratsResult, timeout.duration()));
    assertEquals(2, Await.result(republicansResult, timeout.duration()));
  }
Beispiel #18
0
 @Test
 public void testingWithChildProbe() throws Exception {
   final TestProbe probe = new TestProbe(system);
   // #child-maker-test
   Function<ActorRefFactory, ActorRef> maker =
       new Function<ActorRefFactory, ActorRef>() {
         @Override
         public ActorRef apply(ActorRefFactory param) throws Exception {
           return probe.ref();
         }
       };
   ActorRef parent = system.actorOf(Props.create(GenericDependentParent.class, maker));
   // #child-maker-test
   probe.send(parent, "pingit");
   probe.expectMsg("ping");
 }
  @Test
  public void typedRouterPattern() {
    try {
      // #typed-router
      // prepare routees
      TypedActorExtension typed = TypedActor.get(system);

      Named named1 = typed.typedActorOf(new TypedProps<Named>(Named.class));

      Named named2 = typed.typedActorOf(new TypedProps<Named>(Named.class));

      List<Named> routees = new ArrayList<Named>();
      routees.add(named1);
      routees.add(named2);

      List<String> routeePaths = new ArrayList<String>();
      routeePaths.add(typed.getActorRefFor(named1).path().toStringWithoutAddress());
      routeePaths.add(typed.getActorRefFor(named2).path().toStringWithoutAddress());

      // prepare untyped router
      ActorRef router = system.actorOf(new RoundRobinGroup(routeePaths).props(), "router");

      // prepare typed proxy, forwarding MethodCall messages to `router`
      Named typedRouter = typed.typedActorOf(new TypedProps<Named>(Named.class), router);

      System.out.println("actor was: " + typedRouter.name()); // name-243
      System.out.println("actor was: " + typedRouter.name()); // name-614
      System.out.println("actor was: " + typedRouter.name()); // name-243
      System.out.println("actor was: " + typedRouter.name()); // name-614

      // #typed-router
      typed.poisonPill(named1);
      typed.poisonPill(named2);
      typed.poisonPill(typedRouter);

    } catch (Exception e) {
      // dun care
    }
  }
Beispiel #20
0
 @Test
 public void usePipe() throws Exception {
   TestProbe probe = new TestProbe(system);
   pipe(Futures.successful("ho!"), system.dispatcher()).to(probe.ref());
   probe.expectMsg("ho!");
 }
Beispiel #21
0
 public static void main(String[] args) {
   ActorSystem system = ActorSystem.create("Hello");
   ActorRef a = system.actorOf(Props.create(HelloWorld.class), "helloWorld");
   system.actorOf(Props.create(Terminator.class, a), "terminator");
 }
 @AfterClass
 public static void afterClass() throws Exception {
   Await.result(system.terminate(), Duration.create("5 seconds"));
 }
 @BeforeClass
 public static void beforeClass() {
   system = ActorSystem.create("InitializationDocTest");
 }
 @After
 public void tearDown() {
   system.shutdown();
 }
 @Before
 public void setUp() {
   system = ActorSystem.create("MySystem", AkkaSpec.testConf());
 }
Beispiel #26
0
 @AfterClass
 public static void tearDown() {
   system.shutdown();
 }
Beispiel #27
0
 @BeforeClass
 public static void setUp() {
   system = ActorSystem.create("SchedulerPatternTest", AkkaSpec.testConf());
 }