scala.concurrent.duration.Duration Java Examples

The following examples show how to use scala.concurrent.duration.Duration. 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: ExecutorTest.java    From Nickle-Scheduler with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecutor() {
    ActorRef server = system.actorOf(ServerActor.props());
    Timeout t = new Timeout(Duration.create(3, TimeUnit.SECONDS));
    //使用ask发送消息,actor处理完,必须有返回(超时时间5秒)
    try {
        Future<Object> ask = Patterns.ask(server, "123", t);
        ask.onComplete(new OnComplete<Object>() {
            @Override
            public void onComplete(Throwable throwable, Object o) throws Throwable {
                if (throwable != null) {
                    System.out.println("some thing wrong.{}" + throwable);
                } else {
                    System.out.println("success:" + o);
                }
            }
        }, system.dispatcher());
        System.out.println("执行完毕");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #2
Source File: AssistantCommandManager.java    From restcommander with Apache License 2.0 6 votes vote down vote up
public void waitAndRetry() {
	ContinueToSendToBatchSenderAsstManager continueToSendToBatchSenderAsstManager = new ContinueToSendToBatchSenderAsstManager(
			processedWorkerCount);

	if (VarUtils.IN_DETAIL_DEBUG) {

		models.utils.LogUtils.printLogNormal("NOW WAIT Another " + VarUtils.RETRY_INTERVAL_MILLIS
				+ " MS. at " + DateUtils.getNowDateTimeStrSdsm());
	}
	getContext()
			.system()
			.scheduler()
			.scheduleOnce(
					Duration.create(VarUtils.RETRY_INTERVAL_MILLIS,
							TimeUnit.MILLISECONDS), getSelf(),
					continueToSendToBatchSenderAsstManager,
					getContext().system().dispatcher());
	return;
}
 
Example #3
Source File: FixedDelayRestartStrategy.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a FixedDelayRestartStrategy from the given Configuration.
 *
 * @param configuration Configuration containing the parameter values for the restart strategy
 * @return Initialized instance of FixedDelayRestartStrategy
 * @throws Exception
 */
public static FixedDelayRestartStrategyFactory createFactory(Configuration configuration) throws Exception {
	int maxAttempts = configuration.getInteger(ConfigConstants.RESTART_STRATEGY_FIXED_DELAY_ATTEMPTS, 1);

	String delayString = configuration.getString(ConfigConstants.RESTART_STRATEGY_FIXED_DELAY_DELAY);

	long delay;

	try {
		delay = Duration.apply(delayString).toMillis();
	} catch (NumberFormatException nfe) {
		throw new Exception("Invalid config value for " +
				ConfigConstants.RESTART_STRATEGY_FIXED_DELAY_DELAY + ": " + delayString +
				". Value must be a valid duration (such as '100 milli' or '10 s')");
	}

	return new FixedDelayRestartStrategyFactory(maxAttempts, delay);
}
 
Example #4
Source File: BaseActor.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
protected ActorRef getActorRef(String operation) {
  int waitTime = 10;
  ActorSelection select = null;
  ActorRef actor = RequestRouter.getActor(operation);
  if (null != actor) {
    return actor;
  } else {
    select =
        (BaseMWService.getRemoteRouter(RequestRouter.class.getSimpleName()) == null
            ? (BaseMWService.getRemoteRouter(BackgroundRequestRouter.class.getSimpleName()))
            : BaseMWService.getRemoteRouter(RequestRouter.class.getSimpleName()));
    CompletionStage<ActorRef> futureActor =
        select.resolveOneCS(Duration.create(waitTime, "seconds"));
    try {
      actor = futureActor.toCompletableFuture().get();
    } catch (Exception e) {
      ProjectLogger.log(
          "InterServiceCommunicationImpl : getResponse - unable to get actorref from actorselection "
              + e.getMessage(),
          e);
    }
    return actor;
  }
}
 
Example #5
Source File: SshClientActor.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Object message) throws Throwable {
    if (message instanceof ReceiveTimeout) {
        sshClientService.onSessionCreateTimeout(clientId);
        self().tell(PoisonPill.getInstance(), self());
    } else if (message instanceof SessionCreateResponse) {
        SessionCreateResponse sessionCreateResponse = (SessionCreateResponse)message;
        LOG.info("looking for session actor: {}", sessionCreateResponse.getSessionActorAddress());
        Future<ActorRef> actorRefFuture = context().system()
                .actorSelection(sessionCreateResponse.getSessionActorAddress()).resolveOne(Timeout.apply(2, TimeUnit.SECONDS));
        sshSessionActor = Await.result(actorRefFuture, Duration.apply(2, TimeUnit.SECONDS));
        sshClientService.onSessionCreateReply(sessionCreateResponse.getClientId(), sessionCreateResponse.getSessionId(), sshSessionActor, sessionCreateResponse.getSessionActorAddress());
    } else if (message instanceof SessionDataResponse) {
        SessionDataResponse sessionDataResponse = (SessionDataResponse)message;
        sshClientService.onSessionDataReceived(clientId, sessionDataResponse);
    } else if (message instanceof SessionCloseResponse) {
        SessionCloseResponse sessionCloseResponse = (SessionCloseResponse)message;
        sshClientService.onCloseSessionResponse(clientId, sessionCloseResponse);
        self().tell(PoisonPill.getInstance(), self());
    } else {
        LOG.info("onReceive: {}", message.getClass().getName());
    }
}
 
Example #6
Source File: AriCommandResponseKafkaProcessorTest.java    From ari-proxy with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test()
void properlyHandleInvalidCommandMessage() {
	final TestKit kafkaProducer = new TestKit(system);
	final TestKit metricsService = new TestKit(system);
	final TestKit callContextProvider = new TestKit(system);

	final ConsumerRecord<String, String> consumerRecord = new ConsumerRecord<>("topic", 0, 0,
			"key", "NOT JSON");
	final Source<ConsumerRecord<String, String>, NotUsed> source = Source.single(consumerRecord);
	final Sink<ProducerRecord<String, String>, NotUsed> sink = Sink.<ProducerRecord<String, String>>ignore()
			.mapMaterializedValue(q -> NotUsed.getInstance());

	AriCommandResponseKafkaProcessor.commandResponseProcessing()
			.on(system)
			.withHandler(requestAndContext -> Http.get(system).singleRequest(requestAndContext._1))
			.withCallContextProvider(callContextProvider.getRef())
			.withMetricsService(metricsService.getRef())
			.from(source)
			.to(sink)
			.run();

	kafkaProducer.expectNoMsg(Duration.apply(250, TimeUnit.MILLISECONDS));
}
 
Example #7
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 #8
Source File: SlotManagerConfiguration.java    From flink with Apache License 2.0 6 votes vote down vote up
public static SlotManagerConfiguration fromConfiguration(Configuration configuration) throws ConfigurationException {
	final String strTimeout = configuration.getString(AkkaOptions.ASK_TIMEOUT);
	final Time rpcTimeout;

	try {
		rpcTimeout = Time.milliseconds(Duration.apply(strTimeout).toMillis());
	} catch (NumberFormatException e) {
		throw new ConfigurationException("Could not parse the resource manager's timeout " +
			"value " + AkkaOptions.ASK_TIMEOUT + '.', e);
	}

	final Time slotRequestTimeout = getSlotRequestTimeout(configuration);
	final Time taskManagerTimeout = Time.milliseconds(
			configuration.getLong(ResourceManagerOptions.TASK_MANAGER_TIMEOUT));

	boolean waitResultConsumedBeforeRelease =
		configuration.getBoolean(ResourceManagerOptions.TASK_MANAGER_RELEASE_WHEN_RESULT_CONSUMED);

	return new SlotManagerConfiguration(rpcTimeout, slotRequestTimeout, taskManagerTimeout, waitResultConsumedBeforeRelease);
}
 
Example #9
Source File: Slave.java    From akka-tutorial with Apache License 2.0 6 votes vote down vote up
private void handle(AddressMessage message) {
	
	// Cancel any running connect schedule, because got a new address
	if (this.connectSchedule != null) {
		this.connectSchedule.cancel();
		this.connectSchedule = null;
	}

	// Find the shepherd actor in the remote actor system
	final ActorSelection selection = this.getContext().getSystem().actorSelection(String.format("%s/user/%s", message.address, Shepherd.DEFAULT_NAME));

	// Register the local actor system by periodically sending subscription messages (until an acknowledgement was received)
	final Scheduler scheduler = this.getContext().getSystem().scheduler();
	final ExecutionContextExecutor dispatcher = this.getContext().getSystem().dispatcher();
	this.connectSchedule = scheduler.schedule(
			Duration.Zero(),
			Duration.create(5, TimeUnit.SECONDS),
			() -> selection.tell(new Shepherd.SubscriptionMessage(), this.getSelf()),
			dispatcher
	);
}
 
Example #10
Source File: GradingResponsePoller.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    long checkPoint = System.currentTimeMillis();
    Optional<Message> message = Optional.empty();
    do {
        try {
            message = messageService.receiveMessage(sealtielClientAuthHeader);
            if (message.isPresent()) {
                if (!isConnected) {
                    System.out.println("Connected to Sealtiel!");
                    isConnected = true;
                }

                MessageProcessor processor = new MessageProcessor(submissionService, sealtielClientAuthHeader, messageService, message.get());
                scheduler.scheduleOnce(Duration.create(10, TimeUnit.MILLISECONDS), processor, executor);
            }
        } catch (RemoteException e) {
            if (isConnected) {
                System.out.println("Disconnected from Sealtiel!");
                System.out.println(e.getMessage());
                isConnected = false;
            }
        }
    } while ((System.currentTimeMillis() - checkPoint < interval) && (message != null));
}
 
