@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();
  }
Exemplo n.º 2
0
 @Override
 public void postStop() {
   if (internalLinkEndpoint != null) {
     if (logger.isInfoEnabled()) {
       logger.info(
           "MediaGroup: "
               + self().path()
               + " at postStop, about to stop intenalLinkEndpoint: "
               + internalLinkEndpoint.path()
               + " sender: "
               + sender().path());
     }
     gateway.tell(new DestroyEndpoint(internalLinkEndpoint), null);
     getContext().stop(internalLinkEndpoint);
     internalLinkEndpoint = null;
   }
   if (ivr != null) {
     if (logger.isInfoEnabled()) {
       logger.info(
           "MediaGroup :"
               + self().path()
               + " at postStop, about to stop ivr endpoint :"
               + ivr.path());
     }
     gateway.tell(new DestroyEndpoint(ivr), null);
     getContext().stop(ivr);
     ivr = null;
   }
   if (link != null) {
     if (logger.isInfoEnabled()) {
       logger.info(
           "MediaGroup :" + self().path() + " at postStop, about to stop link :" + link.path());
     }
     getContext().stop(link);
     link = null;
   }
   if (internalLink != null) {
     if (logger.isInfoEnabled()) {
       logger.info(
           "MediaGroup :"
               + self().path()
               + " at postStop, about to stop internal link :"
               + internalLink.path());
     }
     getContext().stop(link);
     link = null;
   }
   getContext().stop(self());
   super.postStop();
 }
Exemplo n.º 3
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);
  }
 private static ActorRef startResourceManager(Configuration config, ActorRef jobManager) {
   return FlinkResourceManager.startResourceManagerActors(
       config,
       actorSystem,
       new StandaloneLeaderRetrievalService(jobManager.path().toString()),
       StandaloneResourceManager.class);
 }
Exemplo n.º 5
0
 public Terminator(ActorRef ref) {
   this.ref = ref;
   getContext().watch(ref);
   receive(
       ReceiveBuilder.match(
               Terminated.class,
               t -> {
                 log().info("{} has terminated, shutting down system", ref.path());
                 context().system().terminate();
               })
           .build());
 }
Exemplo n.º 6
0
  public void generateTruckEventsStream(final StreamGeneratorParam params) {

    try {

      final Class eventEmitterClass = Class.forName(params.getEventEmitterClassName());
      final Class eventCollectorClass = Class.forName(params.getEventCollectorClassName());

      Config config = ConfigFactory.load();

      this.centerCoordinatesLat = params.getCenterCoordinatesLat();
      this.centerCoordinatesLat = params.getCenterCoordinatesLong();
      this.zoomLevel = params.getZoomLevel();
      this.truckSymbolSize = params.getTruckSymbolSize();
      TruckConfiguration.initialize(params.getRouteDirectory());
      int emitters = TruckConfiguration.freeRoutePool.size();

      Thread.sleep(5000);
      System.out.println(
          "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& Number of Emitters is ....." + emitters);

      ActorSystem system =
          ActorSystem.create("EventSimulator", config, getClass().getClassLoader());
      final ActorRef listener = system.actorOf(Props.create(SimulatorListener.class), "listener");
      final ActorRef eventCollector =
          system.actorOf(Props.create(eventCollectorClass), "eventCollector");
      final int numberOfEmitters = emitters;
      System.out.println(eventCollector.path());
      final long demoId = new Random().nextLong();
      final ActorRef master =
          system.actorOf(
              new Props(
                  new UntypedActorFactory() {
                    public UntypedActor create() {
                      return new SimulationMaster(
                          numberOfEmitters,
                          /*eventEmitterClass, listener, params.getNumberOfEvents(), demoId);*/
                          eventEmitterClass,
                          listener,
                          params.getNumberOfEvents(),
                          demoId,
                          params.getDelayBetweenEvents());
                    }
                  }),
              "master");
      master.tell(new StartSimulation(), master);
    } catch (Exception e) {
      throw new RuntimeException("Error running truck stream generator", e);
    }
  }
  private static void executeAskSpecificChildrenLogic(
      BasicActor gridActor, SingleReceiverRequestContainer messages) throws Exception {
    // Patterns.ask() returns a Future<Object>
    List<Future<Object>> childrenResponseList = new ArrayList<Future<Object>>();

    for (SingleReceiverRequestContent secondMessage : messages.getRequests()) {
      for (ActorRef child : gridActor.getContext().getChildren()) {
        if (secondMessage.recieverPath.equals(child.path().toString())) {

          BasicRequest request =
              new BasicRequest(
                  gridActor.getCurrentTimeStep(), gridActor.downStreamTrace, secondMessage);
          ConstantLogger.logMessageSendCounter(request);
          // wait x ms for response
          childrenResponseList.add(
              Patterns.ask(child, request, GridArchitectConfiguration.childrenResponseTime));
        }
      }
    }

    Future<Iterable<Object>> childrenFuturesIterable =
        sequence(childrenResponseList, gridActor.getContext().system().dispatcher());
    Iterable<Object> childrenResponsesIterable =
        Await.result(
            childrenFuturesIterable,
            Duration.create(
                (GridArchitectConfiguration.childrenResponseTime),
                TimeUnit.MILLISECONDS)); // childrenResponsesIterableTimeOut

    gridActor.answerListReceived = new ArrayList<BasicAnswer>();
    for (Object receivedAnswer : childrenResponsesIterable) {

      gridActor.answerListReceived.add((BasicAnswer) receivedAnswer);

      ConstantLogger.logMessageSendCounter((BasicAnswer) receivedAnswer);

      if (((BasicAnswer) receivedAnswer).overrideReportToParent) {
        gridActor.reportToParentEnabled = true;
        gridActor.overrideReportToParent = true;
      }

      for (ActorRef actor : ((BasicAnswer) receivedAnswer).upstreamActorTrace) {
        gridActor.upStreamTrace.add(actor);
      }
    }
  }
