public void preStart() { try { System.out.println("================================================="); final Timeout timeout = new Timeout(Duration.create(1, SECONDS)); Future<Object> rt = Patterns.ask(models.ChatRoom.defaultRoom, new Join(username, out), timeout); String result = (String) Await.result(rt, timeout.duration()); System.out.println("-O-" + getSender()); System.out.println("-O-" + getSelf()); System.out.println("-O-" + getContext().self()); System.out.println("-O-" + getContext().parent()); if ("OK".equals(result)) { System.out.println("OK!"); // go! } else { // Cannot connect, create a Json error. ObjectNode error = Json.newObject(); error.put("error", result); // Send the error to the socket. out.tell(error, null); System.out.println("ERROR!"); // getContext().parent().tell(PoisonPill.getInstance(), self()); out.tell(PoisonPill.getInstance(), self()); } } catch (Exception ex) { ex.printStackTrace(); // force to stop actor } }
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)); } }
@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 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); } } }
@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)); }
@Override public void onReceive(Object message) throws Exception { if (message.equals("tick")) { // send another periodic tick after the specified delay getContext() .system() .scheduler() .scheduleOnce( Duration.create(1000, TimeUnit.MILLISECONDS), getSelf(), "tick", getContext().dispatcher()); // do something useful here // #schedule-receive target.tell(message, getSelf()); // #schedule-receive } // #schedule-receive else if (message.equals("restart")) { throw new ArithmeticException(); } // #schedule-receive else { unhandled(message); } }
private void onMessage(final String message) { try { userActor.send(new WebDataMessage(ref(), message)); } catch (SuspendExecution ex) { throw new AssertionError(ex); } }
@Override public void onReceive(final Object message) throws Exception { if (message instanceof AskParam) { AskParam askParam = (AskParam) message; timeout = askParam.timeout; caller = sender(); targetActor = context().actorOf(askParam.props); context().watch(targetActor); targetActor.forward(askParam.message, context()); final Scheduler scheduler = context().system().scheduler(); timeoutMessage = scheduler.scheduleOnce( askParam.timeout.duration(), self(), new AskTimeout(), context().dispatcher(), null); } else if (message instanceof Terminated) { sendFailureToCaller(new ActorKilledException("Target actor terminated.")); timeoutMessage.cancel(); context().stop(self()); } else if (message instanceof AskTimeout) { sendFailureToCaller( new TimeoutException("Target actor timed out after " + timeout.toString())); context().stop(self()); } else { unhandled(message); } }
@Override public void apply(Object msg) { if (msg.equals(Msg.DONE)) { // Start monitoring if (!timeoutTargets.isEmpty()) { ActorRef timeoutTarget = timeoutTargets.poll(); logger.info("Too Many Messages Timeout"); operator.tell(new BoltOperator.Split(timeoutTarget), getSelf()); logger.info("Ask Operator to Do Split"); } else { getContext().unbecome(); logger.info("Latency Monitor Start Monitoring"); // Start timer again timer = getContext() .system() .scheduler() .schedule( Duration.Zero(), Duration.create(probePeriod, TimeUnit.MILLISECONDS), getSelf(), Msg.TICK, getContext().dispatcher(), getSelf()); } } else unhandled(msg); // Ignore all probes }
@Override public void onReceive(Object message) throws Exception { if ("ping".equals(message)) { parent.tell("pong", self()); } else { unhandled(message); } }
public WebSocketActorAdapter( ChannelHandlerContext ctx, ActorRef<? super WebMessage> userActor) { super(userActor.getName(), new WebSocketChannelAdapter(ctx)); ((WebSocketChannelAdapter) (SendPort) getMailbox()).actor = this; this.ctx = ctx; this.userActor = userActor; watch(userActor); }
@Override public void onReceive(Object message) throws Exception { if ("pingit".equals(message)) { child.tell("ping", self()); } else if ("pong".equals(message)) { ponged = true; } else { unhandled(message); } }
@Override public void onReceive(Object msg) throws Exception { if (msg.equals(Msg.TICK)) { if (probes.timeout()) { timer.cancel(); // Stop timer getContext().become(SPLITTING); getSelf().tell(Msg.DONE, getSelf()); // Start splitting logger.info("Latency Monitor Start Splitting"); return; } // Send probes to all targets for (Pair<ActorRef, ActorRef> targetPort : targetPorts) { ActorRef target = targetPort.first(); ActorRef port = targetPort.second(); port.tell(probes.newProbe(target), getSelf()); } } else if (msg instanceof Probe) { probes.fill((Probe) msg); long now = System.nanoTime(); // TODO Temporary log here, remove or format this later logger.info( "SubOperator: " + ((Probe) msg).target + " Current latency: " + (now - ((Probe) msg).now) / 1000 + "us"); } else if (msg instanceof Target) { Target target = (Target) msg; if (target.toAdd) { probes.addTarget(target.target); targetPorts.add(new Pair<ActorRef, ActorRef>(target.target, target.port)); } else { probes.removeTarget(target.target); for (Pair<ActorRef, ActorRef> targetPort : targetPorts) { if (targetPort.first().equals(target.target)) { targetPorts.remove(targetPort); break; } } } } else unhandled(msg); }
public void apply(Object message) { if (message instanceof MasterWorkerProtocol.WorkIsReady) sendToMaster(new MasterWorkerProtocol.WorkerRequestsWork(workerId)); else if (message instanceof Work) { Work work = (Work) message; log.info("Got work: {}", work.job); currentWorkId = work.workId; workExecutor.tell(work.job, getSelf()); getContext().become(working); } else unhandled(message); }
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()); }
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()); }
final void service(ChannelHandlerContext ctx, FullHttpRequest req) throws SuspendExecution { if (context.watch()) watchToken = watch(userActor); this.ctx = ctx; this.req = req; if (isDone()) { handleDeath(getDeathCause()); return; } userActor.send(new HttpRequestWrapper(ref(), ctx, req)); }
@Override public ActorRef toActor(final ActorRefFactory context) { ActorRef ref = context.actorFor(stegklasse.getSimpleName()); if (ref.isTerminated()) { if (understeg != null) { ref = context.actorOf( new Props( new UntypedActorFactory() { @Override public Actor create() throws Exception { return stegklasse .getConstructor(ActorRef.class) .newInstance(understeg.toActor(context)); } }), stegklasse.getSimpleName()); } else { ref = context.actorOf(new Props(stegklasse), stegklasse.getSimpleName()); } } return ref; }
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())); }
@Override public void onReceive(Object message) throws Exception { if (message.equals("tick")) { // do something useful here // #schedule-constructor target.tell(message, getSelf()); // #schedule-constructor } // #schedule-constructor else if (message.equals("restart")) { throw new ArithmeticException(); } // #schedule-constructor else { unhandled(message); } }
@Override public int compareTo(ActorRef o) { return reference.compareTo(o); }
@Override public boolean equals(Object obj) { return reference.equals(obj); }
private void sendToMaster(Object msg) { clusterClient.tell(new SendToAll("/user/master/singleton", msg), getSelf()); }
private void sendFailureToCaller(final Throwable t) { caller.tell(new Failure(t), self()); }
@Override public int hashCode() { return reference.hashCode(); }
static void addTarget( ActorRef latencyMonitor, ActorRef target, ActorRef port, ActorContext context) { latencyMonitor.tell(new Target(target, port, true), context.self()); }
static void removeTarget(ActorRef latencyMonitor, ActorRef target, ActorContext context) { latencyMonitor.tell(new Target(target, null, false), context.self()); }
static void done(ActorRef latencyMonitor, ActorContext context) { latencyMonitor.tell(Msg.DONE, context.self()); }
@Override public void send(T message, ActorRef to) { reference.send(message, to); }