Java Code Examples for scala.concurrent.Promise#future()

The following examples show how to use scala.concurrent.Promise#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: RestUtil.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
public static Future<HttpResponse<JsonNode>> executeAsync(BaseRequest request) {
  ProjectLogger.log("RestUtil:execute: request url = " + request.getHttpRequest().getUrl());
  Promise<HttpResponse<JsonNode>> promise = Futures.promise();

  request.asJsonAsync(
      new Callback<JsonNode>() {

        @Override
        public void failed(UnirestException e) {
          promise.failure(e);
        }

        @Override
        public void completed(HttpResponse<JsonNode> response) {
          promise.success(response);
        }

        @Override
        public void cancelled() {
          promise.failure(new Exception("cancelled"));
        }
      });

  return promise.future();
}
 
Example 2
Source File: ScalaFutureBenchmark.java    From future with 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 3
Source File: ScalaFutureBenchmark.java    From future with 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 4
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String mapPromiseN() throws Exception {
  Promise<String> p = Promise.<String>apply();
  Future<String> f = p.future();
  for (int i = 0; i < N.n; i++)
    f = f.map(mapF, ec);
  p.success(string);
  return Await.result(f, inf);
}
 
Example 5
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String setValueN() throws Exception {
  Promise<String> p = Promise.<String>apply();
  Future<String> f = p.future();
  for (int i = 0; i < N.n; i++)
    f = f.map(mapF, ec);
  p.success(string);
  return Await.result(f, inf);
}
 
Example 6
Source File: ScalaFutureBenchmark.java    From future with 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 7
Source File: ScalaFutureBenchmark.java    From future with 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 8
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String mapPromiseN() throws Exception {
  Promise<String> p = Promise.<String>apply();
  Future<String> f = p.future();
  for (int i = 0; i < N.n; i++)
    f = f.map(mapF, ec);
  p.success(string);
  return Await.result(f, inf);
}
 
Example 9
Source File: ScalaFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String setValueN() throws Exception {
  Promise<String> p = Promise.<String>apply();
  Future<String> f = p.future();
  for (int i = 0; i < N.n; i++)
    f = f.map(mapF, ec);
  p.success(string);
  return Await.result(f, inf);
}
 
Example 10
Source File: ElasticSearchRestHighImpl.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
/**
 * This method will return map of objects on the basis of ids provided.
 *
 * @param ids List of String
 * @param fields List of String
 * @param index index of elasticserach for query
 * @param data Map<String,Object>
 * @return future of requested data in the form of map
 */
@Override
public Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
    List<String> ids, List<String> fields, String index) {
  long startTime = System.currentTimeMillis();

  Map<String, Object> filters = new HashMap<>();
  filters.put(JsonKey.ID, ids);

  SearchDTO searchDTO = new SearchDTO();
  searchDTO.getAdditionalProperties().put(JsonKey.FILTERS, filters);
  searchDTO.setFields(fields);

  Future<Map<String, Object>> resultF = search(searchDTO, index);
  Map<String, Object> result =
      (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(resultF);
  List<Map<String, Object>> esContent = (List<Map<String, Object>>) result.get(JsonKey.CONTENT);
  Promise<Map<String, Map<String, Object>>> promise = Futures.promise();
  promise.success(
      esContent
          .stream()
          .collect(
              Collectors.toMap(
                  obj -> {
                    return (String) obj.get("id");
                  },
                  val -> val)));
  ProjectLogger.log(
      "ElasticSearchRestHighImpl:getEsResultByListOfIds: method ended for index " + index,
      LoggerEnum.INFO.name());

  return promise.future();
}
 
Example 11
Source File: ElasticSearchRestHighImpl.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
/**
 * This method will do the bulk data insertion.
 *
 * @param index String index name
 * @param type String type name
 * @param dataList List<Map<String, Object>>
 * @return boolean
 */
@Override
public Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList) {
  long startTime = System.currentTimeMillis();
  ProjectLogger.log(
      "ElasticSearchRestHighImpl:bulkInsert: method started at =="
          + startTime
          + " for Index "
          + index,
      LoggerEnum.PERF_LOG.name());
  BulkRequest request = new BulkRequest();
  Promise<Boolean> promise = Futures.promise();
  for (Map<String, Object> data : dataList) {
    request.add(new IndexRequest(index, _DOC, (String) data.get(JsonKey.ID)).source(data));
  }
  ActionListener<BulkResponse> listener =
      new ActionListener<BulkResponse>() {
        @Override
        public void onResponse(BulkResponse bulkResponse) {
          Iterator<BulkItemResponse> responseItr = bulkResponse.iterator();
          if (responseItr != null) {
            promise.success(true);
            while (responseItr.hasNext()) {

              BulkItemResponse bResponse = responseItr.next();

              if (bResponse.isFailed()) {
                ProjectLogger.log(
                    "ElasticSearchRestHighImpl:bulkinsert: api response==="
                        + bResponse.getId()
                        + " "
                        + bResponse.getFailureMessage(),
                    LoggerEnum.INFO.name());
              }
            }
          }
        }

        @Override
        public void onFailure(Exception e) {
          ProjectLogger.log("ElasticSearchRestHighImpl:bulkinsert: Bulk upload error block", e);
          promise.success(false);
        }
      };
  ConnectionManager.getRestClient().bulkAsync(request, listener);

  ProjectLogger.log(
      "ElasticSearchRestHighImpl:bulkInsert: method end =="
          + " for Index "
          + index
          + " ,Total time elapsed = "
          + calculateEndTime(startTime),
      LoggerEnum.PERF_LOG.name());
  return promise.future();
}
 