Example #11
Source File: AkkaSourceTest.java    From bahir-flink with Apache License 2.0 5 votes vote down vote up
@AfterEach
public void afterTest() throws Exception {
  feederActorSystem.terminate();
  Await.result(feederActorSystem.whenTerminated(), Duration.Inf());

  source.cancel();
  sourceThread.join();
}
 
Example #12
Source File: AkkaSource.java    From bahir-flink with Apache License 2.0 5 votes vote down vote up
@Override
public void run(SourceFunction.SourceContext<Object> ctx) throws Exception {
  LOG.info("Starting the Receiver actor {}", actorName);
  receiverActor = receiverActorSystem.actorOf(
    Props.create(classForActor, ctx, urlOfPublisher, autoAck), actorName);

  LOG.info("Started the Receiver actor {} successfully", actorName);
  Await.result(receiverActorSystem.whenTerminated(), Duration.Inf());
}
 
Example #13
Source File: ThingCommandEnforcementTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void rejectQueryByThingNotAccessibleException() {
    final DittoRuntimeException error = ThingNotAccessibleException.newBuilder(THING_ID).build();

    new TestKit(system) {{
        mockEntitiesActorInstance.setReply(THING_SUDO, error);

        final ActorRef underTest = newEnforcerActor(getRef());
        underTest.tell(getReadCommand(), getRef());
        fishForMessage(Duration.create(500, TimeUnit.MILLISECONDS), "error", msg -> msg.equals(error));
    }};
}
 
