scala.concurrent.Future Java Examples

The following examples show how to use scala.concurrent.Future. 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: DockerSwarmServiceDiscovery.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private Future<Resolved> resolveService(final Lookup lookup) {

        final String serviceName = lookup.serviceName();
        return Futures.<Resolved>future(() -> {
            final InetAddress[] allResolvedHosts;
            try {
                allResolvedHosts = InetAddress.getAllByName(serviceName);
            } catch (final UnknownHostException e) {
                return new Resolved(serviceName,
                        JavaConverters.<ResolvedTarget>asScalaBuffer(Collections.emptyList()).toList());
            }
            final List<ResolvedTarget> resolvedTargets = Arrays.stream(allResolvedHosts)
                    .map(a -> new ResolvedTarget(a.getCanonicalHostName(), Option.empty(), Option.apply(a)))
                    .collect(Collectors.toList());

            final Resolved resolved = new Resolved(serviceName, JavaConverters.asScalaBuffer(resolvedTargets).toList());
            system.log().debug("[DockerSwarmServiceDiscovery] Resolved <{}> via InetAddress to: {}", lookup,
                            resolved);
            return resolved;
        }, system.dispatcher());
    }
 
Example #2
Source File: AkkaActorGateway.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Retries to send asynchronously a message up to numberRetries times. The response to this
 * message is returned as a future. The message is re-sent if the number of retries is not yet
 * exceeded and if an exception occurred while sending it.
 *
 * @param message Message to be sent
 * @param numberRetries Number of times to retry sending the message
 * @param timeout Timeout for each sending attempt
 * @param executionContext ExecutionContext which is used to send the message multiple times
 * @return Future of the response to the sent message
 */
@Override
public Future<Object> retry(
		Object message,
		int numberRetries,
		FiniteDuration timeout,
		ExecutionContext executionContext) {

	Object newMessage = decorator.decorate(message);

	return AkkaUtils.retry(
		actor,
		newMessage,
		numberRetries,
		executionContext,
		timeout);
}
 
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: 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 #5
Source File: DbOperationActor.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
/**
 * Method to insert data to ES .
 *
 * @param index
 * @param type
 * @param identifier
 * @param data
 * @return
 */
private boolean insertDataToElastic(
    String index, String type, String identifier, Map<String, Object> data) {
  ProjectLogger.log(
      "making call to ES for index ,identifier ,data==" + type + " " + identifier + data);
  Future<String> responseF = esService.save(index, identifier, data);
  String response = (String) ElasticSearchHelper.getResponseFromFuture(responseF);
  ProjectLogger.log(
      "Getting ES save response for type , identifier=="
          + type
          + "  "
          + identifier
          + "  "
          + response);
  if (!StringUtils.isBlank(response)) {
    ProjectLogger.log("Data is saved successfully ES ." + type + "  " + identifier);
    return true;
  }
  ProjectLogger.log(
      "unbale to save the data inside ES with identifier " + identifier, LoggerEnum.INFO.name());
  return false;
}
 
Example #6
Source File: KafkaSagaEventConsumer.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
private CompletionStage<String> sendSagaActor(BaseEvent event) {
  try {
    long begin = System.currentTimeMillis();
    metricsService.metrics().doActorReceived();
    // Use the synchronous method call to ensure that Kafka's Offset is set after the delivery is successful.
    Timeout timeout = new Timeout(Duration.create(10, "seconds"));
    Future<Object> future = Patterns.ask(sagaShardRegionActor, event, timeout);
    Await.result(future, timeout.duration());
    long end = System.currentTimeMillis();
    metricsService.metrics().doActorAccepted();
    metricsService.metrics().doActorAvgTime(end - begin);
    return CompletableFuture.completedFuture("OK");
  } catch (Exception ex) {
    LOG.error(ex.getMessage(),ex);
    metricsService.metrics().doActorRejected();
    throw new CompletionException(ex);
  }
}
 
