Java Code Examples for akka.dispatch.Futures#promise()

The following examples show how to use akka.dispatch.Futures#promise() . 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: NotesManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testUpdateNoteFailurewithEmptyNote() {
  Request req = new Request();
  req.getContext().put(JsonKey.REQUESTED_BY, userId);
  req.getContext().put(JsonKey.NOTE_ID, noteId);
  Map<String, Object> reqMap = new HashMap<>();
  reqMap.put(JsonKey.USER_ID, userId);
  req.setRequest(reqMap);
  req.setOperation(ActorOperations.UPDATE_NOTE.getValue());
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(reqMap);
  Promise<Map<String, Object>> promiseAny = Futures.promise();
  promiseAny.success(new HashMap<>());
  when(esUtil.getDataByIdentifier(Mockito.anyString(), Mockito.anyString()))
      .thenReturn(promise.future())
      .thenReturn(promiseAny.future());
  boolean result = testScenario(req, ResponseCode.invalidNoteId);
  assertTrue(result);
}
 
Example 2
Source File: NotesManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testGetNoteFailureWithInvalidNoteId() {
  Request req = new Request();
  Map<String, Object> reqMap = new HashMap<>();
  req.getContext().put(JsonKey.REQUESTED_BY, userId);
  req.getContext().put(JsonKey.NOTE_ID, noteId);
  reqMap.put(JsonKey.USER_ID, userId);
  reqMap.put(JsonKey.COUNT, 0L);
  req.setRequest(reqMap);
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(reqMap);
  when(esUtil.getDataByIdentifier(Mockito.anyString(), Mockito.anyString()))
      .thenReturn(promise.future());
  when(esUtil.search(Mockito.any(), Mockito.anyString())).thenReturn(promise.future());
  req.setOperation(ActorOperations.GET_NOTE.getValue());
  boolean result = testScenario(req, ResponseCode.invalidNoteId);
  assertTrue(result);
}
 
Example 3
Source File: OrganisationMetricsActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testOrgCreationMetricsWithInvalidOrgId() {
  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(prop);
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(null);
  when(esService.getDataByIdentifier(Mockito.anyString(), Mockito.anyString()))
      .thenReturn(promise.future());

  Request actorMessage = new Request();
  actorMessage.put(JsonKey.ORG_ID, "ORG_001_INVALID");
  actorMessage.put(JsonKey.PERIOD, "7d");
  actorMessage.setOperation(ActorOperations.ORG_CREATION_METRICS.getValue());

  subject.tell(actorMessage, probe.getRef());
  ProjectCommonException e =
      probe.expectMsgClass(duration("10 second"), ProjectCommonException.class);
  Assert.assertEquals(ResponseCode.invalidOrgData.getErrorCode(), e.getCode());
}
 
Example 4
Source File: NotesManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testGetNoteSuccess() {
  Request req = new Request();
  Map<String, Object> reqMap = new HashMap<>();
  req.getContext().put(JsonKey.REQUESTED_BY, userId);
  req.getContext().put(JsonKey.NOTE_ID, noteId);
  reqMap.put(JsonKey.USER_ID, userId);
  reqMap.put(JsonKey.COUNT, 1L);
  req.setRequest(reqMap);
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(reqMap);
  when(esUtil.getDataByIdentifier(Mockito.anyString(), Mockito.anyString()))
      .thenReturn(promise.future());
  when(esUtil.search(Mockito.any(), Mockito.anyString())).thenReturn(promise.future());
  req.setOperation(ActorOperations.GET_NOTE.getValue());
  boolean result = testScenario(req, null);
  assertTrue(result);
}
 
Example 5
Source File: NotesManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testUpdateNoteFailurewithUserIdMismatch() {
  Request req = new Request();
  req.getContext().put(JsonKey.REQUESTED_BY, userId);
  req.getContext().put(JsonKey.NOTE_ID, noteId);
  Map<String, Object> reqMap = new HashMap<>();
  reqMap.put(JsonKey.USER_ID, "misMatch");
  req.setRequest(reqMap);
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(reqMap);

  req.setOperation(ActorOperations.UPDATE_NOTE.getValue());
  when(esUtil.getDataByIdentifier(Mockito.anyString(), Mockito.anyString()))
      .thenReturn(promise.future());
  boolean result = testScenario(req, ResponseCode.errorForbidden);
  assertTrue(result);
}
 