Example 12
Source File: ElasticSearchRestHighImpl.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
/**
 * This method will update data based on identifier.take the data based on identifier and merge
 * with incoming data then update it.
 *
 * @param index String
 * @param type String
 * @param identifier String
 * @param data Map<String,Object>
 * @return boolean
 */
@Override
public Future<Boolean> upsert(String index, String identifier, Map<String, Object> data) {
  long startTime = System.currentTimeMillis();
  Promise<Boolean> promise = Futures.promise();
  ProjectLogger.log(
      "ElasticSearchRestHighImpl:upsert: method started at =="
          + startTime
          + " for INdex "
          + index,
      LoggerEnum.PERF_LOG.name());
  if (!StringUtils.isBlank(index)
      && !StringUtils.isBlank(identifier)
      && data != null
      && data.size() > 0) {

    IndexRequest indexRequest = new IndexRequest(index, _DOC, identifier).source(data);

    UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).upsert(indexRequest);
    updateRequest.doc(indexRequest);
    ActionListener<UpdateResponse> listener =
        new ActionListener<UpdateResponse>() {
          @Override
          public void onResponse(UpdateResponse updateResponse) {
            promise.success(true);
            ProjectLogger.log(
                "ElasticSearchRestHighImpl:upsert:  Response for index : "
                    + updateResponse.getResult()
                    + ","
                    + index
                    + ",identifier : "
                    + identifier,
                LoggerEnum.INFO.name());
            ProjectLogger.log(
                "ElasticSearchRestHighImpl:upsert: method end =="
                    + " for Index "
                    + index
                    + " ,Total time elapsed = "
                    + calculateEndTime(startTime),
                LoggerEnum.PERF_LOG.name());
          }

          @Override
          public void onFailure(Exception e) {
            ProjectLogger.log(
                "ElasticSearchRestHighImpl:upsert: exception occured:" + e.getMessage(),
                LoggerEnum.ERROR.name());
            promise.failure(e);
          }
        };
    ConnectionManager.getRestClient().updateAsync(updateRequest, listener);
    return promise.future();
  } else {
    ProjectLogger.log(
        "ElasticSearchRestHighImpl:upsert: Requested data is invalid.", LoggerEnum.ERROR.name());
    promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData));
    return promise.future();
  }
}
 
Example 13
Source File: DataSource.java    From ndbc with Apache License 2.0 4 votes vote down vote up
protected final <T> Future<T> convert(final io.trane.future.Future<T> future) {
  final Promise<T> promise = Promise$.MODULE$.apply();
  future.onSuccess(promise::success).onFailure(promise::failure);
  return promise.future();
}
 
Example 14
Source File: ElasticSearchRestHighImpl.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
/**
 * This method will remove data from ES based on identifier.
 *
 * @param index String
 * @param type String
 * @param identifier String
 */
