Java Code Examples for scala.concurrent.Await#result()

The following examples show how to use scala.concurrent.Await#result() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AkkaTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void testForward(final MockTracer tracer) throws Exception {
  final ActorRef actorRef = system.actorOf(TestActor.props(tracer, true), "forward");
  final Timeout timeout = new Timeout(getDefaultDuration());

  final Future<Object> future = ask(actorRef, "forward", timeout);
  final Boolean isSpanNull = (Boolean)Await.result(future, getDefaultDuration());
  assertFalse(isSpanNull);

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(2));

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());
  for (final MockSpan span : spans)
    assertEquals(AkkaAgentIntercept.COMPONENT_NAME, span.tags().get(Tags.COMPONENT.getKey()));
}
 
Example 2
Source File: MetricRegistryImplTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that the query actor will be stopped when the MetricRegistry is shut down.
 */
@Test
public void testQueryActorShutdown() throws Exception {
	final FiniteDuration timeout = new FiniteDuration(10L, TimeUnit.SECONDS);

	MetricRegistryImpl registry = new MetricRegistryImpl(MetricRegistryConfiguration.defaultMetricRegistryConfiguration());

	final ActorSystem actorSystem = AkkaUtils.createDefaultActorSystem();

	registry.startQueryService(actorSystem, null);

	ActorRef queryServiceActor = registry.getQueryService();

	registry.shutdown().get();

	try {
		Await.result(actorSystem.actorSelection(queryServiceActor.path()).resolveOne(timeout), timeout);

		fail("The query actor should be terminated resulting in a ActorNotFound exception.");
	} catch (ActorNotFound e) {
		// we expect the query actor to be shut down
	}
}
 
Example 3
Source File: ClusterClient.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Stops a program on Flink cluster whose job-manager is configured in this client's configuration.
 * Stopping works only for streaming programs. Be aware, that the program might continue to run for
 * a while after sending the stop command, because after sources stopped to emit data all operators
 * need to finish processing.
 *
 * @param jobId
 *            the job ID of the streaming program to stop
 * @throws Exception
 *             If the job ID is invalid (ie, is unknown or refers to a batch job) or if sending the stop signal
 *             failed. That might be due to an I/O problem, ie, the job-manager is unreachable.
 */
public void stop(final JobID jobId) throws Exception {
	final ActorGateway jobManager = getJobManagerGateway();

	Future<Object> response = jobManager.ask(new JobManagerMessages.StopJob(jobId), timeout);

	final Object rc = Await.result(response, timeout);

	if (rc instanceof JobManagerMessages.StoppingSuccess) {
		// no further action required
	} else if (rc instanceof JobManagerMessages.StoppingFailure) {
		throw new Exception("Stopping the job with ID " + jobId + " failed.",
			((JobManagerMessages.StoppingFailure) rc).cause());
	} else {
		throw new IllegalStateException("Unexpected response: " + rc);
	}
}
 
Example 4
Source File: ClusterClient.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Requests and returns the accumulators for the given job identifier. Accumulators can be
 * requested while a is running or after it has finished.
 * @param jobID The job identifier of a job.
 * @param loader The class loader for deserializing the accumulator results.
 * @return A Map containing the accumulator's name and its value.
 */
public Map<String, OptionalFailure<Object>> getAccumulators(JobID jobID, ClassLoader loader) throws Exception {
	ActorGateway jobManagerGateway = getJobManagerGateway();

	Future<Object> response;
	try {
		response = jobManagerGateway.ask(new RequestAccumulatorResults(jobID), timeout);
	} catch (Exception e) {
		throw new Exception("Failed to query the job manager gateway for accumulators.", e);
	}

	Object result = Await.result(response, timeout);

	if (result instanceof AccumulatorResultsFound) {
		Map<String, SerializedValue<OptionalFailure<Object>>> serializedAccumulators =
				((AccumulatorResultsFound) result).result();

		return AccumulatorHelper.deserializeAccumulators(serializedAccumulators, loader);

	} else if (result instanceof AccumulatorResultsErroneous) {
		throw ((AccumulatorResultsErroneous) result).cause();
	} else {
		throw new Exception("Failed to fetch accumulators for the job " + jobID + ".");
	}
}
 