Example 6
Source File: UserProfileActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testSetProfileVisibilityFailure() {
  final String userId = "USER-ID";
  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(null);
  when(esUtil.getDataByIdentifier(ProjectUtil.EsType.user.getTypeName(), userId))
      .thenReturn(promise.future());
  when(ElasticSearchHelper.getResponseFromFuture(Mockito.any())).thenReturn(null);
  Request reqObj = new Request();
  reqObj.setOperation(ActorOperations.PROFILE_VISIBILITY.getValue());
  reqObj.put(JsonKey.USER_ID, userId);
  subject.tell(reqObj, probe.getRef());
  ProjectCommonException res =
      probe.expectMsgClass(duration("10 second"), ProjectCommonException.class);
  Assert.assertTrue(res.getCode() == ResponseCode.userNotFound.getErrorCode());
}
 
Example 7
Source File: NotesManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testGetNoteFailurewithUserIdMismatch() {
  Request req = new Request();
  req.getContext().put(JsonKey.REQUESTED_BY, userId);
  req.getContext().put(JsonKey.NOTE_ID, noteId);
  Map<String, Object> reqMap = new HashMap<>();
  reqMap.put(JsonKey.USER_ID, "misMatch");
  req.setRequest(reqMap);
  req.setOperation(ActorOperations.GET_NOTE.getValue());
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(reqMap);

  when(esUtil.getDataByIdentifier(Mockito.anyString(), Mockito.anyString()))
      .thenReturn(promise.future());
  boolean result = testScenario(req, ResponseCode.errorForbidden);
  assertTrue(result);
}
 
Example 8
Source File: NotesManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testDeleteNoteFailurewithEmptyNote() {
  Request req = new Request();
  req.getContext().put(JsonKey.REQUESTED_BY, userId);
  req.getContext().put(JsonKey.NOTE_ID, noteId);
  Map<String, Object> reqMap = new HashMap<>();
  reqMap.put(JsonKey.USER_ID, userId);
  req.setRequest(reqMap);
  req.setOperation(ActorOperations.DELETE_NOTE.getValue());
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(reqMap);
  Promise<Map<String, Object>> promise_any = Futures.promise();
  promise_any.success(new HashMap<>());
  when(esUtil.getDataByIdentifier(Mockito.anyString(), Mockito.anyString()))
      .thenReturn(promise.future())
      .thenReturn(promise_any.future());
  boolean result = testScenario(req, ResponseCode.invalidNoteId);
  assertTrue(result);
}
 
Example 9
Source File: NotesManagementActorTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Test
public void testSearchNoteSuccess() {
  Request req = new Request();
  req.getContext().put(JsonKey.REQUESTED_BY, userId);
  req.getContext().put(JsonKey.NOTE_ID, noteId);
  Map<String, Object> reqMap = new HashMap<>();
  req.setRequest(reqMap);
  req.setOperation(ActorOperations.SEARCH_NOTE.getValue());
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(reqMap);
  when(esUtil.search(Mockito.any(), Mockito.anyString())).thenReturn(promise.future());
  boolean result = testScenario(req, null);
  assertTrue(result);
}
 
Example 10
Source File: UserTnCActorTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Test
public void testAcceptUserTncForBlockedUser() {
  Promise<Map<String, Object>> promise_recipientSearchQuery = Futures.promise();
  Map<String, Object> recipientSearchQuery = new HashMap<>();
  recipientSearchQuery.put(JsonKey.ROOT_ORG_ID, "anyRootId");
  recipientSearchQuery.put(JsonKey.IS_DELETED, true);
  promise_recipientSearchQuery.trySuccess(recipientSearchQuery);
  when(esService.getDataByIdentifier(Mockito.anyString(), Mockito.anyString()))
      .thenReturn(promise_recipientSearchQuery.future());
  ProjectCommonException response =
      setRequest(ACCEPTED_CORRECT_VERSION)
          .expectMsgClass(duration("10 second"), ProjectCommonException.class);
  Assert.assertEquals(ResponseCode.userAccountlocked.getErrorCode(), response.getCode());
  Assert.assertEquals("User account has been blocked .", response.getMessage());
}
 
