Java Code Examples for scala.concurrent.Future

The following examples show how to use scala.concurrent.Future. These examples are extracted from open source projects. 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 Project: Flink-CEPplus   Author: ljygz   File: AkkaActorGateway.java    License: 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 #2
Source Project: Flink-CEPplus   Author: ljygz   File: LeaderRetrievalUtils.java    License: 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 Project: parallec   Author: eBay   File: UdpWorkerTest.java    License: 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 Project: Flink-CEPplus   Author: ljygz   File: ClusterClient.java    License: 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 #5
Source Project: Flink-CEPplus   Author: ljygz   File: ClusterClient.java    License: 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 #6
Source Project: parallec   Author: eBay   File: UdpWorkerTest.java    License: 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 #7
Source Project: flink   Author: flink-tpc-ds   File: FutureUtils.java    License: 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 #8
Source Project: Nickle-Scheduler   Author: NickleHuang   File: ExecutorTest.java    License: 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 #9
Source Project: parallec   Author: eBay   File: PingWorkerTest.java    License: 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 #10
Source Project: java-specialagent   Author: opentracing-contrib   File: AkkaTest.java    License: 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 #11
Source Project: java-specialagent   Author: opentracing-contrib   File: AkkaTest.java    License: 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 #12
Source Project: ditto   Author: eclipse   File: DockerSwarmServiceDiscovery.java    License: 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 #13
Source Project: ob1k   Author: outbrain   File: BasicTestingDao.java    License: 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 #14
Source Project: sunbird-lms-service   Author: project-sunbird   File: UserUtil.java    License: 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 #15
Source Project: learning-akka   Author: jasongoodwin   File: ArticleParseClusterClient.java    License: 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 #16
Source Project: servicecomb-pack   Author: apache   File: KafkaSagaEventConsumer.java    License: 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 #17
Source Project: sunbird-lms-service   Author: project-sunbird   File: DbOperationActor.java    License: 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 #18
Source Project: future   Author: traneio   File: ScalaFutureBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
@Benchmark
public Void ensurePromiseN() throws Exception {
  Promise<Void> p = Promise.<Void>apply();
  Future<Void> f = p.future();
  for (int i = 0; i < N.n; i++)
    f = f.transform(ensureF, ec);
  p.success(null);
  return Await.result(f, inf);
}
 
Example #19
Source Project: future   Author: traneio   File: ScalaFutureBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
@Benchmark
public String flatMapPromiseN() throws Exception {
  Promise<String> p = Promise.<String>apply();
  Future<String> f = p.future();
  for (int i = 0; i < N.n; i++)
    f = f.flatMap(flatMapF, ec);
  p.success(string);
  return Await.result(f, inf);
}
 
Example #20
Source Project: searchanalytics-bigdata   Author: jaibeermalik   File: BootStrapIndexingServiceImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void preparingIndexes() {
	logger.info("Starting index preparation for {}",
			IndexingMessage.REBUILD_ALL_INDICES);
	setupIndexMasterActor.tell(IndexingMessage.REBUILD_ALL_INDICES, null);
	final Timeout timeout = new Timeout(Duration.create(10, "seconds"));
	final StopWatch stopWatch = new StopWatch();
	Future<Object> future = Patterns.ask(setupIndexMasterActor,
			IndexingMessage.REBUILD_ALL_INDICES_DONE, timeout);
	try {
		// Allow only to run for max 5 min. and check every few sec usign
		// thread sleep.
		stopWatch.start();
		while (!(Boolean) Await.result(future, timeout.duration())
				&& stopWatch.getTotalTimeSeconds() < 5 * 60) {
			future = Patterns.ask(setupIndexMasterActor,
					IndexingMessage.REBUILD_ALL_INDICES_DONE, timeout);
			logger.debug("Index setup status check, Got back " + false);
			// TODO: use this, based on your time taken by ur env. here, 100
			// ms
			Thread.sleep(100);
		}
		logger.debug("Index setup status check, Got back " + true);
	} catch (final Exception e) {
		logger.debug("Index setup status check, Failed getting result: "
				+ e.getMessage());
		throw new RuntimeException(
				"Error occured while setting up search index!", e);
	}
	logger.debug("All indexing setup finished using Akka system, Enjoy!");
}
 
