Java Code Examples for akka.pattern.Patterns#ask()

The following examples show how to use akka.pattern.Patterns#ask() . 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: 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 3
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 4
Source File: ByRoundTripSignalEnrichmentFacade.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public CompletionStage<JsonObject> retrievePartialThing(final ThingId thingId,
        final JsonFieldSelector jsonFieldSelector,
        final DittoHeaders dittoHeaders,
        @Nullable final Signal<?> concernedSignal) {

    if (concernedSignal instanceof ThingDeleted && !(ProtocolAdapter.isLiveSignal(concernedSignal))) {
        // twin deleted events should not be enriched, return empty JsonObject
        return CompletableFuture.completedFuture(JsonObject.empty());
    }

    // remove channel header to prevent looping on live messages
    final DittoHeaders headersWithoutChannel = dittoHeaders.toBuilder().channel(null).build();

    final RetrieveThing command =
            RetrieveThing.getBuilder(thingId, headersWithoutChannel)
                    .withSelectedFields(jsonFieldSelector)
                    .build();

    final CompletionStage<Object> askResult = Patterns.ask(commandHandler, command, askTimeout);

    return askResult.thenCompose(ByRoundTripSignalEnrichmentFacade::extractPartialThing);
}
 
Example 5
Source File: NoPolTask.java    From nopol with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run(@NotNull ProgressIndicator progressIndicator) {
	if (ActorManager.runNopolLocally && !ActorManager.nopolIsRunning) {
		ActorManager.launchNopol();
	}
	Timeout timeout = new Timeout(scala.concurrent.duration.Duration.fromNanos(20*1000000000));// nano = 10^9
	EventSender.send(EventSender.Event.REPAIR_ATTEMPT);
	try {
		ConfigActor configActor = new ConfigActorImpl(nopolContext, Files.readAllBytes(Paths.get(outputZip)));
		this.future = Patterns.ask(ActorManager.remoteActor, configActor, timeout);
		if (Plugin.enableFancyRobot) {
			ApplicationManager.getApplication().invokeLater(runnerFancyRobot);
		}
		this.response = Await.result(future, timeout.duration());
	} catch (Exception e) {
		onError(e);
	}
}
 
Example 6
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 7
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 8
Source File: UdpWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testUdpWorkerDupAndCancel() {
    ActorRef asyncWorker = null;
    logger.info("IN testUdpWorkerDupAndCancel");
    try {
        
        // Start new job
        

        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.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);
    }
}
 
Example 9
Source File: HttpWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpWorkerNormalCheckComplete() {
    ActorRef asyncWorker = null;
    try {
        // Start new job
        
        int actorMaxOperationTimeoutSec = 15;
        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 10
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 11
Source File: ExecutionManagerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testException() {
    ActorRef executionManager = null;
    try {
        // Start new job
        

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

        // fake bad attribute
        task.setTaskId(null);

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

        final FiniteDuration duration = Duration.create(20,
                TimeUnit.SECONDS);

        // set task as null

        Future<Object> future = Patterns.ask(executionManager,
                new InitialRequestToManager(task), new Timeout(duration));

        Await.result(future, duration);
        logger.info("\nWorker response header:"
                + PcStringUtils.renderJson(task.getParallelTaskResult()));

    } catch (Exception ex) {
        logger.error("Exception in testBadMsg : " + ex);
    }
}
 
Example 12
Source File: HttpWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpWorkerBadMsgType() {
    ActorRef asyncWorker = null;
    try {
        String urlComplete = "http://www.parallec.io/validateInternals.html";
        pc.getHttpClientStore();
        int actorMaxOperationTimeoutSec = 0;
        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));

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

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

        logger.error("Exception in test : " + ex);
    }
    // made a timeout
}
 
Example 13
Source File: TcpWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testTcpWorkerNormalCheckComplete() {
    ActorRef asyncWorker = null;
    logger.info("IN testTcpWorkerNormalCheckComplete");
    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 14
Source File: SshWorkerTest.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 testSshWorkerException() {
    ActorRef asyncWorker = null;
    try {
        // Start new job
        
        int actorMaxOperationTimeoutSec = 15;
        SshWorker.setLogger(null);
        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);
    }
    SshWorker.setLogger(LoggerFactory.getLogger(SshWorker.class));
}
 
Example 15
Source File: RabbitMQClientActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private void createConsumerChannelAndNotifySelf(final Status.Status status, final boolean consuming,
        final ActorRef self, final Duration createChannelTimeout) {

    if (consuming && status instanceof Status.Success && null != rmqConnectionActor) {
        // send self the created channel
        final CreateChannel createChannel =
                CreateChannel.apply(ChannelActor.props(SendChannel.to(self)::apply),
                        Option.apply(CONSUMER_CHANNEL));
        // connection actor sends ChannelCreated; use an ASK to swallow the reply in which we are disinterested
        Patterns.ask(rmqConnectionActor, createChannel, createChannelTimeout);
    } else {
        final Object selfMessage = messageFromConnectionStatus(status);
        self.tell(selfMessage, self);
    }
}
 
Example 16
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 17
Source File: SshWorkerTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
@Test
public void testSshWorkerDupAndCancel() {
    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));

        // 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);
    }
}
 
Example 18
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);
    }
}
 
Example 19
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 20
Source File: TcpWorkerIdleTest.java    From parallec with Apache License 2.0 5 votes vote down vote up
/**
 * Timeout here: as if in the none idle one, will immediately return and not to timeout.
 */
@Test
public void testTcpWorkerTimeoutException() {
    ActorRef asyncWorker = null;
    logger.info("IN testTcpWorkerTimeoutException in idle");
    try {
        // Start new job
        
        // made a timeout
        int actorMaxOperationTimeoutSec = 0;
        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);
    }
}