scala.concurrent.duration.FiniteDuration Java Examples

The following examples show how to use scala.concurrent.duration.FiniteDuration. 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: MesosResourceManager.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to shut down the given actor gracefully.
 *
 * @param actorRef specifying the actor to shut down
 * @param timeout  for the graceful shut down
 * @return A future that finishes with {@code true} iff. the actor could be stopped gracefully
 * or {@code actorRef} was {@code null}.
 */
private CompletableFuture<Boolean> stopActor(@Nullable final ActorRef actorRef, FiniteDuration timeout) {
	if (actorRef == null) {
		return CompletableFuture.completedFuture(true);
	}

	return FutureUtils.toJava(Patterns.gracefulStop(actorRef, timeout))
		.exceptionally(
			(Throwable throwable) -> {
				// The actor did not stop gracefully in time, try to directly stop it
				actorSystem.stop(actorRef);

				log.warn("Could not stop actor {} gracefully.", actorRef.path(), throwable);

				return false;
			}
		);
}
 
Example #2
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 #3
Source File: UdpWorkerTest.java    From parallec with Apache License 2.0 6 votes vote down vote up
@Test
public void testUdpWorkerBadMsgTypeDefaultType() {
    
    logger.info("IN testUdpWorkerBadMsgTypeDefaultType");
    ActorRef asyncWorker = null;
    try {
        // made a timeout
        int actorMaxOperationTimeoutSec = 15;
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(UdpWorker.class, actorMaxOperationTimeoutSec,
                        getUdpMetaSample(), LOCALHOST));
        
        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);
        Future<Object> future = Patterns
                .ask(asyncWorker, RequestWorkerMsgType.CHECK_FUTURE_STATE,
                        new Timeout(duration));
        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

        logger.info("\nWorker response:" + response.toString());
    } catch (Throwable ex) {

        logger.error("Exception in test : " + ex);
    }
}
 
Example #4
Source File: UdpWorkerTest.java    From parallec with Apache License 2.0 6 votes vote down vote up
@Test
public void testUdpWorkerBadMsgType() {
    
    logger.info("IN testUdpWorkerBadMsgType");
    ActorRef asyncWorker = null;
    try {
        // made a timeout
        int actorMaxOperationTimeoutSec = 15;
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(UdpWorker.class, actorMaxOperationTimeoutSec,
                        getUdpMetaSample(), LOCALHOST));
        
        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);
        Future<Object> future = Patterns
                .ask(asyncWorker, new Integer(0),
                        new Timeout(duration));
        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

        logger.info("\nWorker response:" + response.toString());
    } catch (Throwable ex) {

        logger.error("Exception in test : " + ex);
    }
}
 
Example #5
Source File: MesosResourceManager.java    From flink with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<Void> stopSupportingActorsAsync() {
	FiniteDuration stopTimeout = new FiniteDuration(5L, TimeUnit.SECONDS);

	CompletableFuture<Boolean> stopTaskMonitorFuture = stopActor(taskMonitor, stopTimeout);
	taskMonitor = null;

	CompletableFuture<Boolean> stopConnectionMonitorFuture = stopActor(connectionMonitor, stopTimeout);
	connectionMonitor = null;

	CompletableFuture<Boolean> stopLaunchCoordinatorFuture = stopActor(launchCoordinator, stopTimeout);
	launchCoordinator = null;

	CompletableFuture<Boolean> stopReconciliationCoordinatorFuture = stopActor(reconciliationCoordinator, stopTimeout);
	reconciliationCoordinator = null;

	return CompletableFuture.allOf(
		stopTaskMonitorFuture,
		stopConnectionMonitorFuture,
		stopLaunchCoordinatorFuture,
		stopReconciliationCoordinatorFuture);
}
 
Example #6
Source File: LeaderRetrievalUtils.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the current leader gateway using the given {@link LeaderRetrievalService}. If the
 * current leader could not be retrieved after the given timeout, then a
 * {@link LeaderRetrievalException} is thrown.
 *
 * @param leaderRetrievalService {@link LeaderRetrievalService} which is used for the leader retrieval
 * @param actorSystem ActorSystem which is used for the {@link LeaderRetrievalListener} implementation
 * @param timeout Timeout value for the retrieval call
 * @return The current leader gateway
 * @throws LeaderRetrievalException If the actor gateway could not be retrieved or the timeout has been exceeded
 */