Example #21
Source Project: parallec   Author: eBay   File: UdpWorkerTest.java    License: 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 testUdpWorkerException() {
    logger.info("IN testUdpWorkerException");
    ActorRef asyncWorker = null;
    try {
        UdpWorker.setLogger(null);
        
        // 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.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);
    }
    UdpWorker.setLogger(LoggerFactory.getLogger(UdpWorker.class));
}
 
Example #22
Source Project: learning-akka   Author: jasongoodwin   File: AskTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void itShouldParseArticleTest() throws Exception {
    Future f = ask(askDemoActor, new ParseArticle(("http://www.google.com")), timeout);
    cacheProbe.expectMsgClass(GetRequest.class);
    cacheProbe.reply(new Status.Failure(new Exception("no cache")));

    httpClientProbe.expectMsgClass(String.class);
    httpClientProbe.reply(new HttpResponse(Articles.article1));

    String result = (String) Await.result(f, timeout.duration());
    assert(result.contains("I’ve been writing a lot in emacs lately"));
    assert(!result.contains("<body>"));
}
 
Example #23
Source Project: sunbird-lms-service   Author: project-sunbird   File: ElasticSearchRestHighImpl.java    License: MIT License 5 votes vote down vote up
/**
 * This method will do the health check of elastic search.
 *
 * @return boolean
 */
@Override
public Future<Boolean> healthCheck() {

  GetIndexRequest indexRequest =
      new GetIndexRequest().indices(ProjectUtil.EsType.user.getTypeName());
  Promise<Boolean> promise = Futures.promise();
  ActionListener<Boolean> listener =
      new ActionListener<Boolean>() {
        @Override
        public void onResponse(Boolean getResponse) {
          if (getResponse) {
            promise.success(getResponse);
          } else {
            promise.success(false);
          }
        }

        @Override
        public void onFailure(Exception e) {
          promise.failure(e);
          ProjectLogger.log(
              "ElasticSearchRestHighImpl:healthCheck: error " + e.getMessage(),
              LoggerEnum.INFO.name());
        }
      };
  ConnectionManager.getRestClient().indices().existsAsync(indexRequest, listener);

  return promise.future();
}
 
Example #24
Source Project: nopol   Author: SpoonLabs   File: NopolActorTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void nopolActor() throws Exception {
	com.typesafe.config.Config config = ConfigFactory.load("nopol");
	String ACTOR_SYSTEM_NAME = config.getString("nopol.system.name");
	String ACTOR_NAME = config.getString("nopol.actor.name");
	system = ActorSystem.create(ACTOR_SYSTEM_NAME, config);
	actorNopol = system.actorOf(Props.create(NoPolActor.class, system), ACTOR_NAME);

	ActorRef actorClient = system.actorOf(Props.create(ActorClient.class, "../test-projects",fullQualifiedNameTest, patchAsString), "Client");
	Timeout timeout = new Timeout(scala.concurrent.duration.Duration.fromNanos(20*1000000000));// nano = 10^9
	Future<Object> future = Patterns.ask(actorClient, "start", timeout);
	Patch patch = (Patch) Await.result(future, timeout.duration());
	assertEquals(patchAsString, patch.asString());
}
 