Example 5
Source File: LeaderRetrievalUtils.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the leader akka url and the current leader session ID. The values are stored in a
 * {@link LeaderConnectionInfo} instance.
 *
 * @param leaderRetrievalService Leader retrieval service to retrieve the leader connection
 *                               information
 * @param timeout Timeout when to give up looking for the leader
 * @return LeaderConnectionInfo containing the leader's akka URL and the current leader session
 * ID
 * @throws LeaderRetrievalException
 */
public static LeaderConnectionInfo retrieveLeaderConnectionInfo(
		LeaderRetrievalService leaderRetrievalService,
		FiniteDuration timeout
) throws LeaderRetrievalException {
	LeaderConnectionInfoListener listener = new LeaderConnectionInfoListener();

	try {
		leaderRetrievalService.start(listener);

		Future<LeaderConnectionInfo> connectionInfoFuture = listener.getLeaderConnectionInfoFuture();

		return Await.result(connectionInfoFuture, timeout);
	} catch (Exception e) {
		throw new LeaderRetrievalException("Could not retrieve the leader address and leader " +
				"session ID.", e);
	} finally {
		try {
			leaderRetrievalService.stop();
		} catch (Exception fe) {
			LOG.warn("Could not stop the leader retrieval service.", fe);
		}
	}
}
 
Example 6
Source File: FlowerActorSystem.java    From flower with Apache License 2.0 5 votes vote down vote up
private void initActorContext() {
	try {
		Props props = SupervisorActor.props(actorFactory).withDispatcher(dispatcherName);
		ActorRef supervierActor = actorSystem.actorOf(props, supervisorPathName);
		Future<Object> future = Patterns.ask(supervierActor, new ActorContextCommand(), DEFAULT_TIMEOUT - 1);
		this.actorContext = (ActorContext) Await.result(future, timeout);
	} catch (Exception e) {
		throw new FlowerException("fail to start flower", e);
	}
}
 
Example 7
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String mapPromise() throws Exception {
  Promise<String> p = Promise.<String>apply();
  Future<String> f = p.future().map(mapF, ec);
  p.success(string);
  return Await.result(f, inf);
}
 
Example 8
Source File: DefaultActorService.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
@PreDestroy
public void stopActorSystem() {
  Future<Terminated> status = system.terminate();
  try {
    Terminated terminated = Await.result(status, Duration.Inf());
    log.info("Actor system terminated: {}", terminated);
  } catch (Exception e) {
    log.error("Failed to terminate actor system.", e);
  }
}
 
Example 9
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String flatMapPromiseN() throws Exception {
  Promise<String> p = Promise.<String>apply();
  Future<String> f = p.future();
  for (int i = 0; i < N.n; i++)
    f = f.flatMap(flatMapF, ec);
  p.success(string);
  return Await.result(f, inf);
}
 
Example 10
Source File: AkkaActorITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
private static void testForward(final ActorSystem system) throws Exception {
  final ActorRef actorRef = system.actorOf(TestActor.props(true), "forward");
  final CountDownLatch latch = TestUtil.initExpectedSpanLatch(2);

  final Future<Object> future = ask(actorRef, "forward", new Timeout(getDefaultDuration()));
  final Boolean isSpanNull = (Boolean)Await.result(future, getDefaultDuration());
  assertFalse(isSpanNull);

  TestUtil.checkSpan(latch, new ComponentSpanCount("java-akka", 2, true));
}
 
Example 11
Source File: InterServiceCommunicationImpl.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Override
public Object getResponse(ActorRef actorRef, Request request) {
  try {
    return Await.result(getFuture(actorRef, request), t.duration());
  } catch (Exception e) {
    ProjectLogger.log(
        "InterServiceCommunicationImpl:getResponse: Exception occurred with error message = "
            + e.getMessage(),
        e);
    ProjectCommonException.throwServerErrorException(
        ResponseCode.unableToCommunicateWithActor,
        ResponseCode.unableToCommunicateWithActor.getErrorMessage());
  }
  return null;
}
 
Example 12
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public Void ensureConstN() throws Exception {
  Future<Void> f = constVoidFuture;
  for (int i = 0; i < N.n; i++)
    f.transform(ensureF, ec);
  return Await.result(f, inf);
}
 
Example 13
Source File: AkkaActorITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
private static void testAsk(final ActorSystem system) throws Exception {
  final ActorRef actorRef = system.actorOf(TestActor.props(false), "ask");
  final CountDownLatch latch = TestUtil.initExpectedSpanLatch(2);

  final Future<Object> future = ask(actorRef, "ask", new Timeout(getDefaultDuration()));
  final Boolean isSpanNull = (Boolean)Await.result(future, getDefaultDuration());
  assertFalse(isSpanNull);
  TestUtil.checkSpan(latch, new ComponentSpanCount("java-akka", 2, true));
}
 