public static ActorGateway retrieveLeaderGateway(
		LeaderRetrievalService leaderRetrievalService,
		ActorSystem actorSystem,
		FiniteDuration timeout)
	throws LeaderRetrievalException {
	LeaderGatewayListener listener = new LeaderGatewayListener(actorSystem, timeout);

	try {
		leaderRetrievalService.start(listener);

		Future<ActorGateway> actorGatewayFuture = listener.getActorGatewayFuture();

		return Await.result(actorGatewayFuture, timeout);
	} catch (Exception e) {
		throw new LeaderRetrievalException("Could not retrieve the leader gateway.", e);
	} finally {
		try {
			leaderRetrievalService.stop();
		} catch (Exception fe) {
			LOG.warn("Could not stop the leader retrieval service.", fe);
		}
	}
}
 
Example #7
Source File: LeaderRetrievalUtils.java    From Flink-CEPplus 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 #8
Source File: LeaderRetrievalUtils.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
public static InetAddress findConnectingAddress(
		LeaderRetrievalService leaderRetrievalService,
		FiniteDuration timeout) throws LeaderRetrievalException {
	ConnectionUtils.LeaderConnectingAddressListener listener = new ConnectionUtils.LeaderConnectingAddressListener();

	try {
		leaderRetrievalService.start(listener);

		LOG.info("Trying to select the network interface and address to use " +
				"by connecting to the leading JobManager.");

		LOG.info("TaskManager will try to connect for " + timeout +
				" before falling back to heuristics");

		return listener.findConnectingAddress(timeout);
	} catch (Exception e) {
		throw new LeaderRetrievalException("Could not find the connecting address by " +
				"connecting to the current leader.", e);
	} finally {
		try {
			leaderRetrievalService.stop();
		} catch (Exception fe) {
			LOG.warn("Could not stop the leader retrieval service.", fe);
		}
	}
}
 
Example #9
Source File: TcpWorkerTest.java    From parallec with Apache License 2.0 6 votes vote down vote up
@Test
public void testTcpWorkerBadMsgTypeDefaultType() {
    
    logger.info("IN testUdpWorkerBadMsgTypeDefaultType");
    ActorRef asyncWorker = null;
    try {
        // made a timeout
        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.CHECK_FUTURE_STATE,
                        new Timeout(duration));
        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

        logger.info("\nWorker response:" + response.toString());
    } catch (Throwable ex) {

        logger.error("Exception in test : " + ex);
    }
}
 
Example #10
Source File: TaskInputSplitProviderTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequestNextInputSplitWithInvalidExecutionID() throws InputSplitProviderException {

	final JobID jobID = new JobID();
	final JobVertexID vertexID = new JobVertexID();
	final ExecutionAttemptID executionID = new ExecutionAttemptID();
	final FiniteDuration timeout = new FiniteDuration(10, TimeUnit.SECONDS);

	final ActorGateway gateway = new NullInputSplitGateway();


	final TaskInputSplitProvider provider = new TaskInputSplitProvider(
		gateway,
		jobID,
		vertexID,
		executionID,
		timeout);

	// The jobManager will return a
	InputSplit nextInputSplit = provider.getNextInputSplit(getClass().getClassLoader());

	assertTrue(nextInputSplit == null);
}
 
Example #11
Source File: ClusterSingleton.java    From ts-reaktive with MIT License 6 votes vote down vote up
/**
 * Starts and returns the an {@link ActorRef} to the {@link ClusterSingletonManager} (and backoff supervisor)
 * that manage this actor singleton.
 *
 * Note that you can't send this ActorRef messages that should go to your actor: use {@link StartProxy} for that.
 *
 * @param constructor Constructor to pass to Props in order to actually create the actor
 */
public ActorRef start(ActorSystem system, Supplier<T> constructor) {
    Config config = system.settings().config().getConfig("ts-reaktive.actors.singleton");
    Props backoffSupervisorProps = BackoffSupervisor.props(
        Backoff.onStop(
            Props.create(type, () -> constructor.get()), "actor",
            FiniteDuration.create(config.getDuration("min-backoff", SECONDS), SECONDS),
            FiniteDuration.create(config.getDuration("max-backoff", SECONDS), SECONDS),
            0.2
        ).withSupervisorStrategy(new OneForOneStrategy(
            DeciderBuilder .matchAny(e -> {
                log.info("{}: Stopping and awaiting restart.", name, e);
                return stop();
            })
            .build()
        ))
    );

    return system.actorOf(
        ClusterSingletonManager.props(backoffSupervisorProps,
            PoisonPill.getInstance(),
            ClusterSingletonManagerSettings.create(system)
        ), name);
}
 
