/** * Tests that a job is properly canceled in the event of a leader change. However, this time only * the TMs are notified about the changing leader. This should be enough to cancel the currently * running job, though. */ @Test public void testStateCleanupAfterListenerNotification() throws Exception { UUID leaderSessionID = UUID.randomUUID(); UUID newLeaderSessionID = UUID.randomUUID(); cluster.grantLeadership(0, leaderSessionID); cluster.notifyRetrievalListeners(0, leaderSessionID); cluster.waitForTaskManagersToBeRegistered(); // submit blocking job cluster.submitJobDetached(job); ActorGateway jm = cluster.getLeaderGateway(timeout); Future<Object> wait = jm.ask(new WaitForAllVerticesToBeRunningOrFinished(job.getJobID()), timeout); Await.ready(wait, timeout); Future<Object> jobRemoval = jm.ask(new NotifyWhenJobRemoved(job.getJobID()), timeout); // notify listeners (TMs) about the leader change cluster.notifyRetrievalListeners(1, newLeaderSessionID); Await.ready(jobRemoval, timeout); }
/** * Tests that a job is properly canceled in the case of a leader change. However, this time only * the JMs are notified about the leader change and the TMs still believe the old leader to have * leadership. */ @Test public void testStateCleanupAfterNewLeaderElection() throws Exception { UUID leaderSessionID = UUID.randomUUID(); UUID newLeaderSessionID = UUID.randomUUID(); cluster.grantLeadership(0, leaderSessionID); cluster.notifyRetrievalListeners(0, leaderSessionID); cluster.waitForTaskManagersToBeRegistered(); // submit blocking job so that we can test job clean up cluster.submitJobDetached(job); ActorGateway jm = cluster.getLeaderGateway(timeout); Future<Object> wait = jm.ask(new WaitForAllVerticesToBeRunningOrFinished(job.getJobID()), timeout); Await.ready(wait, timeout); Future<Object> jobRemoval = jm.ask(new NotifyWhenJobRemoved(job.getJobID()), timeout); // only notify the JMs about the new leader JM(1) cluster.grantLeadership(1, newLeaderSessionID); // job should be removed anyway Await.ready(jobRemoval, timeout); }
@Test public void blockMustBeCallable() throws Exception { Promise<String> p = Futures.promise(); Duration d = Duration.create(1, TimeUnit.SECONDS); p.success("foo"); Await.ready(p.future(), d); assertEquals(Await.result(p.future(), d), "foo"); }
@Test public void mapToMustBeCallable() throws Exception { Promise<Object> p = Futures.promise(); Future<String> f = p.future().mapTo(classTag(String.class)); Duration d = Duration.create(1, TimeUnit.SECONDS); p.success("foo"); Await.ready(p.future(), d); assertEquals(Await.result(p.future(), d), "foo"); }
@Test public void testFindPrimaryShardAsyncLocalPrimaryFound() throws Exception { TestActorRef<MessageCollectorActor> shardManager = TestActorRef.create(getSystem(), Props.create(MessageCollectorActor.class)); DatastoreContext dataStoreContext = DatastoreContext.newBuilder() .dataStoreType("config") .shardLeaderElectionTimeout(100, TimeUnit.MILLISECONDS) .build(); final DataTree mockDataTree = Mockito.mock(DataTree.class); final String expPrimaryPath = "akka://test-system/find-primary-shard"; ActorContext actorContext = new ActorContext( getSystem(), shardManager, mock(ClusterWrapper.class), mock(Configuration.class), dataStoreContext, new PrimaryShardInfoFutureCache()) { @Override protected Future<Object> doAsk(ActorRef actorRef, Object message, Timeout timeout) { return Futures.successful( (Object) new LocalPrimaryShardFound(expPrimaryPath, mockDataTree)); } }; Future<PrimaryShardInfo> foobar = actorContext.findPrimaryShardAsync("foobar"); PrimaryShardInfo actual = Await.result(foobar, Duration.apply(5000, TimeUnit.MILLISECONDS)); assertNotNull(actual); assertEquals("LocalShardDataTree present", true, actual.getLocalShardDataTree().isPresent()); assertSame("LocalShardDataTree", mockDataTree, actual.getLocalShardDataTree().get()); assertTrue( "Unexpected PrimaryShardActor path " + actual.getPrimaryShardActor().path(), expPrimaryPath.endsWith(actual.getPrimaryShardActor().pathString())); assertEquals( "getPrimaryShardVersion", DataStoreVersions.CURRENT_VERSION, actual.getPrimaryShardVersion()); Future<PrimaryShardInfo> cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar"); PrimaryShardInfo cachedInfo = Await.result(cached, FiniteDuration.apply(1, TimeUnit.MILLISECONDS)); assertEquals(cachedInfo, actual); actorContext.getPrimaryShardInfoCache().remove("foobar"); cached = actorContext.getPrimaryShardInfoCache().getIfPresent("foobar"); assertNull(cached); }
@Test public void sendAndSendOffAndReadAwait() throws Exception { Agent<Integer> agent = Agent.create(5, ec); // #send // send a value, enqueues this change // of the value of the Agent agent.send(7); // send a Mapper, enqueues this change // to the value of the Agent agent.send( new Mapper<Integer, Integer>() { public Integer apply(Integer i) { return i * 2; } }); // #send Mapper<Integer, Integer> longRunningOrBlockingFunction = new Mapper<Integer, Integer>() { public Integer apply(Integer i) { return i * 1; } }; ExecutionContext theExecutionContextToExecuteItIn = ec; // #send-off // sendOff a function agent.sendOff(longRunningOrBlockingFunction, theExecutionContextToExecuteItIn); // #send-off assertEquals(Await.result(agent.future(), Duration.create(5, "s")), new Integer(14)); }
@Test public void testTcpWorkerDupAndCancel() { ActorRef asyncWorker = null; logger.info("IN testTcpWorkerDupAndCancel"); try { // Start new job int actorMaxOperationTimeoutSec = 15; asyncWorker = ActorConfig.createAndGetActorSystem() .actorOf( Props.create( TcpWorker.class, actorMaxOperationTimeoutSec, getTcpMetaSample(), LOCALHOST)); final FiniteDuration duration = Duration.create(20, TimeUnit.SECONDS); Future<Object> future = Patterns.ask(asyncWorker, RequestWorkerMsgType.PROCESS_REQUEST, new Timeout(duration)); // test dup asyncWorker.tell(RequestWorkerMsgType.PROCESS_REQUEST, asyncWorker); // test cancel asyncWorker.tell(RequestWorkerMsgType.CANCEL, asyncWorker); ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await.result(future, duration); logger.info("\nWorker response:" + response.toString()); } catch (Throwable ex) { logger.error("Exception in test : " + ex); } } // end func
@Test public void traverseForJavaApiMustWork() throws Exception { LinkedList<String> listStrings = new LinkedList<String>(); LinkedList<String> expectedStrings = new LinkedList<String>(); for (int i = 0; i < 10; i++) { expectedStrings.add("TEST"); listStrings.add("test"); } Future<Iterable<String>> result = Futures.traverse( listStrings, new Function<String, Future<String>>() { public Future<String> apply(final String r) { return Futures.future( new Callable<String>() { public String call() { return r.toUpperCase(); } }, system.dispatcher()); } }, system.dispatcher()); assertEquals(Await.result(result, timeout), expectedStrings); }
@Test public void findForJavaApiMustWork() throws Exception { LinkedList<Future<Integer>> listFutures = new LinkedList<Future<Integer>>(); for (int i = 0; i < 10; i++) { final Integer fi = i; listFutures.add( Futures.future( new Callable<Integer>() { public Integer call() { return fi; } }, system.dispatcher())); } final Integer expect = 5; Future<Option<Integer>> f = Futures.find( listFutures, new Function<Integer, Boolean>() { public Boolean apply(Integer i) { return i == 5; } }, system.dispatcher()); assertEquals(expect, Await.result(f, timeout).get()); }
/** * Verifies a correct error message when vertices with master initialization (input formats / * output formats) fail. */ @Test public void testFailureWhenInitializeOnMasterFails() { try { // create a simple job graph JobVertex jobVertex = new JobVertex("Vertex that fails in initializeOnMaster") { @Override public void initializeOnMaster(ClassLoader loader) throws Exception { throw new RuntimeException("test exception"); } }; jobVertex.setInvokableClass(Tasks.NoOpInvokable.class); JobGraph jg = new JobGraph("test job", jobVertex); // submit the job Future<Object> submitFuture = jmGateway.ask( new JobManagerMessages.SubmitJob(jg, ListeningBehaviour.EXECUTION_RESULT), timeout); try { Await.result(submitFuture, timeout); } catch (JobExecutionException e) { // that is what we expect // test that the exception nesting is not too deep assertTrue(e.getCause() instanceof RuntimeException); } catch (Exception e) { fail("Wrong exception type"); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
// Register a remote location where Restcomm will send monitoring updates protected Response registerForUpdates( final String accountSid, final MultivaluedMap<String, String> data, MediaType responseType) { try { secure(daos.getAccountsDao().getAccount(accountSid), "RestComm:Read:Calls"); } catch (final AuthorizationException exception) { return status(UNAUTHORIZED).build(); } // Get the list of live calls from Monitoring Service MonitoringServiceResponse liveCalls; try { final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); GetLiveCalls getLiveCalls = new GetLiveCalls(); Future<Object> future = (Future<Object>) ask(monitoringService, getLiveCalls, expires); liveCalls = (MonitoringServiceResponse) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); } catch (Exception exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } if (liveCalls != null) { if (APPLICATION_XML_TYPE == responseType) { final RestCommResponse response = new RestCommResponse(liveCalls); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE == responseType) { Response response = ok(gson.toJson(liveCalls), APPLICATION_JSON).build(); return response; } else { return null; } } else { return null; } }
@Override protected void channelRead0(ChannelHandlerContext ctx, Routed routed) throws Exception { if (localJobManagerAddressFuture.isCompleted()) { if (localJobManagerAddress == null) { localJobManagerAddress = Await.result(localJobManagerAddressFuture, timeout); } Option<Tuple2<ActorGateway, Integer>> jobManager = retriever.getJobManagerGatewayAndWebPort(); if (jobManager.isDefined()) { Tuple2<ActorGateway, Integer> gatewayPort = jobManager.get(); String redirectAddress = HandlerRedirectUtils.getRedirectAddress(localJobManagerAddress, gatewayPort); if (redirectAddress != null) { HttpResponse redirect = HandlerRedirectUtils.getRedirectResponse(redirectAddress, routed.path()); KeepAliveWrite.flush(ctx, routed.request(), redirect); } else { respondAsLeader(ctx, routed, gatewayPort._1()); } } else { KeepAliveWrite.flush(ctx, routed.request(), HandlerRedirectUtils.getUnavailableResponse()); } } else { KeepAliveWrite.flush(ctx, routed.request(), HandlerRedirectUtils.getUnavailableResponse()); } }
/** * Entry point. All recent finished azkaban jobs' lineage. Will write to database stagging table * * @param timeFrame in minutes * @param endTimeStamp in millisecond * @throws Exception */ public void run(int timeFrame, long endTimeStamp) throws Exception { // get recent finished job AzJobChecker azJobChecker = new AzJobChecker(prop); List<AzkabanJobExecRecord> jobExecList = azJobChecker.getRecentFinishedJobFromFlow(timeFrame, endTimeStamp); azJobChecker.close(); logger.info("Total number of azkaban jobs : {}", jobExecList.size()); ActorSystem actorSystem = ActorSystem.create("LineageExtractor"); int numOfActor = Integer.valueOf(prop.getProperty(Constant.LINEAGE_ACTOR_NUM, "50")); ActorRef lineageExtractorActor = actorSystem.actorOf( Props.create(AzLineageExtractorActor.class) .withRouter(new SmallestMailboxRouter(numOfActor)), "lineageExtractorActor"); // initialize // AzkabanServiceCommunicator asc = new AzkabanServiceCommunicator(prop); HadoopNameNodeExtractor hnne = new HadoopNameNodeExtractor(prop); AzDbCommunicator adc = new AzDbCommunicator(prop); String wherehowsUrl = prop.getProperty(Constant.WH_DB_URL_KEY); String wherehowsUserName = prop.getProperty(Constant.WH_DB_USERNAME_KEY); String wherehowsPassWord = prop.getProperty(Constant.WH_DB_PASSWORD_KEY); String connUrl = wherehowsUrl + "?" + "user="******"&password="******"stg_job_execution_data_lineage"); AzLogParser.initialize(conn); PathAnalyzer.initialize(conn); int timeout = 30; // default 30 minutes for one job if (prop.containsKey(Constant.LINEAGE_ACTOR_TIMEOUT_KEY)) timeout = Integer.valueOf(prop.getProperty(Constant.LINEAGE_ACTOR_TIMEOUT_KEY)); List<Future<Object>> result = new ArrayList<>(); for (AzkabanJobExecRecord aje : jobExecList) { AzExecMessage message = new AzExecMessage(aje, prop); message.asc = null; message.hnne = hnne; message.adc = adc; message.databaseWriter = databaseWriter; message.connection = conn; Timeout t = new Timeout(timeout, TimeUnit.SECONDS); Future<Object> fut = Patterns.ask(lineageExtractorActor, message, t); result.add(fut); } // join all threads Future<Iterable<Object>> seq = Futures.sequence(result, actorSystem.dispatcher()); try { Await.result(seq, Duration.create(timeout + " seconds")); } catch (TimeoutException exception) { exception.printStackTrace(); } adc.close(); hnne.close(); databaseWriter.close(); logger.info("All job finished lineage collecting!"); }
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 } }
@Test public void reduceForJavaApiMustWork() throws Exception { LinkedList<Future<String>> listFutures = new LinkedList<Future<String>>(); StringBuilder expected = new StringBuilder(); for (int i = 0; i < 10; i++) { expected.append("test"); listFutures.add( Futures.future( new Callable<String>() { public String call() { return "test"; } }, system.dispatcher())); } Future<String> result = Futures.reduce( listFutures, new Function2<String, String, String>() { public String apply(String r, String t) { return r + t; } }, system.dispatcher()); assertEquals(Await.result(result, timeout), expected.toString()); }
@Test public void alterAndAlterOff() throws Exception { Agent<Integer> agent = Agent.create(5, ec); // #alter // alter a value Future<Integer> f1 = agent.alter(7); // alter a function (Mapper) Future<Integer> f2 = agent.alter( new Mapper<Integer, Integer>() { public Integer apply(Integer i) { return i * 2; } }); // #alter Mapper<Integer, Integer> longRunningOrBlockingFunction = new Mapper<Integer, Integer>() { public Integer apply(Integer i) { return i * 1; } }; ExecutionContext theExecutionContextToExecuteItIn = ec; // #alter-off // alterOff a function (Mapper) Future<Integer> f3 = agent.alterOff(longRunningOrBlockingFunction, theExecutionContextToExecuteItIn); // #alter-off assertEquals(Await.result(f3, Duration.create(5, "s")), new Integer(14)); }
/** * Tests that a job is properly canceled in the case of a leader change. In such an event all * TaskManagers have to disconnect from the previous leader and connect to the newly elected * leader. */ @Test public void testStateCleanupAfterNewLeaderElectionAndListenerNotification() throws Exception { UUID leaderSessionID1 = UUID.randomUUID(); UUID leaderSessionID2 = UUID.randomUUID(); // first make JM(0) the leader cluster.grantLeadership(0, leaderSessionID1); // notify all listeners cluster.notifyRetrievalListeners(0, leaderSessionID1); cluster.waitForTaskManagersToBeRegistered(); // submit blocking job so that it is not finished when we cancel it cluster.submitJobDetached(job); ActorGateway jm = cluster.getLeaderGateway(timeout); Future<Object> wait = jm.ask(new WaitForAllVerticesToBeRunningOrFinished(job.getJobID()), timeout); Await.ready(wait, timeout); Future<Object> jobRemoval = jm.ask(new NotifyWhenJobRemoved(job.getJobID()), timeout); // make the JM(1) the new leader cluster.grantLeadership(1, leaderSessionID2); // notify all listeners about the event cluster.notifyRetrievalListeners(1, leaderSessionID2); Await.ready(jobRemoval, timeout); cluster.waitForTaskManagersToBeRegistered(); ActorGateway jm2 = cluster.getLeaderGateway(timeout); Future<Object> futureNumberSlots = jm2.ask(JobManagerMessages.getRequestTotalNumberOfSlots(), timeout); // check that all TMs have registered at the new leader int numberSlots = (Integer) Await.result(futureNumberSlots, timeout); assertEquals(parallelism, numberSlots); // try to resubmit now the non-blocking job, it should complete successfully Tasks.BlockingOnceReceiver$.MODULE$.blocking_$eq(false); cluster.submitJobAndWait(job, false, timeout); }
/** * Tests that the same JobManager can be reelected as the leader. Even though, the same JM is * elected as the next leader, all currently running jobs should be canceled properly and all TMs * should disconnect from the leader and then reconnect to it. */ @Test public void testReelectionOfSameJobManager() throws Exception { UUID leaderSessionID = UUID.randomUUID(); UUID newLeaderSessionID = UUID.randomUUID(); FiniteDuration shortTimeout = new FiniteDuration(20, TimeUnit.SECONDS); cluster.grantLeadership(0, leaderSessionID); cluster.notifyRetrievalListeners(0, leaderSessionID); cluster.waitForTaskManagersToBeRegistered(); // submit blocking job cluster.submitJobDetached(job); ActorGateway jm = cluster.getLeaderGateway(timeout); Future<Object> wait = jm.ask(new WaitForAllVerticesToBeRunningOrFinished(job.getJobID()), timeout); Await.ready(wait, timeout); Future<Object> jobRemoval = jm.ask(new NotifyWhenJobRemoved(job.getJobID()), timeout); // make JM(0) again the leader --> this implies first a leadership revokal cluster.grantLeadership(0, newLeaderSessionID); Await.ready(jobRemoval, timeout); // The TMs should not be able to reconnect since they don't know the current leader // session ID try { cluster.waitForTaskManagersToBeRegistered(shortTimeout); fail("TaskManager should not be able to register at JobManager."); } catch (TimeoutException e) { // expected exception since the TMs have still the old leader session ID } // notify the TMs about the new (old) leader cluster.notifyRetrievalListeners(0, newLeaderSessionID); cluster.waitForTaskManagersToBeRegistered(); // try to resubmit now the non-blocking job, it should complete successfully Tasks.BlockingOnceReceiver$.MODULE$.blocking_$eq(false); cluster.submitJobAndWait(job, false, timeout); }
@Test public void testFailureWhenJarBlobsMissing() { try { // create a simple job graph JobVertex jobVertex = new JobVertex("Test Vertex"); jobVertex.setInvokableClass(Tasks.NoOpInvokable.class); JobGraph jg = new JobGraph("test job", jobVertex); // request the blob port from the job manager Future<Object> future = jmGateway.ask(JobManagerMessages.getRequestBlobManagerPort(), timeout); int blobPort = (Integer) Await.result(future, timeout); // upload two dummy bytes and add their keys to the job graph as dependencies BlobKey key1, key2; BlobClient bc = new BlobClient(new InetSocketAddress("localhost", blobPort)); try { key1 = bc.put(new byte[10]); key2 = bc.put(new byte[10]); // delete one of the blobs to make sure that the startup failed bc.delete(key2); } finally { bc.close(); } jg.addBlob(key1); jg.addBlob(key2); // submit the job Future<Object> submitFuture = jmGateway.ask( new JobManagerMessages.SubmitJob(jg, ListeningBehaviour.EXECUTION_RESULT), timeout); try { Await.result(submitFuture, timeout); } catch (JobExecutionException e) { // that is what we expect assertTrue(e.getCause() instanceof IOException); } catch (Exception e) { fail("Wrong exception type"); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
@Test public void useWatch() throws Exception { ActorSystem system = ActorSystem.create("MySystem"); ActorRef myActor = system.actorOf(new Props(WatchActor.class)); Future<Object> future = Patterns.ask(myActor, "kill", 1000); assert Await.result(future, Duration.create("1 second")).equals("finished"); system.shutdown(); }
@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"))); }
@Override public Topology.Host getHost(UUID hostId) { try { return Await.result(backend.store().get(Topology.Host.class, hostId), TIMEOUT); } catch (Exception e) { throw new RuntimeException("Failed to get host" + hostId); } }
private void retrieveMessages(ActorSystem system) throws Exception { ActorRef service = getService(system); Timeout timeout = new Timeout(Duration.create(2, TimeUnit.SECONDS)); Future<Object> fBets = Patterns.ask(service, new RetrieveBets(), timeout); List<Bet> bets = (List<Bet>) Await.result(fBets, timeout.duration()); assert bets.size() == 200; System.out.println("*** TESTING OK"); }
@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()); }
@Test public void createATypedActor() { try { // #typed-actor-create1 Squarer mySquarer = TypedActor.get(system) .typedActorOf(new TypedProps<SquarerImpl>(Squarer.class, SquarerImpl.class)); // #typed-actor-create1 // #typed-actor-create2 Squarer otherSquarer = TypedActor.get(system) .typedActorOf( new TypedProps<SquarerImpl>( Squarer.class, new Creator<SquarerImpl>() { public SquarerImpl create() { return new SquarerImpl("foo"); } }), "name"); // #typed-actor-create2 // #typed-actor-calls // #typed-actor-call-oneway mySquarer.squareDontCare(10); // #typed-actor-call-oneway // #typed-actor-call-future Future<Integer> fSquare = mySquarer.square(10); // A Future[Int] // #typed-actor-call-future // #typed-actor-call-option Option<Integer> oSquare = mySquarer.squareNowPlease(10); // Option[Int] // #typed-actor-call-option // #typed-actor-call-strict int iSquare = mySquarer.squareNow(10); // Int // #typed-actor-call-strict // #typed-actor-calls assertEquals(100, Await.result(fSquare, Duration.create(3, TimeUnit.SECONDS)).intValue()); assertEquals(100, oSquare.get().intValue()); assertEquals(100, iSquare); // #typed-actor-stop TypedActor.get(system).stop(mySquarer); // #typed-actor-stop // #typed-actor-poisonpill TypedActor.get(system).poisonPill(otherSquarer); // #typed-actor-poisonpill } catch (Exception e) { // Ignore } }
public Result index() throws Exception { if (system == null) { system = CarFactory.startCarFactory(); } ActorRef actor = system.actorFor("akka://carfactory/user/dataFetcher"); Timeout timeout = new Timeout(Duration.create(5000, "seconds")); Future<Object> ask = Patterns.ask(actor, new CountRequest(), timeout); Object result = Await.result(ask, timeout.duration()); return ok(result.toString()); }
@Test public void demonstrateAsk() throws Exception { // #test-behavior final Props props = Props.create(MyActor.class); final TestActorRef<MyActor> ref = TestActorRef.create(system, props, "testB"); final Future<Object> future = akka.pattern.Patterns.ask(ref, "say42", 3000); assertTrue(future.isCompleted()); assertEquals(42, Await.result(future, Duration.Zero())); // #test-behavior }
@Override public void setFloodingProxyWeight(UUID hostId, int weight) { try { Host h = Await.result(backend.store().get(Host.class, toProto(hostId)), TIMEOUT); h = h.toBuilder().setFloodingProxyWeight(weight).build(); backend.store().update(h); } catch (Exception e) { throw new RuntimeException("Can't retrieve flooding proxy weight"); } }
@Override public Integer getFloodingProxyWeight(UUID hostId) { try { return Await.result(backend.store().get(Host.class, toProto(hostId)), TIMEOUT) .getFloodingProxyWeight(); // for backwards compatibility } catch (Exception e) { throw new RuntimeException("Can't retrieve flooding proxy weight"); } }
/* (non-Javadoc) * @see akka.actor.UntypedActor#onReceive(java.lang.Object) */ @Override public void onReceive(Object message) throws Exception { // TODO Auto-generated method stub if (message instanceof RpcEvent.CallMethod) { Future<Object> future = Patterns.ask(rpc, message, new Timeout(Duration.create(10, TimeUnit.SECONDS))); Object o = Await.result(future, Duration.create(10, TimeUnit.SECONDS)); getSender().tell(o, getSelf()); } }