Exemplo n.º 1
0
  /**
   * @param args
   * @throws TimeoutException
   */
  public static void main(String[] args) throws TimeoutException {
    final ActorSystem system = ActorSystem.create("helloakka");
    final ActorRef greeter = system.actorOf(Props.create(Greeter.class), "greeter");

    final Inbox inbox = Inbox.create(system);

    greeter.tell(new WhoToGreet("akka"), ActorRef.noSender());
    ActorPath greeterPath = greeter.path();
    ActorPath greeterPath2 = null;
    System.out.println(greeterPath.root());

    inbox.send(greeter, new Greet());

    Greeting greeting1 = (Greeting) inbox.receive(Duration.create(5, TimeUnit.SECONDS));

    System.out.println("Greeting: " + greeting1.message);

    greeter.tell(new WhoToGreet("typesafe"), ActorRef.noSender());
    inbox.send(greeter, new Greet());
    Greeting greeting2 = (Greeting) inbox.receive(Duration.create(5, TimeUnit.SECONDS));
    System.out.println("Greeting: " + greeting2.message);

    ActorRef greetPrinter = system.actorOf(Props.create(GreetPrimer.class));
    //		greetPrinter.tell(new WhoToGreet("akkau"), ActorRef.noSender());

    //		system.scheduler().schedule(Duration.Zero(),Duration.create(1, TimeUnit.SECONDS),greeter,new
    // Greet(),system.dispatcher(),greetPrinter);

    system.actorSelection(greeterPath2).tell(new WhoToGreet("typo"), greeter);
    inbox.send(greeter, new Greet());
    greeting1 = (Greeting) inbox.receive(Duration.create(5, TimeUnit.SECONDS));

    System.out.println("Greeting: " + greeting1.message);
  }
Exemplo n.º 2
0
 private void closeActor() {
   if (slaveActorRef != null) {
     slaveActorRef.tell(new UnregisterSlaveMountPoint(), ActorRef.noSender());
     slaveActorRef.tell(PoisonPill.getInstance(), ActorRef.noSender());
     slaveActorRef = null;
   }
 }
  @Override
  protected synchronized void removeRegistration() {
    if (listenerRegistrationActor != null) {
      listenerRegistrationActor.tell(
          CloseDataTreeChangeListenerRegistration.getInstance(), ActorRef.noSender());
      listenerRegistrationActor = null;
    }

    dataChangeListenerActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
  }
  public void onReceive(Object message) throws Exception {

    System.out.println("----------------------------------------------------------");
    if (getSender().equals(getContext().parent())) {
      System.out.println("-A-" + getSender()); // == getContext().parent()
      System.out.println("-A-" + getSelf());
      System.out.println("-A-" + getContext().self());
      System.out.println("-A-" + getContext().parent());
      if (message instanceof JsonNode) {
        System.out.println("-A-" + "GO!");
        JsonNode event = (JsonNode) message;
        models.ChatRoom.defaultRoom.tell(
            new Talk(username, event.get("text").asText()), getSender());
      } else {
        unhandled(message);
      }
    } else {
      System.out.println("-B-" + getSender());
      System.out.println("-B-" + getSelf());
      System.out.println("-B-" + getContext().self());
      System.out.println("-B-" + getContext().parent());
      if (message instanceof ObjectNode) {
        System.out.println("-B-" + "GO!");
        // JsonNode event = (JsonNode)message;
        out.tell(message, ActorRef.noSender());
      } else {
        unhandled(message);
      }
    }
  }
Exemplo n.º 5
0
  @Test
  public void mustBeAbleToUseVoidTypeInForeach() {
    final JavaTestKit probe = new JavaTestKit(system);
    final java.lang.Iterable<String> input = Arrays.asList("a", "b", "c");
    Source<String, NotUsed> ints = Source.from(input);

    final CompletionStage<Done> completion =
        ints.runForeach(elem -> probe.getRef().tell(elem, ActorRef.noSender()), materializer);

    completion.thenAccept(elem -> probe.getRef().tell(String.valueOf(elem), ActorRef.noSender()));

    probe.expectMsgEquals("a");
    probe.expectMsgEquals("b");
    probe.expectMsgEquals("c");
    probe.expectMsgEquals("Done");
  }