Example #12
Source File: MesosResourceManager.java    From flink with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<Void> stopSupportingActorsAsync() {
	FiniteDuration stopTimeout = new FiniteDuration(5L, TimeUnit.SECONDS);

	CompletableFuture<Boolean> stopTaskMonitorFuture = stopActor(taskMonitor, stopTimeout);
	taskMonitor = null;

	CompletableFuture<Boolean> stopConnectionMonitorFuture = stopActor(connectionMonitor, stopTimeout);
	connectionMonitor = null;

	CompletableFuture<Boolean> stopLaunchCoordinatorFuture = stopActor(launchCoordinator, stopTimeout);
	launchCoordinator = null;

	CompletableFuture<Boolean> stopReconciliationCoordinatorFuture = stopActor(reconciliationCoordinator, stopTimeout);
	reconciliationCoordinator = null;

	return CompletableFuture.allOf(
		stopTaskMonitorFuture,
		stopConnectionMonitorFuture,
		stopLaunchCoordinatorFuture,
		stopReconciliationCoordinatorFuture);
}
 
Example #13
Source File: MesosResourceManager.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Tries to shut down the given actor gracefully.
 *
 * @param actorRef specifying the actor to shut down
 * @param timeout  for the graceful shut down
 * @return A future that finishes with {@code true} iff. the actor could be stopped gracefully
 * or {@code actorRef} was {@code null}.
 */
private CompletableFuture<Boolean> stopActor(@Nullable final ActorRef actorRef, FiniteDuration timeout) {
	if (actorRef == null) {
		return CompletableFuture.completedFuture(true);
	}

	return FutureUtils.toJava(Patterns.gracefulStop(actorRef, timeout))
		.exceptionally(
			(Throwable throwable) -> {
				// The actor did not stop gracefully in time, try to directly stop it
				actorSystem.stop(actorRef);

				log.warn("Could not stop actor {} gracefully.", actorRef.path(), throwable);

				return false;
			}
		);
}
 
Example #14
Source File: HttpTestClient.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a request to to the server.
 *
 * <pre>
 * HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/overview");
 * request.headers().set(HttpHeaders.Names.HOST, host);
 * request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
 *
 * sendRequest(request);
 * </pre>
 *
 * @param request The {@link HttpRequest} to send to the server
 */
public void sendRequest(HttpRequest request, FiniteDuration timeout) throws InterruptedException, TimeoutException {
	LOG.debug("Writing {}.", request);

	// Make the connection attempt.
	ChannelFuture connect = bootstrap.connect(host, port);

	Channel channel;
	if (connect.await(timeout.toMillis(), TimeUnit.MILLISECONDS)) {
		channel = connect.channel();
	}
	else {
		throw new TimeoutException("Connection failed");
	}

	channel.writeAndFlush(request);
}
 
Example #15
Source File: PingWorkerTest.java    From parallec with Apache License 2.0 6 votes vote down vote up
@Test
public void testSlowAndPollProgress() {
    ActorRef asyncWorker = null;
    try {
        int actorMaxOperationTimeoutSec = 15;
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(PingWorker.class, actorMaxOperationTimeoutSec,
                        getPingMetaSample(), "www.google.com"));

        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);
        Future<Object> future = Patterns
                .ask(asyncWorker, RequestWorkerMsgType.PROCESS_REQUEST,
                        new Timeout(duration));

        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

        logger.info("\nWorker response:" + response.toString());
    } catch (Throwable ex) {

        logger.error("Exception in test : " + ex);
    }
}
 
Example #16
Source File: JobManagerHAProcessFailureRecoveryITCase.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private void waitForTaskManagers(int numberOfTaskManagers, DispatcherGateway dispatcherGateway, FiniteDuration timeLeft) throws ExecutionException, InterruptedException {
	FutureUtils.retrySuccessfulWithDelay(
		() -> dispatcherGateway.requestClusterOverview(Time.milliseconds(timeLeft.toMillis())),
		Time.milliseconds(50L),
		org.apache.flink.api.common.time.Deadline.fromNow(Duration.ofMillis(timeLeft.toMillis())),
		clusterOverview -> clusterOverview.getNumTaskManagersConnected() >= numberOfTaskManagers,
		new ScheduledExecutorServiceAdapter(Executors.newSingleThreadScheduledExecutor()))
		.get();
}
 