Example 11
Source File: NotesManagementActorTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Test
public void testCreateNoteFailureWithInvalidUserId() {
  Request req = new Request();
  Map<String, Object> reqMap = new HashMap<>();
  req.setRequest(reqMap);
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(new HashMap<>());
  when(esUtil.getDataByIdentifier(Mockito.anyString(), Mockito.anyString()))
      .thenReturn(promise.future());
  req.setOperation(ActorOperations.CREATE_NOTE.getValue());
  boolean result = testScenario(req, ResponseCode.invalidUserId);
  assertTrue(result);
}
 
Example 12
Source File: AmazonS3Storage.java    From thunderbit with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public F.Promise<Void> store(Path path, String key, String name) {
    Promise<Void> promise = Futures.promise();

    TransferManager transferManager = new TransferManager(credentials);
    try {
        Upload upload = transferManager.upload(bucketName, key, path.toFile());
        upload.addProgressListener((ProgressListener) progressEvent -> {
            if (progressEvent.getEventType().isTransferEvent()) {
                if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_COMPLETED_EVENT)) {
                    transferManager.shutdownNow();
                    promise.success(null);
                } else if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_FAILED_EVENT)) {
                    transferManager.shutdownNow();
                    logger.error(progressEvent.toString());
                    promise.failure(new Exception(progressEvent.toString()));
                }
            }
        });
    } catch (AmazonServiceException ase) {
        logAmazonServiceException (ase);
    } catch (AmazonClientException ace) {
        logAmazonClientException(ace);
    }

    return F.Promise.wrap(promise.future());
}
 
Example 13
Source File: NotesManagementActorTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Test
public void testGetNoteFailureWithInvalidUserId() {
  Request req = new Request();
  Map<String, Object> reqMap = new HashMap<>();
  req.setRequest(reqMap);
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(new HashMap<>());
  when(esUtil.getDataByIdentifier(Mockito.anyString(), Mockito.anyString()))
      .thenReturn(promise.future());
  req.setOperation(ActorOperations.GET_NOTE.getValue());
  boolean result = testScenario(req, ResponseCode.invalidParameterValue);
  assertTrue(result);
}
 
Example 14
Source File: LocationActorTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Test
public void testDeleteLocationFailureWithInvalidLocationDeleteRequest() {
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(getContentMapFromES());
  when(esSearch.search(Mockito.any(SearchDTO.class), Mockito.anyString()))
      .thenReturn(promise.future());
  boolean result =
      testScenario(
          LocationActorOperation.DELETE_LOCATION,
          false,
          data,
          ResponseCode.invalidLocationDeleteRequest);
  assertTrue(result);
}
 
Example 15
Source File: UserManagementActorTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Test
public void testCreateUserFailureWithInvalidOrg() {
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(null);
  when(esService.getDataByIdentifier(Mockito.anyString(), Mockito.anyString()))
      .thenReturn(promise.future());
  boolean result =
      testScenario(
          getRequest(
              false, false, false, getAdditionalMapData(reqMap), ActorOperations.CREATE_USER),
          ResponseCode.invalidOrgData);
  assertTrue(result);
}
 
Example 16
Source File: OrganisationMetricsActorTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@SuppressWarnings({"unchecked", "deprecation"})
@Test
public void testOrgConsumptionMetricsSuccess() throws JsonProcessingException {
  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(prop);
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(userOrgMap);
  when(esService.getDataByIdentifier(Mockito.anyString(), Mockito.anyString()))
      .thenReturn(promise.future());
  mockHttpPostSuccess(
      HTTP_POST,
      new ByteArrayInputStream(
          (mapper.writeValueAsString(orgConsumptionSuccessMap())).getBytes()));

  Request actorMessage = new Request();
  actorMessage.put(JsonKey.ORG_ID, orgId);
  actorMessage.put(JsonKey.PERIOD, "7d");
  actorMessage.setOperation(ActorOperations.ORG_CONSUMPTION_METRICS.getValue());

  subject.tell(actorMessage, probe.getRef());
  Response res = probe.expectMsgClass(duration("10 second"), Response.class);
  Map<String, Object> data = res.getResult();
  Assert.assertEquals("7d", data.get(JsonKey.PERIOD));
  Assert.assertEquals(orgId, ((Map<String, Object>) data.get("org")).get(JsonKey.ORG_ID));
  Map<String, Object> series = (Map<String, Object>) data.get(JsonKey.SERIES);
  Assert.assertTrue(series.containsKey("org.consumption.content.users.count"));
  Assert.assertTrue(series.containsKey("org.consumption.content.time_spent.sum"));
  List<Map<String, Object>> buckets =
      (List<Map<String, Object>>)
          ((Map<String, Object>) series.get("org.consumption.content.users.count"))
              .get("buckets");
  Assert.assertEquals(7, buckets.size());
  Map<String, Object> snapshot = (Map<String, Object>) data.get(JsonKey.SNAPSHOT);
  Assert.assertTrue(snapshot.containsKey("org.consumption.content.session.count"));
  Assert.assertTrue(snapshot.containsKey("org.consumption.content.time_spent.sum"));
  Assert.assertTrue(snapshot.containsKey("org.consumption.content.time_spent.average"));
}
 