Example #14
Source File: CoffeeHouseApp.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
private void run() throws IOException, TimeoutException, InterruptedException {
    log.warning(
            String.format("{} running%nEnter commands into the terminal, e.g. 'q' or 'quit'"),
            getClass().getSimpleName()
    );
    commandLoop();
    Await.ready(system.whenTerminated(), Duration.Inf());
}
 
Example #15
Source File: CoffeeHouseApp.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
private void run() throws IOException, TimeoutException, InterruptedException {
    log.warning(
            String.format("{} running%nEnter commands into the terminal, e.g. 'q' or 'quit'"),
            getClass().getSimpleName()
    );
    commandLoop();
    Await.ready(system.whenTerminated(), Duration.Inf());
}
 
Example #16
Source File: SshWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testSshWorkerNormalCheckComplete() {
    ActorRef asyncWorker = null;
    try {
        // Start new job
        

        int actorMaxOperationTimeoutSec = 15;
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(SshWorker.class, actorMaxOperationTimeoutSec,
                        SshProviderMockTest.sshMetaPassword, hostIpSample));

        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 #17
Source File: OctopusSystem.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
protected static ActorSystem createSystem(String actorSystemName, Config config) {
	
	// Create the ActorSystem
	final ActorSystem system = ActorSystem.create(actorSystemName, config);
	
	// Register a callback that ends the program when the ActorSystem terminates
	system.registerOnTermination(new Runnable() {
		@Override
		public void run() {
			System.exit(0);
		}
	});
	
	// Register a callback that terminates the ActorSystem when it is detached from the cluster
	Cluster.get(system).registerOnMemberRemoved(new Runnable() {
		@Override
		public void run() {
			system.terminate();

			new Thread() {
				@Override
				public void run() {
					try {
						Await.ready(system.whenTerminated(), Duration.create(10, TimeUnit.SECONDS));
					} catch (Exception e) {
						System.exit(-1);
					}
				}
			}.start();
		}
	});
	
	return system;
}
 
Example #18
Source File: CoffeeHouseApp.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
private void run() throws IOException, TimeoutException, InterruptedException {
    log.warning(
            String.format("{} running%nEnter commands into the terminal, e.g. 'q' or 'quit'"),
            getClass().getSimpleName()
    );
    commandLoop();
    Await.ready(system.whenTerminated(), Duration.Inf());
}
 
Example #19
Source File: CoffeeHouseApp.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
private void run() throws IOException, TimeoutException, InterruptedException {
    log.warning(
            String.format("{} running%nEnter commands into the terminal, e.g. 'q' or 'quit'"),
            getClass().getSimpleName()
    );
    commandLoop();
    Await.ready(system.whenTerminated(), Duration.Inf());
}
 
Example #20
Source File: TcpWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
/**
 * fake a NPE of logger; do not forget to reset it or other tests will fail.
 */
@Test
public void testTcpWorkerException() {
    logger.info("IN testTcpWorkerException");
    ActorRef asyncWorker = null;
    try {
        TcpWorker.setLogger(null);
        
        // 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.CANCEL,
                        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);
    }
    TcpWorker.setLogger(LoggerFactory.getLogger(TcpWorker.class));
}
 