@Override
public Future<Boolean> delete(String index, String identifier) {
  long startTime = System.currentTimeMillis();
  ProjectLogger.log(
      "ElasticSearchRestHighImpl:delete: method started at ==" + startTime,
      LoggerEnum.PERF_LOG.name());
  Promise<Boolean> promise = Futures.promise();
  if (StringUtils.isNotEmpty(identifier) && StringUtils.isNotEmpty(index)) {
    DeleteRequest delRequest = new DeleteRequest(index, _DOC, identifier);
    ActionListener<DeleteResponse> listener =
        new ActionListener<DeleteResponse>() {
          @Override
          public void onResponse(DeleteResponse deleteResponse) {
            if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) {
              ProjectLogger.log(
                  "ElasticSearchRestHighImpl:delete:OnResponse: Document  not found for index : "
                      + index
                      + " , identifier : "
                      + identifier,
                  LoggerEnum.INFO.name());
              promise.success(false);
            } else {
              promise.success(true);
            }
          }

          @Override
          public void onFailure(Exception e) {
            ProjectLogger.log(
                "ElasticSearchRestHighImpl:delete: Async Failed due to error :" + e,
                LoggerEnum.INFO.name());
            promise.failure(e);
          }
        };

    ConnectionManager.getRestClient().deleteAsync(delRequest, listener);
  } else {
    ProjectLogger.log(
        "ElasticSearchRestHighImpl:delete:  "
            + "provided index or identifier is null, index = "
            + index
            + ","
            + " identifier = "
            + identifier,
        LoggerEnum.INFO.name());
    promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData));
  }

  ProjectLogger.log(
      "ElasticSearchRestHighImpl:delete: method end =="
          + " ,Total time elapsed = "
          + calculateEndTime(startTime),
      LoggerEnum.PERF_LOG.name());
  return promise.future();
}
 
Example 15
Source File: ElasticSearchRestHighImpl.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
/**
 * This method will provide data form ES based on incoming identifier. we can get data by passing
 * index and identifier values , or all the three
 *
 * @param type String
 * @param identifier String
 * @return Map<String,Object> or empty map
 */
@Override
public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) {
  long startTime = System.currentTimeMillis();
  Promise<Map<String, Object>> promise = Futures.promise();
  if (StringUtils.isNotEmpty(identifier) && StringUtils.isNotEmpty(index)) {

    ProjectLogger.log(
        "ElasticSearchRestHighImpl:getDataByIdentifier: method started at =="
            + startTime
            + " for Index "
            + index,
        LoggerEnum.PERF_LOG.name());

    GetRequest getRequest = new GetRequest(index, _DOC, identifier);

    ActionListener<GetResponse> listener =
        new ActionListener<GetResponse>() {
          @Override
          public void onResponse(GetResponse getResponse) {
            if (getResponse.isExists()) {
              Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
              if (MapUtils.isNotEmpty(sourceAsMap)) {
                promise.success(sourceAsMap);
                ProjectLogger.log(
                    "ElasticSearchRestHighImpl:getDataByIdentifier: method end =="
                        + " for Index "
                        + index
                        + " ,Total time elapsed = "
                        + calculateEndTime(startTime),
                    LoggerEnum.PERF_LOG.name());
              } else {
                promise.success(new HashMap<>());
              }
            } else {
              promise.success(new HashMap<>());
            }
          }

          @Override
          public void onFailure(Exception e) {
            ProjectLogger.log(
                "ElasticSearchRestHighImpl:getDataByIdentifier: method Failed with error == " + e,
                LoggerEnum.INFO.name());
            promise.failure(e);
          }
        };

    ConnectionManager.getRestClient().getAsync(getRequest, listener);
  } else {
    ProjectLogger.log(
        "ElasticSearchRestHighImpl:getDataByIdentifier:  "
            + "provided index or identifier is null, index = "
            + index
            + ","
            + " identifier = "
            + identifier,
        LoggerEnum.INFO.name());
    promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData));
  }

  return promise.future();
}
 
Example 16
Source File: ElasticSearchRestHighImpl.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
/**
 * This method will update data entry inside Elastic search, using identifier and provided data .
 *
 * @param index String ES index name
 * @param identifier ES column identifier as an String
 * @param data Map<String,Object>
 * @return true or false
 */
