method2testcases
stringlengths
118
6.63k
### Question: TelemetryGenerator { public static String search(Map<String, Object> context, Map<String, Object> params) { if (!validateRequest(context, params)) { return ""; } String actorId = (String) context.get(JsonKey.ACTOR_ID); String actorType = (String) context.get(JsonKey.ACTOR_TYPE); Actor actor = new Actor(actorId, StringUtils.capitalize(actorType)); Context eventContext = getContext(context); String reqId = (String) context.get(JsonKey.X_REQUEST_ID); if (!StringUtils.isBlank(reqId)) { Map<String, Object> map = new HashMap<>(); map.put(JsonKey.ID, reqId); map.put(JsonKey.TYPE, TelemetryEnvKey.REQUEST_UPPER_CAMEL); eventContext.getCdata().add(map); } Map<String, Object> edata = generateSearchEdata(params); Telemetry telemetry = new Telemetry(TelemetryEvents.SEARCH.getName(), actor, eventContext, edata); telemetry.setMid(reqId); return getTelemetry(telemetry); } private TelemetryGenerator(); static String audit(Map<String, Object> context, Map<String, Object> params); static String search(Map<String, Object> context, Map<String, Object> params); static String log(Map<String, Object> context, Map<String, Object> params); static String error(Map<String, Object> context, Map<String, Object> params); }### Answer: @Test public void testSearch() { String audit = TelemetryGenerator.search(context, params); assertNotNull(audit); }
### Question: TelemetryGenerator { public static String log(Map<String, Object> context, Map<String, Object> params) { if (!validateRequest(context, params)) { return ""; } String actorId = (String) context.get(JsonKey.ACTOR_ID); String actorType = (String) context.get(JsonKey.ACTOR_TYPE); Actor actor = new Actor(actorId, StringUtils.capitalize(actorType)); Context eventContext = getContext(context); String reqId = (String) context.get(JsonKey.X_REQUEST_ID); if (!StringUtils.isBlank(reqId)) { Map<String, Object> map = new HashMap<>(); map.put(JsonKey.ID, reqId); map.put(JsonKey.TYPE, TelemetryEnvKey.REQUEST_UPPER_CAMEL); eventContext.getCdata().add(map); } Map<String, Object> edata = generateLogEdata(params); Telemetry telemetry = new Telemetry(TelemetryEvents.LOG.getName(), actor, eventContext, edata); telemetry.setMid(reqId); return getTelemetry(telemetry); } private TelemetryGenerator(); static String audit(Map<String, Object> context, Map<String, Object> params); static String search(Map<String, Object> context, Map<String, Object> params); static String log(Map<String, Object> context, Map<String, Object> params); static String error(Map<String, Object> context, Map<String, Object> params); }### Answer: @Test public void testLog() { String audit = TelemetryGenerator.log(context, params); assertNotNull(audit); }
### Question: TelemetryGenerator { public static String error(Map<String, Object> context, Map<String, Object> params) { if (!validateRequest(context, params)) { return ""; } String actorId = (String) context.get(JsonKey.ACTOR_ID); String actorType = (String) context.get(JsonKey.ACTOR_TYPE); Actor actor = new Actor(actorId, StringUtils.capitalize(actorType)); Context eventContext = getContext(context); String reqId = (String) context.get(JsonKey.X_REQUEST_ID); if (!StringUtils.isBlank(reqId)) { Map<String, Object> map = new HashMap<>(); map.put(JsonKey.ID, reqId); map.put(JsonKey.TYPE, TelemetryEnvKey.REQUEST_UPPER_CAMEL); eventContext.getCdata().add(map); } Map<String, Object> edata = generateErrorEdata(params); Telemetry telemetry = new Telemetry(TelemetryEvents.ERROR.getName(), actor, eventContext, edata); telemetry.setMid(reqId); return getTelemetry(telemetry); } private TelemetryGenerator(); static String audit(Map<String, Object> context, Map<String, Object> params); static String search(Map<String, Object> context, Map<String, Object> params); static String log(Map<String, Object> context, Map<String, Object> params); static String error(Map<String, Object> context, Map<String, Object> params); }### Answer: @Test public void testError() { String audit = TelemetryGenerator.error(context, params); assertNotNull(audit); }
### Question: KeyCloakServiceImpl implements SSOManager { @Override public String getUsernameById(String userId) { String fedUserId = getFederatedUserId(userId); try { UserResource resource = keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId); UserRepresentation ur = resource.toRepresentation(); return ur.getUsername(); } catch (Exception e) { logger.error("KeyCloakServiceImpl:getUsernameById: User not found for userId = " + userId, e); } logger.info("getUsernameById: User not found for userId = " + userId); return ""; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken, RequestContext context); @Override boolean updatePassword(String userId, String password, RequestContext context); @Override String updateUser(Map<String, Object> request, RequestContext context); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request, RequestContext context); @Override String deactivateUser(Map<String, Object> request, RequestContext context); @Override String activateUser(Map<String, Object> request, RequestContext context); @Override boolean isEmailVerified(String userId); @Override void setEmailVerifiedUpdatedFlag(String userId, String flag); @Override String getEmailVerifiedUpdatedFlag(String userId); @Override boolean doPasswordUpdate(String userId, String password); @Override String getLastLoginTime(String userId); @Override boolean addUserLoginTime(String userId); @Override String setEmailVerifiedTrue(String userId); @Override String setEmailVerifiedAsFalse(String userId); @Override void setRequiredAction(String userId, String requiredAction); @Override String getUsernameById(String userId); @Override String verifyToken(String accessToken, String url, RequestContext context); }### Answer: @Test public void testGetUsernameById() { String result = keyCloakService.getUsernameById("1234-567-890"); Assert.assertNotNull(result); }
### Question: KeyCloakServiceImpl implements SSOManager { @Override public String deactivateUser(Map<String, Object> request, RequestContext context) { String userId = (String) request.get(JsonKey.USER_ID); makeUserActiveOrInactive(userId, false, context); return JsonKey.SUCCESS; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken, RequestContext context); @Override boolean updatePassword(String userId, String password, RequestContext context); @Override String updateUser(Map<String, Object> request, RequestContext context); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request, RequestContext context); @Override String deactivateUser(Map<String, Object> request, RequestContext context); @Override String activateUser(Map<String, Object> request, RequestContext context); @Override boolean isEmailVerified(String userId); @Override void setEmailVerifiedUpdatedFlag(String userId, String flag); @Override String getEmailVerifiedUpdatedFlag(String userId); @Override boolean doPasswordUpdate(String userId, String password); @Override String getLastLoginTime(String userId); @Override boolean addUserLoginTime(String userId); @Override String setEmailVerifiedTrue(String userId); @Override String setEmailVerifiedAsFalse(String userId); @Override void setRequiredAction(String userId, String requiredAction); @Override String getUsernameById(String userId); @Override String verifyToken(String accessToken, String url, RequestContext context); }### Answer: @Test(expected = ProjectCommonException.class) public void testDeactivateUserSuccess() { Map<String, Object> request = new HashMap<String, Object>(); request.put(JsonKey.USER_ID, "123"); request.put(JsonKey.FIRST_NAME, userName); keyCloakService.deactivateUser(request, null); }
### Question: KeyCloakServiceImpl implements SSOManager { @Override public String removeUser(Map<String, Object> request, RequestContext context) { Keycloak keycloak = KeyCloakConnectionProvider.getConnection(); String userId = (String) request.get(JsonKey.USER_ID); try { String fedUserId = getFederatedUserId(userId); UserResource resource = keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId); if (isNotNull(resource)) { resource.remove(); } } catch (Exception ex) { logger.error(context, "Error occurred : ", ex); ProjectUtil.createAndThrowInvalidUserDataException(); } return JsonKey.SUCCESS; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken, RequestContext context); @Override boolean updatePassword(String userId, String password, RequestContext context); @Override String updateUser(Map<String, Object> request, RequestContext context); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request, RequestContext context); @Override String deactivateUser(Map<String, Object> request, RequestContext context); @Override String activateUser(Map<String, Object> request, RequestContext context); @Override boolean isEmailVerified(String userId); @Override void setEmailVerifiedUpdatedFlag(String userId, String flag); @Override String getEmailVerifiedUpdatedFlag(String userId); @Override boolean doPasswordUpdate(String userId, String password); @Override String getLastLoginTime(String userId); @Override boolean addUserLoginTime(String userId); @Override String setEmailVerifiedTrue(String userId); @Override String setEmailVerifiedAsFalse(String userId); @Override void setRequiredAction(String userId, String requiredAction); @Override String getUsernameById(String userId); @Override String verifyToken(String accessToken, String url, RequestContext context); }### Answer: @Test(expected = ProjectCommonException.class) public void testRemoveUserSuccess() { Map<String, Object> request = new HashMap<String, Object>(); request.put(JsonKey.USER_ID, "123"); keyCloakService.removeUser(request, null); }
### Question: KeyCloakServiceImpl implements SSOManager { @Override public boolean addUserLoginTime(String userId) { boolean response = true; try { String fedUserId = getFederatedUserId(userId); UserResource resource = keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId); UserRepresentation ur = resource.toRepresentation(); Map<String, List<String>> map = ur.getAttributes(); List<String> list = new ArrayList<>(); if (map == null) { map = new HashMap<>(); } List<String> currentLogTime = map.get(JsonKey.CURRENT_LOGIN_TIME); if (currentLogTime == null || currentLogTime.isEmpty()) { currentLogTime = new ArrayList<>(); currentLogTime.add(Long.toString(System.currentTimeMillis())); } else { list.add(currentLogTime.get(0)); currentLogTime.clear(); currentLogTime.add(0, Long.toString(System.currentTimeMillis())); } map.put(JsonKey.CURRENT_LOGIN_TIME, currentLogTime); map.put(JsonKey.LAST_LOGIN_TIME, list); ur.setAttributes(map); resource.update(ur); } catch (Exception e) { logger.error(e.getMessage(), e); response = false; } return response; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken, RequestContext context); @Override boolean updatePassword(String userId, String password, RequestContext context); @Override String updateUser(Map<String, Object> request, RequestContext context); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request, RequestContext context); @Override String deactivateUser(Map<String, Object> request, RequestContext context); @Override String activateUser(Map<String, Object> request, RequestContext context); @Override boolean isEmailVerified(String userId); @Override void setEmailVerifiedUpdatedFlag(String userId, String flag); @Override String getEmailVerifiedUpdatedFlag(String userId); @Override boolean doPasswordUpdate(String userId, String password); @Override String getLastLoginTime(String userId); @Override boolean addUserLoginTime(String userId); @Override String setEmailVerifiedTrue(String userId); @Override String setEmailVerifiedAsFalse(String userId); @Override void setRequiredAction(String userId, String requiredAction); @Override String getUsernameById(String userId); @Override String verifyToken(String accessToken, String url, RequestContext context); }### Answer: @Test public void testAddUserLoginTimeSuccess() { boolean response = keyCloakService.addUserLoginTime(userId.get(JsonKey.USER_ID)); Assert.assertEquals(true, response); }
### Question: KeyCloakServiceImpl implements SSOManager { @Override public String getLastLoginTime(String userId) { String lastLoginTime = null; try { String fedUserId = getFederatedUserId(userId); UserResource resource = keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId); UserRepresentation ur = resource.toRepresentation(); Map<String, List<String>> map = ur.getAttributes(); if (map == null) { map = new HashMap<>(); } List<String> list = map.get(JsonKey.LAST_LOGIN_TIME); if (list != null && !list.isEmpty()) { lastLoginTime = list.get(0); } } catch (Exception e) { logger.error(e.getMessage(), e); } return lastLoginTime; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken, RequestContext context); @Override boolean updatePassword(String userId, String password, RequestContext context); @Override String updateUser(Map<String, Object> request, RequestContext context); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request, RequestContext context); @Override String deactivateUser(Map<String, Object> request, RequestContext context); @Override String activateUser(Map<String, Object> request, RequestContext context); @Override boolean isEmailVerified(String userId); @Override void setEmailVerifiedUpdatedFlag(String userId, String flag); @Override String getEmailVerifiedUpdatedFlag(String userId); @Override boolean doPasswordUpdate(String userId, String password); @Override String getLastLoginTime(String userId); @Override boolean addUserLoginTime(String userId); @Override String setEmailVerifiedTrue(String userId); @Override String setEmailVerifiedAsFalse(String userId); @Override void setRequiredAction(String userId, String requiredAction); @Override String getUsernameById(String userId); @Override String verifyToken(String accessToken, String url, RequestContext context); }### Answer: @Test public void testGetLastLoginTimeSuccess() { String lastLoginTime = keyCloakService.getLastLoginTime(userId.get(JsonKey.USER_ID)); Assert.assertNull(lastLoginTime); }
### Question: KeyCloakServiceImpl implements SSOManager { @Override public String activateUser(Map<String, Object> request, RequestContext context) { String userId = (String) request.get(JsonKey.USER_ID); makeUserActiveOrInactive(userId, true, context); return JsonKey.SUCCESS; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken, RequestContext context); @Override boolean updatePassword(String userId, String password, RequestContext context); @Override String updateUser(Map<String, Object> request, RequestContext context); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request, RequestContext context); @Override String deactivateUser(Map<String, Object> request, RequestContext context); @Override String activateUser(Map<String, Object> request, RequestContext context); @Override boolean isEmailVerified(String userId); @Override void setEmailVerifiedUpdatedFlag(String userId, String flag); @Override String getEmailVerifiedUpdatedFlag(String userId); @Override boolean doPasswordUpdate(String userId, String password); @Override String getLastLoginTime(String userId); @Override boolean addUserLoginTime(String userId); @Override String setEmailVerifiedTrue(String userId); @Override String setEmailVerifiedAsFalse(String userId); @Override void setRequiredAction(String userId, String requiredAction); @Override String getUsernameById(String userId); @Override String verifyToken(String accessToken, String url, RequestContext context); }### Answer: @Test public void testActivateUserFailureWithEmptyUserId() { Map<String, Object> reqMap = new HashMap<>(); reqMap.put(JsonKey.USER_ID, ""); try { keyCloakService.activateUser(reqMap, null); } catch (ProjectCommonException e) { Assert.assertEquals(ResponseCode.invalidUsrData.getErrorCode(), e.getCode()); Assert.assertEquals(ResponseCode.invalidUsrData.getErrorMessage(), e.getMessage()); Assert.assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); } }
### Question: KeyCloakServiceImpl implements SSOManager { @Override public boolean isEmailVerified(String userId) { String fedUserId = getFederatedUserId(userId); UserResource resource = keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId); if (isNull(resource)) { return false; } return resource.toRepresentation().isEmailVerified(); } PublicKey getPublicKey(); @Override String verifyToken(String accessToken, RequestContext context); @Override boolean updatePassword(String userId, String password, RequestContext context); @Override String updateUser(Map<String, Object> request, RequestContext context); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request, RequestContext context); @Override String deactivateUser(Map<String, Object> request, RequestContext context); @Override String activateUser(Map<String, Object> request, RequestContext context); @Override boolean isEmailVerified(String userId); @Override void setEmailVerifiedUpdatedFlag(String userId, String flag); @Override String getEmailVerifiedUpdatedFlag(String userId); @Override boolean doPasswordUpdate(String userId, String password); @Override String getLastLoginTime(String userId); @Override boolean addUserLoginTime(String userId); @Override String setEmailVerifiedTrue(String userId); @Override String setEmailVerifiedAsFalse(String userId); @Override void setRequiredAction(String userId, String requiredAction); @Override String getUsernameById(String userId); @Override String verifyToken(String accessToken, String url, RequestContext context); }### Answer: @Test public void testIsEmailVerifiedSuccess() { boolean response = keyCloakService.isEmailVerified(userId.get(JsonKey.USER_ID)); Assert.assertEquals(false, response); }
### Question: KeyCloakServiceImpl implements SSOManager { @Override public String setEmailVerifiedTrue(String userId) { updateEmailVerifyStatus(userId, true); return JsonKey.SUCCESS; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken, RequestContext context); @Override boolean updatePassword(String userId, String password, RequestContext context); @Override String updateUser(Map<String, Object> request, RequestContext context); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request, RequestContext context); @Override String deactivateUser(Map<String, Object> request, RequestContext context); @Override String activateUser(Map<String, Object> request, RequestContext context); @Override boolean isEmailVerified(String userId); @Override void setEmailVerifiedUpdatedFlag(String userId, String flag); @Override String getEmailVerifiedUpdatedFlag(String userId); @Override boolean doPasswordUpdate(String userId, String password); @Override String getLastLoginTime(String userId); @Override boolean addUserLoginTime(String userId); @Override String setEmailVerifiedTrue(String userId); @Override String setEmailVerifiedAsFalse(String userId); @Override void setRequiredAction(String userId, String requiredAction); @Override String getUsernameById(String userId); @Override String verifyToken(String accessToken, String url, RequestContext context); }### Answer: @Test public void testSetEmailVerifiedSuccessWithVerifiedTrue() { String response = keyCloakService.setEmailVerifiedTrue(userId.get(JsonKey.USER_ID)); Assert.assertEquals(JsonKey.SUCCESS, response); }
### Question: MigrationUtils { public static boolean updateRecord( Map<String, Object> propertiesMap, String channel, String userExtId, RequestContext context) { Map<String, Object> compositeKeysMap = new HashMap<>(); compositeKeysMap.put(JsonKey.USER_EXT_ID, userExtId); compositeKeysMap.put(JsonKey.CHANNEL, channel); Response response = cassandraOperation.updateRecord( JsonKey.SUNBIRD, JsonKey.SHADOW_USER, propertiesMap, compositeKeysMap, context); logger.info( context, "MigrationUtils:updateRecord:update in cassandra with userExtId" + userExtId + ":and response is:" + response); return true; } static ShadowUser getRecordByUserId(String userId, RequestContext context); static boolean updateRecord( Map<String, Object> propertiesMap, String channel, String userExtId, RequestContext context); static boolean markUserAsRejected(ShadowUser shadowUser, RequestContext context); static boolean updateClaimStatus( ShadowUser shadowUser, int claimStatus, RequestContext context); static List<ShadowUser> getEligibleUsersById( String userId, Map<String, Object> propsMap, RequestContext context); static List<ShadowUser> getEligibleUsersById(String userId, RequestContext context); }### Answer: @Test public void testUpdateRecord() { Map<String, Object> compositeKeysMap = new HashMap<>(); compositeKeysMap.put(JsonKey.USER_EXT_ID, "anyUserExtId"); compositeKeysMap.put(JsonKey.CHANNEL, "anyChannel"); when(cassandraOperationImpl.updateRecord( JsonKey.SUNBIRD, JsonKey.SHADOW_USER, new HashMap<>(), compositeKeysMap, null)) .thenReturn(response); boolean isRecordUpdated = MigrationUtils.updateRecord(new HashMap<>(), "anyChannel", "anyUserExtId", null); Assert.assertEquals(true, isRecordUpdated); }
### Question: KeyCloakServiceImpl implements SSOManager { @Override public boolean doPasswordUpdate(String userId, String password) { boolean response = false; try { String fedUserId = getFederatedUserId(userId); UserResource resource = keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId); CredentialRepresentation newCredential = new CredentialRepresentation(); newCredential.setValue(password); newCredential.setType(CredentialRepresentation.PASSWORD); newCredential.setTemporary(true); resource.resetPassword(newCredential); response = true; } catch (Exception ex) { logger.error(ex.getMessage(), ex); } return response; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken, RequestContext context); @Override boolean updatePassword(String userId, String password, RequestContext context); @Override String updateUser(Map<String, Object> request, RequestContext context); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request, RequestContext context); @Override String deactivateUser(Map<String, Object> request, RequestContext context); @Override String activateUser(Map<String, Object> request, RequestContext context); @Override boolean isEmailVerified(String userId); @Override void setEmailVerifiedUpdatedFlag(String userId, String flag); @Override String getEmailVerifiedUpdatedFlag(String userId); @Override boolean doPasswordUpdate(String userId, String password); @Override String getLastLoginTime(String userId); @Override boolean addUserLoginTime(String userId); @Override String setEmailVerifiedTrue(String userId); @Override String setEmailVerifiedAsFalse(String userId); @Override void setRequiredAction(String userId, String requiredAction); @Override String getUsernameById(String userId); @Override String verifyToken(String accessToken, String url, RequestContext context); }### Answer: @Test public void testDoPasswordUpdateSuccess() { boolean response = keyCloakService.doPasswordUpdate(userId.get(JsonKey.USER_ID), "password"); Assert.assertEquals(true, response); }
### Question: KeyCloakServiceImpl implements SSOManager { private String getFederatedUserId(String userId) { return String.join( ":", "f", ProjectUtil.getConfigValue(JsonKey.SUNBIRD_KEYCLOAK_USER_FEDERATION_PROVIDER_ID), userId); } PublicKey getPublicKey(); @Override String verifyToken(String accessToken, RequestContext context); @Override boolean updatePassword(String userId, String password, RequestContext context); @Override String updateUser(Map<String, Object> request, RequestContext context); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request, RequestContext context); @Override String deactivateUser(Map<String, Object> request, RequestContext context); @Override String activateUser(Map<String, Object> request, RequestContext context); @Override boolean isEmailVerified(String userId); @Override void setEmailVerifiedUpdatedFlag(String userId, String flag); @Override String getEmailVerifiedUpdatedFlag(String userId); @Override boolean doPasswordUpdate(String userId, String password); @Override String getLastLoginTime(String userId); @Override boolean addUserLoginTime(String userId); @Override String setEmailVerifiedTrue(String userId); @Override String setEmailVerifiedAsFalse(String userId); @Override void setRequiredAction(String userId, String requiredAction); @Override String getUsernameById(String userId); @Override String verifyToken(String accessToken, String url, RequestContext context); }### Answer: @Test public void testGetFederatedUserId() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { KeyCloakServiceImpl.class.getDeclaredMethods(); Method m = KeyCloakServiceImpl.class.getDeclaredMethod("getFederatedUserId", String.class); m.setAccessible(true); SSOManager keyCloakService = SSOServiceFactory.getInstance(); String fedUserId = (String) m.invoke(keyCloakService, "userId"); Assert.assertEquals( "f:" + ProjectUtil.getConfigValue(JsonKey.SUNBIRD_KEYCLOAK_USER_FEDERATION_PROVIDER_ID) + ":userId", fedUserId); }
### Question: KeyCloakServiceImpl implements SSOManager { @Override public boolean updatePassword(String userId, String password, RequestContext context) { try { String fedUserId = getFederatedUserId(userId); UserResource ur = keycloak.realm(KeyCloakConnectionProvider.SSO_REALM).users().get(fedUserId); CredentialRepresentation cr = new CredentialRepresentation(); cr.setType(CredentialRepresentation.PASSWORD); cr.setValue(password); ur.resetPassword(cr); return true; } catch (Exception e) { logger.error(context, "updatePassword: Exception occurred: ", e); } return false; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken, RequestContext context); @Override boolean updatePassword(String userId, String password, RequestContext context); @Override String updateUser(Map<String, Object> request, RequestContext context); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request, RequestContext context); @Override String deactivateUser(Map<String, Object> request, RequestContext context); @Override String activateUser(Map<String, Object> request, RequestContext context); @Override boolean isEmailVerified(String userId); @Override void setEmailVerifiedUpdatedFlag(String userId, String flag); @Override String getEmailVerifiedUpdatedFlag(String userId); @Override boolean doPasswordUpdate(String userId, String password); @Override String getLastLoginTime(String userId); @Override boolean addUserLoginTime(String userId); @Override String setEmailVerifiedTrue(String userId); @Override String setEmailVerifiedAsFalse(String userId); @Override void setRequiredAction(String userId, String requiredAction); @Override String getUsernameById(String userId); @Override String verifyToken(String accessToken, String url, RequestContext context); }### Answer: @Test public void testUpdatePassword() throws Exception { boolean updated = keyCloakService.updatePassword(userId.get(JsonKey.USER_ID), "password", null); Assert.assertTrue(updated); }
### Question: KeyCloakRsaKeyFetcher { public PublicKey getPublicKeyFromKeyCloak(String url, String realm) { try { Map<String, String> valueMap = null; Decoder urlDecoder = Base64.getUrlDecoder(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); String publicKeyString = requestKeyFromKeycloak(url, realm); if (publicKeyString != null) { valueMap = getValuesFromJson(publicKeyString); if (valueMap != null) { BigInteger modulus = new BigInteger(1, urlDecoder.decode(valueMap.get(MODULUS))); BigInteger publicExponent = new BigInteger(1, urlDecoder.decode(valueMap.get(EXPONENT))); PublicKey key = keyFactory.generatePublic(new RSAPublicKeySpec(modulus, publicExponent)); saveToCache(key); return key; } } } catch (Exception e) { ProjectLogger.log( "KeyCloakRsaKeyFetcher:getPublicKeyFromKeyCloak: Exception occurred with message = " + e.getMessage(), LoggerEnum.ERROR); } return null; } PublicKey getPublicKeyFromKeyCloak(String url, String realm); }### Answer: @Test public void testGetPublicKeyFromKeyCloakSuccess() throws Exception { response = PowerMockito.mock(CloseableHttpResponse.class); when(client.execute(Mockito.any())).thenReturn(response); when(response.getEntity()).thenReturn(httpEntity); String jsonString = "{\"keys\":[{\"kid\":\"YOw4KbDjM0_HIdGkf_QhRfKc9qHc4W_8Bni91nKFyck\",\"kty\":\"RSA\",\"alg\":\"RS256\",\"use\":\"sig\",\"n\":\"" + "5OwCfx4UZTUfUDSBjOg65HuE4ReOg9GhZyoDJNqbWFrsY3dz7C12lmM3rewBHoY0F5_KW0A7rniS9LcqDg2RODvV8pRtJZ_Ge-jsnPMBY5nDJeEW35PH9ewaBhbY3Dj0bZQda2KdHGwiQ" + "zItMT4vw0uITKsFq9o1bcYj0QvPq10AE_wOx3T5xsysuTTkcvQ6evbbs6P5yz_SHhQFRTk7_ZhMwhBeTolvg9wF4yl4qwr220A1ORsLAwwydpmfMHU9RD97nzHDlhXTBAOhDoA3Z3wA8KG6V" + "i3LxqTLNRVS4hgq310fHzWfCX7shFQxygijW9zit-X1WVXaS1NxazuLJw\",\"e\":\"AQAB\"}]}"; when(EntityUtils.toString(httpEntity)).thenReturn(jsonString); PublicKey key = new KeyCloakRsaKeyFetcher() .getPublicKeyFromKeyCloak( KeyCloakConnectionProvider.SSO_URL, KeyCloakConnectionProvider.SSO_REALM); Assert.assertNotNull(key); } @Test public void testGetPublicKeyFromKeyCloakFailure() throws Exception { PublicKey key = new KeyCloakRsaKeyFetcher() .getPublicKeyFromKeyCloak(KeyCloakConnectionProvider.SSO_URL, FALSE_REALM); Assert.assertEquals(key, null); }
### Question: CloudStorageUtil { public static String upload( CloudStorageType storageType, String container, String objectKey, String filePath) { IStorageService storageService = getStorageService(storageType); return storageService.upload( container, filePath, objectKey, Option.apply(false), Option.apply(1), Option.apply(STORAGE_SERVICE_API_RETRY_COUNT), Option.empty()); } static String upload( CloudStorageType storageType, String container, String objectKey, String filePath); static String getSignedUrl( CloudStorageType storageType, String container, String objectKey); static String getAnalyticsSignedUrl( CloudStorageType storageType, String container, String objectKey); static String getSignedUrl( IStorageService storageService, CloudStorageType storageType, String container, String objectKey); static String getUri( CloudStorageType storageType, String container, String prefix, boolean isDirectory); }### Answer: @Test @Ignore public void testUploadSuccess() { String result = CloudStorageUtil.upload(CloudStorageType.AZURE, "container", "key", "/file/path"); assertTrue(UPLOAD_URL.equals(result)); }
### Question: MigrationUtils { public static boolean markUserAsRejected(ShadowUser shadowUser, RequestContext context) { Map<String, Object> propertiesMap = new HashMap<>(); propertiesMap.put(JsonKey.CLAIM_STATUS, ClaimStatus.REJECTED.getValue()); propertiesMap.put(JsonKey.UPDATED_ON, new Timestamp(System.currentTimeMillis())); boolean isRecordUpdated = updateRecord(propertiesMap, shadowUser.getChannel(), shadowUser.getUserExtId(), context); logger.info( context, "MigrationUtils:markUserAsRejected:update in cassandra with userExtId" + shadowUser.getUserExtId()); return isRecordUpdated; } static ShadowUser getRecordByUserId(String userId, RequestContext context); static boolean updateRecord( Map<String, Object> propertiesMap, String channel, String userExtId, RequestContext context); static boolean markUserAsRejected(ShadowUser shadowUser, RequestContext context); static boolean updateClaimStatus( ShadowUser shadowUser, int claimStatus, RequestContext context); static List<ShadowUser> getEligibleUsersById( String userId, Map<String, Object> propsMap, RequestContext context); static List<ShadowUser> getEligibleUsersById(String userId, RequestContext context); }### Answer: @Test public void testmarkUserAsRejected() { ShadowUser shadowUser = new ShadowUser.ShadowUserBuilder() .setChannel("anyChannel") .setUserExtId("anyUserExtId") .build(); Map<String, Object> compositeKeysMap = new HashMap<>(); compositeKeysMap.put(JsonKey.USER_EXT_ID, "anyUserExtId"); compositeKeysMap.put(JsonKey.CHANNEL, "anyChannel"); when(cassandraOperationImpl.updateRecord( JsonKey.SUNBIRD, JsonKey.SHADOW_USER, new HashMap<>(), compositeKeysMap, null)) .thenReturn(response); boolean isRecordUpdated = MigrationUtils.markUserAsRejected(shadowUser, null); Assert.assertEquals(true, isRecordUpdated); }
### Question: CloudStorageUtil { public static String getSignedUrl( CloudStorageType storageType, String container, String objectKey) { IStorageService storageService = getStorageService(storageType); return getSignedUrl(storageService, storageType, container, objectKey); } static String upload( CloudStorageType storageType, String container, String objectKey, String filePath); static String getSignedUrl( CloudStorageType storageType, String container, String objectKey); static String getAnalyticsSignedUrl( CloudStorageType storageType, String container, String objectKey); static String getSignedUrl( IStorageService storageService, CloudStorageType storageType, String container, String objectKey); static String getUri( CloudStorageType storageType, String container, String prefix, boolean isDirectory); }### Answer: @Test @Ignore public void testGetSignedUrlSuccess() { String signedUrl = CloudStorageUtil.getSignedUrl(CloudStorageType.AZURE, "container", "key"); assertTrue(SIGNED_URL.equals(signedUrl)); }
### Question: ConfigUtil { public static Config getConfigFromJsonString(String jsonString, String configType) { ProjectLogger.log("ConfigUtil: getConfigFromJsonString called", LoggerEnum.DEBUG.name()); if (null == jsonString || StringUtils.isBlank(jsonString)) { ProjectLogger.log( "ConfigUtil:getConfigFromJsonString: Empty string", LoggerEnum.ERROR.name()); ProjectCommonException.throwServerErrorException( ResponseCode.errorConfigLoadEmptyString, ProjectUtil.formatMessage( ResponseCode.errorConfigLoadEmptyString.getErrorMessage(), configType)); } Config jsonConfig = null; try { jsonConfig = ConfigFactory.parseString(jsonString); } catch (Exception e) { ProjectLogger.log( "ConfigUtil:getConfigFromJsonString: Exception occurred during parse with error message = " + e.getMessage(), LoggerEnum.ERROR.name()); ProjectCommonException.throwServerErrorException( ResponseCode.errorConfigLoadParseString, ProjectUtil.formatMessage( ResponseCode.errorConfigLoadParseString.getErrorMessage(), configType)); } if (null == jsonConfig || jsonConfig.isEmpty()) { ProjectLogger.log( "ConfigUtil:getConfigFromJsonString: Empty configuration", LoggerEnum.ERROR.name()); ProjectCommonException.throwServerErrorException( ResponseCode.errorConfigLoadEmptyConfig, ProjectUtil.formatMessage( ResponseCode.errorConfigLoadEmptyConfig.getErrorMessage(), configType)); } ProjectLogger.log( "ConfigUtil:getConfigFromJsonString: Successfully constructed type safe configuration", LoggerEnum.DEBUG.name()); return jsonConfig; } private ConfigUtil(); static Config getConfig(); static Config getConfig(String fileName); static void validateMandatoryConfigValue(String configParameter); static Config getConfigFromJsonString(String jsonString, String configType); }### Answer: @Test(expected = ProjectCommonException.class) public void testGetConfigFromJsonStringFailureWithNullString() { try { ConfigUtil.getConfigFromJsonString(null, configType); } catch (ProjectCommonException e) { assertTrue(e.getCode().equals(ResponseCode.errorConfigLoadEmptyString.getErrorCode())); throw e; } } @Test(expected = ProjectCommonException.class) public void testGetConfigFromJsonStringFailureWithEmptyString() { try { ConfigUtil.getConfigFromJsonString("", configType); } catch (ProjectCommonException e) { assertTrue(e.getCode().equals(ResponseCode.errorConfigLoadEmptyString.getErrorCode())); throw e; } } @Test(expected = ProjectCommonException.class) public void testGetConfigFromJsonStringFailureWithInvalidJsonString() { try { ConfigUtil.getConfigFromJsonString("{dummy}", configType); } catch (ProjectCommonException e) { assertTrue(e.getCode().equals(ResponseCode.errorConfigLoadParseString.getErrorCode())); throw e; } } @Test public void testGetConfigFromJsonStringSuccess() { Config config = ConfigUtil.getConfigFromJsonString(validJson, configType); assertTrue("value".equals(config.getString("key"))); }
### Question: UserProfileRequestValidator extends BaseRequestValidator { @SuppressWarnings("unchecked") public void validateProfileVisibility(Request request) { validateParam( (String) request.getRequest().get(JsonKey.USER_ID), ResponseCode.mandatoryParamsMissing, JsonKey.USER_ID); validateUserId(request, JsonKey.USER_ID); validatePublicAndPrivateFields(request); } @SuppressWarnings("unchecked") void validateProfileVisibility(Request request); }### Answer: @Test public void testValidateProfileVisibilityFailureWithFieldInPrivateAndPublic() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.USER_ID, "9878888888"); List<String> publicList = new ArrayList<>(); publicList.add("Education"); requestObj.put(JsonKey.PUBLIC, publicList); List<String> privateList = new ArrayList<>(); privateList.add("Education"); requestObj.put(JsonKey.PRIVATE, privateList); request.setRequest(requestObj); try { userProfileRequestValidator.validateProfileVisibility(request); } catch (ProjectCommonException e) { Assert.assertNotNull(e); } } @Test public void testValidateProfileVisibilityFailureWithEmptyUserId() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.USER_ID, ""); request.setRequest(requestObj); try { userProfileRequestValidator.validateProfileVisibility(request); } catch (ProjectCommonException e) { Assert.assertNotNull(e); } } @Test public void testValidateProfileVisibilityFailureWithInvalidPrivateType() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.USER_ID, "123"); requestObj.put(JsonKey.PRIVATE, ""); request.setRequest(requestObj); try { userProfileRequestValidator.validateProfileVisibility(request); } catch (ProjectCommonException e) { Assert.assertNotNull(e); } } @Test public void testValidateProfileVisibilityFailureWithInvalidPublicType() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.USER_ID, "123"); requestObj.put(JsonKey.PUBLIC, ""); request.setRequest(requestObj); try { userProfileRequestValidator.validateProfileVisibility(request); } catch (ProjectCommonException e) { Assert.assertNotNull(e); } }
### Question: RequestValidator { public static void validateRegisterClient(Request request) { if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.CLIENT_NAME))) { throw createExceptionInstance(ResponseCode.invalidClientName.getErrorCode()); } } private RequestValidator(); static void validateUploadUser(Map<String, Object> reqObj); static void validateSyncRequest(Request request); static void validateSendMail(Request request); static void validateFileUpload(Request reqObj); static void validateCreateOrgType(Request reqObj); static void validateUpdateOrgType(Request reqObj); @SuppressWarnings("rawtypes") static void validateNote(Request request); static void validateNoteId(String noteId); static void validateRegisterClient(Request request); static void validateUpdateClientKey(String clientId, String masterAccessToken); static void validateGetClientKey(String id, String type); static void validateClientId(String clientId); @SuppressWarnings("unchecked") static void validateSendNotification(Request request); @SuppressWarnings("rawtypes") static void validateGetUserCount(Request request); }### Answer: @Test public void testValidateRegisterClientFailureWithEmptyClientName() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.CLIENT_NAME, ""); request.setRequest(requestObj); try { RequestValidator.validateRegisterClient(request); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidClientName.getErrorCode(), e.getCode()); } } @Test public void testValidateRegisterClientSuccess() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.CLIENT_NAME, "1234"); request.setRequest(requestObj); try { RequestValidator.validateRegisterClient(request); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidClientName.getErrorCode(), e.getCode()); } }
### Question: MigrationUtils { public static boolean updateClaimStatus( ShadowUser shadowUser, int claimStatus, RequestContext context) { Map<String, Object> propertiesMap = new WeakHashMap<>(); propertiesMap.put(JsonKey.CLAIM_STATUS, claimStatus); propertiesMap.put(JsonKey.UPDATED_ON, new Timestamp(System.currentTimeMillis())); updateRecord(propertiesMap, shadowUser.getChannel(), shadowUser.getUserExtId(), context); logger.info( context, "MigrationUtils:markUserAsRejected:update in cassandra with userExtId" + shadowUser.getUserExtId()); return true; } static ShadowUser getRecordByUserId(String userId, RequestContext context); static boolean updateRecord( Map<String, Object> propertiesMap, String channel, String userExtId, RequestContext context); static boolean markUserAsRejected(ShadowUser shadowUser, RequestContext context); static boolean updateClaimStatus( ShadowUser shadowUser, int claimStatus, RequestContext context); static List<ShadowUser> getEligibleUsersById( String userId, Map<String, Object> propsMap, RequestContext context); static List<ShadowUser> getEligibleUsersById(String userId, RequestContext context); }### Answer: @Test public void testUpdateClaimStatus() { ShadowUser shadowUser = new ShadowUser.ShadowUserBuilder() .setChannel("anyChannel") .setUserExtId("anyUserExtId") .build(); Map<String, Object> compositeKeysMap = new HashMap<>(); compositeKeysMap.put(JsonKey.USER_EXT_ID, "anyUserExtId"); compositeKeysMap.put(JsonKey.CHANNEL, "anyChannel"); when(cassandraOperationImpl.updateRecord( JsonKey.SUNBIRD, JsonKey.SHADOW_USER, new HashMap<>(), compositeKeysMap, null)) .thenReturn(response); boolean isRecordUpdated = MigrationUtils.updateClaimStatus(shadowUser, ClaimStatus.ELIGIBLE.getValue(), null); Assert.assertEquals(true, isRecordUpdated); }
### Question: RequestValidator { public static void validateUpdateClientKey(String clientId, String masterAccessToken) { validateClientId(clientId); if (StringUtils.isBlank(masterAccessToken)) { throw createExceptionInstance(ResponseCode.invalidRequestData.getErrorCode()); } } private RequestValidator(); static void validateUploadUser(Map<String, Object> reqObj); static void validateSyncRequest(Request request); static void validateSendMail(Request request); static void validateFileUpload(Request reqObj); static void validateCreateOrgType(Request reqObj); static void validateUpdateOrgType(Request reqObj); @SuppressWarnings("rawtypes") static void validateNote(Request request); static void validateNoteId(String noteId); static void validateRegisterClient(Request request); static void validateUpdateClientKey(String clientId, String masterAccessToken); static void validateGetClientKey(String id, String type); static void validateClientId(String clientId); @SuppressWarnings("unchecked") static void validateSendNotification(Request request); @SuppressWarnings("rawtypes") static void validateGetUserCount(Request request); }### Answer: @Test public void testValidateUpdateClientKeyFailureWithEmptyToken() { try { RequestValidator.validateUpdateClientKey("1234", ""); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidRequestData.getErrorCode(), e.getCode()); } } @Test public void testValidateUpdateClientKeySuccess() { try { RequestValidator.validateUpdateClientKey("1234", "test123"); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidRequestData.getErrorCode(), e.getCode()); } }
### Question: RequestValidator { public static void validateClientId(String clientId) { if (StringUtils.isBlank(clientId)) { throw createExceptionInstance(ResponseCode.invalidClientId.getErrorCode()); } } private RequestValidator(); static void validateUploadUser(Map<String, Object> reqObj); static void validateSyncRequest(Request request); static void validateSendMail(Request request); static void validateFileUpload(Request reqObj); static void validateCreateOrgType(Request reqObj); static void validateUpdateOrgType(Request reqObj); @SuppressWarnings("rawtypes") static void validateNote(Request request); static void validateNoteId(String noteId); static void validateRegisterClient(Request request); static void validateUpdateClientKey(String clientId, String masterAccessToken); static void validateGetClientKey(String id, String type); static void validateClientId(String clientId); @SuppressWarnings("unchecked") static void validateSendNotification(Request request); @SuppressWarnings("rawtypes") static void validateGetUserCount(Request request); }### Answer: @Test public void testValidateClientIdFailureWithEmptyId() { try { RequestValidator.validateClientId(""); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidClientId.getErrorCode(), e.getCode()); } }
### Question: RequestValidator { public static void validateFileUpload(Request reqObj) { if (StringUtils.isBlank((String) reqObj.get(JsonKey.CONTAINER))) { throw new ProjectCommonException( ResponseCode.storageContainerNameMandatory.getErrorCode(), ResponseCode.storageContainerNameMandatory.getErrorMessage(), ERROR_CODE); } } private RequestValidator(); static void validateUploadUser(Map<String, Object> reqObj); static void validateSyncRequest(Request request); static void validateSendMail(Request request); static void validateFileUpload(Request reqObj); static void validateCreateOrgType(Request reqObj); static void validateUpdateOrgType(Request reqObj); @SuppressWarnings("rawtypes") static void validateNote(Request request); static void validateNoteId(String noteId); static void validateRegisterClient(Request request); static void validateUpdateClientKey(String clientId, String masterAccessToken); static void validateGetClientKey(String id, String type); static void validateClientId(String clientId); @SuppressWarnings("unchecked") static void validateSendNotification(Request request); @SuppressWarnings("rawtypes") static void validateGetUserCount(Request request); }### Answer: @Test public void testValidateFileUploadFailureWithoutContainerName() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.CONTAINER, ""); request.setRequest(requestObj); try { RequestValidator.validateFileUpload(request); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.storageContainerNameMandatory.getErrorCode(), e.getCode()); } }
### Question: RequestValidator { public static void validateSyncRequest(Request request) { String operation = (String) request.getRequest().get(JsonKey.OPERATION_FOR); if ((null != operation) && (!operation.equalsIgnoreCase("keycloak"))) { if (request.getRequest().get(JsonKey.OBJECT_TYPE) == null) { throw new ProjectCommonException( ResponseCode.dataTypeError.getErrorCode(), ResponseCode.dataTypeError.getErrorMessage(), ERROR_CODE); } List<String> list = new ArrayList<>(Arrays.asList(new String[] {JsonKey.USER, JsonKey.ORGANISATION})); if (!list.contains(request.getRequest().get(JsonKey.OBJECT_TYPE))) { throw new ProjectCommonException( ResponseCode.invalidObjectType.getErrorCode(), ResponseCode.invalidObjectType.getErrorMessage(), ERROR_CODE); } } } private RequestValidator(); static void validateUploadUser(Map<String, Object> reqObj); static void validateSyncRequest(Request request); static void validateSendMail(Request request); static void validateFileUpload(Request reqObj); static void validateCreateOrgType(Request reqObj); static void validateUpdateOrgType(Request reqObj); @SuppressWarnings("rawtypes") static void validateNote(Request request); static void validateNoteId(String noteId); static void validateRegisterClient(Request request); static void validateUpdateClientKey(String clientId, String masterAccessToken); static void validateGetClientKey(String id, String type); static void validateClientId(String clientId); @SuppressWarnings("unchecked") static void validateSendNotification(Request request); @SuppressWarnings("rawtypes") static void validateGetUserCount(Request request); }### Answer: @Test public void testValidateSyncRequestSuccess() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.OPERATION_FOR, "keycloak"); requestObj.put(JsonKey.OBJECT_TYPE, JsonKey.USER); request.setRequest(requestObj); boolean response = false; try { RequestValidator.validateSyncRequest(request); response = true; } catch (ProjectCommonException e) { Assert.assertNull(e); } Assert.assertTrue(response); } @Test public void testValidateSyncRequestFailureWithNullObjectType() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.OPERATION_FOR, "not keycloack"); requestObj.put(JsonKey.OBJECT_TYPE, null); request.setRequest(requestObj); boolean response = false; try { RequestValidator.validateSyncRequest(request); response = true; } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); } Assert.assertFalse(response); } @Test public void testValidateSyncRequestFailureWithInvalidObjectType() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.OPERATION_FOR, "not keycloack"); List<String> objectLsit = new ArrayList<>(); objectLsit.add("testval"); requestObj.put(JsonKey.OBJECT_TYPE, objectLsit); request.setRequest(requestObj); boolean response = false; try { RequestValidator.validateSyncRequest(request); response = true; } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidObjectType.getErrorCode(), e.getCode()); } Assert.assertFalse(response); }
### Question: MigrationUtils { public static List<ShadowUser> getEligibleUsersById( String userId, Map<String, Object> propsMap, RequestContext context) { List<ShadowUser> shadowUsersList = new ArrayList<>(); Response response = cassandraOperation.searchValueInList( JsonKey.SUNBIRD, JsonKey.SHADOW_USER, JsonKey.USERIDS, userId, propsMap, context); if (!((List) response.getResult().get(JsonKey.RESPONSE)).isEmpty()) { ((List) response.getResult().get(JsonKey.RESPONSE)) .stream() .forEach( shadowMap -> { ShadowUser shadowUser = mapper.convertValue(shadowMap, ShadowUser.class); if (shadowUser.getClaimStatus() == ClaimStatus.ELIGIBLE.getValue()) { shadowUsersList.add(shadowUser); } }); } return shadowUsersList; } static ShadowUser getRecordByUserId(String userId, RequestContext context); static boolean updateRecord( Map<String, Object> propertiesMap, String channel, String userExtId, RequestContext context); static boolean markUserAsRejected(ShadowUser shadowUser, RequestContext context); static boolean updateClaimStatus( ShadowUser shadowUser, int claimStatus, RequestContext context); static List<ShadowUser> getEligibleUsersById( String userId, Map<String, Object> propsMap, RequestContext context); static List<ShadowUser> getEligibleUsersById(String userId, RequestContext context); }### Answer: @Test public void testGetEligibleUserByIdsSuccess() { List<ShadowUser> shadowUserList = MigrationUtils.getEligibleUsersById("ABC", new HashMap<>(), null); Assert.assertEquals(1, shadowUserList.size()); } @Test public void testGetEligibleUserByIdsFailure() { List<ShadowUser> shadowUserList = MigrationUtils.getEligibleUsersById("XYZ", new HashMap<>(), null); Assert.assertEquals(0, shadowUserList.size()); } @Test public void testGetEligibleUserByIdsWithoutProps() { List<ShadowUser> shadowUserList = MigrationUtils.getEligibleUsersById("EFG", null); Assert.assertEquals(1, shadowUserList.size()); }
### Question: RequestValidator { public static void validateUpdateOrgType(Request reqObj) { if (StringUtils.isBlank((String) reqObj.getRequest().get(JsonKey.NAME))) { throw createExceptionInstance(ResponseCode.orgTypeMandatory.getErrorCode()); } if (StringUtils.isBlank((String) reqObj.getRequest().get(JsonKey.ID))) { throw createExceptionInstance(ResponseCode.orgTypeIdRequired.getErrorCode()); } } private RequestValidator(); static void validateUploadUser(Map<String, Object> reqObj); static void validateSyncRequest(Request request); static void validateSendMail(Request request); static void validateFileUpload(Request reqObj); static void validateCreateOrgType(Request reqObj); static void validateUpdateOrgType(Request reqObj); @SuppressWarnings("rawtypes") static void validateNote(Request request); static void validateNoteId(String noteId); static void validateRegisterClient(Request request); static void validateUpdateClientKey(String clientId, String masterAccessToken); static void validateGetClientKey(String id, String type); static void validateClientId(String clientId); @SuppressWarnings("unchecked") static void validateSendNotification(Request request); @SuppressWarnings("rawtypes") static void validateGetUserCount(Request request); }### Answer: @Test public void testValidateUserOrgTypeSuccess() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.NAME, "orgtypeName"); requestObj.put(JsonKey.ID, "orgtypeId"); request.setRequest(requestObj); boolean response = false; try { RequestValidator.validateUpdateOrgType(request); response = true; } catch (ProjectCommonException e) { Assert.assertNull(e); } Assert.assertTrue(response); } @Test public void testValidateUserOrgTypeFailureWithEmptyName() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.NAME, ""); requestObj.put(JsonKey.ID, "orgtypeId"); request.setRequest(requestObj); boolean response = false; try { RequestValidator.validateUpdateOrgType(request); response = true; } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.orgTypeMandatory.getErrorCode(), e.getCode()); } Assert.assertFalse(response); } @Test public void testValidateUserOrgTypeFailureWithEmptyId() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.NAME, "orgTypeName"); requestObj.put(JsonKey.ID, ""); request.setRequest(requestObj); boolean response = false; try { RequestValidator.validateUpdateOrgType(request); response = true; } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.orgTypeIdRequired.getErrorCode(), e.getCode()); } Assert.assertFalse(response); }
### Question: RequestValidator { public static void validateCreateOrgType(Request reqObj) { if (StringUtils.isBlank((String) reqObj.getRequest().get(JsonKey.NAME))) { throw createExceptionInstance(ResponseCode.orgTypeMandatory.getErrorCode()); } } private RequestValidator(); static void validateUploadUser(Map<String, Object> reqObj); static void validateSyncRequest(Request request); static void validateSendMail(Request request); static void validateFileUpload(Request reqObj); static void validateCreateOrgType(Request reqObj); static void validateUpdateOrgType(Request reqObj); @SuppressWarnings("rawtypes") static void validateNote(Request request); static void validateNoteId(String noteId); static void validateRegisterClient(Request request); static void validateUpdateClientKey(String clientId, String masterAccessToken); static void validateGetClientKey(String id, String type); static void validateClientId(String clientId); @SuppressWarnings("unchecked") static void validateSendNotification(Request request); @SuppressWarnings("rawtypes") static void validateGetUserCount(Request request); }### Answer: @Test public void testValidateCreateOrgTypeSuccess() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.NAME, "OrgTypeName"); request.setRequest(requestObj); boolean response = false; try { RequestValidator.validateCreateOrgType(request); response = true; } catch (ProjectCommonException e) { Assert.assertNull(e); } Assert.assertTrue(response); } @Test public void testValidateCreateOrgTypeFailureWithNullName() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.NAME, null); request.setRequest(requestObj); boolean response = false; try { RequestValidator.validateCreateOrgType(request); response = true; } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.orgTypeMandatory.getErrorCode(), e.getCode()); } Assert.assertFalse(response); }
### Question: RequestValidator { public static void validateGetClientKey(String id, String type) { validateClientId(id); if (StringUtils.isBlank(type)) { throw createExceptionInstance(ResponseCode.invalidRequestData.getErrorCode()); } } private RequestValidator(); static void validateUploadUser(Map<String, Object> reqObj); static void validateSyncRequest(Request request); static void validateSendMail(Request request); static void validateFileUpload(Request reqObj); static void validateCreateOrgType(Request reqObj); static void validateUpdateOrgType(Request reqObj); @SuppressWarnings("rawtypes") static void validateNote(Request request); static void validateNoteId(String noteId); static void validateRegisterClient(Request request); static void validateUpdateClientKey(String clientId, String masterAccessToken); static void validateGetClientKey(String id, String type); static void validateClientId(String clientId); @SuppressWarnings("unchecked") static void validateSendNotification(Request request); @SuppressWarnings("rawtypes") static void validateGetUserCount(Request request); }### Answer: @Test public void testValidateGetClientKeySuccess() { boolean response = false; try { RequestValidator.validateGetClientKey("clientId", "clientType"); response = true; } catch (ProjectCommonException e) { Assert.assertNull(e); } Assert.assertTrue(response); } @Test public void testValidateGetClientKeyFailureWithEmptyClientId() { boolean response = false; try { RequestValidator.validateGetClientKey("", "clientType"); response = true; } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidClientId.getErrorCode(), e.getCode()); } Assert.assertFalse(response); } @Test public void testValidateGetClientKeyFailureWithEmptyClientType() { boolean response = false; try { RequestValidator.validateGetClientKey("clientId", ""); response = true; } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidRequestData.getErrorCode(), e.getCode()); } Assert.assertFalse(response); }
### Question: UserRequestValidator extends BaseRequestValidator { public static boolean isGoodPassword(String password) { return password.matches(ProjectUtil.getConfigValue(JsonKey.SUNBIRD_PASS_REGEX)); } void validateCreateUserRequest(Request userRequest); static boolean isGoodPassword(String password); void validateUserCreateV3(Request userRequest); void validateCreateUserV3Request(Request userRequest); void validateUserCreateV4(Request userRequest); void validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); void validateUpdateUserRequest(Request userRequest); void externalIdsValidation(Request userRequest, String operation); void validateChangePassword(Request userRequest); void validateVerifyUser(Request userRequest); void validateAssignRole(Request request); void validateForgotPassword(Request request); @SuppressWarnings("unchecked") void validateMandatoryFrameworkFields( Map<String, Object> userMap, List<String> frameworkFields, List<String> frameworkMandatoryFields); @SuppressWarnings("unchecked") void validateFrameworkCategoryValues( Map<String, Object> userMap, Map<String, List<Map<String, String>>> frameworkMap); void validateUserMergeRequest( Request request, String authUserToken, String sourceUserToken); void validateCertValidationRequest(Request request); void validateUserId(String uuid); void validateUserDeclarationRequest(Request userDeclareRequest); }### Answer: @Test public void testIsGoodPassword() { HashMap<String, Boolean> passwordExpectations = new HashMap<String, Boolean>() { { put("Test 1234", false); put("hello1234", false); put("helloABCD", false); put("hello#$%&'", false); put("sho!1", false); put("B1!\"#$%&'()*+,-./:;<=>?@[]^_`{|}~", false); put("Test @1234", false); put("Test123!", true); put("ALongPassword@123", true); put("Abc1!\"#$%&'()*+,-./:;<=>?@[]^_`{|}~", true); } }; passwordExpectations.forEach( (pwd, expectedResult) -> { assertEquals(expectedResult, UserRequestValidator.isGoodPassword(pwd)); }); }
### Question: UserRequestValidator extends BaseRequestValidator { public void createUserBasicValidation(Request userRequest) { createUserBasicProfileFieldsValidation(userRequest); if (userRequest.getRequest().containsKey(JsonKey.ROLES) && null != userRequest.getRequest().get(JsonKey.ROLES) && !(userRequest.getRequest().get(JsonKey.ROLES) instanceof List)) { throw new ProjectCommonException( ResponseCode.dataTypeError.getErrorCode(), ProjectUtil.formatMessage( ResponseCode.dataTypeError.getErrorMessage(), JsonKey.ROLES, JsonKey.LIST), ERROR_CODE); } if (userRequest.getRequest().containsKey(JsonKey.LANGUAGE) && null != userRequest.getRequest().get(JsonKey.LANGUAGE) && !(userRequest.getRequest().get(JsonKey.LANGUAGE) instanceof List)) { throw new ProjectCommonException( ResponseCode.dataTypeError.getErrorCode(), ProjectUtil.formatMessage( ResponseCode.dataTypeError.getErrorMessage(), JsonKey.LANGUAGE, JsonKey.LIST), ERROR_CODE); } } void validateCreateUserRequest(Request userRequest); static boolean isGoodPassword(String password); void validateUserCreateV3(Request userRequest); void validateCreateUserV3Request(Request userRequest); void validateUserCreateV4(Request userRequest); void validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); void validateUpdateUserRequest(Request userRequest); void externalIdsValidation(Request userRequest, String operation); void validateChangePassword(Request userRequest); void validateVerifyUser(Request userRequest); void validateAssignRole(Request request); void validateForgotPassword(Request request); @SuppressWarnings("unchecked") void validateMandatoryFrameworkFields( Map<String, Object> userMap, List<String> frameworkFields, List<String> frameworkMandatoryFields); @SuppressWarnings("unchecked") void validateFrameworkCategoryValues( Map<String, Object> userMap, Map<String, List<Map<String, String>>> frameworkMap); void validateUserMergeRequest( Request request, String authUserToken, String sourceUserToken); void validateCertValidationRequest(Request request); void validateUserId(String uuid); void validateUserDeclarationRequest(Request userDeclareRequest); }### Answer: @Test public void testValidateCreateUserBasicValidationFailure() { Request request = initailizeRequest(); Map<String, Object> requestObj = request.getRequest(); requestObj.put(JsonKey.ROLES, "admin"); request.setRequest(requestObj); try { userRequestValidator.createUserBasicValidation(request); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.dataTypeError.getErrorCode(), e.getCode()); } } @Test public void testCreateUserBasicValidationFailureWithoutEmailAndPhone() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.USERNAME, "test123"); requestObj.put(JsonKey.FIRST_NAME, "test123"); requestObj.put(JsonKey.DOB, "2018-10-15"); request.setRequest(requestObj); try { userRequestValidator.createUserBasicValidation(request); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.emailorPhoneorManagedByRequired.getErrorCode(), e.getCode()); } } @Test public void testCreateUserBasicValidationFailureWithInvalidEmail() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.USERNAME, "test123"); requestObj.put(JsonKey.FIRST_NAME, "test123"); requestObj.put(JsonKey.DOB, "2018-10-15"); requestObj.put(JsonKey.EMAIL, "asd@as"); request.setRequest(requestObj); try { userRequestValidator.createUserBasicValidation(request); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.emailFormatError.getErrorCode(), e.getCode()); } }
### Question: UserRequestValidator extends BaseRequestValidator { public void fieldsNotAllowed(List<String> fields, Request userRequest) { for (String field : fields) { if (((userRequest.getRequest().get(field) instanceof String) && StringUtils.isNotBlank((String) userRequest.getRequest().get(field))) || (null != userRequest.getRequest().get(field))) { throw new ProjectCommonException( ResponseCode.invalidRequestParameter.getErrorCode(), ProjectUtil.formatMessage( ResponseCode.invalidRequestParameter.getErrorMessage(), field), ERROR_CODE); } } } void validateCreateUserRequest(Request userRequest); static boolean isGoodPassword(String password); void validateUserCreateV3(Request userRequest); void validateCreateUserV3Request(Request userRequest); void validateUserCreateV4(Request userRequest); void validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); void validateUpdateUserRequest(Request userRequest); void externalIdsValidation(Request userRequest, String operation); void validateChangePassword(Request userRequest); void validateVerifyUser(Request userRequest); void validateAssignRole(Request request); void validateForgotPassword(Request request); @SuppressWarnings("unchecked") void validateMandatoryFrameworkFields( Map<String, Object> userMap, List<String> frameworkFields, List<String> frameworkMandatoryFields); @SuppressWarnings("unchecked") void validateFrameworkCategoryValues( Map<String, Object> userMap, Map<String, List<Map<String, String>>> frameworkMap); void validateUserMergeRequest( Request request, String authUserToken, String sourceUserToken); void validateCertValidationRequest(Request request); void validateUserId(String uuid); void validateUserDeclarationRequest(Request userDeclareRequest); }### Answer: @Test public void testValidateFieldsNotAllowedFailure() { Request request = initailizeRequest(); Map<String, Object> requestObj = request.getRequest(); requestObj.put(JsonKey.PROVIDER, "AP"); request.setRequest(requestObj); try { userRequestValidator.fieldsNotAllowed( Arrays.asList( JsonKey.REGISTERED_ORG_ID, JsonKey.ROOT_ORG_ID, JsonKey.PROVIDER, JsonKey.EXTERNAL_ID, JsonKey.EXTERNAL_ID_PROVIDER, JsonKey.EXTERNAL_ID_TYPE, JsonKey.ID_TYPE), request); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidRequestParameter.getErrorCode(), e.getCode()); } }
### Question: UserRequestValidator extends BaseRequestValidator { public void validateCreateUserV3Request(Request userRequest) { validateCreateUserRequest(userRequest); } void validateCreateUserRequest(Request userRequest); static boolean isGoodPassword(String password); void validateUserCreateV3(Request userRequest); void validateCreateUserV3Request(Request userRequest); void validateUserCreateV4(Request userRequest); void validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); void validateUpdateUserRequest(Request userRequest); void externalIdsValidation(Request userRequest, String operation); void validateChangePassword(Request userRequest); void validateVerifyUser(Request userRequest); void validateAssignRole(Request request); void validateForgotPassword(Request request); @SuppressWarnings("unchecked") void validateMandatoryFrameworkFields( Map<String, Object> userMap, List<String> frameworkFields, List<String> frameworkMandatoryFields); @SuppressWarnings("unchecked") void validateFrameworkCategoryValues( Map<String, Object> userMap, Map<String, List<Map<String, String>>> frameworkMap); void validateUserMergeRequest( Request request, String authUserToken, String sourceUserToken); void validateCertValidationRequest(Request request); void validateUserId(String uuid); void validateUserDeclarationRequest(Request userDeclareRequest); }### Answer: @Test public void testValidateValidateCreateUserV3RequestSuccess() { boolean response = false; Request request = initailizeRequest(); Map<String, Object> requestObj = request.getRequest(); requestObj.put(JsonKey.PASSWORD, "Password@1"); request.setRequest(requestObj); try { userRequestValidator.validateCreateUserV3Request(request); response = true; } catch (ProjectCommonException e) { Assert.assertNull(e); } assertEquals(true, response); }
### Question: UserRequestValidator extends BaseRequestValidator { public void validateCreateUserV1Request(Request userRequest) { validateUserName(userRequest); validateCreateUserV3Request(userRequest); } void validateCreateUserRequest(Request userRequest); static boolean isGoodPassword(String password); void validateUserCreateV3(Request userRequest); void validateCreateUserV3Request(Request userRequest); void validateUserCreateV4(Request userRequest); void validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); void validateUpdateUserRequest(Request userRequest); void externalIdsValidation(Request userRequest, String operation); void validateChangePassword(Request userRequest); void validateVerifyUser(Request userRequest); void validateAssignRole(Request request); void validateForgotPassword(Request request); @SuppressWarnings("unchecked") void validateMandatoryFrameworkFields( Map<String, Object> userMap, List<String> frameworkFields, List<String> frameworkMandatoryFields); @SuppressWarnings("unchecked") void validateFrameworkCategoryValues( Map<String, Object> userMap, Map<String, List<Map<String, String>>> frameworkMap); void validateUserMergeRequest( Request request, String authUserToken, String sourceUserToken); void validateCertValidationRequest(Request request); void validateUserId(String uuid); void validateUserDeclarationRequest(Request userDeclareRequest); }### Answer: @Test public void testValidateUserNameFailure() { Request request = initailizeRequest(); Map<String, Object> requestObj = request.getRequest(); requestObj.put(JsonKey.USERNAME, ""); request.setRequest(requestObj); try { userRequestValidator.validateCreateUserV1Request(request); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.mandatoryParamsMissing.getErrorCode(), e.getCode()); } }
### Question: UserRequestValidator extends BaseRequestValidator { public void validateForgotPassword(Request request) { if (request.getRequest().get(JsonKey.USERNAME) == null || StringUtils.isBlank((String) request.getRequest().get(JsonKey.USERNAME))) { throw new ProjectCommonException( ResponseCode.userNameRequired.getErrorCode(), ResponseCode.userNameRequired.getErrorMessage(), ERROR_CODE); } } void validateCreateUserRequest(Request userRequest); static boolean isGoodPassword(String password); void validateUserCreateV3(Request userRequest); void validateCreateUserV3Request(Request userRequest); void validateUserCreateV4(Request userRequest); void validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); void validateUpdateUserRequest(Request userRequest); void externalIdsValidation(Request userRequest, String operation); void validateChangePassword(Request userRequest); void validateVerifyUser(Request userRequest); void validateAssignRole(Request request); void validateForgotPassword(Request request); @SuppressWarnings("unchecked") void validateMandatoryFrameworkFields( Map<String, Object> userMap, List<String> frameworkFields, List<String> frameworkMandatoryFields); @SuppressWarnings("unchecked") void validateFrameworkCategoryValues( Map<String, Object> userMap, Map<String, List<Map<String, String>>> frameworkMap); void validateUserMergeRequest( Request request, String authUserToken, String sourceUserToken); void validateCertValidationRequest(Request request); void validateUserId(String uuid); void validateUserDeclarationRequest(Request userDeclareRequest); }### Answer: @Test public void testValidateForgotPasswordSuccess() { Request request = new Request(); boolean response = false; Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.USERNAME, "manzarul07"); request.setRequest(requestObj); try { userRequestValidator.validateForgotPassword(request); response = true; } catch (ProjectCommonException e) { Assert.assertNull(e); } assertEquals(true, response); } @Test public void testValidateForgotPasswordFailureWithEmptyName() { try { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.USERNAME, ""); request.setRequest(requestObj); userRequestValidator.validateForgotPassword(request); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.userNameRequired.getErrorCode(), e.getCode()); } } @Test public void testValidateForgotPasswordFailureWithoutName() { try { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); request.setRequest(requestObj); userRequestValidator.validateForgotPassword(request); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.userNameRequired.getErrorCode(), e.getCode()); } }
### Question: UserExternalIdentityAdapter { public static List<Map<String, String>> convertSelfDeclareFieldsToExternalIds( Map<String, Object> selfDeclaredFields) { List<Map<String, String>> externalIds = new ArrayList<>(); if (MapUtils.isNotEmpty(selfDeclaredFields)) { Map<String, String> userInfo = (Map<String, String>) selfDeclaredFields.get(JsonKey.USER_INFO); if (MapUtils.isNotEmpty(userInfo)) { for (Map.Entry<String, String> itr : userInfo.entrySet()) { Map<String, String> externalIdMap = new HashMap<>(); externalIdMap.put(JsonKey.USER_ID, (String) selfDeclaredFields.get(JsonKey.USER_ID)); externalIdMap.put(JsonKey.ID_TYPE, itr.getKey()); externalIdMap.put(JsonKey.ORIGINAL_ID_TYPE, itr.getKey()); externalIdMap.put(JsonKey.PROVIDER, (String) selfDeclaredFields.get(JsonKey.ORG_ID)); externalIdMap.put( JsonKey.ORIGINAL_PROVIDER, (String) selfDeclaredFields.get(JsonKey.ORG_ID)); externalIdMap.put(JsonKey.EXTERNAL_ID, itr.getValue()); externalIdMap.put(JsonKey.ORIGINAL_EXTERNAL_ID, itr.getValue()); externalIds.add(externalIdMap); } } } return externalIds; } static List<Map<String, String>> convertSelfDeclareFieldsToExternalIds( Map<String, Object> selfDeclaredFields); static Map<String, Object> convertExternalFieldsToSelfDeclareFields( List<Map<String, String>> externalIds); }### Answer: @Test public void testConvertSelfDeclareFieldsToExternalIds() { Map<String, Object> selfDeclaredFields = getSelfDeclareFields(); List<Map<String, String>> externalIds = UserExternalIdentityAdapter.convertSelfDeclareFieldsToExternalIds(selfDeclaredFields); String declaredEmail = ""; String declaredPhone = ""; for (Map<String, String> extIdMap : externalIds) { if (JsonKey.DECLARED_EMAIL.equals((String) extIdMap.get(JsonKey.ORIGINAL_ID_TYPE))) { declaredEmail = (String) extIdMap.get(JsonKey.ORIGINAL_EXTERNAL_ID); } if (JsonKey.DECLARED_PHONE.equals((String) extIdMap.get(JsonKey.ORIGINAL_ID_TYPE))) { declaredPhone = (String) extIdMap.get(JsonKey.ORIGINAL_EXTERNAL_ID); } } Assert.assertEquals("[email protected]", declaredEmail); Assert.assertEquals("999999999", declaredPhone); }
### Question: UserExternalIdentityAdapter { public static Map<String, Object> convertExternalFieldsToSelfDeclareFields( List<Map<String, String>> externalIds) { Map<String, Object> selfDeclaredField = new HashMap<>(); if (CollectionUtils.isNotEmpty(externalIds)) { Map<String, String> userInfo = new HashMap<>(); for (Map<String, String> extIdMap : externalIds) { userInfo.put( extIdMap.get(JsonKey.ORIGINAL_ID_TYPE), extIdMap.get(JsonKey.ORIGINAL_EXTERNAL_ID)); } selfDeclaredField.put(JsonKey.USER_ID, externalIds.get(0).get(JsonKey.USER_ID)); selfDeclaredField.put(JsonKey.ORG_ID, externalIds.get(0).get(JsonKey.ORIGINAL_PROVIDER)); selfDeclaredField.put(JsonKey.PERSONA, JsonKey.TEACHER_PERSONA); selfDeclaredField.put(JsonKey.USER_INFO, userInfo); } return selfDeclaredField; } static List<Map<String, String>> convertSelfDeclareFieldsToExternalIds( Map<String, Object> selfDeclaredFields); static Map<String, Object> convertExternalFieldsToSelfDeclareFields( List<Map<String, String>> externalIds); }### Answer: @Test public void testConvertExternalFieldsToSelfDeclareFields() { Map<String, Object> declaredFeilds = getSelfDeclareFields(); List<Map<String, String>> externalIds = UserExternalIdentityAdapter.convertSelfDeclareFieldsToExternalIds(declaredFeilds); Map<String, Object> resultDeclaredFields = UserExternalIdentityAdapter.convertExternalFieldsToSelfDeclareFields(externalIds); Assert.assertEquals( declaredFeilds.get(JsonKey.USER_ID), resultDeclaredFields.get(JsonKey.USER_ID)); Assert.assertEquals( ((Map<String, Object>) declaredFeilds.get(JsonKey.USER_INFO)).get(JsonKey.DECLARED_EMAIL), ((Map<String, Object>) resultDeclaredFields.get(JsonKey.USER_INFO)) .get(JsonKey.DECLARED_EMAIL)); }
### Question: UserLookUp { public void checkPhoneUniqueness(String phone, RequestContext context) { if (StringUtils.isNotBlank(phone)) { List<Map<String, Object>> userMapList = getPhoneByType(phone, context); if (CollectionUtils.isNotEmpty(userMapList)) { ProjectCommonException.throwClientErrorException(ResponseCode.PhoneNumberInUse, null); } } } Response insertRecords(List<Map<String, Object>> reqMap, RequestContext context); void deleteRecords(List<Map<String, String>> reqMap, RequestContext context); Response insertExternalIdIntoUserLookup( List<Map<String, Object>> reqMap, String userId, RequestContext context); List<Map<String, Object>> getRecordByType( String type, String value, boolean encrypt, RequestContext context); List<Map<String, Object>> getEmailByType(String email, RequestContext context); void checkEmailUniqueness(String email, RequestContext context); void checkEmailUniqueness(User user, String opType, RequestContext context); List<Map<String, Object>> getPhoneByType(String phone, RequestContext context); void checkPhoneUniqueness(String phone, RequestContext context); void checkPhoneUniqueness(User user, String opType, RequestContext context); boolean checkUsernameUniqueness( String username, boolean isEncrypted, RequestContext context); void checkExternalIdUniqueness(User user, String operation, RequestContext context); }### Answer: @Test public void checkPhoneUniquenessExist() throws Exception { User user = new User(); user.setPhone("9663890400"); boolean response = false; try { new UserLookUp().checkPhoneUniqueness(user, "create", null); response = true; } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), 400); } assertFalse(response); } @Test public void checkPhoneUniqueness() throws Exception { User user = new User(); user.setPhone("9663890400"); boolean response = false; try { new UserLookUp().checkPhoneUniqueness(user, "update", null); response = true; } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), 400); } assertFalse(response); } @Test public void checkPhoneExist() { boolean response = false; try { new UserLookUp().checkPhoneUniqueness("9663890400", null); response = true; } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), 400); } assertFalse(response); }
### Question: UserRequestValidator extends BaseRequestValidator { public void validateUpdateUserRequest(Request userRequest) { if (userRequest.getRequest().containsKey(JsonKey.MANAGED_BY)) { ProjectCommonException.throwClientErrorException(ResponseCode.managedByNotAllowed); } externalIdsValidation(userRequest, JsonKey.UPDATE); phoneValidation(userRequest); updateUserBasicValidation(userRequest); validateUserType(userRequest); validateUserOrgField(userRequest); if (userRequest.getRequest().containsKey(JsonKey.ROOT_ORG_ID) && StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.ROOT_ORG_ID))) { ProjectCommonException.throwClientErrorException(ResponseCode.invalidRootOrganisationId); } validateLocationCodes(userRequest); validateExtIdTypeAndProvider(userRequest); validateFrameworkDetails(userRequest); validateRecoveryEmailOrPhone(userRequest); } void validateCreateUserRequest(Request userRequest); static boolean isGoodPassword(String password); void validateUserCreateV3(Request userRequest); void validateCreateUserV3Request(Request userRequest); void validateUserCreateV4(Request userRequest); void validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); void validateUpdateUserRequest(Request userRequest); void externalIdsValidation(Request userRequest, String operation); void validateChangePassword(Request userRequest); void validateVerifyUser(Request userRequest); void validateAssignRole(Request request); void validateForgotPassword(Request request); @SuppressWarnings("unchecked") void validateMandatoryFrameworkFields( Map<String, Object> userMap, List<String> frameworkFields, List<String> frameworkMandatoryFields); @SuppressWarnings("unchecked") void validateFrameworkCategoryValues( Map<String, Object> userMap, Map<String, List<Map<String, String>>> frameworkMap); void validateUserMergeRequest( Request request, String authUserToken, String sourceUserToken); void validateCertValidationRequest(Request request); void validateUserId(String uuid); void validateUserDeclarationRequest(Request userDeclareRequest); }### Answer: @Test public void testUpdateUserSuccess() { Request request = initailizeRequest(); Map<String, Object> requestObj = request.getRequest(); requestObj.remove(JsonKey.USERNAME); requestObj.put(JsonKey.USER_ID, "userId"); List<String> roles = new ArrayList<String>(); roles.add("PUBLIC"); roles.add("CONTENT-CREATOR"); requestObj.put(JsonKey.ROLE, roles); List<String> language = new ArrayList<>(); language.add("English"); requestObj.put(JsonKey.LANGUAGE, language); List<Map<String, Object>> addressList = new ArrayList<>(); Map<String, Object> map = new HashMap<>(); map.put(JsonKey.ADDRESS_LINE1, "test"); map.put(JsonKey.CITY, "Bangalore"); map.put(JsonKey.COUNTRY, "India"); map.put(JsonKey.ADD_TYPE, "current"); addressList.add(map); requestObj.put(JsonKey.ADDRESS, addressList); List<Map<String, Object>> educationList = new ArrayList<>(); Map<String, Object> map1 = new HashMap<>(); map1.put(JsonKey.COURSE_NAME, "M.C.A"); map1.put(JsonKey.DEGREE, "Master"); map1.put(JsonKey.NAME, "CUSAT"); educationList.add(map1); requestObj.put(JsonKey.EDUCATION, educationList); List<Map<String, Object>> jobProfileList = new ArrayList<>(); map1 = new HashMap<>(); map1.put(JsonKey.JOB_NAME, "SE"); map1.put(JsonKey.ORGANISATION_NAME, "Tarento"); jobProfileList.add(map1); requestObj.put(JsonKey.JOB_PROFILE, jobProfileList); boolean response = false; request.setRequest(requestObj); try { userRequestValidator.validateUpdateUserRequest(request); response = true; } catch (ProjectCommonException e) { Assert.assertNull(e); } assertEquals(true, response); }
### Question: UserRequestValidator extends BaseRequestValidator { public void validateAssignRole(Request request) { if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.USER_ID))) { ProjectCommonException.throwClientErrorException(ResponseCode.userIdRequired); } if (request.getRequest().get(JsonKey.ROLES) == null || !(request.getRequest().get(JsonKey.ROLES) instanceof List)) { throw new ProjectCommonException( ResponseCode.dataTypeError.getErrorCode(), ProjectUtil.formatMessage( ResponseCode.dataTypeError.getErrorMessage(), JsonKey.ROLES, JsonKey.LIST), ERROR_CODE); } String organisationId = (String) request.getRequest().get(JsonKey.ORGANISATION_ID); String externalId = (String) request.getRequest().get(JsonKey.EXTERNAL_ID); String provider = (String) request.getRequest().get(JsonKey.PROVIDER); if (StringUtils.isBlank(organisationId) && (StringUtils.isBlank(externalId) || StringUtils.isBlank(provider))) { throw new ProjectCommonException( ResponseCode.mandatoryParamsMissing.getErrorCode(), ProjectUtil.formatMessage( ResponseCode.mandatoryParamsMissing.getErrorMessage(), (StringFormatter.joinByOr( JsonKey.ORGANISATION_ID, StringFormatter.joinByAnd(JsonKey.EXTERNAL_ID, JsonKey.PROVIDER)))), ERROR_CODE); } } void validateCreateUserRequest(Request userRequest); static boolean isGoodPassword(String password); void validateUserCreateV3(Request userRequest); void validateCreateUserV3Request(Request userRequest); void validateUserCreateV4(Request userRequest); void validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); void validateUpdateUserRequest(Request userRequest); void externalIdsValidation(Request userRequest, String operation); void validateChangePassword(Request userRequest); void validateVerifyUser(Request userRequest); void validateAssignRole(Request request); void validateForgotPassword(Request request); @SuppressWarnings("unchecked") void validateMandatoryFrameworkFields( Map<String, Object> userMap, List<String> frameworkFields, List<String> frameworkMandatoryFields); @SuppressWarnings("unchecked") void validateFrameworkCategoryValues( Map<String, Object> userMap, Map<String, List<Map<String, String>>> frameworkMap); void validateUserMergeRequest( Request request, String authUserToken, String sourceUserToken); void validateCertValidationRequest(Request request); void validateUserId(String uuid); void validateUserDeclarationRequest(Request userDeclareRequest); }### Answer: @Test public void testValidateAssignRoleSuccess() { Request request = new Request(); boolean response = false; Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.USER_ID, "ORG-provider"); requestObj.put(JsonKey.EXTERNAL_ID, "EXT_ID"); requestObj.put(JsonKey.ORGANISATION_ID, "ORG_ID"); requestObj.put(JsonKey.ORG_PROVIDER, "ORG_PROVIDER"); List<String> roles = new ArrayList<>(); roles.add("PUBLIC"); requestObj.put(JsonKey.ROLES, roles); request.setRequest(requestObj); try { userRequestValidator.validateAssignRole(request); response = true; } catch (ProjectCommonException e) { Assert.assertNull(e); } assertEquals(true, response); } @Test public void testValidateAssignRoleSuccessWithProviderAndExternalId() { Request request = new Request(); boolean response = false; Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.PROVIDER, "ORG-provider"); requestObj.put(JsonKey.EXTERNAL_ID, "ORG-1233"); requestObj.put(JsonKey.USER_ID, "User1"); List<String> roles = new ArrayList<>(); roles.add("PUBLIC"); requestObj.put(JsonKey.ROLES, roles); request.setRequest(requestObj); try { userRequestValidator.validateAssignRole(request); response = true; } catch (ProjectCommonException e) { Assert.assertNull(e); } assertEquals(true, response); }
### Question: UserRequestValidator extends BaseRequestValidator { public void validateVerifyUser(Request userRequest) { if (StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.LOGIN_ID))) { ProjectCommonException.throwClientErrorException(ResponseCode.loginIdRequired); } } void validateCreateUserRequest(Request userRequest); static boolean isGoodPassword(String password); void validateUserCreateV3(Request userRequest); void validateCreateUserV3Request(Request userRequest); void validateUserCreateV4(Request userRequest); void validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); void validateUpdateUserRequest(Request userRequest); void externalIdsValidation(Request userRequest, String operation); void validateChangePassword(Request userRequest); void validateVerifyUser(Request userRequest); void validateAssignRole(Request request); void validateForgotPassword(Request request); @SuppressWarnings("unchecked") void validateMandatoryFrameworkFields( Map<String, Object> userMap, List<String> frameworkFields, List<String> frameworkMandatoryFields); @SuppressWarnings("unchecked") void validateFrameworkCategoryValues( Map<String, Object> userMap, Map<String, List<Map<String, String>>> frameworkMap); void validateUserMergeRequest( Request request, String authUserToken, String sourceUserToken); void validateCertValidationRequest(Request request); void validateUserId(String uuid); void validateUserDeclarationRequest(Request userDeclareRequest); }### Answer: @Test public void testValidateVerifyUserSuccess() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.LOGIN_ID, "username@provider"); request.setRequest(requestObj); boolean response = false; try { new UserRequestValidator().validateVerifyUser(request); response = true; } catch (ProjectCommonException e) { Assert.assertNull(e); } Assert.assertTrue(response); } @Test public void testValidateGerUserCountFailureWithEstCntReqTrue() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.LOGIN_ID, ""); request.setRequest(requestObj); boolean response = false; try { new UserRequestValidator().validateVerifyUser(request); response = true; } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.loginIdRequired.getErrorCode(), e.getCode()); } Assert.assertFalse(response); } @Test public void testValidateVerifyUserFailureWithEmptyId() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.LOGIN_ID, ""); request.setRequest(requestObj); boolean response = false; try { userRequestValidator.validateVerifyUser(request); response = true; } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.loginIdRequired.getErrorCode(), e.getCode()); } Assert.assertFalse(response); }
### Question: ProjectUtil { public static String createAuthToken(String name, String source) { String data = name + source + System.currentTimeMillis(); UUID authId = UUID.nameUUIDFromBytes(data.getBytes(StandardCharsets.UTF_8)); return authId.toString(); } static String getFormattedDate(); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static boolean isNull(Object obj); static boolean isNotNull(Object obj); static String formatMessage(String exceptionMsg, Object... fieldValue); static SimpleDateFormat getDateFormatter(); static VelocityContext getContext(Map<String, Object> map); static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e); static String registertag( String tagId, String body, Map<String, String> header, RequestContext context); static String generateRandomPassword(); static boolean validatePhoneNumber(String phone); static Map<String, String> getEkstepHeader(); static boolean validatePhone(String phNumber, String countryCode); static boolean validateCountryCode(String countryCode); static boolean validateUUID(String uuidStr); static String getSMSBody(Map<String, String> smsTemplate); static boolean isDateValidFormat(String format, String value); static void createAndThrowServerError(); static ProjectCommonException createServerError(ResponseCode responseCode); static void createAndThrowInvalidUserDataException(); static boolean isUrlvalid(String url); static String getConfigValue(String key); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static T convertToRequestPojo(Request request, Class<T> clazz); static Map<String, String> getDateRange(int numDays); static ProjectCommonException createClientException(ResponseCode responseCode); static String getLmsUserId(String fedUserId); static String getFirstNCharacterString(String originalText, int noOfChar); static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; }### Answer: @Test public void testCreateAuthTokenSuccess() { String authToken = ProjectUtil.createAuthToken("test", "tset1234"); assertNotNull(authToken); }
### Question: ProjectUtil { public static boolean validatePhoneNumber(String phone) { String phoneNo = ""; phoneNo = phone.replace("+", ""); if (phoneNo.matches("\\d{10}")) return true; else if (phoneNo.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) return true; else if (phoneNo.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}")) return true; else return (phoneNo.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}")); } static String getFormattedDate(); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static boolean isNull(Object obj); static boolean isNotNull(Object obj); static String formatMessage(String exceptionMsg, Object... fieldValue); static SimpleDateFormat getDateFormatter(); static VelocityContext getContext(Map<String, Object> map); static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e); static String registertag( String tagId, String body, Map<String, String> header, RequestContext context); static String generateRandomPassword(); static boolean validatePhoneNumber(String phone); static Map<String, String> getEkstepHeader(); static boolean validatePhone(String phNumber, String countryCode); static boolean validateCountryCode(String countryCode); static boolean validateUUID(String uuidStr); static String getSMSBody(Map<String, String> smsTemplate); static boolean isDateValidFormat(String format, String value); static void createAndThrowServerError(); static ProjectCommonException createServerError(ResponseCode responseCode); static void createAndThrowInvalidUserDataException(); static boolean isUrlvalid(String url); static String getConfigValue(String key); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static T convertToRequestPojo(Request request, Class<T> clazz); static Map<String, String> getDateRange(int numDays); static ProjectCommonException createClientException(ResponseCode responseCode); static String getLmsUserId(String fedUserId); static String getFirstNCharacterString(String originalText, int noOfChar); static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; }### Answer: @Test public void testValidatePhoneNumberFailureWithInvalidPhoneNumber() { assertFalse(ProjectUtil.validatePhoneNumber("312")); } @Test public void testValidatePhoneNumberSuccess() { assertTrue(ProjectUtil.validatePhoneNumber("9844016699")); }
### Question: ProjectUtil { public static String generateRandomPassword() { String SALTCHARS = "abcdef12345ghijklACDEFGHmnopqrs67IJKLMNOP890tuvQRSTUwxyzVWXYZ"; StringBuilder salt = new StringBuilder(); Random rnd = new Random(); while (salt.length() < randomPasswordLength) { int index = (int) (rnd.nextFloat() * SALTCHARS.length()); salt.append(SALTCHARS.charAt(index)); } String saltStr = salt.toString(); return saltStr; } static String getFormattedDate(); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static boolean isNull(Object obj); static boolean isNotNull(Object obj); static String formatMessage(String exceptionMsg, Object... fieldValue); static SimpleDateFormat getDateFormatter(); static VelocityContext getContext(Map<String, Object> map); static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e); static String registertag( String tagId, String body, Map<String, String> header, RequestContext context); static String generateRandomPassword(); static boolean validatePhoneNumber(String phone); static Map<String, String> getEkstepHeader(); static boolean validatePhone(String phNumber, String countryCode); static boolean validateCountryCode(String countryCode); static boolean validateUUID(String uuidStr); static String getSMSBody(Map<String, String> smsTemplate); static boolean isDateValidFormat(String format, String value); static void createAndThrowServerError(); static ProjectCommonException createServerError(ResponseCode responseCode); static void createAndThrowInvalidUserDataException(); static boolean isUrlvalid(String url); static String getConfigValue(String key); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static T convertToRequestPojo(Request request, Class<T> clazz); static Map<String, String> getDateRange(int numDays); static ProjectCommonException createClientException(ResponseCode responseCode); static String getLmsUserId(String fedUserId); static String getFirstNCharacterString(String originalText, int noOfChar); static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; }### Answer: @Test public void testGenerateRandomPasswordSuccess() { assertNotNull(ProjectUtil.generateRandomPassword()); }
### Question: ProjectUtil { public static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e) { Map<String, Object> responseMap = new HashMap<>(); responseMap.put(JsonKey.NAME, serviceName); if (!isError) { responseMap.put(JsonKey.Healthy, true); responseMap.put(JsonKey.ERROR, ""); responseMap.put(JsonKey.ERRORMSG, ""); } else { responseMap.put(JsonKey.Healthy, false); if (e != null && e instanceof ProjectCommonException) { ProjectCommonException commonException = (ProjectCommonException) e; responseMap.put(JsonKey.ERROR, commonException.getResponseCode()); responseMap.put(JsonKey.ERRORMSG, commonException.getMessage()); } else { responseMap.put(JsonKey.ERROR, e != null ? e.getMessage() : "CONNECTION_ERROR"); responseMap.put(JsonKey.ERRORMSG, e != null ? e.getMessage() : "Connection error"); } } return responseMap; } static String getFormattedDate(); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static boolean isNull(Object obj); static boolean isNotNull(Object obj); static String formatMessage(String exceptionMsg, Object... fieldValue); static SimpleDateFormat getDateFormatter(); static VelocityContext getContext(Map<String, Object> map); static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e); static String registertag( String tagId, String body, Map<String, String> header, RequestContext context); static String generateRandomPassword(); static boolean validatePhoneNumber(String phone); static Map<String, String> getEkstepHeader(); static boolean validatePhone(String phNumber, String countryCode); static boolean validateCountryCode(String countryCode); static boolean validateUUID(String uuidStr); static String getSMSBody(Map<String, String> smsTemplate); static boolean isDateValidFormat(String format, String value); static void createAndThrowServerError(); static ProjectCommonException createServerError(ResponseCode responseCode); static void createAndThrowInvalidUserDataException(); static boolean isUrlvalid(String url); static String getConfigValue(String key); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static T convertToRequestPojo(Request request, Class<T> clazz); static Map<String, String> getDateRange(int numDays); static ProjectCommonException createClientException(ResponseCode responseCode); static String getLmsUserId(String fedUserId); static String getFirstNCharacterString(String originalText, int noOfChar); static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; }### Answer: @Test public void testCreateCheckResponseSuccess() { Map<String, Object> responseMap = ProjectUtil.createCheckResponse("LearnerService", false, null); assertEquals(true, responseMap.get(JsonKey.Healthy)); } @Test public void testCreateCheckResponseFailureWithException() { Map<String, Object> responseMap = ProjectUtil.createCheckResponse( "LearnerService", true, new ProjectCommonException( ResponseCode.invalidObjectType.getErrorCode(), ResponseCode.invalidObjectType.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode())); assertEquals(false, responseMap.get(JsonKey.Healthy)); assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), responseMap.get(JsonKey.ERROR)); assertEquals( ResponseCode.invalidObjectType.getErrorMessage(), responseMap.get(JsonKey.ERRORMSG)); }
### Question: ProjectUtil { public static String formatMessage(String exceptionMsg, Object... fieldValue) { return MessageFormat.format(exceptionMsg, fieldValue); } static String getFormattedDate(); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static boolean isNull(Object obj); static boolean isNotNull(Object obj); static String formatMessage(String exceptionMsg, Object... fieldValue); static SimpleDateFormat getDateFormatter(); static VelocityContext getContext(Map<String, Object> map); static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e); static String registertag( String tagId, String body, Map<String, String> header, RequestContext context); static String generateRandomPassword(); static boolean validatePhoneNumber(String phone); static Map<String, String> getEkstepHeader(); static boolean validatePhone(String phNumber, String countryCode); static boolean validateCountryCode(String countryCode); static boolean validateUUID(String uuidStr); static String getSMSBody(Map<String, String> smsTemplate); static boolean isDateValidFormat(String format, String value); static void createAndThrowServerError(); static ProjectCommonException createServerError(ResponseCode responseCode); static void createAndThrowInvalidUserDataException(); static boolean isUrlvalid(String url); static String getConfigValue(String key); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static T convertToRequestPojo(Request request, Class<T> clazz); static Map<String, String> getDateRange(int numDays); static ProjectCommonException createClientException(ResponseCode responseCode); static String getLmsUserId(String fedUserId); static String getFirstNCharacterString(String originalText, int noOfChar); static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; }### Answer: @Test public void testFormatMessageSuccess() { String msg = ProjectUtil.formatMessage("Hello {0}", "user"); assertEquals("Hello user", msg); } @Test public void testFormatMessageFailureWithInvalidVariable() { String msg = ProjectUtil.formatMessage("Hello ", "user"); assertNotEquals("Hello user", msg); }
### Question: ProjectUtil { public static boolean isEmailvalid(final String email) { if (StringUtils.isBlank(email)) { return false; } Matcher matcher = pattern.matcher(email); return matcher.matches(); } static String getFormattedDate(); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static boolean isNull(Object obj); static boolean isNotNull(Object obj); static String formatMessage(String exceptionMsg, Object... fieldValue); static SimpleDateFormat getDateFormatter(); static VelocityContext getContext(Map<String, Object> map); static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e); static String registertag( String tagId, String body, Map<String, String> header, RequestContext context); static String generateRandomPassword(); static boolean validatePhoneNumber(String phone); static Map<String, String> getEkstepHeader(); static boolean validatePhone(String phNumber, String countryCode); static boolean validateCountryCode(String countryCode); static boolean validateUUID(String uuidStr); static String getSMSBody(Map<String, String> smsTemplate); static boolean isDateValidFormat(String format, String value); static void createAndThrowServerError(); static ProjectCommonException createServerError(ResponseCode responseCode); static void createAndThrowInvalidUserDataException(); static boolean isUrlvalid(String url); static String getConfigValue(String key); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static T convertToRequestPojo(Request request, Class<T> clazz); static Map<String, String> getDateRange(int numDays); static ProjectCommonException createClientException(ResponseCode responseCode); static String getLmsUserId(String fedUserId); static String getFirstNCharacterString(String originalText, int noOfChar); static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; }### Answer: @Test public void testIsEmailValidFailureWithWrongEmail() { boolean msg = ProjectUtil.isEmailvalid("Hello "); assertFalse(msg); } @Test public void testIsEmailValidFailureWithInvalidFormat() { boolean bool = ProjectUtil.isEmailvalid("amit.kumartarento.com"); Assert.assertFalse(bool); } @Test public void testIsEmailValidSuccess() { boolean bool = ProjectUtil.isEmailvalid("[email protected]"); assertTrue(bool); }
### Question: ProjectUtil { public static boolean isDateValidFormat(String format, String value) { Date date = null; try { SimpleDateFormat sdf = new SimpleDateFormat(format); date = sdf.parse(value); if (!value.equals(sdf.format(date))) { date = null; } } catch (ParseException ex) { ProjectLogger.log(ex.getMessage(), ex); } return date != null; } static String getFormattedDate(); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static boolean isNull(Object obj); static boolean isNotNull(Object obj); static String formatMessage(String exceptionMsg, Object... fieldValue); static SimpleDateFormat getDateFormatter(); static VelocityContext getContext(Map<String, Object> map); static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e); static String registertag( String tagId, String body, Map<String, String> header, RequestContext context); static String generateRandomPassword(); static boolean validatePhoneNumber(String phone); static Map<String, String> getEkstepHeader(); static boolean validatePhone(String phNumber, String countryCode); static boolean validateCountryCode(String countryCode); static boolean validateUUID(String uuidStr); static String getSMSBody(Map<String, String> smsTemplate); static boolean isDateValidFormat(String format, String value); static void createAndThrowServerError(); static ProjectCommonException createServerError(ResponseCode responseCode); static void createAndThrowInvalidUserDataException(); static boolean isUrlvalid(String url); static String getConfigValue(String key); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static T convertToRequestPojo(Request request, Class<T> clazz); static Map<String, String> getDateRange(int numDays); static ProjectCommonException createClientException(ResponseCode responseCode); static String getLmsUserId(String fedUserId); static String getFirstNCharacterString(String originalText, int noOfChar); static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; }### Answer: @Test public void testIsDateValidFormatSuccess() { boolean bool = ProjectUtil.isDateValidFormat("yyyy-MM-dd", "2017-12-18"); assertTrue(bool); } @Test public void testIsDateValidFormatFailureWithEmptyDate() { boolean bool = ProjectUtil.isDateValidFormat("yyyy-MM-dd", ""); assertFalse(bool); } @Test public void testIsDateValidFormatFailureWithInvalidDate() { boolean bool = ProjectUtil.isDateValidFormat("yyyy-MM-dd", "2017-12-18"); assertTrue(bool); } @Test public void testIsDateValidFormatFailureWithEmptyDateTime() { boolean bool = ProjectUtil.isDateValidFormat("yyyy-MM-dd HH:mm:ss:SSSZ", ""); assertFalse(bool); }
### Question: ProjectUtil { public static Map<String, String> getEkstepHeader() { Map<String, String> headerMap = new HashMap<>(); String header = System.getenv(JsonKey.EKSTEP_AUTHORIZATION); if (StringUtils.isBlank(header)) { header = PropertiesCache.getInstance().getProperty(JsonKey.EKSTEP_AUTHORIZATION); } else { header = JsonKey.BEARER + header; } headerMap.put(JsonKey.AUTHORIZATION, header); headerMap.put("Content-Type", "application/json"); return headerMap; } static String getFormattedDate(); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static boolean isNull(Object obj); static boolean isNotNull(Object obj); static String formatMessage(String exceptionMsg, Object... fieldValue); static SimpleDateFormat getDateFormatter(); static VelocityContext getContext(Map<String, Object> map); static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e); static String registertag( String tagId, String body, Map<String, String> header, RequestContext context); static String generateRandomPassword(); static boolean validatePhoneNumber(String phone); static Map<String, String> getEkstepHeader(); static boolean validatePhone(String phNumber, String countryCode); static boolean validateCountryCode(String countryCode); static boolean validateUUID(String uuidStr); static String getSMSBody(Map<String, String> smsTemplate); static boolean isDateValidFormat(String format, String value); static void createAndThrowServerError(); static ProjectCommonException createServerError(ResponseCode responseCode); static void createAndThrowInvalidUserDataException(); static boolean isUrlvalid(String url); static String getConfigValue(String key); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static T convertToRequestPojo(Request request, Class<T> clazz); static Map<String, String> getDateRange(int numDays); static ProjectCommonException createClientException(ResponseCode responseCode); static String getLmsUserId(String fedUserId); static String getFirstNCharacterString(String originalText, int noOfChar); static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; }### Answer: @Test public void testGetEkstepHeaderSuccess() { Map<String, String> map = ProjectUtil.getEkstepHeader(); assertEquals(map.get("Content-Type"), "application/json"); assertNotNull(map.get(JsonKey.AUTHORIZATION)); }
### Question: ProjectUtil { public static void createAndThrowServerError() { throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } static String getFormattedDate(); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static boolean isNull(Object obj); static boolean isNotNull(Object obj); static String formatMessage(String exceptionMsg, Object... fieldValue); static SimpleDateFormat getDateFormatter(); static VelocityContext getContext(Map<String, Object> map); static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e); static String registertag( String tagId, String body, Map<String, String> header, RequestContext context); static String generateRandomPassword(); static boolean validatePhoneNumber(String phone); static Map<String, String> getEkstepHeader(); static boolean validatePhone(String phNumber, String countryCode); static boolean validateCountryCode(String countryCode); static boolean validateUUID(String uuidStr); static String getSMSBody(Map<String, String> smsTemplate); static boolean isDateValidFormat(String format, String value); static void createAndThrowServerError(); static ProjectCommonException createServerError(ResponseCode responseCode); static void createAndThrowInvalidUserDataException(); static boolean isUrlvalid(String url); static String getConfigValue(String key); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static T convertToRequestPojo(Request request, Class<T> clazz); static Map<String, String> getDateRange(int numDays); static ProjectCommonException createClientException(ResponseCode responseCode); static String getLmsUserId(String fedUserId); static String getFirstNCharacterString(String originalText, int noOfChar); static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; }### Answer: @Test public void testCreateAndThrowServerErrorSuccess() { try { ProjectUtil.createAndThrowServerError(); } catch (ProjectCommonException e) { assertEquals(ResponseCode.SERVER_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.SERVER_ERROR.getErrorCode(), e.getCode()); } }
### Question: ProjectUtil { public static void createAndThrowInvalidUserDataException() { throw new ProjectCommonException( ResponseCode.invalidUsrData.getErrorCode(), ResponseCode.invalidUsrData.getErrorMessage(), ResponseCode.CLIENT_ERROR.getResponseCode()); } static String getFormattedDate(); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static boolean isNull(Object obj); static boolean isNotNull(Object obj); static String formatMessage(String exceptionMsg, Object... fieldValue); static SimpleDateFormat getDateFormatter(); static VelocityContext getContext(Map<String, Object> map); static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e); static String registertag( String tagId, String body, Map<String, String> header, RequestContext context); static String generateRandomPassword(); static boolean validatePhoneNumber(String phone); static Map<String, String> getEkstepHeader(); static boolean validatePhone(String phNumber, String countryCode); static boolean validateCountryCode(String countryCode); static boolean validateUUID(String uuidStr); static String getSMSBody(Map<String, String> smsTemplate); static boolean isDateValidFormat(String format, String value); static void createAndThrowServerError(); static ProjectCommonException createServerError(ResponseCode responseCode); static void createAndThrowInvalidUserDataException(); static boolean isUrlvalid(String url); static String getConfigValue(String key); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static T convertToRequestPojo(Request request, Class<T> clazz); static Map<String, String> getDateRange(int numDays); static ProjectCommonException createClientException(ResponseCode responseCode); static String getLmsUserId(String fedUserId); static String getFirstNCharacterString(String originalText, int noOfChar); static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; }### Answer: @Test public void testCreateAndThrowInvalidUserDataExceptionSuccess() { try { ProjectUtil.createAndThrowInvalidUserDataException(); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidUsrData.getErrorCode(), e.getCode()); } }
### Question: ProjectUtil { public static String getLmsUserId(String fedUserId) { String userId = fedUserId; String prefix = "f:" + getConfigValue(JsonKey.SUNBIRD_KEYCLOAK_USER_FEDERATION_PROVIDER_ID) + ":"; if (StringUtils.isNotBlank(fedUserId) && fedUserId.startsWith(prefix)) { userId = fedUserId.replace(prefix, ""); } return userId; } static String getFormattedDate(); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static boolean isNull(Object obj); static boolean isNotNull(Object obj); static String formatMessage(String exceptionMsg, Object... fieldValue); static SimpleDateFormat getDateFormatter(); static VelocityContext getContext(Map<String, Object> map); static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e); static String registertag( String tagId, String body, Map<String, String> header, RequestContext context); static String generateRandomPassword(); static boolean validatePhoneNumber(String phone); static Map<String, String> getEkstepHeader(); static boolean validatePhone(String phNumber, String countryCode); static boolean validateCountryCode(String countryCode); static boolean validateUUID(String uuidStr); static String getSMSBody(Map<String, String> smsTemplate); static boolean isDateValidFormat(String format, String value); static void createAndThrowServerError(); static ProjectCommonException createServerError(ResponseCode responseCode); static void createAndThrowInvalidUserDataException(); static boolean isUrlvalid(String url); static String getConfigValue(String key); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static T convertToRequestPojo(Request request, Class<T> clazz); static Map<String, String> getDateRange(int numDays); static ProjectCommonException createClientException(ResponseCode responseCode); static String getLmsUserId(String fedUserId); static String getFirstNCharacterString(String originalText, int noOfChar); static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; }### Answer: @Test public void testGetLmsUserIdSuccessWithoutFedUserId() { String userid = ProjectUtil.getLmsUserId("1234567890"); assertEquals("1234567890", userid); }
### Question: ProjectUtil { public static boolean validateCountryCode(String countryCode) { String pattern = "^(?:[+] ?){0,1}(?:[0-9] ?){1,3}"; try { Pattern patt = Pattern.compile(pattern); Matcher matcher = patt.matcher(countryCode); return matcher.matches(); } catch (RuntimeException e) { return false; } } static String getFormattedDate(); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static boolean isNull(Object obj); static boolean isNotNull(Object obj); static String formatMessage(String exceptionMsg, Object... fieldValue); static SimpleDateFormat getDateFormatter(); static VelocityContext getContext(Map<String, Object> map); static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e); static String registertag( String tagId, String body, Map<String, String> header, RequestContext context); static String generateRandomPassword(); static boolean validatePhoneNumber(String phone); static Map<String, String> getEkstepHeader(); static boolean validatePhone(String phNumber, String countryCode); static boolean validateCountryCode(String countryCode); static boolean validateUUID(String uuidStr); static String getSMSBody(Map<String, String> smsTemplate); static boolean isDateValidFormat(String format, String value); static void createAndThrowServerError(); static ProjectCommonException createServerError(ResponseCode responseCode); static void createAndThrowInvalidUserDataException(); static boolean isUrlvalid(String url); static String getConfigValue(String key); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static T convertToRequestPojo(Request request, Class<T> clazz); static Map<String, String> getDateRange(int numDays); static ProjectCommonException createClientException(ResponseCode responseCode); static String getLmsUserId(String fedUserId); static String getFirstNCharacterString(String originalText, int noOfChar); static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; }### Answer: @Test public void testValidateCountryCode() { boolean isValid = ProjectUtil.validateCountryCode("+91"); assertTrue(isValid); isValid = ProjectUtil.validateCountryCode("9a"); assertFalse(isValid); }
### Question: ProjectUtil { public static boolean validateUUID(String uuidStr) { try { UUID.fromString(uuidStr); return true; } catch (Exception ex) { return false; } } static String getFormattedDate(); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static boolean isNull(Object obj); static boolean isNotNull(Object obj); static String formatMessage(String exceptionMsg, Object... fieldValue); static SimpleDateFormat getDateFormatter(); static VelocityContext getContext(Map<String, Object> map); static Map<String, Object> createCheckResponse( String serviceName, boolean isError, Exception e); static String registertag( String tagId, String body, Map<String, String> header, RequestContext context); static String generateRandomPassword(); static boolean validatePhoneNumber(String phone); static Map<String, String> getEkstepHeader(); static boolean validatePhone(String phNumber, String countryCode); static boolean validateCountryCode(String countryCode); static boolean validateUUID(String uuidStr); static String getSMSBody(Map<String, String> smsTemplate); static boolean isDateValidFormat(String format, String value); static void createAndThrowServerError(); static ProjectCommonException createServerError(ResponseCode responseCode); static void createAndThrowInvalidUserDataException(); static boolean isUrlvalid(String url); static String getConfigValue(String key); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static T convertToRequestPojo(Request request, Class<T> clazz); static Map<String, String> getDateRange(int numDays); static ProjectCommonException createClientException(ResponseCode responseCode); static String getLmsUserId(String fedUserId); static String getFirstNCharacterString(String originalText, int noOfChar); static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; }### Answer: @Test public void testValidateUUID() { boolean isValid = ProjectUtil.validateUUID("1df03f56-ceba-4f2d-892c-2b1609e7b05f"); assertTrue(isValid); }
### Question: HttpClientUtil { public static String get(String requestURL, Map<String, String> headers) { CloseableHttpResponse response = null; try { HttpGet httpGet = new HttpGet(requestURL); if (MapUtils.isNotEmpty(headers)) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpGet.addHeader(entry.getKey(), entry.getValue()); } } response = httpclient.execute(httpGet); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity httpEntity = response.getEntity(); byte[] bytes = EntityUtils.toByteArray(httpEntity); StatusLine sl = response.getStatusLine(); ProjectLogger.log( "Response from get call : " + sl.getStatusCode() + " - " + sl.getReasonPhrase(), LoggerEnum.INFO.name()); return new String(bytes); } else { return ""; } } catch (Exception ex) { ProjectLogger.log("Exception occurred while calling get method", ex); return ""; } finally { if (null != response) { try { response.close(); } catch (Exception ex) { ProjectLogger.log("Exception occurred while closing get response object", ex); } } } } private HttpClientUtil(); static HttpClientUtil getInstance(); static String get(String requestURL, Map<String, String> headers); static String post(String requestURL, String params, Map<String, String> headers); static String postFormData( String requestURL, Map<String, String> params, Map<String, String> headers); static String patch(String requestURL, String params, Map<String, String> headers); }### Answer: @Test public void testGetSuccess() throws IOException { CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); StatusLine statusLine = PowerMockito.mock(StatusLine.class); PowerMockito.when(response.getStatusLine()).thenReturn(statusLine); PowerMockito.when(statusLine.getStatusCode()).thenReturn(200); HttpEntity entity = PowerMockito.mock(HttpEntity.class); PowerMockito.when(response.getEntity()).thenReturn(entity); PowerMockito.mockStatic(EntityUtils.class); byte[] bytes = "{\"message\":\"success\"}".getBytes(); PowerMockito.when(EntityUtils.toByteArray(Mockito.any(HttpEntity.class))).thenReturn(bytes); PowerMockito.when(httpclient.execute(Mockito.any(HttpGet.class))).thenReturn(response); String res = HttpClientUtil.get("http: assertTrue("{\"message\":\"success\"}".equals(res)); }
### Question: HttpClientUtil { public static String post(String requestURL, String params, Map<String, String> headers) { CloseableHttpResponse response = null; try { HttpPost httpPost = new HttpPost(requestURL); if (MapUtils.isNotEmpty(headers)) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpPost.addHeader(entry.getKey(), entry.getValue()); } } StringEntity entity = new StringEntity(params); httpPost.setEntity(entity); response = httpclient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity httpEntity = response.getEntity(); byte[] bytes = EntityUtils.toByteArray(httpEntity); StatusLine sl = response.getStatusLine(); ProjectLogger.log( "Response from post call : " + sl.getStatusCode() + " - " + sl.getReasonPhrase(), LoggerEnum.INFO.name()); return new String(bytes); } else { return ""; } } catch (Exception ex) { ProjectLogger.log("Exception occurred while calling Post method", ex); return ""; } finally { if (null != response) { try { response.close(); } catch (Exception ex) { ProjectLogger.log("Exception occurred while closing Post response object", ex); } } } } private HttpClientUtil(); static HttpClientUtil getInstance(); static String get(String requestURL, Map<String, String> headers); static String post(String requestURL, String params, Map<String, String> headers); static String postFormData( String requestURL, Map<String, String> params, Map<String, String> headers); static String patch(String requestURL, String params, Map<String, String> headers); }### Answer: @Test public void testPostSuccess() throws IOException { CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); StatusLine statusLine = PowerMockito.mock(StatusLine.class); PowerMockito.when(response.getStatusLine()).thenReturn(statusLine); PowerMockito.when(statusLine.getStatusCode()).thenReturn(200); HttpEntity entity = PowerMockito.mock(HttpEntity.class); PowerMockito.when(response.getEntity()).thenReturn(entity); PowerMockito.mockStatic(EntityUtils.class); byte[] bytes = "{\"message\":\"success\"}".getBytes(); PowerMockito.when(EntityUtils.toByteArray(Mockito.any(HttpEntity.class))).thenReturn(bytes); PowerMockito.when(httpclient.execute(Mockito.any(HttpPost.class))).thenReturn(response); String res = HttpClientUtil.post("http: assertTrue("{\"message\":\"success\"}".equals(res)); }
### Question: HttpClientUtil { public static String postFormData( String requestURL, Map<String, String> params, Map<String, String> headers) { CloseableHttpResponse response = null; try { HttpPost httpPost = new HttpPost(requestURL); if (MapUtils.isNotEmpty(headers)) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpPost.addHeader(entry.getKey(), entry.getValue()); } } List<NameValuePair> form = new ArrayList<>(); for (Map.Entry<String, String> entry : params.entrySet()) { form.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form, Consts.UTF_8); httpPost.setEntity(entity); response = httpclient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity httpEntity = response.getEntity(); byte[] bytes = EntityUtils.toByteArray(httpEntity); StatusLine sl = response.getStatusLine(); ProjectLogger.log( "Response from post call : " + sl.getStatusCode() + " - " + sl.getReasonPhrase(), LoggerEnum.INFO.name()); return new String(bytes); } else { return ""; } } catch (Exception ex) { ProjectLogger.log("Exception occurred while calling Post method", ex); return ""; } finally { if (null != response) { try { response.close(); } catch (Exception ex) { ProjectLogger.log("Exception occurred while closing Post response object", ex); } } } } private HttpClientUtil(); static HttpClientUtil getInstance(); static String get(String requestURL, Map<String, String> headers); static String post(String requestURL, String params, Map<String, String> headers); static String postFormData( String requestURL, Map<String, String> params, Map<String, String> headers); static String patch(String requestURL, String params, Map<String, String> headers); }### Answer: @Test public void testPostFormSuccess() throws IOException { CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); StatusLine statusLine = PowerMockito.mock(StatusLine.class); PowerMockito.when(response.getStatusLine()).thenReturn(statusLine); PowerMockito.when(statusLine.getStatusCode()).thenReturn(200); HttpEntity entity = PowerMockito.mock(HttpEntity.class); PowerMockito.when(response.getEntity()).thenReturn(entity); PowerMockito.mockStatic(EntityUtils.class); byte[] bytes = "{\"message\":\"success\"}".getBytes(); PowerMockito.when(EntityUtils.toByteArray(Mockito.any(HttpEntity.class))).thenReturn(bytes); PowerMockito.when(httpclient.execute(Mockito.any(HttpPost.class))).thenReturn(response); Map<String,String> fields = new HashMap<>(); fields.put("message", "success"); String res = HttpClientUtil.postFormData("http: assertTrue("{\"message\":\"success\"}".equals(res)); }
### Question: HttpClientUtil { public static String patch(String requestURL, String params, Map<String, String> headers) { CloseableHttpResponse response = null; try { HttpPatch httpPatch = new HttpPatch(requestURL); if (MapUtils.isNotEmpty(headers)) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpPatch.addHeader(entry.getKey(), entry.getValue()); } } StringEntity entity = new StringEntity(params); httpPatch.setEntity(entity); response = httpclient.execute(httpPatch); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity httpEntity = response.getEntity(); byte[] bytes = EntityUtils.toByteArray(httpEntity); StatusLine sl = response.getStatusLine(); ProjectLogger.log( "Response from patch call : " + sl.getStatusCode() + " - " + sl.getReasonPhrase(), LoggerEnum.INFO.name()); return new String(bytes); } else { return ""; } } catch (Exception ex) { ProjectLogger.log("Exception occurred while calling patch method", ex); return ""; } finally { if (null != response) { try { response.close(); } catch (Exception ex) { ProjectLogger.log("Exception occurred while closing patch response object", ex); } } } } private HttpClientUtil(); static HttpClientUtil getInstance(); static String get(String requestURL, Map<String, String> headers); static String post(String requestURL, String params, Map<String, String> headers); static String postFormData( String requestURL, Map<String, String> params, Map<String, String> headers); static String patch(String requestURL, String params, Map<String, String> headers); }### Answer: @Test public void testPatchSuccess() throws IOException { CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); StatusLine statusLine = PowerMockito.mock(StatusLine.class); PowerMockito.when(response.getStatusLine()).thenReturn(statusLine); PowerMockito.when(statusLine.getStatusCode()).thenReturn(200); HttpEntity entity = PowerMockito.mock(HttpEntity.class); PowerMockito.when(response.getEntity()).thenReturn(entity); PowerMockito.mockStatic(EntityUtils.class); byte[] bytes = "{\"message\":\"success\"}".getBytes(); PowerMockito.when(EntityUtils.toByteArray(Mockito.any(HttpEntity.class))).thenReturn(bytes); PowerMockito.when(httpclient.execute(Mockito.any(HttpPost.class))).thenReturn(response); String res = HttpClientUtil.patch("http: assertTrue("{\"message\":\"success\"}".equals(res)); }
### Question: Slug { public static String makeSlug(String input, boolean transliterate) { String origInput = input; String tempInputValue = ""; if (input == null) { ProjectLogger.log("Provided input value is null"); return input; } tempInputValue = input.trim(); tempInputValue = urlDecode(tempInputValue); if (transliterate) { String transliterated = transliterate(tempInputValue); tempInputValue = transliterated; } tempInputValue = WHITESPACE.matcher(tempInputValue).replaceAll("-"); tempInputValue = Normalizer.normalize(tempInputValue, Form.NFD); tempInputValue = NONLATIN.matcher(tempInputValue).replaceAll(""); tempInputValue = normalizeDashes(tempInputValue); validateResult(tempInputValue, origInput); return tempInputValue.toLowerCase(Locale.ENGLISH); } static String makeSlug(String input, boolean transliterate); static String transliterate(String input); static String urlDecode(String input); static String removeDuplicateChars(String text); static String normalizeDashes(String text); }### Answer: @Test public void createSlugWithNullValue() { String slug = Slug.makeSlug(null, true); Assert.assertEquals(null, slug); } @Test public void createSlug() { String val = "NTP@#Test"; String slug = Slug.makeSlug(val, true); Assert.assertEquals("ntptest", slug); }
### Question: Slug { public static String removeDuplicateChars(String text) { Set<Character> set = new LinkedHashSet<>(); StringBuilder ret = new StringBuilder(text.length()); if (text.length() == 0) { return ""; } for (int i = 0; i < text.length(); i++) { set.add(text.charAt(i)); } Iterator<Character> itr = set.iterator(); while (itr.hasNext()) { ret.append(itr.next()); } return ret.toString(); } static String makeSlug(String input, boolean transliterate); static String transliterate(String input); static String urlDecode(String input); static String removeDuplicateChars(String text); static String normalizeDashes(String text); }### Answer: @Test public void removeDuplicateChar() { String val = Slug.removeDuplicateChars("ntpntest"); Assert.assertEquals("ntpes", val); }
### Question: LogMaskServiceImpl implements DataMaskingService { public String maskEmail(String email) { if (email.indexOf("@") > 4) { return email.replaceAll("(^[^@]{4}|(?!^)\\G)[^@]", "$1*"); } else { return email.replaceAll("(^[^@]{2}|(?!^)\\G)[^@]", "$1*"); } } String maskEmail(String email); String maskPhone(String phone); }### Answer: @Test public void maskEmail() { HashMap<String, String> emailMaskExpectations = new HashMap<String, String>() { { put("[email protected]", "ab*@gmail.com"); put("[email protected]", "ab**@yahoo.com"); put("[email protected]", "abcd****@testmail.org"); } }; emailMaskExpectations.forEach( (email, expectedResult) -> { assertEquals(expectedResult, logMaskService.maskEmail(email)); }); } @Test public void maskEmail() { HashMap<String, String> emailMaskExpectations = new HashMap<String, String>(){ { put("[email protected]", "ab*@gmail.com"); put("[email protected]", "ab**@yahoo.com"); put("[email protected]", "abcd****@testmail.org"); } }; emailMaskExpectations.forEach((email, expectedResult) -> { assertEquals(expectedResult, logMaskService.maskEmail(email)); }); }
### Question: LogMaskServiceImpl implements DataMaskingService { public String maskPhone(String phone) { return phone.replaceAll("(^[^*]{9}|(?!^)\\G)[^*]", "$1*"); } String maskEmail(String email); String maskPhone(String phone); }### Answer: @Test public void maskPhone() { HashMap<String, String> phoneMaskExpectations = new HashMap<String, String>() { { put("0123456789", "012345678*"); put("123-456-789", "123-456-7**"); put("123", "123"); } }; phoneMaskExpectations.forEach( (phone, expectedResult) -> { assertEquals(expectedResult, logMaskService.maskPhone(phone)); }); } @Test public void maskPhone() { HashMap<String, String> phoneMaskExpectations = new HashMap<String, String>(){ { put("0123456789", "012345678*"); put("123-456-789", "123-456-7**"); put("123", "123"); } }; phoneMaskExpectations.forEach((phone, expectedResult) -> { assertEquals(expectedResult, logMaskService.maskPhone(phone)); }); }
### Question: ExcelFileUtil extends FileUtil { @SuppressWarnings({"resource", "unused"}) public File writeToFile(String fileName, List<List<Object>> dataValues) { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("Data"); FileOutputStream out = null; File file = null; int rownum = 0; for (Object key : dataValues) { Row row = sheet.createRow(rownum); List<Object> objArr = dataValues.get(rownum); int cellnum = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); if (obj instanceof String) { cell.setCellValue((String) obj); } else if (obj instanceof Integer) { cell.setCellValue((Integer) obj); } else if (obj instanceof List) { cell.setCellValue(getListValue(obj)); } else if (obj instanceof Double) { cell.setCellValue((Double) obj); } else { if (ProjectUtil.isNotNull(obj)) { cell.setCellValue(obj.toString()); } } } rownum++; } try { file = new File(fileName + ".xlsx"); out = new FileOutputStream(file); workbook.write(out); ProjectLogger.log("File " + fileName + " created successfully"); } catch (Exception e) { ProjectLogger.log(e.getMessage(), e); } finally { if (null != out) { try { out.close(); } catch (IOException e) { ProjectLogger.log(e.getMessage(), e); } } } return file; } @SuppressWarnings({"resource", "unused"}) File writeToFile(String fileName, List<List<Object>> dataValues); }### Answer: @Test public void testWriteToFile() { String fileName = "test"; List<List<Object>> data = new ArrayList<>(); List<Object> dataObjects = new ArrayList<>(); dataObjects.add("test1"); dataObjects.add(new ArrayList<>()); dataObjects.add(1); dataObjects.add(2.0D); data.add(dataObjects); ExcelFileUtil excelFileUtil = new ExcelFileUtil(); File file = excelFileUtil.writeToFile(fileName, data); String[] expectedFileName = StringUtils.split(file.getName(), '.'); Assert.assertEquals("test", expectedFileName[0]); Assert.assertEquals("xlsx", expectedFileName[1]); }
### Question: LocationDaoImpl implements LocationDao { public SearchDTO addSortBy(SearchDTO searchDtO) { if (MapUtils.isNotEmpty(searchDtO.getAdditionalProperties()) && searchDtO.getAdditionalProperties().containsKey(JsonKey.FILTERS) && searchDtO.getAdditionalProperties().get(JsonKey.FILTERS) instanceof Map && ((Map<String, Object>) searchDtO.getAdditionalProperties().get(JsonKey.FILTERS)) .containsKey(JsonKey.TYPE)) { if (MapUtils.isEmpty(searchDtO.getSortBy())) { logger.info("search:addSortBy added sort type name attribute."); searchDtO.getSortBy().put(JsonKey.NAME, DEFAULT_SORT_BY); } } return searchDtO; } @Override Response create(Location location, RequestContext context); @Override Response update(Location location, RequestContext context); @Override Response delete(String locationId, RequestContext context); @Override Response search(Map<String, Object> searchQueryMap, RequestContext context); @Override Response read(String locationId, RequestContext context); @Override Response getRecordByProperty(Map<String, Object> queryMap, RequestContext context); SearchDTO addSortBy(SearchDTO searchDtO); }### Answer: @Test public void addSortBySuccess() { LocationDaoImpl dao = new LocationDaoImpl(); SearchDTO searchDto = createSearchDtoObj(); searchDto = dao.addSortBy(searchDto); Assert.assertTrue(searchDto.getSortBy().size() == 1); } @Test public void sortByNotAddedInCaseFilterWontHaveTypeKey() { LocationDaoImpl dao = new LocationDaoImpl(); SearchDTO searchDto = createSearchDtoObj(); ((Map<String, Object>) searchDto.getAdditionalProperties().get(JsonKey.FILTERS)) .remove(JsonKey.TYPE); searchDto = dao.addSortBy(searchDto); Assert.assertTrue(searchDto.getSortBy().size() == 0); } @Test public void sortByNotAddedInCasePresent() { LocationDaoImpl dao = new LocationDaoImpl(); SearchDTO searchDto = createSearchDtoObj(); searchDto.getSortBy().put("some key", "DESC"); searchDto = dao.addSortBy(searchDto); Assert.assertTrue(searchDto.getSortBy().size() == 1); }
### Question: SystemSettingDaoImpl implements SystemSettingDao { @Override public Response write(SystemSetting systemSetting, RequestContext context) { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = mapper.convertValue(systemSetting, Map.class); Response response = cassandraOperation.upsertRecord(KEYSPACE_NAME, TABLE_NAME, map, context); response.put(JsonKey.ID, map.get(JsonKey.ID)); return response; } SystemSettingDaoImpl(CassandraOperation cassandraOperation); @Override Response write(SystemSetting systemSetting, RequestContext context); @Override SystemSetting readById(String id, RequestContext context); @Override SystemSetting readByField(String field, RequestContext context); List<SystemSetting> readAll(RequestContext context); }### Answer: @Test public void testSetSystemSettingSuccess() { PowerMockito.when( cassandraOperation.upsertRecord( Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(RequestContext.class))) .thenReturn(new Response()); boolean thrown = false; try { SystemSetting systemSetting = new SystemSetting(ROOT_ORG_ID, FIELD, VALUE); Response upsertResp = systemSettingDaoImpl.write(systemSetting, null); Assert.assertNotEquals(null, upsertResp); } catch (Exception e) { thrown = true; } Assert.assertEquals(false, thrown); }
### Question: SystemSettingDaoImpl implements SystemSettingDao { @Override public SystemSetting readByField(String field, RequestContext context) { Response response = cassandraOperation.getRecordsByIndexedProperty( KEYSPACE_NAME, TABLE_NAME, JsonKey.FIELD, field, context); List<Map<String, Object>> list = (List<Map<String, Object>>) response.get(JsonKey.RESPONSE); if (CollectionUtils.isEmpty(list)) { return null; } return getSystemSetting(list); } SystemSettingDaoImpl(CassandraOperation cassandraOperation); @Override Response write(SystemSetting systemSetting, RequestContext context); @Override SystemSetting readById(String id, RequestContext context); @Override SystemSetting readByField(String field, RequestContext context); List<SystemSetting> readAll(RequestContext context); }### Answer: @Test public void testReadSystemSettingSuccess() { PowerMockito.when( cassandraOperation.getRecordsByIndexedProperty( Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(RequestContext.class))) .thenReturn(getSystemSettingSuccessResponse(false)); SystemSetting systemSetting = systemSettingDaoImpl.readByField(ROOT_ORG_ID, null); Assert.assertTrue(null != systemSetting); } @Test public void testReadSystemSettingEmpty() { PowerMockito.when( cassandraOperation.getRecordsByIndexedProperty( Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.any(RequestContext.class))) .thenReturn(getSystemSettingSuccessResponse(true)); SystemSetting systemSetting = systemSettingDaoImpl.readByField(FIELD, null); Assert.assertTrue(null == systemSetting); }
### Question: SystemSettingDaoImpl implements SystemSettingDao { public List<SystemSetting> readAll(RequestContext context) { Response response = cassandraOperation.getAllRecords(KEYSPACE_NAME, TABLE_NAME, context); List<Map<String, Object>> list = (List<Map<String, Object>>) response.get(JsonKey.RESPONSE); List<SystemSetting> systemSettings = new ArrayList<>(); ObjectMapper mapper = new ObjectMapper(); list.forEach( map -> { SystemSetting systemSetting = mapper.convertValue(map, SystemSetting.class); systemSettings.add(systemSetting); }); return systemSettings; } SystemSettingDaoImpl(CassandraOperation cassandraOperation); @Override Response write(SystemSetting systemSetting, RequestContext context); @Override SystemSetting readById(String id, RequestContext context); @Override SystemSetting readByField(String field, RequestContext context); List<SystemSetting> readAll(RequestContext context); }### Answer: @Test public void testReadAllSystemSettingsSuccess() { PowerMockito.when( cassandraOperation.getAllRecords( Mockito.anyString(), Mockito.anyString(), Mockito.any(RequestContext.class))) .thenReturn(getSystemSettingSuccessResponse(false)); List<SystemSetting> result = systemSettingDaoImpl.readAll(null); Assert.assertTrue(null != result); } @Test public void testReadAllSystemSettingsEmpty() { PowerMockito.when( cassandraOperation.getAllRecords( Mockito.anyString(), Mockito.anyString(), Mockito.any(RequestContext.class))) .thenReturn(getSystemSettingSuccessResponse(true)); List<SystemSetting> result = systemSettingDaoImpl.readAll(null); Assert.assertTrue(null != result); }
### Question: UserOrgDaoImpl implements UserOrgDao { @Override public Response updateUserOrg(UserOrg userOrg, RequestContext context) { Map<String, Object> compositeKey = new LinkedHashMap<>(2); Map<String, Object> request = mapper.convertValue(userOrg, Map.class); compositeKey.put(JsonKey.USER_ID, request.remove(JsonKey.USER_ID)); compositeKey.put(JsonKey.ORGANISATION_ID, request.remove(JsonKey.ORGANISATION_ID)); return cassandraOperation.updateRecord( Util.KEY_SPACE_NAME, TABLE_NAME, request, compositeKey, context); } private UserOrgDaoImpl(); static UserOrgDao getInstance(); @Override Response updateUserOrg(UserOrg userOrg, RequestContext context); @Override Response createUserOrg(UserOrg userOrg, RequestContext context); }### Answer: @Test public void testupdateUserOrg() { Response response = new Response(); when(ServiceFactory.getInstance()).thenReturn(cassandraOperationImpl); when(cassandraOperationImpl.updateRecord( Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.anyMap(), Mockito.any())) .thenReturn(response); UserOrg userOrg = new UserOrg(); userOrg.setUserId("123-456-789"); userOrg.setOrganisationId("1234567890"); userOrg.setDeleted(true); UserOrgDao userOrgDao = UserOrgDaoImpl.getInstance(); Response res = userOrgDao.updateUserOrg(userOrg, null); Assert.assertNotNull(res); }
### Question: UserConsentActor extends BaseActor { private void updateUserConsent(Request request) { Map<String, Object> consent = (Map<String, Object>) request.getRequest().getOrDefault(JsonKey.CONSENT_BODY, new HashMap<String, Object>()); String userId = (String) consent.getOrDefault(JsonKey.USER_ID, ""); if(StringUtils.isEmpty(userId)){ userId = (String) request.getContext().get(JsonKey.REQUESTED_BY); } String managedFor = (String)request.getContext().get(JsonKey.MANAGED_FOR); if(StringUtils.isNotEmpty(managedFor)){ userId = managedFor; } consent.put(JsonKey.USER_ID,userId); userService.validateUserId(request, null, request.getRequestContext()); Map consentReq = constructConsentRequest(consent, request.getRequestContext()); userConsentService.updateConsent(consentReq, request.getRequestContext()); Response response = new Response(); Map consentResponse = new HashMap<String, Object>(); consentResponse.put(JsonKey.USER_ID, userId); response.put(JsonKey.CONSENT_BODY, consentResponse); response.put(JsonKey.MESSAGE, JsonKey.CONSENT_SUCCESS_MESSAGE); sender().tell(response, self()); Map<String, Object> targetObject = null; List<Map<String, Object>> correlatedObject = new ArrayList<>(); targetObject = TelemetryUtil.generateTargetObject( userId, TelemetryEnvKey.USER, JsonKey.UPDATE, null); TelemetryUtil.telemetryProcessingCall( consent, targetObject, correlatedObject, request.getContext()); } @Override void onReceive(Request request); }### Answer: @Test public void updateUserConsentTest() { TestKit probe = new TestKit(system); ActorRef subject = system.actorOf(props); when(cassandraOperation.getRecordsByProperties( Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(RequestContext.class))) .thenReturn(getSuccessResponse()); when(cassandraOperation.upsertRecord( Mockito.anyString(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(RequestContext.class))) .thenReturn(getSuccessResponse()); subject.tell(updateUserConsentRequest(), probe.getRef()); Response res = probe.expectMsgClass(duration("10 second"), Response.class); Assert.assertTrue(null != res && res.getResponseCode() == ResponseCode.OK); }
### Question: OrgExternalService { public String getOrgIdFromOrgExternalIdAndProvider( String externalId, String provider, RequestContext context) { Map<String, Object> dbRequestMap = new HashMap<>(); dbRequestMap.put(JsonKey.EXTERNAL_ID, externalId.toLowerCase()); dbRequestMap.put(JsonKey.PROVIDER, provider.toLowerCase()); Response response = getCassandraOperation() .getRecordsByCompositeKey(KEYSPACE_NAME, ORG_EXTERNAL_IDENTITY, dbRequestMap, context); List<Map<String, Object>> orgList = (List<Map<String, Object>>) response.getResult().get(JsonKey.RESPONSE); if (CollectionUtils.isNotEmpty(orgList)) { Map<String, Object> orgExternalMap = orgList.get(0); if (MapUtils.isNotEmpty(orgExternalMap)) { return (String) orgExternalMap.get(JsonKey.ORG_ID); } } return null; } String getOrgIdFromOrgExternalIdAndProvider( String externalId, String provider, RequestContext context); }### Answer: @Test public void testGetOrgIdFromOrgExtIdFailure() { try { Map<String, Object> dbRequestMap = new HashMap<>(); dbRequestMap.put(JsonKey.EXTERNAL_ID, "anyorgextid"); dbRequestMap.put(JsonKey.PROVIDER, "anyprovider"); Response response = new Response(); List<Map<String, Object>> orgList = new ArrayList<>(); Map<String, Object> map = new HashMap<>(); orgList.add(map); response.put(JsonKey.RESPONSE, orgList); when(cassandraOperation.getRecordsByCompositeKey( Util.KEY_SPACE_NAME, ORG_EXTERNAL_IDENTITY, dbRequestMap, null)) .thenReturn(response); String resp = orgExternalService.getOrgIdFromOrgExternalIdAndProvider( "anyOrgExtid", "anyprovider", null); Assert.assertEquals(null, resp); } catch (Exception e) { Assert.assertTrue(false); } } @Test public void testGetOrgIdFromOrgExtIdSuccess() { try { Map<String, Object> dbRequestMap = new HashMap<>(); dbRequestMap.put(JsonKey.EXTERNAL_ID, "orgextid"); dbRequestMap.put(JsonKey.PROVIDER, "provider"); Response response = new Response(); List<Map<String, Object>> orgList = new ArrayList<>(); Map<String, Object> map = new HashMap<>(); map.put(JsonKey.ORG_ID, "anyOrgId"); orgList.add(map); response.put(JsonKey.RESPONSE, orgList); when(cassandraOperation.getRecordsByCompositeKey( Util.KEY_SPACE_NAME, ORG_EXTERNAL_IDENTITY, dbRequestMap, null)) .thenReturn(response); String resp = orgExternalService.getOrgIdFromOrgExternalIdAndProvider("OrgExtid", "provider", null); Assert.assertEquals("anyOrgId", resp); } catch (Exception e) { Assert.assertTrue(false); } }
### Question: AdminUtilHandler { public static AdminUtilRequestPayload prepareAdminUtilPayload(List<AdminUtilRequestData> reqData){ AdminUtilRequestPayload adminUtilsReq = new AdminUtilRequestPayload(); adminUtilsReq.setId(JsonKey.EKSTEP_SIGNING_SIGN_PAYLOAD); adminUtilsReq.setVer(JsonKey.EKSTEP_SIGNING_SIGN_PAYLOAD_VER); adminUtilsReq.setTs(Calendar.getInstance().getTime().getTime()); adminUtilsReq.setParams(new AdminUtilParams()); adminUtilsReq.setRequest(new AdminUtilRequest(reqData)); return adminUtilsReq; } static AdminUtilRequestPayload prepareAdminUtilPayload(List<AdminUtilRequestData> reqData); static Map<String, Object> fetchEncryptedToken(AdminUtilRequestPayload reqObject); }### Answer: @Test public void testPrepareAdminUtilPayload(){ List<AdminUtilRequestData> reqData = new ArrayList<AdminUtilRequestData>(); reqData.add(new AdminUtilRequestData("parentId", "childId1")); reqData.add(new AdminUtilRequestData("parentId", "childId2")); AdminUtilRequestPayload payload = AdminUtilHandler.prepareAdminUtilPayload(reqData); assertEquals(2,payload.getRequest().getData().size()); }
### Question: AdminUtilHandler { public static Map<String, Object> fetchEncryptedToken(AdminUtilRequestPayload reqObject){ Map<String, Object> data = null; ObjectMapper mapper = new ObjectMapper(); try { String body = mapper.writeValueAsString(reqObject); ProjectLogger.log( "AdminUtilHandler :: fetchEncryptedToken: request payload" + body, LoggerEnum.DEBUG); Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); String response = HttpClientUtil.post( ProjectUtil.getConfigValue(JsonKey.ADMINUTIL_BASE_URL) + ProjectUtil.getConfigValue(JsonKey.ADMINUTIL_SIGN_ENDPOINT), body, headers); ProjectLogger.log( "AdminUtilHandler :: fetchEncryptedToken: response payload" + response, LoggerEnum.DEBUG); data = mapper.readValue(response, Map.class); if (MapUtils.isNotEmpty(data)) { data = (Map<String, Object>) data.get(JsonKey.RESULT); } } catch (IOException e) { ProjectLogger.log( "AdminUtilHandler:fetchEncryptedToken Exception occurred : " + e.getMessage(), e, null, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.unableToConnectToAdminUtil.getErrorCode(), ResponseCode.unableToConnectToAdminUtil.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } catch (Exception e) { ProjectLogger.log( "AdminUtilHandler:fetchEncryptedToken Exception occurred : " + e.getMessage(), e, null, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.unableToParseData.getErrorCode(), ResponseCode.unableToParseData.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } return data; } static AdminUtilRequestPayload prepareAdminUtilPayload(List<AdminUtilRequestData> reqData); static Map<String, Object> fetchEncryptedToken(AdminUtilRequestPayload reqObject); }### Answer: @Test public void testFetchEncryptedToken() throws IOException { List<AdminUtilRequestData> reqData = new ArrayList<AdminUtilRequestData>(); reqData.add(new AdminUtilRequestData("parentId", "childId1")); reqData.add(new AdminUtilRequestData("parentId", "childId2")); when(HttpClientUtil.post(Mockito.anyString(),Mockito.anyString(),Mockito.anyObject())).thenReturn("{\"id\": \"ekstep.api.am.adminutil.sign.payload\",\"ver\": \"1.0\",\"ets\":1591589862198,\"params\": {\"status\": \"successful\",\"err\": null,\"errmsg\": null,\"msgid\": \"\",\"resmsgid\": \"328749cb-45e3-4b26-aea6-b7f4b97d548b\"}, \"result\": {\"data\": [{\"parentId\": \"parentId\", \"sub\":\"childId1\",\"token\":\"encryptedtoken1\"},{\"parentId\": \"parentId\",\"sub\": \"childId2\",\"token\":\"encryptedtoken2\"}]}}"); Map<String, Object> encryptedTokenList = AdminUtilHandler.fetchEncryptedToken(AdminUtilHandler.prepareAdminUtilPayload(reqData)); ArrayList<Map<String, Object>> data = (ArrayList<Map<String, Object>>) encryptedTokenList.get(JsonKey.DATA); for (Object object : data) { Map<String, Object> tempMap = (Map<String, Object>) object; assertNotNull(tempMap.get(JsonKey.TOKEN)); } }
### Question: UserUtility { public static Map<String, Object> encryptUserData(Map<String, Object> userMap) throws Exception { return encryptSpecificUserData(userMap, userKeyToEncrypt); } private UserUtility(); static Map<String, Object> encryptUserData(Map<String, Object> userMap); @SuppressWarnings("unchecked") static Map<String, Object> encryptSpecificUserData( Map<String, Object> userMap, List<String> fieldsToEncrypt); static List<Map<String, Object>> encryptUserAddressData( List<Map<String, Object>> addressList); static Map<String, Object> decryptUserData(Map<String, Object> userMap); static Map<String, Object> decryptSpecificUserData( Map<String, Object> userMap, List<String> fieldsToDecrypt); static boolean isMasked(String data); static Map<String, Object> decryptUserDataFrmES(Map<String, Object> userMap); static List<Map<String, Object>> decryptUserAddressData( List<Map<String, Object>> addressList); static Map<String, Object> encryptUserSearchFilterQueryData(Map<String, Object> map); static String encryptData(String data); static String maskEmailOrPhone(String encryptedEmailOrPhone, String type); }### Answer: @Test public void encryptSpecificUserDataSuccess() { String email = "[email protected]"; String userName = "test_user"; String city = "Bangalore"; String addressLine1 = "xyz"; Map<String, Object> userMap = new HashMap<String, Object>(); userMap.put(JsonKey.FIRST_NAME, "test user"); userMap.put(JsonKey.EMAIL, email); userMap.put(JsonKey.USER_NAME, userName); List<Map<String, Object>> addressList = new ArrayList<Map<String, Object>>(); Map<String, Object> address = new HashMap<String, Object>(); address.put(JsonKey.COUNTRY, "India"); address.put(JsonKey.CITY, city); address.put(JsonKey.ADDRESS_LINE1, addressLine1); addressList.add(address); userMap.put(JsonKey.ADDRESS, addressList); Map<String, Object> response = null; try { response = UserUtility.encryptUserData(userMap); } catch (Exception e) { e.printStackTrace(); } assertEquals(userMap.get(JsonKey.FIRST_NAME), response.get(JsonKey.FIRST_NAME)); assertNotEquals(email, response.get(JsonKey.EMAIL)); assertNotEquals( "India", ((List<Map<String, Object>>) response.get(JsonKey.ADDRESS)).get(0).get(JsonKey.COUNTRY)); assertNotEquals( addressLine1, ((List<Map<String, Object>>) response.get(JsonKey.ADDRESS)) .get(0) .get(JsonKey.ADDRESS_LINE1)); }
### Question: UserUtility { public static List<Map<String, Object>> encryptUserAddressData( List<Map<String, Object>> addressList) throws Exception { EncryptionService service = ServiceFactory.getEncryptionServiceInstance(null); for (Map<String, Object> map : addressList) { for (String key : addressKeyToEncrypt) { if (map.containsKey(key)) { map.put(key, service.encryptData((String) map.get(key), null)); } } } return addressList; } private UserUtility(); static Map<String, Object> encryptUserData(Map<String, Object> userMap); @SuppressWarnings("unchecked") static Map<String, Object> encryptSpecificUserData( Map<String, Object> userMap, List<String> fieldsToEncrypt); static List<Map<String, Object>> encryptUserAddressData( List<Map<String, Object>> addressList); static Map<String, Object> decryptUserData(Map<String, Object> userMap); static Map<String, Object> decryptSpecificUserData( Map<String, Object> userMap, List<String> fieldsToDecrypt); static boolean isMasked(String data); static Map<String, Object> decryptUserDataFrmES(Map<String, Object> userMap); static List<Map<String, Object>> decryptUserAddressData( List<Map<String, Object>> addressList); static Map<String, Object> encryptUserSearchFilterQueryData(Map<String, Object> map); static String encryptData(String data); static String maskEmailOrPhone(String encryptedEmailOrPhone, String type); }### Answer: @Test public void encryptUserAddressDataSuccess() { String city = "Bangalore"; String addressLine1 = "xyz"; String state = "Karnataka"; List<Map<String, Object>> addressList = new ArrayList<Map<String, Object>>(); Map<String, Object> address = new HashMap<String, Object>(); address.put(JsonKey.COUNTRY, "India"); address.put(JsonKey.CITY, city); address.put(JsonKey.ADDRESS_LINE1, addressLine1); address.put(JsonKey.STATE, state); addressList.add(address); List<Map<String, Object>> response = null; try { response = UserUtility.encryptUserAddressData(addressList); } catch (Exception e) { e.printStackTrace(); } assertNotEquals("India", response.get(0).get(JsonKey.COUNTRY)); assertNotEquals(addressLine1, response.get(0).get(JsonKey.ADDRESS_LINE1)); assertNotEquals(state, response.get(0).get(JsonKey.STATE)); }
### Question: UserFlagUtil { public static int getFlagValue(String userFlagType, boolean flagEnabled) { int decimalValue = 0; if (userFlagType.equals(UserFlagEnum.PHONE_VERIFIED.getUserFlagType()) && flagEnabled) { decimalValue = UserFlagEnum.PHONE_VERIFIED.getUserFlagValue(); } else if (userFlagType.equals(UserFlagEnum.EMAIL_VERIFIED.getUserFlagType()) && flagEnabled) { decimalValue = UserFlagEnum.EMAIL_VERIFIED.getUserFlagValue(); } else if (userFlagType.equals(UserFlagEnum.STATE_VALIDATED.getUserFlagType()) && flagEnabled) { decimalValue = UserFlagEnum.STATE_VALIDATED.getUserFlagValue(); } return decimalValue; } static int getFlagValue(String userFlagType, boolean flagEnabled); static Map<String, Boolean> assignUserFlagValues(int flagsValue); }### Answer: @Test public void testGetFlagValue() { Assert.assertEquals( 2, UserFlagUtil.getFlagValue(UserFlagEnum.EMAIL_VERIFIED.getUserFlagType(), true)); Assert.assertEquals( 1, UserFlagUtil.getFlagValue(UserFlagEnum.PHONE_VERIFIED.getUserFlagType(), true)); Assert.assertEquals( 4, UserFlagUtil.getFlagValue(UserFlagEnum.STATE_VALIDATED.getUserFlagType(), true)); }
### Question: UserFlagUtil { public static Map<String, Boolean> assignUserFlagValues(int flagsValue) { Map<String, Boolean> userFlagMap = new HashMap<>(); setDefaultValues(userFlagMap); if ((flagsValue & UserFlagEnum.PHONE_VERIFIED.getUserFlagValue()) == UserFlagEnum.PHONE_VERIFIED.getUserFlagValue()) { userFlagMap.put(UserFlagEnum.PHONE_VERIFIED.getUserFlagType(), true); } if ((flagsValue & UserFlagEnum.EMAIL_VERIFIED.getUserFlagValue()) == UserFlagEnum.EMAIL_VERIFIED.getUserFlagValue()) { userFlagMap.put(UserFlagEnum.EMAIL_VERIFIED.getUserFlagType(), true); } if ((flagsValue & UserFlagEnum.STATE_VALIDATED.getUserFlagValue()) == UserFlagEnum.STATE_VALIDATED.getUserFlagValue()) { userFlagMap.put(UserFlagEnum.STATE_VALIDATED.getUserFlagType(), true); } return userFlagMap; } static int getFlagValue(String userFlagType, boolean flagEnabled); static Map<String, Boolean> assignUserFlagValues(int flagsValue); }### Answer: @Test public void testAssignUserFlagValues() { Map<String, Boolean> userFlagMap = UserFlagUtil.assignUserFlagValues(1); Assert.assertEquals(true, userFlagMap.get(JsonKey.PHONE_VERIFIED)); userFlagMap = UserFlagUtil.assignUserFlagValues(2); Assert.assertEquals(true, userFlagMap.get(JsonKey.EMAIL_VERIFIED)); userFlagMap = UserFlagUtil.assignUserFlagValues(4); Assert.assertEquals(true, userFlagMap.get(JsonKey.STATE_VALIDATED)); }
### Question: OTPUtil { private static String generateOTP() { String otpSize = ProjectUtil.getConfigValue(JsonKey.SUNBIRD_OTP_LENGTH); int codeDigits = StringUtils.isBlank(otpSize) ? MAXIMUM_OTP_LENGTH : Integer.valueOf(otpSize); GoogleAuthenticatorConfig config = new GoogleAuthenticatorConfig.GoogleAuthenticatorConfigBuilder() .setCodeDigits(codeDigits) .setKeyRepresentation(KeyRepresentation.BASE64) .build(); GoogleAuthenticator gAuth = new GoogleAuthenticator(config); GoogleAuthenticatorKey key = gAuth.createCredentials(); String secret = key.getKey(); int code = gAuth.getTotpPassword(secret); return String.valueOf(code); } private OTPUtil(); static String generateOtp(RequestContext context); static void sendOTPViaSMS(Map<String, Object> otpMap, RequestContext context); static String getEmailPhoneByUserId(String userId, String type, RequestContext context); static Request sendOTPViaEmail( Map<String, Object> emailTemplateMap, String otpType, RequestContext context); static Request sendOTPViaEmail( Map<String, Object> emailTemplateMap, RequestContext context); static String getOTPExpirationInMinutes(); }### Answer: @Test public void generateOtpTest() { for (int i = 0; i < 10000; i++) { String code = OTPUtil.generateOtp(null); Assert.assertTrue(code.length() >= 4); } }
### Question: RoleDaoImpl implements RoleDao { @SuppressWarnings("unchecked") @Override public List<Role> getRoles() { Response roleResults = getCassandraOperation().getAllRecords(Util.KEY_SPACE_NAME, TABLE_NAME, null); TypeReference<List<Role>> roleMapType = new TypeReference<List<Role>>() {}; List<Map<String, Object>> roleMapList = (List<Map<String, Object>>) roleResults.get(JsonKey.RESPONSE); List<Role> roleList = mapper.convertValue(roleMapList, roleMapType); return roleList; } static RoleDao getInstance(); @SuppressWarnings("unchecked") @Override List<Role> getRoles(); CassandraOperation getCassandraOperation(); }### Answer: @Test public void testGetRoles() { try { cassandraOperation = PowerMockito.mock(CassandraOperation.class); PowerMockito.mockStatic(ServiceFactory.class); when(ServiceFactory.getInstance()).thenReturn(cassandraOperation); when(cassandraOperation.getAllRecords(Util.KEY_SPACE_NAME, TABLE_NAME, null)) .thenReturn(response); List<Role> roleList = roleDao.getRoles(); Assert.assertEquals("TEACHER", roleList.get(0).getName()); } catch (Exception e) { Assert.assertTrue(false); } }
### Question: UserLookUp { public void checkEmailUniqueness(String email, RequestContext context) { if (StringUtils.isNotBlank(email)) { List<Map<String, Object>> userMapList = getEmailByType(email, context); if (CollectionUtils.isNotEmpty(userMapList)) { ProjectCommonException.throwClientErrorException(ResponseCode.emailAlreadyExistError, null); } } } Response insertRecords(List<Map<String, Object>> reqMap, RequestContext context); void deleteRecords(List<Map<String, String>> reqMap, RequestContext context); Response insertExternalIdIntoUserLookup( List<Map<String, Object>> reqMap, String userId, RequestContext context); List<Map<String, Object>> getRecordByType( String type, String value, boolean encrypt, RequestContext context); List<Map<String, Object>> getEmailByType(String email, RequestContext context); void checkEmailUniqueness(String email, RequestContext context); void checkEmailUniqueness(User user, String opType, RequestContext context); List<Map<String, Object>> getPhoneByType(String phone, RequestContext context); void checkPhoneUniqueness(String phone, RequestContext context); void checkPhoneUniqueness(User user, String opType, RequestContext context); boolean checkUsernameUniqueness( String username, boolean isEncrypted, RequestContext context); void checkExternalIdUniqueness(User user, String operation, RequestContext context); }### Answer: @Test public void checkEmailUniqueness() throws Exception { boolean response = false; try { new UserLookUp().checkEmailUniqueness("[email protected]", null); response = true; } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), 400); } assertFalse(response); } @Test public void checkEmailUniquenessWithOpType() throws Exception { User user = new User(); user.setEmail("[email protected]"); boolean response = false; try { new UserLookUp().checkEmailUniqueness(user, "create", null); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), 400); } assertFalse(response); }
### Question: EmailTemplateDaoImpl implements EmailTemplateDao { @Override public String getTemplate(String templateName, RequestContext context) { List<String> idList = new ArrayList<>(); if (StringUtils.isBlank(templateName)) { idList.add(DEFAULT_EMAIL_TEMPLATE_NAME); } else { idList.add(templateName); } Response response = getCassandraOperation() .getRecordsByPrimaryKeys( JsonKey.SUNBIRD, EMAIL_TEMPLATE, idList, JsonKey.NAME, context); List<Map<String, Object>> emailTemplateList = (List<Map<String, Object>>) response.get(JsonKey.RESPONSE); Map<String, Object> map = Collections.emptyMap(); if (CollectionUtils.isNotEmpty(emailTemplateList)) { map = emailTemplateList.get(0); } return (String) map.get(TEMPLATE); } static EmailTemplateDao getInstance(); @Override String getTemplate(String templateName, RequestContext context); }### Answer: @Test public void testGetTemplateWithBlankTemplateName() { List<String> idList = new ArrayList<>(); idList.add(DEFAULT_EMAIL_TEMPLATE_NAME); Response response = new Response(); List<Map<String, Object>> orgList = new ArrayList<>(); Map<String, Object> map = new HashMap<>(); orgList.add(map); response.put(JsonKey.RESPONSE, orgList); when(cassandraOperation.getRecordsByPrimaryKeys( JsonKey.SUNBIRD, EMAIL_TEMPLATE, idList, JsonKey.NAME, null)) .thenReturn(response); String resp = emailTemplateDao.getTemplate(StringUtils.EMPTY, null); Assert.assertEquals(null, resp); } @Test public void testGetTemplateWithTemplateName() { List<String> idList = new ArrayList<>(); idList.add("Sunbird_email_template"); Response response = new Response(); List<Map<String, Object>> orgList = new ArrayList<>(); Map<String, Object> map = new HashMap<>(); map.put(TEMPLATE, "Course is Been completed"); orgList.add(map); response.put(JsonKey.RESPONSE, orgList); when(cassandraOperation.getRecordsByPrimaryKeys( JsonKey.SUNBIRD, EMAIL_TEMPLATE, idList, JsonKey.NAME, null)) .thenReturn(response); String resp = emailTemplateDao.getTemplate("Sunbird_email_template", null); Assert.assertEquals("Course is Been completed", resp); }
### Question: EmailTemplateDaoImpl implements EmailTemplateDao { public static EmailTemplateDao getInstance() { if (emailTemplateDao == null) { emailTemplateDao = new EmailTemplateDaoImpl(); } return emailTemplateDao; } static EmailTemplateDao getInstance(); @Override String getTemplate(String templateName, RequestContext context); }### Answer: @Test public void testGetInstance() { Assert.assertEquals( emailTemplateDao.getClass().getSimpleName(), EmailTemplateDaoImpl.getInstance().getClass().getSimpleName()); }
### Question: OnDemandSchedulerManager extends SchedulerManager { public void triggerScheduler(String[] jobs) { String identifier = "NetOps-PC1502295457753"; for (String job : jobs) { switch (job) { case BULK_UPLOAD: case SHADOW_USER: scheduleOnDemand(identifier, job); break; default: ProjectLogger.log( "OnDemandSchedulerManager:triggerScheduler: There is no such job", LoggerEnum.INFO.name()); } } } OnDemandSchedulerManager(); void scheduleOnDemand(String identifier, String job); static OnDemandSchedulerManager getInstance(); void triggerScheduler(String[] jobs); static Map<String, String> schedulerMap; }### Answer: @Test public void testTriggerScheduler() throws SchedulerException { PowerMockito.suppress(PowerMockito.constructor(SchedulerManager.class)); PowerMockito.suppress(PowerMockito.methodsDeclaredIn(SchedulerManager.class)); scheduler = mock(Scheduler.class); PowerMockito.mockStatic(SchedulerManager.class); String[] jobs = {"shadowuser"}; onDemandSchedulerManager = spy(OnDemandSchedulerManager.class); when(scheduler.checkExists((JobKey) Mockito.anyObject())).thenReturn(false); onDemandSchedulerManager.triggerScheduler(jobs); verify(onDemandSchedulerManager).scheduleOnDemand(Mockito.anyString(), Mockito.anyString()); }
### Question: UserBulkUploadRequestValidator { public static void validateUserBulkUploadRequest(Map<String, Object> userMap) { validateUserType(userMap); validateOrganisationId(userMap); } private UserBulkUploadRequestValidator(); static void validateUserBulkUploadRequest(Map<String, Object> userMap); static void validateUserType(Map<String, Object> userMap); static void validateOrganisationId(Map<String, Object> userMap); }### Answer: @Test public void testValidateOrganisationIdWithMandatoryParamMissing() { Map<String, Object> userMap = new HashMap<>(); userMap.put(JsonKey.USER_TYPE, UserType.TEACHER.getTypeName()); try { UserBulkUploadRequestValidator.validateUserBulkUploadRequest(userMap); } catch (Exception e) { Assert.assertEquals("Mandatory parameter orgId or orgExternalId is missing.", e.getMessage()); } } @Test public void testValidateUserTypeWithMissingUserTypeParam() { Map<String, Object> userMap = new HashMap<>(); try { userMap.put(JsonKey.USER_TYPE, "invalid"); UserBulkUploadRequestValidator.validateUserBulkUploadRequest(userMap); } catch (Exception e) { Assert.assertEquals( "Invalid userType: invalid. Valid values are: [TEACHER, OTHER].", e.getMessage()); } } @Test public void testUserBulkRequestValidatorSuccess() { Map<String, Object> userMap = new HashMap<>(); try { userMap.put(JsonKey.USER_TYPE, UserType.TEACHER.getTypeName()); userMap.put(JsonKey.ORG_ID, "anyOrgId"); UserBulkUploadRequestValidator.validateUserBulkUploadRequest(userMap); } catch (Exception e) { System.out.println(e.getMessage()); Assert.assertTrue(false); } }
### Question: FeedUtil { public static Response saveFeed( ShadowUser shadowUser, List<String> userIds, RequestContext context) { return saveFeed(shadowUser, userIds.get(0), context); } static Response saveFeed( ShadowUser shadowUser, List<String> userIds, RequestContext context); static Response saveFeed(ShadowUser shadowUser, String userId, RequestContext context); }### Answer: @Test public void saveFeedInsertTest() { List<String> userIds = new ArrayList<>(); userIds.add("123-456-7890"); Response response = FeedUtil.saveFeed(getShadowUser(), userIds, null); Assert.assertNotNull(response); }
### Question: FeedServiceImpl implements IFeedService { @Override public Response insert(Feed feed, RequestContext context) { logger.info(context, "FeedServiceImpl:insert method called : "); Map<String, Object> feedData = feed.getData(); Map<String, Object> dbMap = mapper.convertValue(feed, Map.class); String feedId = ProjectUtil.generateUniqueId(); dbMap.put(JsonKey.ID, feedId); dbMap.put(JsonKey.CREATED_ON, new Timestamp(Calendar.getInstance().getTimeInMillis())); try { if (MapUtils.isNotEmpty(feed.getData())) { dbMap.put(JsonKey.FEED_DATA, mapper.writeValueAsString(feed.getData())); } } catch (Exception ex) { logger.error(context, "FeedServiceImpl:insert Exception occurred while mapping.", ex); } Response response = saveFeed(dbMap, context); dbMap.put(JsonKey.FEED_DATA, feedData); dbMap.put(JsonKey.CREATED_ON, Calendar.getInstance().getTimeInMillis()); getESInstance().save(ProjectUtil.EsType.userfeed.getTypeName(), feedId, dbMap, context); return response; } static CassandraOperation getCassandraInstance(); static ElasticSearchService getESInstance(); @Override Response insert(Feed feed, RequestContext context); @Override Response update(Feed feed, RequestContext context); @Override List<Feed> getRecordsByUserId(Map<String, Object> properties, RequestContext context); @Override Response search(SearchDTO searchDTO, RequestContext context); @Override void delete(String id, String userId, String category, RequestContext context); }### Answer: @Test public void testInsert() { Response res = feedService.insert(getFeed(false), null); Assert.assertTrue( ((String) res.getResult().get(JsonKey.RESPONSE)).equalsIgnoreCase(JsonKey.SUCCESS)); }
### Question: FeedServiceImpl implements IFeedService { @Override public Response update(Feed feed, RequestContext context) { logger.info(context, "FeedServiceImpl:update method called : "); Map<String, Object> feedData = feed.getData(); Map<String, Object> dbMap = mapper.convertValue(feed, Map.class); try { if (MapUtils.isNotEmpty(feed.getData())) { dbMap.put(JsonKey.FEED_DATA, mapper.writeValueAsString(feed.getData())); } } catch (Exception ex) { logger.error(context, "FeedServiceImpl:update Exception occurred while mapping.", ex); } dbMap.remove(JsonKey.CREATED_ON); dbMap.put(JsonKey.UPDATED_ON, new Timestamp(Calendar.getInstance().getTimeInMillis())); Response response = saveFeed(dbMap, context); dbMap.put(JsonKey.FEED_DATA, feedData); dbMap.put(JsonKey.UPDATED_ON, Calendar.getInstance().getTimeInMillis()); getESInstance().update(ProjectUtil.EsType.userfeed.getTypeName(), feed.getId(), dbMap, context); return response; } static CassandraOperation getCassandraInstance(); static ElasticSearchService getESInstance(); @Override Response insert(Feed feed, RequestContext context); @Override Response update(Feed feed, RequestContext context); @Override List<Feed> getRecordsByUserId(Map<String, Object> properties, RequestContext context); @Override Response search(SearchDTO searchDTO, RequestContext context); @Override void delete(String id, String userId, String category, RequestContext context); }### Answer: @Test public void testUpdate() { Response res = feedService.update(getFeed(true), null); Assert.assertTrue( ((String) res.getResult().get(JsonKey.RESPONSE)).equalsIgnoreCase(JsonKey.SUCCESS)); }
### Question: FeedServiceImpl implements IFeedService { @Override public void delete(String id, String userId, String category, RequestContext context) { logger.info(context, "FeedServiceImpl:delete method called for feedId : " + id); Map<String, String> compositeKey = new HashMap(); compositeKey.put("userid", userId); compositeKey.put("id", id); compositeKey.put("category", category); getCassandraInstance() .deleteRecord( usrFeedDbInfo.getKeySpace(), usrFeedDbInfo.getTableName(), compositeKey, context); getESInstance().delete(ProjectUtil.EsType.userfeed.getTypeName(), id, context); } static CassandraOperation getCassandraInstance(); static ElasticSearchService getESInstance(); @Override Response insert(Feed feed, RequestContext context); @Override Response update(Feed feed, RequestContext context); @Override List<Feed> getRecordsByUserId(Map<String, Object> properties, RequestContext context); @Override Response search(SearchDTO searchDTO, RequestContext context); @Override void delete(String id, String userId, String category, RequestContext context); }### Answer: @Test public void testDelete() { boolean response = false; try { feedService.delete("123-456-789", null, null, null); response = true; } catch (Exception ex) { Assert.assertTrue(response); } Assert.assertTrue(response); }
### Question: FeedServiceImpl implements IFeedService { @Override public List<Feed> getRecordsByUserId(Map<String, Object> properties, RequestContext context) { logger.info(context, "FeedServiceImpl:getRecordsByUserId method called : "); Response dbResponse = getCassandraInstance() .getRecordById( usrFeedDbInfo.getKeySpace(), usrFeedDbInfo.getTableName(), properties, context); List<Map<String, Object>> responseList = null; List<Feed> feedList = new ArrayList<>(); if (null != dbResponse && null != dbResponse.getResult()) { responseList = (List<Map<String, Object>>) dbResponse.getResult().get(JsonKey.RESPONSE); if (CollectionUtils.isNotEmpty(responseList)) { responseList.forEach( s -> { try { String data = (String) s.get(JsonKey.FEED_DATA); if (StringUtils.isNotBlank(data)) { s.put( JsonKey.FEED_DATA, mapper.readValue(data, new TypeReference<Map<String, Object>>() {})); } else { s.put(JsonKey.FEED_DATA, Collections.emptyMap()); } feedList.add(mapper.convertValue(s, Feed.class)); } catch (Exception ex) { logger.error( context, "FeedServiceImpl:getRecordsByUserId :Exception occurred while mapping feed data.", ex); } }); } } return feedList; } static CassandraOperation getCassandraInstance(); static ElasticSearchService getESInstance(); @Override Response insert(Feed feed, RequestContext context); @Override Response update(Feed feed, RequestContext context); @Override List<Feed> getRecordsByUserId(Map<String, Object> properties, RequestContext context); @Override Response search(SearchDTO searchDTO, RequestContext context); @Override void delete(String id, String userId, String category, RequestContext context); }### Answer: @Test public void testGetRecordsByProperties() { Map<String, Object> props = new HashMap<>(); props.put(JsonKey.USER_ID, "123-456-789"); List<Feed> res = feedService.getRecordsByUserId(props, null); Assert.assertTrue(res != null); }
### Question: FeedServiceImpl implements IFeedService { @Override public Response search(SearchDTO searchDTO, RequestContext context) { logger.info(context, "FeedServiceImpl:search method called : "); Future<Map<String, Object>> resultF = getESInstance().search(searchDTO, ProjectUtil.EsType.userfeed.getTypeName(), context); Map<String, Object> result = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(resultF); Response response = new Response(); response.put(JsonKey.RESPONSE, result); return response; } static CassandraOperation getCassandraInstance(); static ElasticSearchService getESInstance(); @Override Response insert(Feed feed, RequestContext context); @Override Response update(Feed feed, RequestContext context); @Override List<Feed> getRecordsByUserId(Map<String, Object> properties, RequestContext context); @Override Response search(SearchDTO searchDTO, RequestContext context); @Override void delete(String id, String userId, String category, RequestContext context); }### Answer: @Test public void testSearch() { Response response = feedService.search(search, null); when(ElasticSearchHelper.getResponseFromFuture(Mockito.any())).thenReturn(esResponse); PowerMockito.when(esUtil.search(search, ProjectUtil.EsType.userfeed.getTypeName(), null)) .thenReturn(promise.future()); Assert.assertTrue(esResponse != null); }
### Question: KeyManager { public static PublicKey loadPublicKey(String key) throws Exception { String publicKey = new String(key.getBytes(), StandardCharsets.UTF_8); publicKey = publicKey.replaceAll("(-+BEGIN PUBLIC KEY-+)", ""); publicKey = publicKey.replaceAll("(-+END PUBLIC KEY-+)", ""); publicKey = publicKey.replaceAll("[\\r\\n]+", ""); byte[] keyBytes = Base64Util.decode(publicKey.getBytes("UTF-8"), Base64Util.DEFAULT); X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePublic(X509publicKey); } static void init(); static KeyData getPublicKey(String keyId); static PublicKey loadPublicKey(String key); }### Answer: @Test public void testLoadPublicKey() throws Exception { PublicKey key = KeyManager.loadPublicKey( "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAysH/wWtg0IjBL1JZZDYvUJC42JCxVobalckr2/3d3eEiWkk7Zh/4DAPYOs4UPjAevTs5VMUjq9EZu/u4H5hNzoVmYNvhtxbhWNY3n4mxpA4Lgt4sNGiGYNNGrN34ML+7+TR3Z1dlrhA271PiuanHI11YymskQRPhBfuwK923Kl/lgI4rS9OQ4GnkvwkUPvMUIRfNt8wL9uTbWm3V9p8VTcmQbW+pPw9QhO9v95NOgXQrLnT8xwnzQE6UCTY2al3B0fc3ULmcxvK+7P1R3/0w1qJLEKSiHl0xnv4WNEfS+2UmN+8jfdSCfoyVIglQl5/tb05j89nfZZp8k24AWLxIJQIDAQAB"); assertNotNull(key); }
### Question: KeyManager { public static KeyData getPublicKey(String keyId) { return keyMap.get(keyId); } static void init(); static KeyData getPublicKey(String keyId); static PublicKey loadPublicKey(String key); }### Answer: @Test public void testGetPublicKey() { KeyData key = KeyManager.getPublicKey("keyId"); assertNull(key); }
### Question: EsClientFactory { private static ElasticSearchService getRestClient() { if (restClient == null) { synchronized (EsClientFactory.class) { if (restClient == null) { restClient = new ElasticSearchRestHighImpl(); } } } return restClient; } static ElasticSearchService getInstance(String type); }### Answer: @Test public void testGetRestClient() { ElasticSearchService service = EsClientFactory.getInstance("rest"); Assert.assertTrue(service instanceof ElasticSearchRestHighImpl); }
### Question: EsClientFactory { public static ElasticSearchService getInstance(String type) { if (JsonKey.REST.equals(type)) { return getRestClient(); } else { ProjectLogger.log( "EsClientFactory:getInstance: value for client type provided null ", LoggerEnum.ERROR); } return null; } static ElasticSearchService getInstance(String type); }### Answer: @Test public void testInstanceNull() { ElasticSearchService service = EsClientFactory.getInstance("test"); Assert.assertNull(service); }
### Question: ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<String> save( String index, String identifier, Map<String, Object> data, RequestContext context) { long startTime = System.currentTimeMillis(); Promise<String> promise = Futures.promise(); logger.info( context, "ElasticSearchUtilRest:save: method started at ==" + startTime + " for Index " + index); if (StringUtils.isBlank(identifier) || StringUtils.isBlank(index)) { logger.info( context, "ElasticSearchRestHighImpl:save: " + "Identifier or Index value is null or empty, identifier : " + "" + identifier + ",index: " + index + ",not able to save data."); 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) { logger.info( context, "ElasticSearchRestHighImpl:save: Success for index : " + index + ", identifier :" + identifier); promise.success(indexResponse.getId()); logger.info( context, "ElasticSearchRestHighImpl:save: method end at ==" + System.currentTimeMillis() + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime)); } @Override public void onFailure(Exception e) { promise.failure(e); logger.error( context, "ElasticSearchRestHighImpl:save: " + "Error while saving " + index + " id : " + identifier, e); logger.info( context, "ElasticSearchRestHighImpl:save: method end at ==" + System.currentTimeMillis() + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime)); } }; ConnectionManager.getRestClient().indexAsync(indexRequest, listener); return promise.future(); } @Override Future<String> save( String index, String identifier, Map<String, Object> data, RequestContext context); @Override Future<Boolean> update( String index, String identifier, Map<String, Object> data, RequestContext context); @Override Future<Map<String, Object>> getDataByIdentifier( String index, String identifier, RequestContext context); @Override Future<Boolean> delete(String index, String identifier, RequestContext context); @Override @SuppressWarnings({"unchecked", "rawtypes"}) Future<Map<String, Object>> search( SearchDTO searchDTO, String index, RequestContext context); @Override Future<Boolean> healthCheck(); @Override Future<Boolean> bulkInsert( String index, List<Map<String, Object>> dataList, RequestContext context); @Override Future<Boolean> upsert( String index, String identifier, Map<String, Object> data, RequestContext context); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds( List<String> ids, List<String> fields, String index, RequestContext context); }### Answer: @Test public void testSaveSuccess() { mockRulesForSave(false); Future<String> result = esService.save("test", "001", new HashMap<>(), null); String res = (String) ElasticSearchHelper.getResponseFromFuture(result); assertEquals("001", res); } @Test public void testSaveFailureWithEmptyIndex() { Future<String> result = esService.save("", "001", new HashMap<>(), null); String res = (String) ElasticSearchHelper.getResponseFromFuture(result); assertEquals("ERROR", res); } @Test public void testSaveFailureWithEmptyIdentifier() { Future<String> result = esService.save("test", "", new HashMap<>(), null); String res = (String) ElasticSearchHelper.getResponseFromFuture(result); assertEquals("ERROR", res); } @Test public void testSaveFailure() { mockRulesForSave(true); Future<String> result = esService.save("test", "001", new HashMap<>(), null); String res = (String) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(null, res); }
### Question: ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier( String index, String identifier, RequestContext context) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); if (StringUtils.isNotEmpty(identifier) && StringUtils.isNotEmpty(index)) { logger.info( context, "ElasticSearchRestHighImpl:getDataByIdentifier: method started at ==" + startTime + " for Index " + index); 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); logger.info( context, "ElasticSearchRestHighImpl:getDataByIdentifier: method end ==" + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime)); } else { promise.success(new HashMap<>()); } } else { promise.success(new HashMap<>()); } } @Override public void onFailure(Exception e) { logger.error( context, "ElasticSearchRestHighImpl:getDataByIdentifier: method Failed with error == ", e); promise.failure(e); } }; ConnectionManager.getRestClient().getAsync(getRequest, listener); } else { logger.info( context, "ElasticSearchRestHighImpl:getDataByIdentifier: " + "provided index or identifier is null, index = " + index + "," + " identifier = " + identifier); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @Override Future<String> save( String index, String identifier, Map<String, Object> data, RequestContext context); @Override Future<Boolean> update( String index, String identifier, Map<String, Object> data, RequestContext context); @Override Future<Map<String, Object>> getDataByIdentifier( String index, String identifier, RequestContext context); @Override Future<Boolean> delete(String index, String identifier, RequestContext context); @Override @SuppressWarnings({"unchecked", "rawtypes"}) Future<Map<String, Object>> search( SearchDTO searchDTO, String index, RequestContext context); @Override Future<Boolean> healthCheck(); @Override Future<Boolean> bulkInsert( String index, List<Map<String, Object>> dataList, RequestContext context); @Override Future<Boolean> upsert( String index, String identifier, Map<String, Object> data, RequestContext context); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds( List<String> ids, List<String> fields, String index, RequestContext context); }### Answer: @Test public void testGetDataByIdentifierFailureWithEmptyIndex() { try { esService.getDataByIdentifier("", "001", null); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } } @Test public void testGetDataByIdentifierFailureWithEmptyIdentifier() { try { esService.getDataByIdentifier("test", "", null); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } } @Test public void testGetDataByIdentifierFailure() { mockRulesForGet(true); Future<Map<String, Object>> result = esService.getDataByIdentifier("test", "001", null); Object res = ElasticSearchHelper.getResponseFromFuture(result); assertEquals(null, res); }
### Question: Email { public String getPassword() { return password; } Email(); Email(EmailConfig config); boolean sendMail(List<String> emailList, String subject, String body); boolean sendMail( List<String> emailList, String subject, String body, List<String> ccEmailList); void sendAttachment( List<String> emailList, String emailBody, String subject, String filePath); boolean sendEmail(String fromEmail, String subject, String body, List<String> bccList); String getHost(); String getPort(); String getUserName(); String getPassword(); String getFromEmail(); }### Answer: @Test public void passwordAuthTest() { PasswordAuthentication authentication = authenticator.getPasswordAuthentication(); Assert.assertEquals("test", authentication.getPassword()); }
### Question: ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<String> save(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); Promise<String> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:save: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); if (StringUtils.isBlank(identifier) || StringUtils.isBlank(index)) { ProjectLogger.log( "ElasticSearchTcpImpl:save: Identifier value is null or empty ,not able to save data.", LoggerEnum.ERROR.name()); promise.success("ERROR"); return promise.future(); } try { data.put("identifier", identifier); IndexResponse response = ConnectionManager.getClient().prepareIndex(index, _DOC, identifier).setSource(data).get(); ProjectLogger.log( "ElasticSearchTcpImpl:save: " + "Save value==" + response.getId() + " " + response.status(), LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchTcpImpl:save: method end at ==" + System.currentTimeMillis() + " for INdex " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getId()); return promise.future(); } catch (Exception e) { ProjectLogger.log( "ElasticSearchTcpImpl:save: Error while saving index " + index + " id : " + identifier + " with error :" + e, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchTcpImpl:save: method end at ==" + System.currentTimeMillis() + " for Index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(""); } return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds( List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); static final int WAIT_TIME; static Timeout timeout; }### Answer: @Test public void testSaveDataFailureWithoutIndexName() { Future<String> response = esService.save("", (String) chemistryMap.get("courseId"), chemistryMap); String result = (String) ElasticSearchHelper.getResponseFromFuture(response); assertEquals("ERROR", result); } @Test public void testCreateDataSuccess() { mockRulesForInsert(); esService.save(INDEX_NAME, (String) chemistryMap.get("courseId"), chemistryMap); assertNotNull(chemistryMap.get("courseId")); esService.save(INDEX_NAME, (String) physicsMap.get("courseId"), physicsMap); assertNotNull(physicsMap.get("courseId")); }
### Question: ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds( List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); static final int WAIT_TIME; static Timeout timeout; }### Answer: @Test public void testGetDataByIdentifierFailureByEmptyIdentifier() { Future<Map<String, Object>> responseMap = esService.getDataByIdentifier(INDEX_NAME, ""); Map<String, Object> response = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(responseMap); assertEquals(0, response.size()); } @Test public void testGetByIdentifierSuccess() { Future<Map<String, Object>> responseMapF = esService.getDataByIdentifier(INDEX_NAME, (String) chemistryMap.get("courseId")); Map<String, Object> responseMap = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(responseMapF); assertEquals(responseMap.get("courseId"), chemistryMap.get("courseId")); } @Test public void testGetByIdentifierFailureWithoutIndex() { try { esService.getDataByIdentifier(null, (String) chemistryMap.get("courseId")); } catch (ProjectCommonException ex) { assertEquals(ResponseCode.SERVER_ERROR.getResponseCode(), ex.getResponseCode()); } } @Test public void testGetByIdentifierFailureWithoutTypeAndIndexIdentifier() { try { esService.getDataByIdentifier(null, ""); } catch (ProjectCommonException ex) { assertEquals(ResponseCode.SERVER_ERROR.getResponseCode(), ex.getResponseCode()); } } @Test public void testGetDataByIdentifierFailureWithoutIdentifier() { Future<Map<String, Object>> responseMap = esService.getDataByIdentifier(INDEX_NAME, ""); Map<String, Object> map = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(responseMap); assertEquals(0, map.size()); }