private void setOperational(final ActorIdentity pingResponse) { if (mediaQueue == null && IDENTIFY_MEDIA_QUEUE_ID.equals(pingResponse.correlationId())) { mediaQueue = pingResponse.getRef(); } if (mediaDecoder == null && IDENTIFY_MEDIA_DECODER_ID.equals(pingResponse.correlationId())) { mediaDecoder = pingResponse.getRef(); } if (mediaQueue != null && mediaDecoder != null) { getContext() .become( ReceiveBuilder.match(ImageSegment.class, msg -> build(msg)) .match(ImageData.class, msg -> breakDown(msg)) .match(AudioData.class, msg -> handleCommon(msg, mediaQueue)) .match(FrameRate.class, msg -> handleCommon(msg, mediaQueue)) .match(Play.class, msg -> handleCommon(msg, mediaQueue, mediaDecoder)) .match(Pause.class, msg -> handleCommon(msg, mediaQueue, mediaDecoder)) .match(Connect.class, msg -> handleConnect(msg)) .match(JoinRequest.class, msg -> handleRequest(msg)) .match(JoinAck.class, msg -> handleAck(msg)) .match(NewMember.class, msg -> handleNewMember(msg)) .build()); } }
public GenericActor() { receive( ReceiveBuilder.match( GenericMessage.class, (GenericMessage<String> msg) -> { GenericMessage<String> message = msg; sender().tell(message.value.toUpperCase(), self()); }) .build()); }
public MessageInitExample() { // #messageInit receive( ReceiveBuilder.matchEquals( "init", m1 -> { initializeMe = "Up and running"; context() .become( ReceiveBuilder.matchEquals( "U OK?", m2 -> { sender().tell(initializeMe, self()); }) .build()); }) .build() // #messageInit ); }
public GenericActorWithPredicate() { FI.TypedPredicate<GenericMessage<String>> typedPredicate = s -> !s.value.isEmpty(); receive( ReceiveBuilder.match( GenericMessage.class, typedPredicate, (GenericMessage<String> msg) -> { sender().tell(msg.value.toUpperCase(), self()); }) .build()); }
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()); }
public EventEndpointActor( BrickStateEventDispatcher brickStateEventDispatcher, ProjectRepository projectRepository) { receive( ReceiveBuilder.match(EventMsg.class, msg -> {}) .match( BrickStateEvent.class, msg -> { LOGGER.debug("Receive BrickStateEvent to BrickStateEventPersistenceActor."); getContext() .actorOf(BrickStateEventPersistenceActor.PROPS(projectRepository)) .forward(msg, getContext()); brickStateEventDispatcher.receive( msg); // Legacy, must be removed when migrate WebsoketEntrypoint. }) .matchAny(this::unhandled) .build()); }
@Override public PartialFunction<Object, BoxedUnit> receive() { return ReceiveBuilder.match(NewNumberCalculationMessage.class, this::log, this::queueNewMessage) .match(RegisterForNotifications.class, this::log, this::registerNewSSESubscription) .match( Worker.CalculationStarted.class, this::log, m -> recordStateChange(m.getTaskId(), Status.STARTED)) .match( Worker.CalculationFinished.class, this::log, m -> recordStateChange(m.getTaskId(), Status.FINISHED)) .match(GetTaskStatusMessage.class, this::log, this::handleGet) .match(DistributedPubSubMediator.SubscribeAck.class, m -> logSubscribeAck()) .matchAny(this::unhandled) .build(); }
@SuppressWarnings("unchecked") @Test public void demonstrateGetWithRequestContext() { probe = new JavaTestKit(system); // #get-request-context final ActorRef replicator = DistributedData.get(system).replicator(); final ReadConsistency readTwo = new ReadFrom(2, Duration.create(3, SECONDS)); final Key<PNCounter> counter1Key = PNCounterKey.create("counter1"); receive( ReceiveBuilder.match( String.class, a -> a.equals("get-count"), a -> { // incoming request to retrieve current value of the counter Optional<Object> reqContext = Optional.of(sender()); replicator.tell(new Replicator.Get<PNCounter>(counter1Key, readTwo), self()); }) .match( GetSuccess.class, a -> a.key().equals(counter1Key), a -> { ActorRef replyTo = (ActorRef) a.getRequest().get(); GetSuccess<PNCounter> g = a; long value = g.dataValue().getValue().longValue(); replyTo.tell(value, self()); }) .match( GetFailure.class, a -> a.key().equals(counter1Key), a -> { ActorRef replyTo = (ActorRef) a.getRequest().get(); replyTo.tell(-1L, self()); }) .match( NotFound.class, a -> a.key().equals(counter1Key), a -> { ActorRef replyTo = (ActorRef) a.getRequest().get(); replyTo.tell(0L, self()); }) .build()); // #get-request-context }
@Test public void demonstrateUpdateWithRequestContext() { probe = new JavaTestKit(system); // #update-request-context final Cluster node = Cluster.get(system); final ActorRef replicator = DistributedData.get(system).replicator(); final WriteConsistency writeTwo = new WriteTo(2, Duration.create(3, SECONDS)); final Key<PNCounter> counter1Key = PNCounterKey.create("counter1"); receive( ReceiveBuilder.match( String.class, a -> a.equals("increment"), a -> { // incoming command to increase the counter Optional<Object> reqContext = Optional.of(sender()); Replicator.Update<PNCounter> upd = new Replicator.Update<PNCounter>( counter1Key, PNCounter.create(), writeTwo, reqContext, curr -> curr.increment(node, 1)); replicator.tell(upd, self()); }) .match( UpdateSuccess.class, a -> a.key().equals(counter1Key), a -> { ActorRef replyTo = (ActorRef) a.getRequest().get(); replyTo.tell("ack", self()); }) .match( UpdateTimeout.class, a -> a.key().equals(counter1Key), a -> { ActorRef replyTo = (ActorRef) a.getRequest().get(); replyTo.tell("nack", self()); }) .build()); // #update-request-context }
public MyActor() { receive( ReceiveBuilder.match( Changed.class, a -> a.key().equals(counter1Key), a -> { Changed<PNCounter> g = a; currentValue = g.dataValue().getValue(); }) .match( String.class, a -> a.equals("get-count"), a -> { // incoming request to retrieve current value of the counter sender().tell(currentValue, sender()); }) .build()); }
private MediaTransportWorker(final int instance) { this.instance = instance; segments = new HashMap<>(); mediaQueue = null; mediaDecoder = null; others = new LinkedList<>(); id = Integer.MIN_VALUE; getContext() .actorSelection("../../" + ActorConstants.MEDIA_QUEUE_NAME) .tell(new Identify(IDENTIFY_MEDIA_QUEUE_ID), self()); getContext() .actorSelection("../../" + ActorConstants.MEDIA_DECODER_NAME) .tell(new Identify(IDENTIFY_MEDIA_DECODER_ID), self()); receive(ReceiveBuilder.match(ActorIdentity.class, msg -> setOperational(msg)).build()); }
public WorkerNode(InetAddress address, FiniteDuration checkInterval) { checkTimer = getContext() .system() .scheduler() .schedule( checkInterval, checkInterval, self(), DoHealthCheck.instance, getContext().dispatcher(), self()); List<WorkerNodeMessage> msgs = new ArrayList<>(); receive( ReceiveBuilder.match(WorkerNodeMessage.class, msgs::add) .match( DoHealthCheck.class, dhc -> { /* perform check */ }) .match( Shutdown.class, s -> { msgs.stream() .forEach( msg -> msg.replyTo() .tell( new WorkerCommandFailed("shutting down", msg.id()), self())); /* ask Resource Pool to shut down this instance */ }) .match( WorkerNodeReady.class, wnr -> { /* send msgs to the worker */ getContext().become(initialized()); }) .build()); }
@Override public PartialFunction<Object, BoxedUnit> receiveCommand() { return ReceiveBuilder.match( String.class, s -> s.equals("boom"), s -> { throw new RuntimeException("boom"); }) .match( String.class, s -> s.equals("print"), s -> System.out.println("received " + received)) .match( String.class, s -> { persist( s, evt -> { received.add(evt); }); }) .build(); }
public Master() { final ActorRef reader = getContext().actorOf(Props.create(FileReader.class), "fileReader"); final ActorRef writer = getContext().actorOf(Props.create(FileWriter.class), "fileWriter"); receive( ReceiveBuilder.match( ReadFile.class, readFile -> { reader.tell(new GetMap(), self()); }) .match( Result.class, result -> { writer.tell(result, self()); }) .match( End.class, end -> { context().system().shutdown(); }) .build()); }
@Override public PartialFunction<Object, BoxedUnit> receive() { return ReceiveBuilder.match( Waiter.DrinkServered.class, ds -> { drinkCount += 1; log().info("Enjoying my {}. yummy {}!", drinkCount, favoriteDrink); System.out.println(">>>>>>>>> " + maxDrinkCount); scheduleCoffeeFinished(); }) .match( DrinkFinished.class, d -> { if (drinkCount > maxDrinkCount) { throw new DrunkException(); } else { waiter.tell(new Waiter.ServeDrink(favoriteDrink), self()); } }) .build(); }
public EmailSenderActor(EmailSender emailSender) { if (emailSender == null) { throw new IllegalArgumentException("emailSender must be defined."); } receive( ReceiveBuilder.match( EmailSenderMsg.class, msg -> { try { emailSender.send( msg.to, msg.cc, msg.ci, msg.object, msg.content, msg.htmlContent, msg.attachments); } catch (RuntimeException e) { LOGGER.error( "Unable to sent email to '{}', with subject '{}'", Arrays.toString(msg.to.toArray()), msg.object, e); sender().tell(Futures.failed(e), self()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Email sent to '{}' with subject '{}'", Arrays.toString(msg.to.toArray()), msg.object); } getContext().stop(self()); }) .matchAny(this::unhandled) .build()); }
/* (non-Javadoc) * @see akka.actor.AbstractActor#receive() */ @Override public PartialFunction<Object, BoxedUnit> receive() { return ReceiveBuilder.match( BucketActionMessage.class, m -> !m.handling_clients().isEmpty() && !m.handling_clients() .contains(_context.getInformationService().getHostname()), __ -> {}) // (do nothing if it's not for me) .match( BucketActionOfferMessage.class, m -> { _logger.info( ErrorUtils.get( "Actor {0} received message {1} from {2} bucket {3}", this.self(), m.getClass().getSimpleName(), this.sender(), m.bucket().full_name())); final ActorRef closing_sender = this.sender(); final ActorRef closing_self = this.self(); final String hostname = _context.getInformationService().getHostname(); // (this isn't async so doesn't require any futures) final boolean accept_or_ignore = new File(_globals.local_yarn_config_dir() + File.separator + "storm.yaml") .exists(); final BucketActionReplyMessage reply = accept_or_ignore ? new BucketActionReplyMessage.BucketActionWillAcceptMessage(hostname) : new BucketActionReplyMessage.BucketActionIgnoredMessage(hostname); closing_sender.tell(reply, closing_self); }) .match( BucketActionMessage.class, m -> { _logger.info( ErrorUtils.get( "Actor {0} received message {1} from {2} bucket={3}", this.self(), m.getClass().getSimpleName(), this.sender(), m.bucket().full_name())); final ActorRef closing_sender = this.sender(); final ActorRef closing_self = this.self(); final String hostname = _context.getInformationService().getHostname(); // (cacheJars can't throw checked or unchecked in this thread, only from within // exceptions) cacheJars( m.bucket(), _management_db, _globals, _fs, _context.getServiceContext(), hostname, m) .thenComposeAsync( err_or_map -> { final StreamingEnrichmentContext e_context = _context.getNewStreamingEnrichmentContext(); final Validation<BasicMessageBean, IEnrichmentStreamingTopology> err_or_tech_module = getStreamingTopology(m.bucket(), m, hostname, err_or_map); final CompletableFuture<BucketActionReplyMessage> ret = talkToStream( _storm_controller, m.bucket(), m, err_or_tech_module, err_or_map, hostname, e_context, _globals.local_yarn_config_dir(), _globals.local_cached_jar_dir()); return ret; }) .thenAccept( reply -> { // (reply can contain an error or successful reply, they're the // same bean type) // Some information logging: Patterns.match(reply) .andAct() .when( BucketActionHandlerMessage.class, msg -> _logger.info( ErrorUtils.get( "Standard reply to message={0}, bucket={1}, success={2}", m.getClass().getSimpleName(), m.bucket().full_name(), msg.reply().success()))) .when( BucketActionReplyMessage.BucketActionWillAcceptMessage.class, msg -> _logger.info( ErrorUtils.get( "Standard reply to message={0}, bucket={1}", m.getClass().getSimpleName(), m.bucket().full_name()))) .otherwise( msg -> _logger.info( ErrorUtils.get( "Unusual reply to message={0}, type={2}, bucket={1}", m.getClass().getSimpleName(), m.bucket().full_name(), msg.getClass().getSimpleName()))); closing_sender.tell(reply, closing_self); }) .exceptionally( e -> { // another bit of error handling that shouldn't ever be called but is a // useful backstop // Some information logging: _logger.warn( "Unexpected error replying to '{0}': error = {1}, bucket={2}", BeanTemplateUtils.toJson(m).toString(), ErrorUtils.getLongForm("{0}", e), m.bucket().full_name()); final BasicMessageBean error_bean = SharedErrorUtils.buildErrorMessage( hostname, m, ErrorUtils.getLongForm( StreamErrorUtils.STREAM_UNKNOWN_ERROR, e, m.bucket().full_name())); closing_sender.tell( new BucketActionHandlerMessage(hostname, error_bean), closing_self); return null; }); }) .build(); }
public PaintRedActor() { receive( ReceiveBuilder.match(Car.class, this::paint) .match(CountRequest.class, this::sendCount) .build()); }
@SuppressWarnings({"unused", "unchecked"}) @Test public void demonstrateGet() { probe = new JavaTestKit(system); // #get final ActorRef replicator = DistributedData.get(system).replicator(); final Key<PNCounter> counter1Key = PNCounterKey.create("counter1"); final Key<GSet<String>> set1Key = GSetKey.create("set1"); final Key<ORSet<String>> set2Key = ORSetKey.create("set2"); final Key<Flag> activeFlagKey = FlagKey.create("active"); replicator.tell(new Replicator.Get<PNCounter>(counter1Key, Replicator.readLocal()), self()); final ReadConsistency readFrom3 = new ReadFrom(3, Duration.create(1, SECONDS)); replicator.tell(new Replicator.Get<GSet<String>>(set1Key, readFrom3), self()); final ReadConsistency readMajority = new ReadMajority(Duration.create(5, SECONDS)); replicator.tell(new Replicator.Get<ORSet<String>>(set2Key, readMajority), self()); final ReadConsistency readAll = new ReadAll(Duration.create(5, SECONDS)); replicator.tell(new Replicator.Get<Flag>(activeFlagKey, readAll), self()); // #get // #get-response1 receive( ReceiveBuilder.match( GetSuccess.class, a -> a.key().equals(counter1Key), a -> { GetSuccess<PNCounter> g = a; BigInteger value = g.dataValue().getValue(); }) .match( NotFound.class, a -> a.key().equals(counter1Key), a -> { // key counter1 does not exist }) .build()); // #get-response1 // #get-response2 receive( ReceiveBuilder.match( GetSuccess.class, a -> a.key().equals(set1Key), a -> { GetSuccess<GSet<String>> g = a; Set<String> 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 }) .build()); // #get-response2 }
@Test public void demonstrateUpdate() { probe = new JavaTestKit(system); // #update final Cluster node = Cluster.get(system); final ActorRef replicator = DistributedData.get(system).replicator(); final Key<PNCounter> counter1Key = PNCounterKey.create("counter1"); final Key<GSet<String>> set1Key = GSetKey.create("set1"); final Key<ORSet<String>> set2Key = ORSetKey.create("set2"); final Key<Flag> activeFlagKey = FlagKey.create("active"); replicator.tell( new Replicator.Update<PNCounter>( counter1Key, PNCounter.create(), Replicator.writeLocal(), curr -> curr.increment(node, 1)), self()); final WriteConsistency writeTo3 = new WriteTo(3, Duration.create(1, SECONDS)); replicator.tell( new Replicator.Update<GSet<String>>( set1Key, GSet.create(), writeTo3, curr -> curr.add("hello")), self()); final WriteConsistency writeMajority = new WriteMajority(Duration.create(5, SECONDS)); replicator.tell( new Replicator.Update<ORSet<String>>( set2Key, ORSet.create(), writeMajority, curr -> curr.add(node, "hello")), self()); final WriteConsistency writeAll = new WriteAll(Duration.create(5, SECONDS)); replicator.tell( new Replicator.Update<Flag>( activeFlagKey, Flag.create(), writeAll, curr -> curr.switchOn()), self()); // #update probe.expectMsgClass(UpdateSuccess.class); // #update-response1 receive( ReceiveBuilder.match( UpdateSuccess.class, a -> a.key().equals(counter1Key), a -> { // ok }) .build()); // #update-response1 // #update-response2 receive( ReceiveBuilder.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 }) .build()); // #update-response2 }
public WebsocketTransport(Messages.JoinWebsocket join) { this.out = join.out; this.in = join.in; this.context = join.context; final ActorRef self = getContext().self(); in.onClose( () -> { signalJActor.tell(new Messages.Quit(context.connectionId), self); self.tell(PoisonPill.getInstance(), self); }); in.onMessage( json -> { Logger.debug("Message from user: "******" : " + json); signalJActor.tell(new Messages.Execute(context, json), self); }); context() .setReceiveTimeout( Duration.create( SignalJPlugin.getConfiguration().getKeepAliveTimeout() / 2, TimeUnit.SECONDS)); receive( ReceiveBuilder.match( Messages.JoinWebsocket.class, r -> out.write(JsonHelper.writeConnect(prefix))) .match( Messages.MethodReturn.class, methodReturn -> { out.write(JsonHelper.writeMethodReturn(methodReturn)); sendAck(methodReturn); }) .match( Messages.ClientFunctionCall.class, clientFunctionCall -> { out.write(JsonHelper.writeClientFunctionCall(clientFunctionCall, prefix)); sendAck(clientFunctionCall); }) .match( Messages.ClientCallEnd.class, clientCallEnd -> { out.write(JsonHelper.writeConfirm(clientCallEnd.context)); sendAck(clientCallEnd); }) .match(ReceiveTimeout.class, r -> out.write(JsonHelper.writeHeartbeat())) .match( Messages.ReconnectWebsocket.class, r -> Logger.debug("Reconnect Websocket " + r.context.connectionId)) .match( Messages.StateChange.class, state -> { out.write(JsonHelper.writeState(state)); sendAck(state); }) .match( Messages.Error.class, error -> { out.write(JsonHelper.writeError(error)); sendAck(error); }) .build()); }
@Override public PartialFunction<Object, BoxedUnit> receiveRecover() { return ReceiveBuilder.match(String.class, s -> received.add(s)).build(); }