@Override
public Future<Boolean> update(String index, String identifier, Map<String, Object> data) {
  long startTime = System.currentTimeMillis();
  ProjectLogger.log(
      "ElasticSearchRestHighImpl:update: method started at =="
          + startTime
          + " for Index "
          + index,
      LoggerEnum.PERF_LOG.name());
  Promise<Boolean> promise = Futures.promise();
  ;

  if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) {
    UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data);

    ActionListener<UpdateResponse> listener =
        new ActionListener<UpdateResponse>() {
          @Override
          public void onResponse(UpdateResponse updateResponse) {
            promise.success(true);
            ProjectLogger.log(
                "ElasticSearchRestHighImpl:update:  Success with "
                    + updateResponse.getResult()
                    + " response from elastic search for index"
                    + index
                    + ",identifier : "
                    + identifier,
                LoggerEnum.INFO.name());
            ProjectLogger.log(
                "ElasticSearchRestHighImpl:update: method end =="
                    + " for INdex "
                    + index
                    + " ,Total time elapsed = "
                    + calculateEndTime(startTime),
                LoggerEnum.PERF_LOG.name());
          }

          @Override
          public void onFailure(Exception e) {
            ProjectLogger.log(
                "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(),
                LoggerEnum.ERROR.name());
            promise.failure(e);
          }
        };
    ConnectionManager.getRestClient().updateAsync(updateRequest, listener);

  } else {
    ProjectLogger.log(
        "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name());
    promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData));
  }
  return promise.future();
}
 
Example 17
Source File: ElasticSearchRestHighImpl.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
/**
 * This method will put a new data entry inside Elastic search. identifier value becomes _id
 * inside ES, so every time provide a unique value while saving it.
 *
 * @param index String ES index name
 * @param identifier ES column identifier as an String
 * @param data Map<String,Object>
 * @return Future<String> which contains identifier for created data
 */
@Override
public Future<String> save(String index, String identifier, Map<String, Object> data) {
  long startTime = System.currentTimeMillis();
  Promise<String> promise = Futures.promise();
  ProjectLogger.log(
      "ElasticSearchUtilRest:save: method started at ==" + startTime + " for Index " + index,
      LoggerEnum.PERF_LOG.name());
  if (StringUtils.isBlank(identifier) || StringUtils.isBlank(index)) {
    ProjectLogger.log(
        "ElasticSearchRestHighImpl:save: "
            + "Identifier or Index value is null or empty, identifier : "
            + ""
            + identifier
            + ",index: "
            + index
            + ",not able to save data.",
        LoggerEnum.INFO.name());
    promise.success(ERROR);
    return promise.future();
  }
  data.put("identifier", identifier);

  IndexRequest indexRequest = new IndexRequest(index, _DOC, identifier).source(data);

  ActionListener<IndexResponse> listener =
      new ActionListener<IndexResponse>() {
        @Override
        public void onResponse(IndexResponse indexResponse) {
          ProjectLogger.log(
              "ElasticSearchRestHighImpl:save: Success for index : "
                  + index
                  + ", identifier :"
                  + identifier,
              LoggerEnum.INFO.name());

          promise.success(indexResponse.getId());
          ProjectLogger.log(
              "ElasticSearchRestHighImpl:save: method end at =="
                  + System.currentTimeMillis()
                  + " for Index "
                  + index
                  + " ,Total time elapsed = "
                  + calculateEndTime(startTime),
              LoggerEnum.PERF_LOG.name());
        }

        @Override
        public void onFailure(Exception e) {
          promise.failure(e);
          ProjectLogger.log(
              "ElasticSearchRestHighImpl:save: "
                  + "Error while saving "
                  + index
                  + " id : "
                  + identifier
                  + " with error :"
                  + e,
              LoggerEnum.ERROR.name());
          ProjectLogger.log(
              "ElasticSearchRestHighImpl:save: method end at =="
                  + System.currentTimeMillis()
                  + " for INdex "
                  + index
                  + " ,Total time elapsed = "
                  + calculateEndTime(startTime),
              LoggerEnum.PERF_LOG.name());
        }
      };

  ConnectionManager.getRestClient().indexAsync(indexRequest, listener);

  return promise.future();
}
 
Example 18
Source File: DataSource.java    From ndbc with Apache License 2.0 4 votes vote down vote up
protected final <T> Future<T> convert(final io.trane.future.Future<T> future) {
  final Promise<T> promise = Promise$.MODULE$.apply();
  future.onSuccess(promise::success).onFailure(promise::failure);
  return promise.future();
}
 
Example 19
Source File: DataSource.java    From ndbc with Apache License 2.0 4 votes vote down vote up
protected final <T> Future<T> convert(final io.trane.future.Future<T> future) {
  final Promise<T> promise = Promise$.MODULE$.apply();
  future.onSuccess(promise::success).onFailure(promise::failure);
  return promise.future();
}
 
Example 20
Source File: DataSource.java    From ndbc with Apache License 2.0 4 votes vote down vote up
protected final <T> Future<T> convert(final io.trane.future.Future<T> future) {
  final Promise<T> promise = Promise$.MODULE$.apply();
  future.onSuccess(promise::success).onFailure(promise::failure);
  return promise.future();
}