Exemplo n.º 6
0
  @Override
  protected void onRecoveryComplete() {
    restoreFromSnapshot = null;

    // notify shard manager
    getContext().parent().tell(new ActorInitialized(), getSelf());

    // Being paranoid here - this method should only be called once but just in case...
    if (txCommitTimeoutCheckSchedule == null) {
      // Schedule a message to be periodically sent to check if the current in-progress
      // transaction should be expired and aborted.
      FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
      txCommitTimeoutCheckSchedule =
          getContext()
              .system()
              .scheduler()
              .schedule(
                  period,
                  period,
                  getSelf(),
                  TX_COMMIT_TIMEOUT_CHECK_MESSAGE,
                  getContext().dispatcher(),
                  ActorRef.noSender());
    }
  }
Exemplo n.º 7
0
  @Test
  public void mustBeAbleToRecover() throws Exception {
    final ManualProbe<Integer> publisherProbe = TestPublisher.manualProbe(true, system);
    final JavaTestKit probe = new JavaTestKit(system);

    final Source<Integer, NotUsed> source =
        Source.fromPublisher(publisherProbe)
            .map(
                elem -> {
                  if (elem == 1) throw new RuntimeException("ex");
                  else return elem;
                })
            .recover(new PFBuilder<Throwable, Integer>().matchAny(ex -> 0).build());

    final CompletionStage<Done> future =
        source.runWith(
            Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer);
    final PublisherProbeSubscription<Integer> s = publisherProbe.expectSubscription();
    s.sendNext(0);
    probe.expectMsgEquals(0);
    s.sendNext(1);
    probe.expectMsgEquals(0);

    future.toCompletableFuture().get(200, TimeUnit.MILLISECONDS);
  }
 protected void createGuest(int count, Drink drink, int maxDrinkCount) {
   IntStream.range(0, count)
       .forEach(
           c -> {
             bar.tell(new CocktailBar.CreateGuest(drink, maxDrinkCount), ActorRef.noSender());
           });
 }
Exemplo n.º 9
0
  /**
   * ERP推送订单
   *
   * @return shopOrderNo 订单编号
   * @throws ApiException
   */
  public Result shopOrderPush() throws ApiException, ParseException {
    JsonNode json = request().body().asJson();
    //        List<String> shopOrderCodeList = new ArrayList<>();
    for (int i = 0; i < json.size(); i++) {
      Long orderId = (json.get(i)).asLong();
      // 推送之前先查询,先从ERP查询该订单若已存在则不推送
      //            String shopOrderNo = "";
      List<Object> salesOrderList = shopOrderMiddle.salesOrderQuery(orderId.toString());
      if ((null == salesOrderList) || salesOrderList.size() == 0) {
        // 调用推送订单Actor
        system.actorSelection(SysParCom.ERP_ORDER_PUSH).tell(orderId, ActorRef.noSender());

        //                shopOrderNo = shopOrderMiddle.shopOrderPush(orderId);
        //                Logger.error("推送结果:"+shopOrderNo);
        //                shopOrderCodeList.add(shopOrderNo);
        //                //推送成功的订单再创建schedule
        //                if (Json.parse(shopOrderNo).has("ShopOrderNo")) {
        //                    shopOrderNo =
        // Json.parse(shopOrderNo).findValue("ShopOrderNo").asText();
        //                    Logger.error("订单"+shopOrderNo+":push to ERP");
        //                    //启动scheduler从erp查询订单,海关审核通过,更新物流信息
        //                    scheduler.schedule(Duration.create(SysParCom.ORDER_QUERY_DELAY,
        // TimeUnit.MILLISECONDS),Duration.create(SysParCom.ORDER_QUERY_INTERVAL,
        // TimeUnit.MILLISECONDS),salesOrderQueryActor,orderId);
        //                }
      }
    }
    //        return ok(shopOrderCodeList.toString());
    return ok();
  }
  private void sendInitialElectionTimeoutToFollowerMember2() {
    testLog.info("sendInitialElectionTimeoutToFollowerMember2 starting");

    // Send ElectionTimeout to member 2 to simulate missing heartbeat from the Leader. member 2
    // should switch to Candidate and send out RequestVote messages. Set member 1 and 3 actors
    // to capture RequestVote but not to forward to the behavior just yet as we want to
    // control the order of RequestVote messages to member 1 and 3.

    member1Actor.dropMessagesToBehavior(RequestVote.class);

    member2Actor.expectBehaviorStateChange();

    member3Actor.dropMessagesToBehavior(RequestVote.class);

    member2ActorRef.tell(new ElectionTimeout(), ActorRef.noSender());

    member1Actor.waitForExpectedMessages(RequestVote.class);
    member3Actor.waitForExpectedMessages(RequestVote.class);

    member2Actor.waitForBehaviorStateChange();
    verifyBehaviorState("member 2", member2Actor, RaftState.Candidate);

    assertEquals("member 1 election term", 1, member1Context.getTermInformation().getCurrentTerm());
    assertEquals("member 2 election term", 2, member2Context.getTermInformation().getCurrentTerm());
    assertEquals("member 3 election term", 1, member3Context.getTermInformation().getCurrentTerm());

    testLog.info("sendInitialElectionTimeoutToFollowerMember2 ending");
  }