Exemplo n.º 8
0
 private void applyModificationToState(
     ActorRef clientActor, String identifier, Object modification) {
   if (modification == null) {
     LOG.error(
         "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
         persistenceId(),
         identifier,
         clientActor != null ? clientActor.path().toString() : null);
   } else if (clientActor == null) {
     // There's no clientActor to which to send a commit reply so we must be applying
     // replicated state from the leader.
     commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
   } else {
     // This must be the OK to commit after replication consensus.
     finishCommit(clientActor, identifier);
   }
 }
Exemplo n.º 9
0
  // FSM logic.
  @Override
  public void onReceive(final Object message) throws Exception {
    final Class<?> klass = message.getClass();
    final State state = fsm.state();
    final ActorRef sender = sender();

    if (logger.isInfoEnabled()) {
      logger.info(
          "********** Media Group " + self().path() + " Current State: \"" + state.toString());
      logger.info(
          "********** Media Group "
              + self().path()
              + " Processing Message: \""
              + klass.getName()
              + " sender : "
              + sender.getClass());
    }

    if (Observe.class.equals(klass)) {
      observe(message);
    } else if (StopObserving.class.equals(klass)) {
      stopObserving(message);
    } else if (MediaGroupStatus.class.equals(klass)) {
      if (active.equals(state)) {
        sender().tell(new MediaGroupStateChanged(MediaGroupStateChanged.State.ACTIVE), self());
      } else {
        sender().tell(new MediaGroupStateChanged(MediaGroupStateChanged.State.INACTIVE), self());
      }
    } else if (StartMediaGroup.class.equals(klass)) {
      if (logger.isInfoEnabled()) {
        logger.info(
            "MediaGroup: "
                + self().path()
                + " got StartMediaGroup from: "
                + sender().path()
                + " endpoint: "
                + endpoint.path()
                + " isTerminated: "
                + endpoint.isTerminated());
      }
      fsm.transition(message, acquiringIvr);
    } else if (Join.class.equals(klass)) {
      fsm.transition(message, acquiringInternalLink);
    } else if (MediaGatewayResponse.class.equals(klass)) {
      if (acquiringIvr.equals(state)) {
        fsm.transition(message, acquiringLink);
      } else if (acquiringLink.equals(state)) {
        fsm.transition(message, initializingLink);
      } else if (acquiringInternalLink.equals(state)) {
        fsm.transition(message, initializingInternalLink);
      }
    } else if (LinkStateChanged.class.equals(klass)) {
      final LinkStateChanged response = (LinkStateChanged) message;
      if (LinkStateChanged.State.CLOSED == response.state()) {
        if (initializingLink.equals(state)) {
          fsm.transition(message, openingLink);
        } else if (openingLink.equals(state)
            || deactivating.equals(state)
            || updatingLink.equals(state)) {
          fsm.transition(message, inactive);
        }
        if (initializingInternalLink.equals(state)) {
          fsm.transition(message, openingInternalLink);
        }
      } else if (LinkStateChanged.State.OPEN == response.state()) {
        if (openingLink.equals(state)) {
          fsm.transition(message, updatingLink);
        } else if (updatingLink.equals(state)) {
          fsm.transition(message, active);
        }
        if (openingInternalLink.equals(state)) {
          fsm.transition(message, updatingInternalLink);
        }
        if (updatingInternalLink.equals(state)) {
          fsm.transition(message, active);
        }
      }
    } else if (StopMediaGroup.class.equals(klass)) {
      if (acquiringLink.equals(state) || initializingLink.equals(state)) {
        fsm.transition(message, inactive);
      } else if (active.equals(state) || openingLink.equals(state) || updatingLink.equals(state)) {
        fsm.transition(message, deactivating);
      }
    } else if (EndpointStateChanged.class.equals(klass)) {
      onEndpointStateChanged((EndpointStateChanged) message, self(), sender);
    } else if (active.equals(state)) {
      if (Play.class.equals(klass)) {
        play(message);
      } else if (Collect.class.equals(klass)) {
        collect(message);
      } else if (Record.class.equals(klass)) {
        record(message);
      } else if (Stop.class.equals(klass)) {
        stop(lastEvent);
        // Send message to originator telling media group has been stopped
        // Needed for call bridging scenario, where inbound call must stop
        // ringing before attempting to perform join operation.
        sender().tell(new MediaGroupResponse<String>("stopped"), self());
      } else if (IvrEndpointResponse.class.equals(klass)) {
        notification(message);
      }
    } else if (ivrInUse) {
      if (Stop.class.equals(klass)) {
        stop(lastEvent);
      }
    }
  }