Example #7
Source File: UserUtil.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
public static Map<String, Object> validateManagedByUser(String managedBy) {
  Future<Map<String, Object>> managedByInfoF =
      esUtil.getDataByIdentifier(ProjectUtil.EsType.user.getTypeName(), managedBy);
  Map<String, Object> managedByInfo =
      (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(managedByInfoF);
  if (ProjectUtil.isNull(managedByInfo)
      || StringUtils.isBlank((String) managedByInfo.get(JsonKey.FIRST_NAME))
      || StringUtils.isNotBlank((String) managedByInfo.get(JsonKey.MANAGED_BY))
      || (null != managedByInfo.get(JsonKey.IS_DELETED)
          && (boolean) (managedByInfo.get(JsonKey.IS_DELETED)))) {
    throw new ProjectCommonException(
        ResponseCode.invalidRequestData.getErrorCode(),
        ResponseCode.invalidRequestData.getErrorMessage(),
        ResponseCode.CLIENT_ERROR.getResponseCode());
  }
  UserUtility.decryptUserDataFrmES(managedByInfo);
  return managedByInfo;
}
 
Example #8
Source File: ArticleParseClusterClient.java    From learning-akka with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Timeout timeout = new Timeout(Duration.create(5, "seconds"));

    ActorSystem system = ActorSystem.create("clientSystem");

    Set<ActorSelection> initialContacts = new HashSet<ActorSelection>();
    initialContacts.add(system.actorSelection("akka.tcp://[email protected]:2552/user/receptionist"));
    initialContacts.add(system.actorSelection("akka.tcp://[email protected]:2551/user/receptionist"));

    ActorRef receptionist = system.actorOf(ClusterClient.defaultProps(initialContacts));

    ClusterClient.Send msg = new ClusterClient.Send("/user/workers", articleToParse, false);

    Future f = Patterns.ask(receptionist, msg, timeout);
    String result = (String) Await.result(f, timeout.duration());
    System.out.println("result: " + result);
}
 
Example #9
Source File: BasicTestingDao.java    From ob1k with Apache License 2.0 6 votes vote down vote up
@Override
public MySQLConnection create() {
  numOfCreations++;
  if (numOfCreations > 1) {
    throw new IllegalStateException("trying to create more that one connection per test");
  }

  final MySQLConnection conn = super.create();
  final Future<QueryResult> futureRes = conn.sendQuery("start transaction;");
  try {
    Await.result(futureRes, configuration.connectTimeout());
    return conn;
  } catch (final Exception e) {
    throw new IllegalStateException("can't start transaction on the connection", e);
  }
}
 