Exemplo n.º 11
0
 @Test
 public void useLoggingActorWithMDC() {
   ActorSystem system = ActorSystem.create("MyDiagnosticSystem");
   ActorRef mdcActor = system.actorOf(Props.create(MdcActor.class, this));
   mdcActor.tell("some request", ActorRef.noSender());
   JavaTestKit.shutdownActorSystem(system);
 }
Exemplo n.º 12
0
 @Test
 public void useLoggingActor() {
   ActorSystem system = ActorSystem.create("MySystem");
   ActorRef myActor = system.actorOf(Props.create(MyActor.class, this));
   myActor.tell("test", ActorRef.noSender());
   JavaTestKit.shutdownActorSystem(system);
 }
Exemplo n.º 13
0
 @Test
 public void test() throws InterruptedException {
   final ActorSystem system = ActorSystem.create("helloakka");
   final ActorRef akkaBot = system.actorOf(Props.create(AkkaBotMaster.class), "master");
   System.out.println("JavaBotMain Actor System was created");
   akkaBot.tell(3, ActorRef.noSender());
   Thread.sleep(100);
 }
Exemplo n.º 14
0
 @Test
 public void mustBeAbleToUseActorRefSource() throws Exception {
   final JavaTestKit probe = new JavaTestKit(system);
   final Source<Integer, ActorRef> actorRefSource = Source.actorRef(10, OverflowStrategy.fail());
   final ActorRef ref =
       actorRefSource
           .to(
               Sink.foreach(
                   new Procedure<Integer>() {
                     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());
   probe.expectMsgEquals(2);
 }
Exemplo n.º 15
0
 /**
  * 订单申报 Added By Sunny Wu 2016.09.18
  *
  * @return
  */
 public Result shopOrderDeclara() {
   JsonNode json = request().body().asJson();
   for (int i = 0; i < json.size(); i++) {
     Long orderId = (json.get(i)).asLong();
     // 调用订单申报Actor
     Logger.error(orderId + "订单申报。。。。");
     system.actorSelection(SysParCom.ORDER_DECLARA).tell(orderId, ActorRef.noSender());
   }
   return ok();
 }
Exemplo n.º 16
0
  @Override
  public void run(String... args) throws Exception {
    logger.info("Actor System Started");
    ActorRef printerSupervisor =
        actorSystem.actorOf(
            SpringExtension.SpringExtProvider.get(actorSystem).props("printerSupervisorActor"),
            "printer");

    printerSupervisor.tell("start", ActorRef.noSender());
  }
Exemplo n.º 17
0
 @Test
 public void mustBeAbleToUseMapFuture() throws Exception {
   final JavaTestKit probe = new JavaTestKit(system);
   final Iterable<String> 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);
   probe.expectMsgEquals("A");
   probe.expectMsgEquals("B");
   probe.expectMsgEquals("C");
 }
Exemplo n.º 18
0
  /** https://github.com/akka/akka/tree/master/akka-samples/akka-sample-fsm-java-lambda */
  public static void main(String[] args) {
    ActorSystem system = ActorSystem.create("example");

    ActorRef chopstick1 = system.actorOf(Chopstick.props(), "Chopstick1");
    ActorRef chopstick2 = system.actorOf(Chopstick.props(), "Chopstick2");
    ActorRef chopstick3 = system.actorOf(Chopstick.props(), "Chopstick3");
    ActorRef chopstick4 = system.actorOf(Chopstick.props(), "Chopstick4");
    ActorRef chopstick5 = system.actorOf(Chopstick.props(), "Chopstick5");

    ActorRef hakker1 = system.actorOf(Hakker.props(chopstick1, chopstick2), "Hakker1");
    ActorRef hakker2 = system.actorOf(Hakker.props(chopstick2, chopstick3), "Hakker2");
    ActorRef hakker3 = system.actorOf(Hakker.props(chopstick3, chopstick4), "Hakker3");
    ActorRef hakker4 = system.actorOf(Hakker.props(chopstick4, chopstick5), "Hakker4");
    ActorRef hakker5 = system.actorOf(Hakker.props(chopstick5, chopstick1), "Hakker5");

    hakker1.tell(Protocol.Think, ActorRef.noSender());
    hakker2.tell(Protocol.Think, ActorRef.noSender());
    hakker3.tell(Protocol.Think, ActorRef.noSender());
    hakker4.tell(Protocol.Think, ActorRef.noSender());
    hakker5.tell(Protocol.Think, ActorRef.noSender());
  }
Exemplo n.º 19
0
  @Override
  public Cancellable runOnce(long initialDelay, String actorName, Object message) {

    ActorRef actor = getActor(actorName);
    if (actor == null) {
      return null;
    }
    FiniteDuration initial = new FiniteDuration(initialDelay, TimeUnit.MILLISECONDS);
    Scheduler scheduler = actorSystem.scheduler();
    return scheduler.scheduleOnce(
        initial, actor, message, actorSystem.dispatcher(), ActorRef.noSender());
  }
Exemplo n.º 20
0
  public void messageReceived(IoSession session, Object message) {
    Player player = (Player) session.getAttachment();
    if (session.isClosing() || player.destroyed()) {
      return;
    }
    RSCPacket p = (RSCPacket) message;

    if (p.getID() == 55) player.addInterval();

    Instance.loggingService().tell(p, ActorRef.noSender());

    packets.add(p);
  }
Exemplo n.º 21
0
  @Test
  public void mustBeAbleToUseOnCompleteError() {
    final JavaTestKit probe = new JavaTestKit(system);
    final Iterable<String> input = Arrays.asList("A", "B", "C");

    Source.from(input)
        .<String>map(
            in -> {
              throw new RuntimeException("simulated err");
            })
        .runWith(Sink.<String>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");
  }
Exemplo n.º 22
0
  public static void main(String[] args) {
    ActorSystem system = ActorSystem.create("MySystem");
    long now = System.currentTimeMillis();
    //        ActorRef smsA = system.actorOf(Props.create(SmsActor.class), "sms_" + "" + "");

    for (int i = 0; i < 1000; i++) {
      ActorRef smsA = system.actorOf(Props.create(SmsActor.class), "sms_" + i + "");
      Sms sms = new Sms();
      sms.content = "hello wj + " + i;
      sms.sender = "wj +" + i;
      sms.receiver = "jj +" + i;
      smsA.tell(sms, ActorRef.noSender());
    }
    Util.report(System.currentTimeMillis() - now);
  }
  void initializeLeaderBehavior(MemberActor actor, RaftActorContext context, int numActiveFollowers)
      throws Exception {
    // Leader sends immediate heartbeats - we don't care about it so ignore it.

    actor.expectMessageClass(AppendEntriesReply.class, numActiveFollowers);

    @SuppressWarnings("resource")
    Leader leader = new Leader(context);
    actor.waitForExpectedMessages(AppendEntriesReply.class);
    // Delay assignment here so the AppendEntriesReply isn't forwarded to the behavior.
    actor.behavior = leader;

    actor.forwardCapturedMessagesToBehavior(AppendEntriesReply.class, ActorRef.noSender());
    actor.clear();
  }
Exemplo n.º 24
0
 public static void main(String... args) {
   ActorSystem system = ActorSystem.create("MySystem");
   ActorRef swap = system.actorOf(Props.create(Swapper.class));
   swap.tell(SWAP, ActorRef.noSender()); // logs Hi
   swap.tell(SWAP, ActorRef.noSender()); // logs Ho
   swap.tell(SWAP, ActorRef.noSender()); // logs Hi
   swap.tell(SWAP, ActorRef.noSender()); // logs Ho
   swap.tell(SWAP, ActorRef.noSender()); // logs Hi
   swap.tell(SWAP, ActorRef.noSender()); // logs Ho
 }
Exemplo n.º 25
0
  public static void main(String[] args) throws Exception {
    ActorSystem akkaSystem = ActorSystem.create("SearchAkkaSystem");

    final Props indexProps = Props.create(IndexDispatcherActor.class);
    ActorRef indexDispatcherActor = akkaSystem.actorOf(indexProps);

    // indexDispatcherActor.tell(new LocalPasswordMessage(
    //       "/common_passwords.txt", 10000), ActorRef.noSender());

    final Props searchProps = Props.create(SearchRouterActor.class);
    ActorRef searchRouterActor = akkaSystem.actorOf(searchProps);

    searchRouterActor.tell(new SearchPasswordMessage(0L, 10L), ActorRef.noSender());

    // will run forever
  }
  private int fetch_reply_struct() {
    try {

      rows_num = rep_type.getField("out_columns_num").getInt(null);

    } catch (NoSuchFieldException | IllegalAccessException ex) {
      real_requester.tell(new DbmsLayerError(ex), ActorRef.noSender());
      return (-1);
    }

    try {
      lines_num = rep_type.getField("out_lines_num").getInt(null);
    } catch (NoSuchFieldException | IllegalAccessException ex) {

    }
    return (0);
  }
Exemplo n.º 27
0
  @Test
  public void testNegativePerformingWriteOperationOnReadTransaction() throws Exception {
    try {

      final ActorRef shard = getSystem().actorOf(Shard.props("config", Collections.EMPTY_MAP));
      final Props props =
          ShardTransaction.props(
              store.newReadOnlyTransaction(), shard, TestModel.createTestContext());
      final TestActorRef subject = TestActorRef.apply(props, getSystem());

      subject.receive(new DeleteData(TestModel.TEST_PATH).toSerializable(), ActorRef.noSender());
      Assert.assertFalse(true);

    } catch (Exception cs) {
      assertEquals(cs.getClass().getSimpleName(), Exception.class.getSimpleName());
      assertTrue(
          cs.getMessage().startsWith("ShardTransaction:handleRecieve received an unknown message"));
    }
  }
  private void sendElectionTimeoutToFollowerMember3() throws Exception {
    testLog.info("sendElectionTimeoutToFollowerMember3 starting");

    // Send ElectionTimeout to member 3 to simulate missing heartbeat from a Leader. member 3
    // should switch to Candidate and send out RequestVote messages. member 1 should grant the
    // vote and send a reply. After receiving the RequestVoteReply, member 3 should switch to
    // leader.

    member2Actor.expectBehaviorStateChange();
    member3Actor.clear();
    member3Actor.expectMessageClass(RequestVoteReply.class, 1);
    member3Actor.expectMessageClass(AppendEntriesReply.class, 2);

    member3ActorRef.tell(new ElectionTimeout(), ActorRef.noSender());

    member3Actor.waitForExpectedMessages(RequestVoteReply.class);

    RequestVoteReply requestVoteReply = member3Actor.getCapturedMessage(RequestVoteReply.class);
    assertEquals(
        "getTerm",
        member3Context.getTermInformation().getCurrentTerm(),
        requestVoteReply.getTerm());
    assertEquals("isVoteGranted", true, requestVoteReply.isVoteGranted());

    verifyBehaviorState("member 3", member3Actor, RaftState.Leader);

    // member 2 should've switched to Follower as member 3's RequestVote term (3) was greater
    // than member 2's term (2).

    member2Actor.waitForBehaviorStateChange();
    verifyBehaviorState("member 2", member2Actor, RaftState.Follower);

    // The switch to leader should cause an immediate AppendEntries heartbeat from member 3.

    member3Actor.waitForExpectedMessages(AppendEntriesReply.class);

    assertEquals("member 1 election term", 3, member1Context.getTermInformation().getCurrentTerm());
    assertEquals("member 2 election term", 3, member2Context.getTermInformation().getCurrentTerm());
    assertEquals("member 3 election term", 3, member3Context.getTermInformation().getCurrentTerm());

    testLog.info("sendElectionTimeoutToFollowerMember3 ending");
  }
Exemplo n.º 29
0
  @Test
  public void mustBeAbleToUseDropWhile() throws Exception {
    final JavaTestKit probe = new JavaTestKit(system);
    final Source<Integer, NotUsed> source =
        Source.from(Arrays.asList(0, 1, 2, 3))
            .dropWhile(
                new Predicate<Integer>() {
                  public boolean test(Integer elem) {
                    return elem < 2;
                  }
                });

    final CompletionStage<Done> future =
        source.runWith(
            Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer);

    probe.expectMsgEquals(2);
    probe.expectMsgEquals(3);
    future.toCompletableFuture().get(200, TimeUnit.MILLISECONDS);
  }
Exemplo n.º 30
0
  @Test
  public void mustBeAbleToCombine() throws Exception {
    final JavaTestKit probe = new JavaTestKit(system);
    final Source<Integer, NotUsed> source1 = Source.from(Arrays.asList(0, 1));
    final Source<Integer, NotUsed> source2 = Source.from(Arrays.asList(2, 3));

    final Source<Integer, NotUsed> source =
        Source.combine(
            source1,
            source2,
            new ArrayList<Source<Integer, ?>>(),
            width -> Merge.<Integer>create(width));

    final CompletionStage<Done> future =
        source.runWith(
            Sink.foreach(elem -> probe.getRef().tell(elem, ActorRef.noSender())), materializer);

    probe.expectMsgAllOf(0, 1, 2, 3);

    future.toCompletableFuture().get(200, TimeUnit.MILLISECONDS);
  }