Example #17
Source File: ExecutionManagerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpWorkerNormalCheckCancel() {
    ActorRef executionManager = null;
    try {
        // Start new job
        

        ParallelTask task = genParallelTask();
        InternalDataProvider adp = InternalDataProvider.getInstance();
        adp.genNodeDataMap(task);

        executionManager = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(ExecutionManager.class, task),
                "executionManager-" + task.getTaskId());

        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);
        Future<Object> future = Patterns.ask(executionManager,
                new InitialRequestToManager(task), new Timeout(duration));

        executionManager.tell(ExecutionManagerMsgType.CANCEL, executionManager);

        Await.result(future, duration);
        logger.info("\nWorker response header:"
                + PcStringUtils.renderJson(task.getParallelTaskResult()));
        // logger.info("\nWorker response:" +
        // PcStringUtils.renderJson(task));
    } catch (Exception ex) {
        logger.error("Exception in testHttpWorkerNormalCheckCancel : " + ex);
    }
}
 
Example #18
Source File: HttpTestClient.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Sends a simple GET request to the given path. You only specify the $path part of
 * http://$host:$host/$path.
 *
 * @param path The $path to GET (http://$host:$host/$path)
 */
public void sendGetRequest(String path, FiniteDuration timeout) throws TimeoutException, InterruptedException {
	if (!path.startsWith("/")) {
		path = "/" + path;
	}

	HttpRequest getRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
			HttpMethod.GET, path);
	getRequest.headers().set(HttpHeaders.Names.HOST, host);
	getRequest.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);

	sendRequest(getRequest, timeout);
}
 
Example #19
Source File: Guest.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
public Guest(ActorRef waiter, Coffee favoriteCoffee, FiniteDuration finishCoffeeDuration, int caffeineLimit) {
    this.waiter = waiter;
    this.favoriteCoffee = favoriteCoffee;
    this.finishCoffeeDuration = finishCoffeeDuration;
    this.caffeineLimit = caffeineLimit;
    orderFavoriteCoffee();
}
 
Example #20
Source File: HttpTestClient.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the next available HTTP response . A call to this method blocks until a response
 * becomes available or throws an Exception if the timeout fires.
 *
 * @param timeout Timeout in milliseconds for the next response to become available
 * @return The next available {@link SimpleHttpResponse}
 */
public SimpleHttpResponse getNextResponse(FiniteDuration timeout) throws InterruptedException,
		TimeoutException {

	SimpleHttpResponse response = responses.poll(timeout.toMillis(), TimeUnit.MILLISECONDS);

	if (response == null) {
		throw new TimeoutException("No response within timeout of " + timeout + " ms");
	}
	else {
		return response;
	}
}
 
Example #21
Source File: ActorGatewayKvStateLocationOracle.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public ActorGatewayKvStateLocationOracle(
		ActorGateway jobManagerActorGateway,
		Time timeout) {
	this.jobManagerActorGateway = Preconditions.checkNotNull(jobManagerActorGateway);

	Preconditions.checkNotNull(timeout);
	this.timeout = FiniteDuration.apply(timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
}
 
Example #22
Source File: Guest.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
public Guest(ActorRef waiter, Coffee favoriteCoffee, FiniteDuration finishCoffeeDuration, int caffeineLimit) {
    this.waiter = waiter;
    this.favoriteCoffee = favoriteCoffee;
    this.finishCoffeeDuration = finishCoffeeDuration;
    this.caffeineLimit = caffeineLimit;
    orderFavoriteCoffee();
}
 
Example #23
Source File: AkkaRpcServiceConfiguration.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public static AkkaRpcServiceConfiguration fromConfiguration(Configuration configuration) {
	final FiniteDuration duration = AkkaUtils.getTimeout(configuration);
	final Time timeout = Time.of(duration.length(), duration.unit());

	final long maximumFramesize = AkkaRpcServiceUtils.extractMaximumFramesize(configuration);

	return new AkkaRpcServiceConfiguration(configuration, timeout, maximumFramesize);
}
 
Example #24
Source File: ExecutionManagerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpWorkerNormalCheckTimeout() {
    ActorRef executionManager = null;
    try {
        // Start new job
        

        ParallelTask task = genParallelTask();
        InternalDataProvider adp = InternalDataProvider.getInstance();
        adp.genNodeDataMap(task);

        executionManager = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(ExecutionManager.class, task),
                "ExecutionManager-" + task.getTaskId());

        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);
        Future<Object> future = Patterns.ask(executionManager,
                new InitialRequestToManager(task), new Timeout(duration));

        executionManager.tell(ExecutionManagerMsgType.OPERATION_TIMEOUT,
                executionManager);

        Await.result(future, duration);
        logger.info("\nWorker response header:"
                + PcStringUtils.renderJson(task.getParallelTaskResult()));
        // logger.info("\nWorker response:" +
        // PcStringUtils.renderJson(task));
    } catch (Throwable ex) {
        logger.error("Exception in testHttpWorkerNormalCheckTimeout : "
                + ex);
    }
}
 