Example #21
Source File: HttpWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
/**
 * fake a NPE of logger; do not forget to reset it or other tests will fail.
 */
@Test
public void testHttpWorkerException() {
    ActorRef asyncWorker = null;
    try {
        // Start new job
        
        int actorMaxOperationTimeoutSec = 15;
        HttpWorker.setLogger(null);
        String urlComplete = "http://www.parallec.io/validateInternals.html";
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(HttpWorker.class, actorMaxOperationTimeoutSec,
                        HttpClientStore.getInstance()
                                .getCurrentDefaultClient(), urlComplete,
                        HttpMethod.GET, "", null,null));
        ;

        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);
    }
    HttpWorker.setLogger(LoggerFactory.getLogger(HttpWorker.class));
}
 
Example #22
Source File: SlaveSystem.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
public static void start() {
	final Configuration c = ConfigurationSingleton.get();
	
	final Config config = ConfigFactory.parseString(
			"akka.remote.artery.canonical.hostname = \"" + c.getHost() + "\"\n" +
			"akka.remote.artery.canonical.port = " + c.getPort() + "\n" +
			"akka.cluster.roles = [" + SLAVE_ROLE + "]\n" +
			"akka.cluster.seed-nodes = [\"akka://" + c.getActorSystemName() + "@" + c.getMasterHost() + ":" + c.getMasterPort() + "\"]")
		.withFallback(ConfigFactory.load("application"));
	
	final ActorSystem system = ActorSystem.create(c.getActorSystemName(), config);
	
	ActorRef reaper = system.actorOf(Reaper.props(), Reaper.DEFAULT_NAME);
	
	Cluster.get(system).registerOnMemberUp(new Runnable() {
		@Override
		public void run() {
			for (int i = 0; i < c.getNumWorkers(); i++)
				system.actorOf(Worker.props(), Worker.DEFAULT_NAME + i);
		}
	});
	
	Cluster.get(system).registerOnMemberRemoved(new Runnable() {
		@Override
		public void run() {
			system.terminate();

			new Thread() {
				@Override
				public void run() {
					try {
						Await.ready(system.whenTerminated(), Duration.create(10, TimeUnit.SECONDS));
					} catch (Exception e) {
						System.exit(-1);
					}
				}
			}.start();
		}
	});
}
 