Example 14
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String flatMapPromise() throws Exception {
  Promise<String> p = Promise.<String>apply();
  Future<String> f = p.future().flatMap(flatMapF, ec);
  p.success(string);
  return Await.result(f, inf);
}
 
Example 15
Source File: AkkaHttpServerTest.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
@AfterClass
public static void afterClass() throws Exception {
  if (system != null)
    Await.result(system.terminate(), Duration.create(15, "seconds"));
}
 
Example 16
Source File: AkkaTest.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
@AfterClass
public static void afterClass() throws Exception {
  if (system != null)
    Await.result(system.terminate(), getDefaultDuration());
}
 
Example 17
Source File: TaskManagerTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that the TaskManager sends a proper exception back to the sender if the trigger stack
 * trace message fails.
 */
@Test
public void testUpdateTaskInputPartitionsFailure() throws Exception {
	ActorGateway jobManager = null;
	ActorGateway taskManager = null;

	try {

		final ExecutionAttemptID executionAttemptId = new ExecutionAttemptID();

		ActorRef jm = system.actorOf(Props.create(SimpleJobManager.class, LEADER_SESSION_ID));
		jobManager = new AkkaActorGateway(jm, LEADER_SESSION_ID);

		highAvailabilityServices.setJobMasterLeaderRetriever(
			HighAvailabilityServices.DEFAULT_JOB_ID,
			new StandaloneLeaderRetrievalService(jobManager.path(), jobManager.leaderSessionID()));

		taskManager = TestingUtils.createTaskManager(
			system,
			highAvailabilityServices,
			new Configuration(),
			true,
			true);

		TaskDeploymentDescriptor tdd = createTaskDeploymentDescriptor(
			new JobID(),
			"test job",
			new JobVertexID(),
			executionAttemptId,
			new SerializedValue<>(new ExecutionConfig()),
			"test task",
			1,
			0,
			1,
			0,
			new Configuration(),
			new Configuration(),
			BlockingNoOpInvokable.class.getName(),
			Collections.<ResultPartitionDeploymentDescriptor>emptyList(),
			Collections.<InputGateDeploymentDescriptor>emptyList(),
			Collections.emptyList(),
			Collections.emptyList(),
			0);

		Future<Object> submitResponse = taskManager.ask(new SubmitTask(tdd), timeout);

		Await.result(submitResponse, timeout);

		Future<Object> partitionUpdateResponse = taskManager.ask(
			new TaskMessages.UpdateTaskSinglePartitionInfo(
				executionAttemptId,
				new IntermediateDataSetID(),
				new InputChannelDeploymentDescriptor(new ResultPartitionID(), ResultPartitionLocation.createLocal())),
			timeout);

		try {
			Await.result(partitionUpdateResponse, timeout);

			fail("The update task input partitions message should have failed.");
		} catch (Exception e) {
			// expected
		}
	} finally {
		TestingUtils.stopActor(jobManager);
		TestingUtils.stopActor(taskManager);
	}
}
 
Example 18
Source File: TaskManagerTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that the TaskManager sends a proper exception back to the sender if the trigger stack
 * trace message fails.
 */
@Test
public void testStackTraceSampleFailure() throws Exception {
	ActorGateway jobManager = null;
	ActorGateway taskManager = null;

	try {

		ActorRef jm = system.actorOf(Props.create(SimpleJobManager.class, LEADER_SESSION_ID));
		jobManager = new AkkaActorGateway(jm, LEADER_SESSION_ID);

		highAvailabilityServices.setJobMasterLeaderRetriever(
			HighAvailabilityServices.DEFAULT_JOB_ID,
			new StandaloneLeaderRetrievalService(jobManager.path(), jobManager.leaderSessionID()));

		taskManager = TestingUtils.createTaskManager(
			system,
			highAvailabilityServices,
			new Configuration(),
			true,
			true);

		Future<Object> stackTraceResponse = taskManager.ask(
			new TriggerStackTraceSample(
				0,
				new ExecutionAttemptID(),
				0,
				Time.milliseconds(1L),
				0),
			timeout);

		try {
			Await.result(stackTraceResponse, timeout);

			fail("The trigger stack trace message should have failed.");
		} catch (IllegalStateException e) {
			// expected
		}
	} finally {
		TestingUtils.stopActor(jobManager);
		TestingUtils.stopActor(taskManager);
	}
}
 