Example #25
Source File: ThrottleActor.java    From ts-reaktive with MIT License 5 votes vote down vote up
public ThrottleActor(int tokensPerRefill, Duration refill, int maximumBurst) {
    this.tokensPerRefill = tokensPerRefill;
    this.refill = refill;
    this.maximumBurst = maximumBurst;
    this.value = maximumBurst;
    this.lastUpdate = Instant.now();
    
    // We've reached maximumBurst for sure after not seeing any requests for this long:
    Duration receiveTimeout = refill.multipliedBy((long) Math.ceil( (double)maximumBurst / tokensPerRefill));
    context().setReceiveTimeout(FiniteDuration.fromNanos(receiveTimeout.toNanos()));
}
 
Example #26
Source File: TcpWorkerIdleTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testTcpWorkerNormalCheckCompleteForIdle() {
    ActorRef asyncWorker = null;
    logger.info("IN testTcpWorkerNormalCheckCompleteForIdle");
    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));

        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

        logger.info("\nWorker response:" + response.toString());
    } catch (Throwable ex) {

        logger.error("Exception in test : " + ex);
    }
}
 
Example #27
Source File: SetupDocumentTypeWorkerActorTest.java    From searchanalytics-bigdata with MIT License 5 votes vote down vote up
@Test
public void handleUnhandledMessage() {
	final Props props = Props.create(SetupDocumentTypeWorkerActor.class,
			null, null);
	final TestActorRef<SetupDocumentTypeWorkerActor> ref = TestActorRef
			.create(system, props);
	final SetupDocumentTypeWorkerActor actor = ref.underlyingActor();
	// Mock the behavior of child/worker actors.
	TestProbe testProbeIndexDataWorker = TestProbe.apply(system);
	actor.setIndexDocumentWorkerRouter(testProbeIndexDataWorker.ref());
	// Actor state check
	assertEquals(null, actor.getIndexDocumentType());
	// Subscribe first
	TestProbe subscriber = TestProbe.apply(system);
	system.eventStream()
			.subscribe(subscriber.ref(), UnhandledMessage.class);
	// garbage
	String invalidMessage = "blah blah";
	ref.tell(invalidMessage, null);
	// Expect the unhandled message now.
	FiniteDuration duration = Duration.create(1, TimeUnit.SECONDS);
	subscriber.expectMsgClass(duration, UnhandledMessage.class);
	TestActor.Message message = subscriber.lastMessage();
	UnhandledMessage resultMsg = (UnhandledMessage) message.msg();
	assertEquals(invalidMessage, resultMsg.getMessage());
	// Actor state check
	assertEquals(null, actor.getIndexDocumentType());
}
 
Example #28
Source File: StreamingSessionActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Cancellable startSessionTimeout(final Instant sessionExpirationTime) {
    final long timeout = sessionExpirationTime.minusMillis(Instant.now().toEpochMilli()).toEpochMilli();

    logger.debug("Starting session timeout - session will expire in {} ms", timeout);
    final FiniteDuration sessionExpirationTimeMillis = FiniteDuration.apply(timeout, TimeUnit.MILLISECONDS);
    return getContext().getSystem().getScheduler().scheduleOnce(sessionExpirationTimeMillis,
            this::handleSessionTimeout, getContext().getDispatcher());
}
 
Example #29
Source File: ActorTaskManagerGateway.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Acknowledge> submitTask(TaskDeploymentDescriptor tdd, Time timeout) {
	Preconditions.checkNotNull(tdd);
	Preconditions.checkNotNull(timeout);

	scala.concurrent.Future<Acknowledge> submitResult = actorGateway.ask(
		new TaskMessages.SubmitTask(tdd),
		new FiniteDuration(timeout.getSize(), timeout.getUnit()))
		.mapTo(ClassTag$.MODULE$.<Acknowledge>apply(Acknowledge.class));

	return FutureUtils.toJava(submitResult);
}
 
Example #30
Source File: ActorTaskManagerGateway.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Acknowledge> stopTask(ExecutionAttemptID executionAttemptID, Time timeout) {
	Preconditions.checkNotNull(executionAttemptID);
	Preconditions.checkNotNull(timeout);

	scala.concurrent.Future<Acknowledge> stopResult = actorGateway.ask(
		new TaskMessages.StopTask(executionAttemptID),
		new FiniteDuration(timeout.getSize(), timeout.getUnit()))
		.mapTo(ClassTag$.MODULE$.<Acknowledge>apply(Acknowledge.class));

	return FutureUtils.toJava(stopResult);
}