Example #23
Source File: CoffeeHouseApp.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
private void run() throws IOException, TimeoutException, InterruptedException {
    log.warning(
            String.format("{} running%nEnter commands into the terminal, e.g. 'q' or 'quit'"),
            getClass().getSimpleName()
    );
    commandLoop();
    Await.ready(system.whenTerminated(), Duration.Inf());
}
 
Example #24
Source File: FullStackHttpIdentityProcessorVerificationTest.java    From netty-reactive-streams with Apache License 2.0 5 votes vote down vote up
@AfterClass
public void stop() throws Exception {
    serverBindChannel.close().await();
    executorService.shutdown();
    Await.ready(actorSystem.terminate(), Duration.create(10000, TimeUnit.MILLISECONDS));
    eventLoop.shutdownGracefully(100, 10000, TimeUnit.MILLISECONDS).await();
}
 
Example #25
Source File: HttpWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpWorkerTimeoutException() {
    ActorRef asyncWorker = null;
    try {
        // Start new job
        
        // made a timeout
        int actorMaxOperationTimeoutSec = 0;
        String urlComplete = "http://www.parallec.io/validateInternals.html";
        pc.getHttpClientStore();
        asyncWorker = ActorConfig.createAndGetActorSystem().actorOf(
                Props.create(HttpWorker.class, actorMaxOperationTimeoutSec,
                        HttpClientStore.getInstance()
                                .getCurrentDefaultClient(), urlComplete,
                        HttpMethod.GET, "", null,null));

        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 #26
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 #27
Source File: SshWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testSshWorkerTimeoutException() {
    ActorRef asyncWorker = null;
    try {
        // Start new job
        
        // made a timeout
        int actorMaxOperationTimeoutSec = 0;
        asyncWorker = ActorConfig.createAndGetActorSystem()
                .actorOf(
                        Props.create(SshWorker.class,
                                actorMaxOperationTimeoutSec,
                                SshProviderMockTest.sshMetaPassword,
                                hostIpSample2));

        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 #28
Source File: CoffeeHouseApp.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
private void run() throws IOException, TimeoutException, InterruptedException {
    log.warning(
            String.format("{} running%nEnter commands into the terminal, e.g. 'q' or 'quit'"),
            getClass().getSimpleName()
    );
    commandLoop();
    Await.ready(system.whenTerminated(), Duration.Inf());
}
 
Example #29
Source File: CoffeeHouseApp.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
private void run() throws IOException, TimeoutException, InterruptedException {
    log.warning(
            String.format("{} running%nEnter commands into the terminal, e.g. 'q' or 'quit'"),
            getClass().getSimpleName()
    );
    commandLoop();
    Await.ready(system.whenTerminated(), Duration.Inf());
}
 
Example #30
Source File: SshWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testSshWorkerBadMsgType() {
    ActorRef asyncWorker = null;
    try {
        // made a timeout
        int actorMaxOperationTimeoutSec = 15;
        asyncWorker = ActorConfig.createAndGetActorSystem()
                .actorOf(
                        Props.create(SshWorker.class,
                                actorMaxOperationTimeoutSec,
                                SshProviderMockTest.sshMetaPassword,
                                hostIpSample2));

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

        // test invalid type
        asyncWorker.tell(new Integer(0), asyncWorker);
        ResponseOnSingeRequest response = (ResponseOnSingeRequest) Await
                .result(future, duration);

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

        logger.error("Exception in test : " + ex);
    }
}