Example #25
Source Project: sunbird-lms-service   Author: project-sunbird   File: UserClientImpl.java    License: MIT License 5 votes vote down vote up
private void esVerifyFieldUniqueness(String facetsKey, String objectType) {
  SearchDTO searchDto = null;
  searchDto = new SearchDTO();
  searchDto.setLimit(0);

  Map<String, String> facets = new HashMap<>();
  facets.put(facetsKey, null);
  List<Map<String, String>> list = new ArrayList<>();
  list.add(facets);
  searchDto.setFacets(list);

  Future<Map<String, Object>> esResponseF =
      esUtil.search(searchDto, ProjectUtil.EsType.user.getTypeName());
  Map<String, Object> esResponse =
      (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(esResponseF);

  if (null != esResponse) {
    List<Map<String, Object>> facetsResponse =
        (List<Map<String, Object>>) esResponse.get(JsonKey.FACETS);

    if (CollectionUtils.isNotEmpty(facetsResponse)) {
      Map<String, Object> map = facetsResponse.get(0);
      List<Map<String, Object>> valueList = (List<Map<String, Object>>) map.get("values");

      for (Map<String, Object> value : valueList) {
        long count = (long) value.get(JsonKey.COUNT);
        if (count > 1) {
          throw new ProjectCommonException(
              ResponseCode.errorDuplicateEntries.getErrorCode(),
              MessageFormat.format(
                  ResponseCode.errorDuplicateEntries.getErrorMessage(), objectType),
              ResponseCode.CLIENT_ERROR.getResponseCode());
        }
      }
    }
  }
}
 
Example #26
Source Project: parallec   Author: eBay   File: HttpWorkerTest.java    License: 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 #27
Source Project: sunbird-lms-service   Author: project-sunbird   File: ElasticSearchRestHighImplTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testSaveFailure() {
  mockRulesForSave(true);
  Future<String> result = esService.save("test", "001", new HashMap<>());
  String res = (String) ElasticSearchHelper.getResponseFromFuture(result);
  assertEquals(null, res);
}
 
Example #28
Source Project: sunbird-lms-service   Author: project-sunbird   File: Util.java    License: MIT License 5 votes vote down vote up
public static List<Map<String, Object>> getUserOrgDetails(String userId) {
  List<Map<String, Object>> userOrgList = null;
  List<Map<String, Object>> userOrganisations = new ArrayList<>();
  try {
    Map<String, Object> reqMap = new WeakHashMap<>();
    reqMap.put(JsonKey.USER_ID, userId);
    reqMap.put(JsonKey.IS_DELETED, false);
    Util.DbInfo orgUsrDbInfo = Util.dbInfoMap.get(JsonKey.USER_ORG_DB);
    Response result =
        cassandraOperation.getRecordsByProperties(
            orgUsrDbInfo.getKeySpace(), orgUsrDbInfo.getTableName(), reqMap);
    userOrgList = (List<Map<String, Object>>) result.get(JsonKey.RESPONSE);
    if (CollectionUtils.isNotEmpty(userOrgList)) {
      List<String> organisationIds =
          userOrgList
              .stream()
              .map(m -> (String) m.get(JsonKey.ORGANISATION_ID))
              .distinct()
              .collect(Collectors.toList());
      List<String> fields = Arrays.asList(JsonKey.ORG_NAME, JsonKey.PARENT_ORG_ID, JsonKey.ID);

      Future<Map<String, Map<String, Object>>> orgInfoMapF =
          esService.getEsResultByListOfIds(
              organisationIds, fields, EsType.organisation.getTypeName());
      Map<String, Map<String, Object>> orgInfoMap =
          (Map<String, Map<String, Object>>)
              ElasticSearchHelper.getResponseFromFuture(orgInfoMapF);

      for (Map<String, Object> userOrg : userOrgList) {
        Map<String, Object> esOrgMap = orgInfoMap.get(userOrg.get(JsonKey.ORGANISATION_ID));
        esOrgMap.remove(JsonKey.ID);
        userOrg.putAll(esOrgMap);
        userOrganisations.add(userOrg);
      }
    }
  } catch (Exception e) {
    ProjectLogger.log(e.getMessage(), e);
  }
  return userOrganisations;
}
 
Example #29
Source Project: parallec   Author: eBay   File: HttpWorkerTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * fake a bad request
 */
@Test
public void testHttpWorkerCreateRequestException() {
    ActorRef asyncWorker = null;
    try {
        // Start new job
        
        int actorMaxOperationTimeoutSec = 15;
        String urlComplete = "http://www.parallec.io/v**``\"..,++08alidateInternals.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);
    }
}
 
Example #30
Source Project: akka-java-springfactory   Author: sabomichal   File: ITActors.java    License: MIT License 5 votes vote down vote up
@Test
public void testActor() throws Exception {
	ActorRef dummyActor = actorSystem.actorOf(SpringProps.create(actorSystem, TestActor.class));
	dummyActor.tell(new TestActor.Increment(), null);
	dummyActor.tell(new TestActor.Increment(), null);
	dummyActor.tell(new TestActor.Increment(), null);

	FiniteDuration duration = FiniteDuration.create(3, TimeUnit.SECONDS);
	Future<Object> result = ask(dummyActor, new TestActor.Get(), Timeout.durationToTimeout(duration));
	assertEquals(3, Await.result(result, duration));
}