Example 17
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 18
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 19
Source File: UserProfileReadActorTest.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
public void setEsResponse(Map<String, Object> esResponse) {
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(esResponse);
  when(esService.getDataByIdentifier(Mockito.anyString(), Mockito.anyString()))
      .thenReturn(promise.future());
}
 
Example 20
Source File: EmailServiceActorTest.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
@Before
public void beforeTest() {

  PowerMockito.mockStatic(ServiceFactory.class);
  PowerMockito.mockStatic(ElasticSearchHelper.class);
  esService = mock(ElasticSearchRestHighImpl.class);
  PowerMockito.mockStatic(EsClientFactory.class);
  when(EsClientFactory.getInstance(Mockito.anyString())).thenReturn(esService);
  PowerMockito.mockStatic(org.sunbird.common.models.util.datasecurity.impl.ServiceFactory.class);
  PowerMockito.mockStatic(EmailTemplateDaoImpl.class);
  when(ServiceFactory.getInstance()).thenReturn(cassandraOperation);
  when(org.sunbird.common.models.util.datasecurity.impl.ServiceFactory
          .getDecryptionServiceInstance(null))
      .thenReturn(defaultDecryptionService);
  when(org.sunbird.common.models.util.datasecurity.impl.ServiceFactory
          .getEncryptionServiceInstance(null))
      .thenReturn(defaultEncryptionServivce);
  when(cassandraOperation.getRecordsByIdsWithSpecifiedColumns(
          Mockito.anyString(), Mockito.anyString(), Mockito.anyList(), Mockito.anyList()))
      .thenReturn(cassandraGetRecordById());

  emailTemplateDao = mock(EmailTemplateDaoImpl.class);
  when(EmailTemplateDaoImpl.getInstance()).thenReturn(emailTemplateDao);
  when(emailTemplateDao.getTemplate(Mockito.anyString())).thenReturn("templateName");

  Map<String, Object> recipientSearchQuery = new HashMap<>();
  recipientSearchQuery.put(JsonKey.FILTERS, "anyName");
  recipientSearchQuery.put(JsonKey.ROOT_ORG_ID, "anyRootId");
  Map<String, Object> esOrgResult = new HashMap<>();
  esOrgResult.put(JsonKey.ORGANISATION_NAME, "anyOrgName");
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(createGetSkillResponse());
  when(esService.search(
          Mockito.eq(ElasticSearchHelper.createSearchDTO(recipientSearchQuery)),
          Mockito.eq(ProjectUtil.EsType.user.getTypeName())))
      .thenReturn(promise.future());
  Promise<Map<String, Object>> promise_recipientSearchQuery = Futures.promise();

  promise_recipientSearchQuery.trySuccess(recipientSearchQuery);
  when(esService.getDataByIdentifier(
          Mockito.eq(ProjectUtil.EsType.user.getTypeName()), Mockito.eq("001")))
      .thenReturn(promise_recipientSearchQuery.future());

  Promise<Map<String, Object>> promise_esOrgResult = Futures.promise();
  promise_esOrgResult.trySuccess(esOrgResult);
  when(esService.getDataByIdentifier(
          Mockito.eq(ProjectUtil.EsType.organisation.getTypeName()), Mockito.eq("anyRootId")))
      .thenReturn(promise_esOrgResult.future());
}