Example #10
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 #11
Source File: ClusterClient.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Triggers a savepoint for the job identified by the job id. The savepoint will be written to the given savepoint
 * directory, or {@link org.apache.flink.configuration.CheckpointingOptions#SAVEPOINT_DIRECTORY} if it is null.
 *
 * @param jobId job id
 * @param savepointDirectory directory the savepoint should be written to
 * @return path future where the savepoint is located
 * @throws FlinkException if no connection to the cluster could be established
 */
public CompletableFuture<String> triggerSavepoint(JobID jobId, @Nullable String savepointDirectory) throws FlinkException {
	final ActorGateway jobManager = getJobManagerGateway();

	Future<Object> response = jobManager.ask(new JobManagerMessages.TriggerSavepoint(jobId, Option.<String>apply(savepointDirectory)),
		new FiniteDuration(1, TimeUnit.HOURS));
	CompletableFuture<Object> responseFuture = FutureUtils.toJava(response);

	return responseFuture.thenApply((responseMessage) -> {
		if (responseMessage instanceof JobManagerMessages.TriggerSavepointSuccess) {
			JobManagerMessages.TriggerSavepointSuccess success = (JobManagerMessages.TriggerSavepointSuccess) responseMessage;
			return success.savepointPath();
		} else if (responseMessage instanceof JobManagerMessages.TriggerSavepointFailure) {
			JobManagerMessages.TriggerSavepointFailure failure = (JobManagerMessages.TriggerSavepointFailure) responseMessage;
			throw new CompletionException(failure.cause());
		} else {
			throw new CompletionException(
				new IllegalStateException("Unknown JobManager response of type " + responseMessage.getClass()));
		}
	});
}
 
Example #12
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 #13
Source File: FutureUtils.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a Scala {@link Future} to a {@link CompletableFuture}.
 *
 * @param scalaFuture to convert to a Java 8 CompletableFuture
 * @param <T> type of the future value
 * @param <U> type of the original future
 * @return Java 8 CompletableFuture
 */
public static <T, U extends T> CompletableFuture<T> toJava(Future<U> scalaFuture) {
	final CompletableFuture<T> result = new CompletableFuture<>();

	scalaFuture.onComplete(new OnComplete<U>() {
		@Override
		public void onComplete(Throwable failure, U success) {
			if (failure != null) {
				result.completeExceptionally(failure);
			} else {
				result.complete(success);
			}
		}
	}, Executors.directExecutionContext());

	return result;
}
 
Example #14
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 #15
Source File: PingWorkerTest.java    From parallec with Apache License 2.0 6 votes vote down vote up
@Test
public void testTcpWorkerBadMsgType() {
    
    logger.info("IN testTcpWorkerBadMsgType");
    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, 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 #16
Source File: AkkaTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsk(final MockTracer tracer) throws Exception {
  final ActorRef actorRef = system.actorOf(TestActor.props(tracer, false), "ask");
  final Timeout timeout = new Timeout(getDefaultDuration());

  final Future<Object> future = ask(actorRef, "ask", 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 #17
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 #18
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 #19
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 #20
Source File: UserProfileUpdateActor.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
private Future<Object> saveUserOrgDetails(Map<String, Object> userMap, String operationType) {
  String actorOperation = UserActorOperations.UPDATE_USER_ORG_DETAILS.getValue();

  if (JsonKey.CREATE.equalsIgnoreCase(operationType)) {
    actorOperation = UserActorOperations.INSERT_USER_ORG_DETAILS.getValue();
  }

  return saveUserAttributes(userMap, actorOperation);
}
 
Example #21
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 #22
Source File: JobDeployer.java    From AthenaX with Apache License 2.0 5 votes vote down vote up
private void stopAfterJob(ClusterClient client, JobID jobID) {
  Preconditions.checkNotNull(jobID, "The job id must not be null");
  try {
    Future<Object> replyFuture =
        client.getJobManagerGateway().ask(
            new ShutdownClusterAfterJob(jobID),
            AKKA_TIMEOUT);
    Await.ready(replyFuture, AKKA_TIMEOUT);
  } catch (Exception e) {
    throw new RuntimeException("Unable to tell application master to stop"
        + " once the specified job has been finished", e);
  }
}
 
Example #23
Source File: DittoMongoCollectionCache.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Future<C> getOrElseCreate(final String collectionName,
        final Function1<String, Future<C>> collectionCreator) {

    return toScala(cache.get(collectionName, (key, ec) ->
            toJava(collectionCreator.apply(key)).toCompletableFuture()));
}
 
Example #24
Source File: ServiceActorFactory.java    From flower with Apache License 2.0 5 votes vote down vote up
private ActorRemoteWrapper createRemoteActor(URL url, ActorCommand command) throws Exception {
  try {
    ActorRemoteWrapper superActor = getOrCreateRemoteSupervisorActor(url.getHost(), url.getPort());
    // superActor.tell(command);
    Future<Object> future = Patterns.ask(superActor.getActorRef(), command, FlowerActorSystem.DEFAULT_TIMEOUT - 1);
    Await.result(future, FlowerActorSystem.timeout);
    ActorRef remoteActor = flowerActorSystem.createRemoteActor(url.getHost(), url.getPort(), command.getServiceName(),
        command.getIndex());
    return new ActorRemoteWrapper(remoteActor).setServiceName(command.getServiceName()).setUrl(url);
  } catch (Throwable e) {
    throw new FlowerException("", e);
  }
}
 
Example #25
Source File: UserProfileUpdateActor.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
private void saveUserAttributes(Request request) {
  Map<String, Object> userMap = request.getRequest();
  String operationType = (String) userMap.get(JsonKey.OPERATION_TYPE);
  userMap.remove(JsonKey.OPERATION_TYPE);
  List<Future<Object>> futures = getFutures(userMap, operationType);
  Future<Iterable<Object>> futuresSequence = Futures.sequence(futures, getContext().dispatcher());
  Future<Response> consolidatedFutureResponse = getConsolidatedFutureResponse(futuresSequence);
  Patterns.pipe(consolidatedFutureResponse, getContext().dispatcher()).to(sender());
}
 
Example #26
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 #27
Source File: AsynchronousDataSchemaManager.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
private synchronized void startQueryModel() {
  if ( this.actor == null ) {
    this.actor = ActorSystemHost.INSTANCE.createActor( QueryMetaDataActor.class, QueryMetaDataActorImpl.class );
  }
  Future<ContextAwareDataSchemaModel> retrieve = this.actor.retrieve( masterReport, report );
  // IntelliJ does not know how to handle this construct, thinks it is not valid.
  retrieve.onSuccess( new SuccessHandler(), ActorSystemHost.INSTANCE.getSystem().dispatcher() );
  retrieve.onFailure( new FailureHandler(), ActorSystemHost.INSTANCE.getSystem().dispatcher() );
}
 
Example #28
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 #29
Source File: UserProfileUpdateActor.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
private Future<Object> saveEducation(Map<String, Object> userMap, String operationType) {
  String actorOperation = UserActorOperations.UPDATE_USER_EDUCATION.getValue();

  if (JsonKey.CREATE.equalsIgnoreCase(operationType)) {
    actorOperation = UserActorOperations.INSERT_USER_EDUCATION.getValue();
  }

  return saveUserAttributes(userMap, actorOperation);
}
 
Example #30
Source File: UserManagementActor.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
private Future<String> saveUserToES(Map<String, Object> completeUserMap) {

    return esUtil.save(
        ProjectUtil.EsType.user.getTypeName(),
        (String) completeUserMap.get(JsonKey.USER_ID),
        completeUserMap);
  }