Example 19
Source File: TaskManagerTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that the TaskManager sends a proper exception back to the sender if the stop task
 * message fails.
 */
@Test
public void testStopTaskFailure() throws Exception {
	ActorGateway jobManager = null;
	ActorGateway taskManager = null;

	try {
		final ExecutionAttemptID executionAttemptId = new ExecutionAttemptID();

		ActorRef jm = system.actorOf(Props.create(SimpleJobManager.class, LEADER_SESSION_ID));
		jobManager = new AkkaActorGateway(jm, LEADER_SESSION_ID);

		highAvailabilityServices.setJobMasterLeaderRetriever(
			HighAvailabilityServices.DEFAULT_JOB_ID,
			new StandaloneLeaderRetrievalService(jobManager.path(), jobManager.leaderSessionID()));

		taskManager = TestingUtils.createTaskManager(
			system,
			highAvailabilityServices,
			new Configuration(),
			true,
			true);

		TaskDeploymentDescriptor tdd = createTaskDeploymentDescriptor(
			new JobID(),
			"test job",
			new JobVertexID(),
			executionAttemptId,
			new SerializedValue<>(new ExecutionConfig()),
			"test task",
			1,
			0,
			1,
			0,
			new Configuration(),
			new Configuration(),
			BlockingNoOpInvokable.class.getName(),
			Collections.<ResultPartitionDeploymentDescriptor>emptyList(),
			Collections.<InputGateDeploymentDescriptor>emptyList(),
			Collections.emptyList(),
			Collections.emptyList(),
			0);

		Future<Object> submitResponse = taskManager.ask(new SubmitTask(tdd), timeout);

		Await.result(submitResponse, timeout);

		final Future<Object> taskRunning = taskManager.ask(new TestingTaskManagerMessages.NotifyWhenTaskIsRunning(executionAttemptId), timeout);

		Await.result(taskRunning, timeout);

		Future<Object> stopResponse = taskManager.ask(new StopTask(executionAttemptId), timeout);

		try {
			Await.result(stopResponse, timeout);

			fail("The stop task message should have failed.");
		} catch (UnsupportedOperationException e) {
			// expected
		}
	} finally {
		TestingUtils.stopActor(jobManager);
		TestingUtils.stopActor(taskManager);
	}
}
 
Example 20
Source File: ThingPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void unavailableExpectedIfPersistenceActorTerminates() throws Exception {
    new TestKit(actorSystem) {
        {
            final Thing thing = createThingV2WithRandomId();
            final ThingId thingId = getIdOrThrow(thing);

            final ActorRef underTest = createSupervisorActorFor(thingId);

            final CreateThing createThing = CreateThing.of(thing, null, dittoHeadersV2);
            underTest.tell(createThing, getRef());

            final CreateThingResponse createThingResponse = expectMsgClass(CreateThingResponse.class);
            assertThingInResponse(createThingResponse.getThingCreated().orElse(null), thing);

            // retrieve created thing
            final RetrieveThing retrieveThing = RetrieveThing.of(thingId, dittoHeadersV2);
            underTest.tell(retrieveThing, getRef());
            expectMsgEquals(retrieveThingResponse(thing, thing.toJson(), dittoHeadersV2));

            // terminate thing persistence actor
            final String thingActorPath = String.format("akka://AkkaTestSystem/user/%s/pa", thingId);
            final ActorSelection thingActorSelection = actorSystem.actorSelection(thingActorPath);
            final Future<ActorRef> thingActorFuture =
                    thingActorSelection.resolveOne(Duration.create(5, TimeUnit.SECONDS));
            Await.result(thingActorFuture, Duration.create(6, TimeUnit.SECONDS));
            final ActorRef thingActor = watch(thingActorFuture.value().get().get());

            watch(thingActor);
            thingActor.tell(PoisonPill.getInstance(), getRef());
            expectTerminated(thingActor);

            // wait for supervisor to react to termination message
            Thread.sleep(500L);

            // retrieve unavailable thing
            underTest.tell(retrieveThing, getRef());
            expectMsgClass(ThingUnavailableException.class);
        }
    };
}