method2testcases
stringlengths
118
6.63k
### Question: ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Boolean> delete(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Boolean> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:delete: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); DeleteResponse deleteResponse = null; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier)) { try { deleteResponse = ConnectionManager.getClient().prepareDelete(index, _DOC, identifier).get(); ProjectLogger.log( "ElasticSearchTcpImpl:delete: info ==" + deleteResponse.getResult().name() + " " + deleteResponse.getId(), LoggerEnum.INFO.name()); } catch (Exception e) { promise.failure(e); ProjectLogger.log( "ElasticSearchTcpImpl:delete: error occured for index and identifier == " + index + " and " + identifier + " with error " + e.getMessage(), e); } } else { ProjectLogger.log( "ElasticSearchTcpImpl:delete: Data can not be deleted due to invalid input.", LoggerEnum.INFO.name()); promise.success(false); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:delete: method end ==" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(deleteResponse.getResult().name().equalsIgnoreCase("DELETED")); 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 testRemoveDataSuccessByIdentifier() { Future<Boolean> response = esService.delete(INDEX_NAME, (String) chemistryMap.get("courseId")); boolean result = (boolean) ElasticSearchHelper.getResponseFromFuture(response); assertEquals(true, result); } @Test public void testRemoveDataFailureByIdentifierEmpty() { Future<Boolean> response = esService.delete(INDEX_NAME, ""); boolean result = (boolean) ElasticSearchHelper.getResponseFromFuture(response); assertEquals(false, result); }
### Question: JavaMigrationResolver implements MigrationResolver { ResolvedMigration extractMigrationInfo(JavaMigration javaMigration) { Integer checksum = null; if (javaMigration instanceof MigrationChecksumProvider) { MigrationChecksumProvider checksumProvider = (MigrationChecksumProvider) javaMigration; checksum = checksumProvider.getChecksum(); } MigrationVersion version; String description; if (javaMigration instanceof MigrationInfoProvider) { MigrationInfoProvider infoProvider = (MigrationInfoProvider) javaMigration; version = infoProvider.getVersion(); description = infoProvider.getDescription(); if (!StringUtils.hasText(description)) { throw new CassandraMigrationException("Missing description for migration " + version); } } else { Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription( ClassUtils.getShortName(javaMigration.getClass()), "V", "__", ""); version = info.getLeft(); description = info.getRight(); } String script = javaMigration.getClass().getName(); ResolvedMigration resolvedMigration = new ResolvedMigration(); resolvedMigration.setVersion(version); resolvedMigration.setDescription(description); resolvedMigration.setScript(script); resolvedMigration.setChecksum(checksum); resolvedMigration.setType(MigrationType.JAVA_DRIVER); return resolvedMigration; } JavaMigrationResolver(ClassLoader classLoader, ScriptsLocation location); List<ResolvedMigration> resolveMigrations(); }### Answer: @Test public void explicitInfo() { JavaMigrationResolver jdbcMigrationResolver = new JavaMigrationResolver(Thread.currentThread().getContextClassLoader(), null); ResolvedMigration migrationInfo = jdbcMigrationResolver.extractMigrationInfo(new Version3dot5()); assertEquals("3.5", migrationInfo.getVersion().toString()); assertEquals("Three Dot Five", migrationInfo.getDescription()); assertEquals(35, migrationInfo.getChecksum().intValue()); } @Test public void conventionOverConfiguration() { JavaMigrationResolver jdbcMigrationResolver = new JavaMigrationResolver(Thread.currentThread().getContextClassLoader(), null); ResolvedMigration migrationInfo = jdbcMigrationResolver.extractMigrationInfo(new V2__InterfaceBasedMigration()); assertEquals("2", migrationInfo.getVersion().toString()); assertEquals("InterfaceBasedMigration", migrationInfo.getDescription()); assertNull(migrationInfo.getChecksum()); }
### Question: ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Boolean> healthCheck() { Promise<Boolean> promise = Futures.promise(); boolean indexResponse = false; try { indexResponse = ConnectionManager.getClient() .admin() .indices() .exists(Requests.indicesExistsRequest(ProjectUtil.EsType.user.getTypeName())) .get() .isExists(); } catch (Exception e) { ProjectLogger.log("ElasticSearchTcpImpl:healthCheck: error " + e.getMessage(), e); promise.failure(e); } promise.success(indexResponse); 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 testHealthCheckSuccess() { Future<Boolean> response = esService.healthCheck(); boolean result = (boolean) ElasticSearchHelper.getResponseFromFuture(response); assertEquals(true, result); }
### Question: ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList) { Promise<Boolean> promise = Futures.promise(); long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchTcpImpl:bulkInsert: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); promise.success(true); try { BulkProcessor bulkProcessor = BulkProcessor.builder( ConnectionManager.getClient(), new BulkProcessor.Listener() { @Override public void beforeBulk(long executionId, BulkRequest request) {} @Override public void afterBulk( long executionId, BulkRequest request, BulkResponse response) { Iterator<BulkItemResponse> bulkResponse = response.iterator(); if (bulkResponse != null) { while (bulkResponse.hasNext()) { BulkItemResponse bResponse = bulkResponse.next(); ProjectLogger.log( "ElasticSearchTcpImpl:bulkInsert: " + "Bulk insert api response===" + bResponse.getId() + " " + bResponse.isFailed(), LoggerEnum.INFO.name()); } } } @Override public void afterBulk( long executionId, BulkRequest request, Throwable failure) { ProjectLogger.log( "ElasticSearchTcpImpl:bulkInsert: Bulk upload error block with error " + failure, LoggerEnum.INFO.name()); } }) .setBulkActions(10000) .setConcurrentRequests(0) .build(); for (Map<String, Object> map : dataList) { map.put(JsonKey.IDENTIFIER, map.get(JsonKey.ID)); IndexRequest request = new IndexRequest(index, _DOC, (String) map.get(JsonKey.IDENTIFIER)).source(map); bulkProcessor.add(request); } bulkProcessor.flush(); bulkProcessor.close(); ConnectionManager.getClient().admin().indices().prepareRefresh().get(); } catch (Exception e) { promise.success(false); ProjectLogger.log("ElasticSearchTcpImpl:bulkInsert: Bulk upload error " + e.getMessage(), e); } ProjectLogger.log( "ElasticSearchTcpImpl:bulkInsert: method end at ==" + System.currentTimeMillis() + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); 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 testBulkInsertDataSuccess() { Map<String, Object> data = new HashMap<String, Object>(); data.put("test1", "test"); data.put("test2", "manzarul"); List<Map<String, Object>> listOfMap = new ArrayList<Map<String, Object>>(); listOfMap.add(data); Future<Boolean> response = esService.bulkInsert(INDEX_NAME, listOfMap); boolean result = (boolean) ElasticSearchHelper.getResponseFromFuture(response); assertEquals(true, result); }
### Question: ConnectionManager { private static boolean initialiseConnection() { try { if (initialiseConnectionFromEnv()) { ProjectLogger.log("value found under system variable.", LoggerEnum.INFO.name()); return true; } return initialiseConnectionFromPropertiesFile(cluster, hostName, port); } catch (Exception e) { ProjectLogger.log("Error while initialising elastic search connection", e); return false; } } private ConnectionManager(); static TransportClient getClient(); static RestHighLevelClient getRestClient(); static boolean initialiseConnectionFromPropertiesFile( String cluster, String hostName, String port); static void closeClient(); static void registerShutDownHook(); }### Answer: @Test public void testInitialiseConnection() { TransportClient client = ConnectionManager.getClient(); Assert.assertNotNull(client); }
### Question: ConnectionManager { public static RestHighLevelClient getRestClient() { if (restClient == null) { ProjectLogger.log( "ConnectionManager:getRestClient eLastic search rest clinet is null " + client, LoggerEnum.INFO.name()); initialiseRestClientConnection(); ProjectLogger.log( "ConnectionManager:getRestClient after calling initialiseRestClientConnection ES client value " + client, LoggerEnum.INFO.name()); } return restClient; } private ConnectionManager(); static TransportClient getClient(); static RestHighLevelClient getRestClient(); static boolean initialiseConnectionFromPropertiesFile( String cluster, String hostName, String port); static void closeClient(); static void registerShutDownHook(); }### Answer: @Test public void testGetRestClientNull() { RestHighLevelClient client = ConnectionManager.getRestClient(); Assert.assertNull(client); }
### Question: ConnectionManager { public static boolean initialiseConnectionFromPropertiesFile( String cluster, String hostName, String port) { try { String[] splitedHost = hostName.split(","); for (String val : splitedHost) { host.add(val); } String[] splitedPort = port.split(","); for (String val : splitedPort) { ports.add(Integer.parseInt(val)); } boolean response = createClient(cluster, host); ProjectLogger.log( "ES Connection Established from Properties file Cluster " + cluster + " host " + hostName + " port " + port + " Response " + response, LoggerEnum.INFO.name()); } catch (Exception e) { ProjectLogger.log("Error while initialising connection From Properties File", e); return false; } return true; } private ConnectionManager(); static TransportClient getClient(); static RestHighLevelClient getRestClient(); static boolean initialiseConnectionFromPropertiesFile( String cluster, String hostName, String port); static void closeClient(); static void registerShutDownHook(); }### Answer: @Test @Ignore public void testInitialiseConnectionFromPropertiesFile() { boolean response = ConnectionManager.initialiseConnectionFromPropertiesFile("test", "localhost", "9200"); Assert.assertTrue(response); } @Test public void testInitialiseConnectionFromPropertiesFileFailWithEmpty() { boolean response = ConnectionManager.initialiseConnectionFromPropertiesFile("test", "localhost", ""); Assert.assertFalse(response); } @Test public void testInitialiseConnectionFromPropertiesFileFailWithNull() { boolean response = ConnectionManager.initialiseConnectionFromPropertiesFile("test", "localhost", null); Assert.assertFalse(response); }
### Question: ConnectionManager { public static void closeClient() { client.close(); } private ConnectionManager(); static TransportClient getClient(); static RestHighLevelClient getRestClient(); static boolean initialiseConnectionFromPropertiesFile( String cluster, String hostName, String port); static void closeClient(); static void registerShutDownHook(); }### Answer: @Test public void testCloseConnection () { ConnectionManager.closeClient(); Assert.assertTrue(true); }
### Question: CompositeMigrationResolver implements MigrationResolver { public List<ResolvedMigration> resolveMigrations() { if (availableMigrations == null) { availableMigrations = doFindAvailableMigrations(); } return availableMigrations; } CompositeMigrationResolver( ClassLoader classLoader, ScriptsLocations locations, String encoding, MigrationResolver... customMigrationResolvers); List<ResolvedMigration> resolveMigrations(); }### Answer: @Test public void resolveMigrationsMultipleLocations() { MigrationResolver migrationResolver = new CompositeMigrationResolver( Thread.currentThread().getContextClassLoader(), new ScriptsLocations( "migration/subdir/dir2", "migration.outoforder", "migration/subdir/dir1"), "UTF-8"); Collection<ResolvedMigration> migrations = migrationResolver.resolveMigrations(); List<ResolvedMigration> migrationList = new ArrayList<ResolvedMigration>(migrations); assertEquals(3, migrations.size()); assertEquals("First", migrationList.get(0).getDescription()); assertEquals("Late arrival", migrationList.get(1).getDescription()); assertEquals("Add contents table", migrationList.get(2).getDescription()); }
### 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) { ProjectLogger.log( "KeyCloakServiceImpl:getUsernameById: User not found for userId = " + userId + " error message = " + e.getMessage(), e); } ProjectLogger.log( "KeyCloakServiceImpl:getUsernameById: User not found for userId = " + userId, LoggerEnum.INFO.name()); return ""; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken); @Override boolean updatePassword(String userId, String password); @Override String updateUser(Map<String, Object> request); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request); @Override String deactivateUser(Map<String, Object> request); @Override String activateUser(Map<String, Object> request); @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); }### 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) { String userId = (String) request.get(JsonKey.USER_ID); makeUserActiveOrInactive(userId, false); return JsonKey.SUCCESS; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken); @Override boolean updatePassword(String userId, String password); @Override String updateUser(Map<String, Object> request); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request); @Override String deactivateUser(Map<String, Object> request); @Override String activateUser(Map<String, Object> request); @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); }### 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); }
### Question: KeyCloakServiceImpl implements SSOManager { @Override public String removeUser(Map<String, Object> request) { 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) { ProjectUtil.createAndThrowInvalidUserDataException(); } return JsonKey.SUCCESS; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken); @Override boolean updatePassword(String userId, String password); @Override String updateUser(Map<String, Object> request); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request); @Override String deactivateUser(Map<String, Object> request); @Override String activateUser(Map<String, Object> request); @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); }### 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); }
### 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) { ProjectLogger.log(e.getMessage(), e); response = false; } return response; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken); @Override boolean updatePassword(String userId, String password); @Override String updateUser(Map<String, Object> request); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request); @Override String deactivateUser(Map<String, Object> request); @Override String activateUser(Map<String, Object> request); @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); }### Answer: @Test public void testAddUserLoginTimeSuccess() { boolean response = keyCloakService.addUserLoginTime(userId.get(JsonKey.USER_ID)); Assert.assertEquals(true, response); }
### Question: CompositeMigrationResolver implements MigrationResolver { static Collection<ResolvedMigration> collectMigrations( Collection<MigrationResolver> migrationResolvers) { Set<ResolvedMigration> migrations = new HashSet<ResolvedMigration>(); for (MigrationResolver migrationResolver : migrationResolvers) { migrations.addAll(migrationResolver.resolveMigrations()); } return migrations; } CompositeMigrationResolver( ClassLoader classLoader, ScriptsLocations locations, String encoding, MigrationResolver... customMigrationResolvers); List<ResolvedMigration> resolveMigrations(); }### Answer: @Test public void collectMigrations() { MigrationResolver migrationResolver = new MigrationResolver() { public List<ResolvedMigration> resolveMigrations() { List<ResolvedMigration> migrations = new ArrayList<ResolvedMigration>(); migrations.add( createTestMigration( MigrationType.JAVA_DRIVER, "1", "Description", "Migration1", 123)); migrations.add( createTestMigration( MigrationType.JAVA_DRIVER, "1", "Description", "Migration1", 123)); migrations.add( createTestMigration(MigrationType.CQL, "2", "Description2", "Migration2", 1234)); return migrations; } }; Collection<MigrationResolver> migrationResolvers = new ArrayList<MigrationResolver>(); migrationResolvers.add(migrationResolver); Collection<ResolvedMigration> migrations = CompositeMigrationResolver.collectMigrations(migrationResolvers); assertEquals(2, migrations.size()); }
### 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) { ProjectLogger.log(e.getMessage(), e); } return lastLoginTime; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken); @Override boolean updatePassword(String userId, String password); @Override String updateUser(Map<String, Object> request); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request); @Override String deactivateUser(Map<String, Object> request); @Override String activateUser(Map<String, Object> request); @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); }### 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) { String userId = (String) request.get(JsonKey.USER_ID); makeUserActiveOrInactive(userId, true); return JsonKey.SUCCESS; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken); @Override boolean updatePassword(String userId, String password); @Override String updateUser(Map<String, Object> request); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request); @Override String deactivateUser(Map<String, Object> request); @Override String activateUser(Map<String, Object> request); @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); }### Answer: @Test public void testActivateUserFailureWithEmptyUserId() { Map<String, Object> reqMap = new HashMap<>(); reqMap.put(JsonKey.USER_ID, ""); try { keyCloakService.activateUser(reqMap); } 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); @Override boolean updatePassword(String userId, String password); @Override String updateUser(Map<String, Object> request); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request); @Override String deactivateUser(Map<String, Object> request); @Override String activateUser(Map<String, Object> request); @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); }### 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); @Override boolean updatePassword(String userId, String password); @Override String updateUser(Map<String, Object> request); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request); @Override String deactivateUser(Map<String, Object> request); @Override String activateUser(Map<String, Object> request); @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); }### Answer: @Test public void testSetEmailVerifiedSuccessWithVerifiedTrue() { String response = keyCloakService.setEmailVerifiedTrue(userId.get(JsonKey.USER_ID)); Assert.assertEquals(JsonKey.SUCCESS, response); }
### 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) { ProjectLogger.log(ex.getMessage(), ex); } return response; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken); @Override boolean updatePassword(String userId, String password); @Override String updateUser(Map<String, Object> request); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request); @Override String deactivateUser(Map<String, Object> request); @Override String activateUser(Map<String, Object> request); @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); }### 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); @Override boolean updatePassword(String userId, String password); @Override String updateUser(Map<String, Object> request); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request); @Override String deactivateUser(Map<String, Object> request); @Override String activateUser(Map<String, Object> request); @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); }### 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: CompositeMigrationResolver implements MigrationResolver { static void checkForIncompatibilities(List<ResolvedMigration> migrations) { for (int i = 0; i < migrations.size() - 1; i++) { ResolvedMigration current = migrations.get(i); ResolvedMigration next = migrations.get(i + 1); if (current.getVersion().compareTo(next.getVersion()) == 0) { throw new CassandraMigrationException( String.format( "Found more than one migration with version %s\nOffenders:\n-> %s (%s)\n-> %s (%s)", current.getVersion(), current.getPhysicalLocation(), current.getType(), next.getPhysicalLocation(), next.getType())); } } } CompositeMigrationResolver( ClassLoader classLoader, ScriptsLocations locations, String encoding, MigrationResolver... customMigrationResolvers); List<ResolvedMigration> resolveMigrations(); }### Answer: @Test public void checkForIncompatibilitiesMessage() { ResolvedMigration migration1 = createTestMigration(MigrationType.CQL, "1", "First", "V1__First.cql", 123); migration1.setPhysicalLocation("target/test-classes/migration/validate/V1__First.cql"); ResolvedMigration migration2 = createTestMigration(MigrationType.JAVA_DRIVER, "1", "Description", "Migration1", 123); migration2.setPhysicalLocation("Migration1"); List<ResolvedMigration> migrations = new ArrayList<ResolvedMigration>(); migrations.add(migration1); migrations.add(migration2); try { CompositeMigrationResolver.checkForIncompatibilities(migrations); } catch (CassandraMigrationException e) { assertTrue(e.getMessage().contains("target/test-classes/migration/validate/V1__First.cql")); assertTrue(e.getMessage().contains("Migration1")); } } @Test public void checkForIncompatibilitiesNoConflict() { List<ResolvedMigration> migrations = new ArrayList<ResolvedMigration>(); migrations.add( createTestMigration(MigrationType.JAVA_DRIVER, "1", "Description", "Migration1", 123)); migrations.add(createTestMigration(MigrationType.CQL, "2", "Description2", "Migration2", 1234)); CompositeMigrationResolver.checkForIncompatibilities(migrations); }
### Question: KeyCloakServiceImpl implements SSOManager { @Override public boolean updatePassword(String userId, String password) { 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) { ProjectLogger.log( "KeyCloakServiceImpl:updatePassword: Exception occurred with error message = " + e, LoggerEnum.ERROR.name()); } return false; } PublicKey getPublicKey(); @Override String verifyToken(String accessToken); @Override boolean updatePassword(String userId, String password); @Override String updateUser(Map<String, Object> request); @Override String syncUserData(Map<String, Object> request); @Override String removeUser(Map<String, Object> request); @Override String deactivateUser(Map<String, Object> request); @Override String activateUser(Map<String, Object> request); @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); }### Answer: @Test public void testUpdatePassword() throws Exception { boolean updated = keyCloakService.updatePassword(userId.get(JsonKey.USER_ID), "password"); Assert.assertTrue(updated); }
### 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(); @SuppressWarnings("unchecked") static void validateUpdateContent(Request contentRequestDto); static void validateGetPageData(Request request); static void validateAddBatchCourse(Request courseRequest); static void validateGetBatchCourse(Request courseRequest); static void validateUpdateCourse(Request request); static void validatePublishCourse(Request request); static void validateDeleteCourse(Request request); static void validateCreateSection(Request request); static void validateUpdateSection(Request request); static void validateCreatePage(Request request); static void validateUpdatepage(Request request); static void validateUploadUser(Map<String, Object> reqObj); static void validateCreateBatchReq(Request request); static void validateUpdateCourseBatchReq(Request request); static void validateEnrolmentType(String enrolmentType); static void validateSyncRequest(Request request); static void validateUpdateSystemSettingsRequest(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: MigrationInfoHelper { public static Pair<MigrationVersion, String> extractVersionAndDescription( String migrationName, String prefix, String separator, String suffix) { String cleanMigrationName = migrationName.substring(prefix.length(), migrationName.length() - suffix.length()); int descriptionPos = cleanMigrationName.indexOf(separator); if (descriptionPos < 0) { throw new CassandraMigrationException( "Wrong migration name format: " + migrationName + "(It should look like this: " + prefix + "1_2" + separator + "Description" + suffix + ")"); } String version = cleanMigrationName.substring(0, descriptionPos); String description = cleanMigrationName.substring(descriptionPos + separator.length()).replaceAll("_", " "); return Pair.of(MigrationVersion.fromVersion(version), description); } private MigrationInfoHelper(); static Pair<MigrationVersion, String> extractVersionAndDescription( String migrationName, String prefix, String separator, String suffix); }### Answer: @Test(expected = CassandraMigrationException.class) public void extractSchemaVersionNoDescription() { MigrationInfoHelper.extractVersionAndDescription("9_4", "", "__", ""); } @Test public void extractSchemaVersionDefaults() { Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription("V9_4__EmailAxel.cql", "V", "__", ".cql"); MigrationVersion version = info.getLeft(); String description = info.getRight(); assertEquals("9.4", version.toString()); assertEquals("EmailAxel", description); } @Test public void extractSchemaVersionCustomSeparator() { Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription("V9_4-EmailAxel.cql", "V", "-", ".cql"); MigrationVersion version = info.getLeft(); String description = info.getRight(); assertEquals("9.4", version.toString()); assertEquals("EmailAxel", description); } @Test public void extractSchemaVersionWithDescription() { Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription("9_4__EmailAxel", "", "__", ""); MigrationVersion version = info.getLeft(); String description = info.getRight(); assertEquals("9.4", version.toString()); assertEquals("EmailAxel", description); } @Test public void extractSchemaVersionWithDescriptionWithSpaces() { Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription("9_4__Big_jump", "", "__", ""); MigrationVersion version = info.getLeft(); String description = info.getRight(); assertEquals("9.4", version.toString()); assertEquals("Big jump", description); } @Test public void extractSchemaVersionWithLeadingZeroes() { Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription("009_4__EmailAxel", "", "__", ""); MigrationVersion version = info.getLeft(); String description = info.getRight(); assertEquals("009.4", version.toString()); assertEquals("EmailAxel", description); } @Test(expected = CassandraMigrationException.class) public void extractSchemaVersionWithLeadingUnderscore() { MigrationInfoHelper.extractVersionAndDescription("_8_0__Description", "", "__", ""); } @Test(expected = CassandraMigrationException.class) public void extractSchemaVersionWithLeadingUnderscoreAndPrefix() { MigrationInfoHelper.extractVersionAndDescription("V_8_0__Description.cql", "V", "__", ".cql"); } @Test public void extractSchemaVersionWithVUnderscorePrefix() { Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription( "V_8_0__Description.cql", "V_", "__", ".cql"); MigrationVersion version = info.getLeft(); String description = info.getRight(); assertEquals("8.0", version.toString()); assertEquals("Description", description); }
### Question: RequestValidator { public static void validateUpdateClientKey(String clientId, String masterAccessToken) { validateClientId(clientId); if (StringUtils.isBlank(masterAccessToken)) { throw createExceptionInstance(ResponseCode.invalidRequestData.getErrorCode()); } } private RequestValidator(); @SuppressWarnings("unchecked") static void validateUpdateContent(Request contentRequestDto); static void validateGetPageData(Request request); static void validateAddBatchCourse(Request courseRequest); static void validateGetBatchCourse(Request courseRequest); static void validateUpdateCourse(Request request); static void validatePublishCourse(Request request); static void validateDeleteCourse(Request request); static void validateCreateSection(Request request); static void validateUpdateSection(Request request); static void validateCreatePage(Request request); static void validateUpdatepage(Request request); static void validateUploadUser(Map<String, Object> reqObj); static void validateCreateBatchReq(Request request); static void validateUpdateCourseBatchReq(Request request); static void validateEnrolmentType(String enrolmentType); static void validateSyncRequest(Request request); static void validateUpdateSystemSettingsRequest(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(); @SuppressWarnings("unchecked") static void validateUpdateContent(Request contentRequestDto); static void validateGetPageData(Request request); static void validateAddBatchCourse(Request courseRequest); static void validateGetBatchCourse(Request courseRequest); static void validateUpdateCourse(Request request); static void validatePublishCourse(Request request); static void validateDeleteCourse(Request request); static void validateCreateSection(Request request); static void validateUpdateSection(Request request); static void validateCreatePage(Request request); static void validateUpdatepage(Request request); static void validateUploadUser(Map<String, Object> reqObj); static void validateCreateBatchReq(Request request); static void validateUpdateCourseBatchReq(Request request); static void validateEnrolmentType(String enrolmentType); static void validateSyncRequest(Request request); static void validateUpdateSystemSettingsRequest(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(); @SuppressWarnings("unchecked") static void validateUpdateContent(Request contentRequestDto); static void validateGetPageData(Request request); static void validateAddBatchCourse(Request courseRequest); static void validateGetBatchCourse(Request courseRequest); static void validateUpdateCourse(Request request); static void validatePublishCourse(Request request); static void validateDeleteCourse(Request request); static void validateCreateSection(Request request); static void validateUpdateSection(Request request); static void validateCreatePage(Request request); static void validateUpdatepage(Request request); static void validateUploadUser(Map<String, Object> reqObj); static void validateCreateBatchReq(Request request); static void validateUpdateCourseBatchReq(Request request); static void validateEnrolmentType(String enrolmentType); static void validateSyncRequest(Request request); static void validateUpdateSystemSettingsRequest(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 validateEnrolmentType(String enrolmentType) { if (StringUtils.isBlank(enrolmentType)) { throw new ProjectCommonException( ResponseCode.enrolmentTypeRequired.getErrorCode(), ResponseCode.enrolmentTypeRequired.getErrorMessage(), ERROR_CODE); } if (!(ProjectUtil.EnrolmentType.open.getVal().equalsIgnoreCase(enrolmentType) || ProjectUtil.EnrolmentType.inviteOnly.getVal().equalsIgnoreCase(enrolmentType))) { throw new ProjectCommonException( ResponseCode.enrolmentIncorrectValue.getErrorCode(), ResponseCode.enrolmentIncorrectValue.getErrorMessage(), ERROR_CODE); } } private RequestValidator(); @SuppressWarnings("unchecked") static void validateUpdateContent(Request contentRequestDto); static void validateGetPageData(Request request); static void validateAddBatchCourse(Request courseRequest); static void validateGetBatchCourse(Request courseRequest); static void validateUpdateCourse(Request request); static void validatePublishCourse(Request request); static void validateDeleteCourse(Request request); static void validateCreateSection(Request request); static void validateUpdateSection(Request request); static void validateCreatePage(Request request); static void validateUpdatepage(Request request); static void validateUploadUser(Map<String, Object> reqObj); static void validateCreateBatchReq(Request request); static void validateUpdateCourseBatchReq(Request request); static void validateEnrolmentType(String enrolmentType); static void validateSyncRequest(Request request); static void validateUpdateSystemSettingsRequest(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 testValidateEnrolmentTypeFailureWithEmptyType() { try { RequestValidator.validateEnrolmentType(""); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.enrolmentTypeRequired.getErrorCode(), e.getCode()); } } @Test public void testValidateEnrolmentTypeFailureWithWrongType() { try { RequestValidator.validateEnrolmentType("test"); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.enrolmentIncorrectValue.getErrorCode(), e.getCode()); } } @Test public void testValidateEnrolmentTypeSuccessWithOpenType() { boolean response = false; try { RequestValidator.validateEnrolmentType(ProjectUtil.EnrolmentType.open.getVal()); response = true; } catch (ProjectCommonException e) { Assert.assertNull(e); } Assert.assertTrue(response); } @Test public void testValidateEnrolmentTypeSuccessWithInviteType() { boolean response = false; try { RequestValidator.validateEnrolmentType(ProjectUtil.EnrolmentType.inviteOnly.getVal()); response = true; } catch (ProjectCommonException e) { Assert.assertNull(e); } Assert.assertTrue(response); }
### 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, JsonKey.BATCH, JsonKey.USER_COURSE })); if (!list.contains(request.getRequest().get(JsonKey.OBJECT_TYPE))) { throw new ProjectCommonException( ResponseCode.invalidObjectType.getErrorCode(), ResponseCode.invalidObjectType.getErrorMessage(), ERROR_CODE); } } } private RequestValidator(); @SuppressWarnings("unchecked") static void validateUpdateContent(Request contentRequestDto); static void validateGetPageData(Request request); static void validateAddBatchCourse(Request courseRequest); static void validateGetBatchCourse(Request courseRequest); static void validateUpdateCourse(Request request); static void validatePublishCourse(Request request); static void validateDeleteCourse(Request request); static void validateCreateSection(Request request); static void validateUpdateSection(Request request); static void validateCreatePage(Request request); static void validateUpdatepage(Request request); static void validateUploadUser(Map<String, Object> reqObj); static void validateCreateBatchReq(Request request); static void validateUpdateCourseBatchReq(Request request); static void validateEnrolmentType(String enrolmentType); static void validateSyncRequest(Request request); static void validateUpdateSystemSettingsRequest(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: 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(); @SuppressWarnings("unchecked") static void validateUpdateContent(Request contentRequestDto); static void validateGetPageData(Request request); static void validateAddBatchCourse(Request courseRequest); static void validateGetBatchCourse(Request courseRequest); static void validateUpdateCourse(Request request); static void validatePublishCourse(Request request); static void validateDeleteCourse(Request request); static void validateCreateSection(Request request); static void validateUpdateSection(Request request); static void validateCreatePage(Request request); static void validateUpdatepage(Request request); static void validateUploadUser(Map<String, Object> reqObj); static void validateCreateBatchReq(Request request); static void validateUpdateCourseBatchReq(Request request); static void validateEnrolmentType(String enrolmentType); static void validateSyncRequest(Request request); static void validateUpdateSystemSettingsRequest(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(); @SuppressWarnings("unchecked") static void validateUpdateContent(Request contentRequestDto); static void validateGetPageData(Request request); static void validateAddBatchCourse(Request courseRequest); static void validateGetBatchCourse(Request courseRequest); static void validateUpdateCourse(Request request); static void validatePublishCourse(Request request); static void validateDeleteCourse(Request request); static void validateCreateSection(Request request); static void validateUpdateSection(Request request); static void validateCreatePage(Request request); static void validateUpdatepage(Request request); static void validateUploadUser(Map<String, Object> reqObj); static void validateCreateBatchReq(Request request); static void validateUpdateCourseBatchReq(Request request); static void validateEnrolmentType(String enrolmentType); static void validateSyncRequest(Request request); static void validateUpdateSystemSettingsRequest(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(); @SuppressWarnings("unchecked") static void validateUpdateContent(Request contentRequestDto); static void validateGetPageData(Request request); static void validateAddBatchCourse(Request courseRequest); static void validateGetBatchCourse(Request courseRequest); static void validateUpdateCourse(Request request); static void validatePublishCourse(Request request); static void validateDeleteCourse(Request request); static void validateCreateSection(Request request); static void validateUpdateSection(Request request); static void validateCreatePage(Request request); static void validateUpdatepage(Request request); static void validateUploadUser(Map<String, Object> reqObj); static void validateCreateBatchReq(Request request); static void validateUpdateCourseBatchReq(Request request); static void validateEnrolmentType(String enrolmentType); static void validateSyncRequest(Request request); static void validateUpdateSystemSettingsRequest(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 validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); @SuppressWarnings("unchecked") void validateWebPages(Request request); 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); void validateBulkUserData(Request userRequest); @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); }### 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 validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); @SuppressWarnings("unchecked") void validateWebPages(Request request); 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); void validateBulkUserData(Request userRequest); @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); }### 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 validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); @SuppressWarnings("unchecked") void validateWebPages(Request request); 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); void validateBulkUserData(Request userRequest); @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); }### 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 validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); @SuppressWarnings("unchecked") void validateWebPages(Request request); 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); void validateBulkUserData(Request userRequest); @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); }### 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 validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); @SuppressWarnings("unchecked") void validateWebPages(Request request); 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); void validateBulkUserData(Request userRequest); @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); }### 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: Email { public boolean sendEmail(String fromEmail, String subject, String body, List<String> bccList) { boolean sentStatus = true; try { Session session = getSession(); MimeMessage message = new MimeMessage(session); addRecipient(message, Message.RecipientType.BCC, bccList); setMessageAttribute(message, fromEmail, subject, body); sentStatus = sendEmail(session, message); } catch (Exception e) { sentStatus = false; logger.error("SendMail:sendMail: Exception occurred with message = " + e.getMessage(), e); } return sentStatus; } 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 sendEmailTest() throws MessagingException { List<String> to = new ArrayList<String>(); to.add("[email protected]"); to.add("[email protected]"); emailService.sendEmail("[email protected]", subject, "Hi how are you", to); List<Message> inbox = Mailbox.get("[email protected]"); Assert.assertTrue(inbox.size() > 0); Assert.assertEquals(subject, inbox.get(0).getSubject()); } @Test public void sendEmailTOBCC() throws MessagingException{ List<String> bcc = new ArrayList<String>(); bcc.add("[email protected]"); emailService.sendEmail("[email protected]", subject, "Bcc email test body", bcc); List<Message> inbox = Mailbox.get("[email protected]"); Assert.assertTrue(inbox.size() > 0); Assert.assertEquals(subject, inbox.get(0).getSubject()); }
### 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 validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); @SuppressWarnings("unchecked") void validateWebPages(Request request); 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); void validateBulkUserData(Request userRequest); @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); }### 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: 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); validateAddressField(userRequest); validateJobProfileField(userRequest); validateEducationField(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 validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); @SuppressWarnings("unchecked") void validateWebPages(Request request); 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); void validateBulkUserData(Request userRequest); @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); }### 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 validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); @SuppressWarnings("unchecked") void validateWebPages(Request request); 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); void validateBulkUserData(Request userRequest); @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); }### 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 { @SuppressWarnings("unchecked") public void validateWebPages(Request request) { if (request.getRequest().containsKey(JsonKey.WEB_PAGES)) { List<Map<String, String>> data = (List<Map<String, String>>) request.getRequest().get(JsonKey.WEB_PAGES); if (null == data || data.isEmpty()) { ProjectCommonException.throwClientErrorException(ResponseCode.invalidWebPageData); } } } void validateCreateUserRequest(Request userRequest); static boolean isGoodPassword(String password); void validateUserCreateV3(Request userRequest); void validateCreateUserV3Request(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); @SuppressWarnings("unchecked") void validateWebPages(Request request); 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); void validateBulkUserData(Request userRequest); @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); }### Answer: @Test public void testValidateWebPagesFailureWithEmptyWebPages() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.WEB_PAGES, new ArrayList<>()); request.setRequest(requestObj); try { userRequestValidator.validateWebPages(request); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidWebPageData.getErrorCode(), e.getCode()); } } @Test public void testValidateWebPagesFailureWithNullWebPages() { Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.WEB_PAGES, null); request.setRequest(requestObj); try { userRequestValidator.validateWebPages(request); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidWebPageData.getErrorCode(), e.getCode()); } }
### 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 validateCreateUserV1Request(Request userRequest); void validateCreateUserV2Request(Request userRequest); void fieldsNotAllowed(List<String> fields, Request userRequest); void phoneValidation(Request userRequest); void createUserBasicValidation(Request userRequest); @SuppressWarnings("unchecked") void validateWebPages(Request request); 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); void validateBulkUserData(Request userRequest); @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); }### 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: CqlMigrationResolver implements MigrationResolver { public List<ResolvedMigration> resolveMigrations() { List<ResolvedMigration> migrations = new ArrayList<>(); Resource[] resources = scanner.scanForResources(location, CQL_MIGRATION_PREFIX, CQL_MIGRATION_SUFFIX); for (Resource resource : resources) { ResolvedMigration resolvedMigration = extractMigrationInfo(resource); resolvedMigration.setPhysicalLocation(resource.getLocationOnDisk()); resolvedMigration.setExecutor(new CqlMigrationExecutor(resource, encoding)); migrations.add(resolvedMigration); } Collections.sort(migrations, new ResolvedMigrationComparator()); return migrations; } CqlMigrationResolver(ClassLoader classLoader, ScriptsLocation location, String encoding); List<ResolvedMigration> resolveMigrations(); }### Answer: @Test public void resolveMigrations() { CqlMigrationResolver cqlMigrationResolver = new CqlMigrationResolver( Thread.currentThread().getContextClassLoader(), new ScriptsLocation("migration/subdir"), "UTF-8"); Collection<ResolvedMigration> migrations = cqlMigrationResolver.resolveMigrations(); assertEquals(3, migrations.size()); List<ResolvedMigration> migrationList = new ArrayList<ResolvedMigration>(migrations); assertEquals("1", migrationList.get(0).getVersion().toString()); assertEquals("1.1", migrationList.get(1).getVersion().toString()); assertEquals("2.0", migrationList.get(2).getVersion().toString()); assertEquals("dir1/V1__First.cql", migrationList.get(0).getScript()); assertEquals("V1_1__Populate_table.cql", migrationList.get(1).getScript()); assertEquals("dir2/V2_0__Add_contents_table.cql", migrationList.get(2).getScript()); } @Test(expected = CassandraMigrationException.class) public void resolveMigrationsNonExisting() { CqlMigrationResolver cqlMigrationResolver = new CqlMigrationResolver( Thread.currentThread().getContextClassLoader(), new ScriptsLocation("non/existing"), "UTF-8"); cqlMigrationResolver.resolveMigrations(); }
### 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 boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static double calculatePercentage(double score, double maxScore); static AssessmentResult calcualteAssessmentResult(double percentage); 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); 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 String createIndex(); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static Map convertJsonStringToMap(String jsonString); 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 Integer DEFAULT_BATCH_SIZE; static final long BACKGROUND_ACTOR_WAIT_TIME; static final String ELASTIC_DATE_FORMAT; static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; static final String[] defaultPrivateFields; }### 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 boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static double calculatePercentage(double score, double maxScore); static AssessmentResult calcualteAssessmentResult(double percentage); 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); 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 String createIndex(); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static Map convertJsonStringToMap(String jsonString); 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 Integer DEFAULT_BATCH_SIZE; static final long BACKGROUND_ACTOR_WAIT_TIME; static final String ELASTIC_DATE_FORMAT; static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; static final String[] defaultPrivateFields; }### 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 boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static double calculatePercentage(double score, double maxScore); static AssessmentResult calcualteAssessmentResult(double percentage); 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); 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 String createIndex(); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static Map convertJsonStringToMap(String jsonString); 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 Integer DEFAULT_BATCH_SIZE; static final long BACKGROUND_ACTOR_WAIT_TIME; static final String ELASTIC_DATE_FORMAT; static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; static final String[] defaultPrivateFields; }### 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 boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static double calculatePercentage(double score, double maxScore); static AssessmentResult calcualteAssessmentResult(double percentage); 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); 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 String createIndex(); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static Map convertJsonStringToMap(String jsonString); 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 Integer DEFAULT_BATCH_SIZE; static final long BACKGROUND_ACTOR_WAIT_TIME; static final String ELASTIC_DATE_FORMAT; static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; static final String[] defaultPrivateFields; }### 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 boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static double calculatePercentage(double score, double maxScore); static AssessmentResult calcualteAssessmentResult(double percentage); 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); 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 String createIndex(); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static Map convertJsonStringToMap(String jsonString); 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 Integer DEFAULT_BATCH_SIZE; static final long BACKGROUND_ACTOR_WAIT_TIME; static final String ELASTIC_DATE_FORMAT; static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; static final String[] defaultPrivateFields; }### 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 boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static double calculatePercentage(double score, double maxScore); static AssessmentResult calcualteAssessmentResult(double percentage); 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); 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 String createIndex(); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static Map convertJsonStringToMap(String jsonString); 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 Integer DEFAULT_BATCH_SIZE; static final long BACKGROUND_ACTOR_WAIT_TIME; static final String ELASTIC_DATE_FORMAT; static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; static final String[] defaultPrivateFields; }### 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 boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static double calculatePercentage(double score, double maxScore); static AssessmentResult calcualteAssessmentResult(double percentage); 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); 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 String createIndex(); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static Map convertJsonStringToMap(String jsonString); 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 Integer DEFAULT_BATCH_SIZE; static final long BACKGROUND_ACTOR_WAIT_TIME; static final String ELASTIC_DATE_FORMAT; static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; static final String[] defaultPrivateFields; }### 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: CqlMigrationResolver implements MigrationResolver { String extractScriptName(Resource resource) { if (location.getPath().isEmpty()) { return resource.getLocation(); } return resource.getLocation().substring(location.getPath().length() + 1); } CqlMigrationResolver(ClassLoader classLoader, ScriptsLocation location, String encoding); List<ResolvedMigration> resolveMigrations(); }### Answer: @Test public void extractScriptName() { CqlMigrationResolver cqlMigrationResolver = new CqlMigrationResolver( Thread.currentThread().getContextClassLoader(), new ScriptsLocation("db/migration"), "UTF-8"); assertEquals( "db_0__init.cql", cqlMigrationResolver.extractScriptName( new ClassPathResource( "db/migration/db_0__init.cql", Thread.currentThread().getContextClassLoader()))); } @Test public void extractScriptNameRootLocation() { CqlMigrationResolver cqlMigrationResolver = new CqlMigrationResolver( Thread.currentThread().getContextClassLoader(), new ScriptsLocation(""), "UTF-8"); assertEquals( "db_0__init.cql", cqlMigrationResolver.extractScriptName( new ClassPathResource( "db_0__init.cql", Thread.currentThread().getContextClassLoader()))); } @Test public void extractScriptNameFileSystemPrefix() { CqlMigrationResolver cqlMigrationResolver = new CqlMigrationResolver( Thread.currentThread().getContextClassLoader(), new ScriptsLocation("filesystem:/some/dir"), "UTF-8"); assertEquals( "V3.171__patch.cql", cqlMigrationResolver.extractScriptName( new FileSystemResource("/some/dir/V3.171__patch.cql"))); }
### 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 boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static double calculatePercentage(double score, double maxScore); static AssessmentResult calcualteAssessmentResult(double percentage); 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); 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 String createIndex(); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static Map convertJsonStringToMap(String jsonString); 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 Integer DEFAULT_BATCH_SIZE; static final long BACKGROUND_ACTOR_WAIT_TIME; static final String ELASTIC_DATE_FORMAT; static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; static final String[] defaultPrivateFields; }### 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 boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static double calculatePercentage(double score, double maxScore); static AssessmentResult calcualteAssessmentResult(double percentage); 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); 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 String createIndex(); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static Map convertJsonStringToMap(String jsonString); 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 Integer DEFAULT_BATCH_SIZE; static final long BACKGROUND_ACTOR_WAIT_TIME; static final String ELASTIC_DATE_FORMAT; static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; static final String[] defaultPrivateFields; }### 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 boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static double calculatePercentage(double score, double maxScore); static AssessmentResult calcualteAssessmentResult(double percentage); 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); 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 String createIndex(); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static Map convertJsonStringToMap(String jsonString); 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 Integer DEFAULT_BATCH_SIZE; static final long BACKGROUND_ACTOR_WAIT_TIME; static final String ELASTIC_DATE_FORMAT; static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; static final String[] defaultPrivateFields; }### 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 boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static double calculatePercentage(double score, double maxScore); static AssessmentResult calcualteAssessmentResult(double percentage); 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); 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 String createIndex(); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static Map convertJsonStringToMap(String jsonString); 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 Integer DEFAULT_BATCH_SIZE; static final long BACKGROUND_ACTOR_WAIT_TIME; static final String ELASTIC_DATE_FORMAT; static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; static final String[] defaultPrivateFields; }### 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 boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static double calculatePercentage(double score, double maxScore); static AssessmentResult calcualteAssessmentResult(double percentage); 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); 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 String createIndex(); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static Map convertJsonStringToMap(String jsonString); 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 Integer DEFAULT_BATCH_SIZE; static final long BACKGROUND_ACTOR_WAIT_TIME; static final String ELASTIC_DATE_FORMAT; static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; static final String[] defaultPrivateFields; }### Answer: @Test public void testValidateCountryCode() { boolean isValid = ProjectUtil.validateCountryCode("+91"); assertTrue(isValid); }
### Question: ProjectUtil { public static boolean validateUUID(String uuidStr) { try { UUID.fromString(uuidStr); return true; } catch (Exception ex) { return false; } } static boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); static String createAuthToken(String name, String source); static String getUniqueIdFromTimestamp(int environmentId); static synchronized String generateUniqueId(); static double calculatePercentage(double score, double maxScore); static AssessmentResult calcualteAssessmentResult(double percentage); 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); 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 String createIndex(); static boolean isNotEmptyStringArray(String[] strArray); static String convertMapToJsonString(List<Map<String, Object>> mapList); static void removeUnwantedFields(Map<String, Object> map, String... keys); static Map convertJsonStringToMap(String jsonString); 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 Integer DEFAULT_BATCH_SIZE; static final long BACKGROUND_ACTOR_WAIT_TIME; static final String ELASTIC_DATE_FORMAT; static final String YEAR_MONTH_DATE_FORMAT; static PropertiesCache propertiesCache; static final String[] excludes; static final String[] defaultPrivateFields; }### Answer: @Test public void testValidateUUID() { boolean isValid = ProjectUtil.validateUUID("1df03f56-ceba-4f2d-892c-2b1609e7b05f"); assertTrue(isValid); }
### Question: HttpUtil { public static String sendPostRequest( String requestURL, Map<String, String> params, Map<String, String> headers) throws IOException { long startTime = System.currentTimeMillis(); Map<String, Object> logInfo = genarateLogInfo(JsonKey.API_CALL, "API CALL : " + requestURL); HttpURLConnection httpURLConnection = postRequest(requestURL, params, headers, startTime); String str = getResponse(httpURLConnection); long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; telemetryProcessingCall(logInfo); ProjectLogger.log( "HttpUtil sendPostRequest method end at ==" + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return str; } private HttpUtil(); static String sendGetRequest(String requestURL, Map<String, String> headers); static HttpUtilResponse doGetRequest(String requestURL, Map<String, String> headers); static String sendPostRequest( String requestURL, Map<String, String> params, Map<String, String> headers); static HttpUtilResponse doPostRequest( String requestURL, Map<String, String> params, Map<String, String> headers); static String sendPostRequest( String requestURL, String params, Map<String, String> headers); static HttpUtilResponse doPostRequest( String requestURL, String params, Map<String, String> headers); static String sendPatchRequest( String requestURL, String params, Map<String, String> headers); static void telemetryProcessingCall(Map<String, Object> request); static HttpUtilResponse doPatchRequest( String requestURL, String params, Map<String, String> headers); static HttpUtilResponse postFormData( Map<String, String> reqData, Map<String, byte[]> fileData, Map<String, String> headers, String url); static HttpUtilResponse sendDeleteRequest(Map<String, String> headers, String url); static HttpUtilResponse sendDeleteRequest( Map<String, Object> reqBody, Map<String, String> headers, String url); static HttpUtilResponse postInputStream( byte[] byteArr, Map<String, String> headers, String url); static HttpUtilResponse sendDeleteRequest( String reqBody, Map<String, String> headers, String url); static Map<String, String> getHeader(Map<String, String> input); }### Answer: @Test public void testSendPostRequestSuccess() { Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "123456"); String url = "http: try { String response = HttpUtil.sendPostRequest(url, "{\"message\":\"success\"}", headers); assertTrue("{\"message\":\"success\"}".equals(response)); } catch (IOException e) { ProjectLogger.log(e.getMessage()); } }
### Question: HttpUtil { public static String sendGetRequest(String requestURL, Map<String, String> headers) throws IOException { long startTime = System.currentTimeMillis(); Map<String, Object> logInfo = genarateLogInfo(JsonKey.API_CALL, "API CALL : " + requestURL); HttpURLConnection httpURLConnection = getRequest(requestURL, headers, startTime); String str = getResponse(httpURLConnection); long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; telemetryProcessingCall(logInfo); ProjectLogger.log( "HttpUtil sendGetRequest method end at ==" + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return str; } private HttpUtil(); static String sendGetRequest(String requestURL, Map<String, String> headers); static HttpUtilResponse doGetRequest(String requestURL, Map<String, String> headers); static String sendPostRequest( String requestURL, Map<String, String> params, Map<String, String> headers); static HttpUtilResponse doPostRequest( String requestURL, Map<String, String> params, Map<String, String> headers); static String sendPostRequest( String requestURL, String params, Map<String, String> headers); static HttpUtilResponse doPostRequest( String requestURL, String params, Map<String, String> headers); static String sendPatchRequest( String requestURL, String params, Map<String, String> headers); static void telemetryProcessingCall(Map<String, Object> request); static HttpUtilResponse doPatchRequest( String requestURL, String params, Map<String, String> headers); static HttpUtilResponse postFormData( Map<String, String> reqData, Map<String, byte[]> fileData, Map<String, String> headers, String url); static HttpUtilResponse sendDeleteRequest(Map<String, String> headers, String url); static HttpUtilResponse sendDeleteRequest( Map<String, Object> reqBody, Map<String, String> headers, String url); static HttpUtilResponse postInputStream( byte[] byteArr, Map<String, String> headers, String url); static HttpUtilResponse sendDeleteRequest( String reqBody, Map<String, String> headers, String url); static Map<String, String> getHeader(Map<String, String> input); }### Answer: @Test public void testSendGetRequestSuccess() { Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "123456"); String urlString = "http: try { String response = HttpUtil.sendGetRequest(urlString, headers); assertTrue("{\"message\":\"success\"}".equals(response)); } catch (Exception e) { ProjectLogger.log(e.getMessage()); } }
### Question: MigrationVersion implements Comparable<MigrationVersion> { @Override public int compareTo(MigrationVersion o) { if (o == null) { return 1; } if (this == EMPTY) { return o == EMPTY ? 0 : Integer.MIN_VALUE; } if (this == CURRENT) { return o == CURRENT ? 0 : Integer.MIN_VALUE; } if (this == LATEST) { return o == LATEST ? 0 : Integer.MAX_VALUE; } if (o == EMPTY) { return Integer.MAX_VALUE; } if (o == CURRENT) { return Integer.MAX_VALUE; } if (o == LATEST) { return Integer.MIN_VALUE; } final List<BigInteger> elements1 = versionParts; final List<BigInteger> elements2 = o.versionParts; int largestNumberOfElements = Math.max(elements1.size(), elements2.size()); for (int i = 0; i < largestNumberOfElements; i++) { final int compared = getOrZero(elements1, i).compareTo(getOrZero(elements2, i)); if (compared != 0) { return compared; } } return 0; } MigrationVersion(BigInteger version, String displayText); private MigrationVersion(String version); static MigrationVersion fromVersion(String version); String getVersion(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(MigrationVersion o); String getTable(); static final MigrationVersion EMPTY; static final MigrationVersion LATEST; static final MigrationVersion CURRENT; }### Answer: @Test public void compareTo() { MigrationVersion v1 = MigrationVersion.fromVersion("1"); MigrationVersion v10 = MigrationVersion.fromVersion("1.0"); MigrationVersion v11 = MigrationVersion.fromVersion("1.1"); MigrationVersion v1100 = MigrationVersion.fromVersion("1.1.0.0"); MigrationVersion v1101 = MigrationVersion.fromVersion("1.1.0.1"); MigrationVersion v2 = MigrationVersion.fromVersion("2"); MigrationVersion v201004171859 = MigrationVersion.fromVersion("201004171859"); MigrationVersion v201004180000 = MigrationVersion.fromVersion("201004180000"); assertTrue(v1.compareTo(v10) == 0); assertTrue(v10.compareTo(v1) == 0); assertTrue(v1.compareTo(v11) < 0); assertTrue(v11.compareTo(v1) > 0); assertTrue(v11.compareTo(v1100) == 0); assertTrue(v1100.compareTo(v11) == 0); assertTrue(v11.compareTo(v1101) < 0); assertTrue(v1101.compareTo(v11) > 0); assertTrue(v1101.compareTo(v2) < 0); assertTrue(v2.compareTo(v1101) > 0); assertTrue(v201004171859.compareTo(v201004180000) < 0); assertTrue(v201004180000.compareTo(v201004171859) > 0); assertTrue(v2.compareTo(MigrationVersion.LATEST) < 0); assertTrue(MigrationVersion.LATEST.compareTo(v2) > 0); assertTrue(v201004180000.compareTo(MigrationVersion.LATEST) < 0); assertTrue(MigrationVersion.LATEST.compareTo(v201004180000) > 0); } @Test public void empty() { assertEquals(MigrationVersion.EMPTY, MigrationVersion.EMPTY); assertTrue(MigrationVersion.EMPTY.compareTo(MigrationVersion.EMPTY) == 0); } @Test public void latest() { assertEquals(MigrationVersion.LATEST, MigrationVersion.LATEST); assertTrue(MigrationVersion.LATEST.compareTo(MigrationVersion.LATEST) == 0); }
### Question: Email { public boolean sendMail(List<String> emailList, String subject, String body) { return sendMail(emailList, subject, body, null); } 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 sendEmailToMultipleUser() throws MessagingException { List<String> to = new ArrayList<String>(); to.add("[email protected]"); to.add("[email protected]"); emailService.sendMail(to, subject, "Test email body"); List<Message> inbox = Mailbox.get("[email protected]"); Assert.assertTrue(inbox.size() > 0); Assert.assertEquals(subject, inbox.get(0).getSubject()); } @Test public void sendEmailWithCCTest() throws MessagingException { List<String> emailList = new ArrayList<String>(); emailList.add("[email protected]"); emailList.add("[email protected]"); List<String> ccEmailList = new ArrayList<String>(); ccEmailList.add("[email protected]"); ccEmailList.add("[email protected]"); emailService.sendMail(emailList, subject, "Email body to do email test", ccEmailList); List<Message> inbox = Mailbox.get("[email protected]"); Assert.assertTrue(inbox.size() > 0); Assert.assertEquals(subject, inbox.get(0).getSubject()); }
### Question: HttpUtil { public static Map<String, String> getHeader(Map<String, String> input) throws Exception { return new HashMap<String, String>() {{ put("Content-Type", "application/json"); put(JsonKey.X_AUTHENTICATED_USER_TOKEN, KeycloakRequiredActionLinkUtil.getAdminAccessToken()); if(MapUtils.isNotEmpty(input)) putAll(input); }}; } private HttpUtil(); static String sendGetRequest(String requestURL, Map<String, String> headers); static HttpUtilResponse doGetRequest(String requestURL, Map<String, String> headers); static String sendPostRequest( String requestURL, Map<String, String> params, Map<String, String> headers); static HttpUtilResponse doPostRequest( String requestURL, Map<String, String> params, Map<String, String> headers); static String sendPostRequest( String requestURL, String params, Map<String, String> headers); static HttpUtilResponse doPostRequest( String requestURL, String params, Map<String, String> headers); static String sendPatchRequest( String requestURL, String params, Map<String, String> headers); static void telemetryProcessingCall(Map<String, Object> request); static HttpUtilResponse doPatchRequest( String requestURL, String params, Map<String, String> headers); static HttpUtilResponse postFormData( Map<String, String> reqData, Map<String, byte[]> fileData, Map<String, String> headers, String url); static HttpUtilResponse sendDeleteRequest(Map<String, String> headers, String url); static HttpUtilResponse sendDeleteRequest( Map<String, Object> reqBody, Map<String, String> headers, String url); static HttpUtilResponse postInputStream( byte[] byteArr, Map<String, String> headers, String url); static HttpUtilResponse sendDeleteRequest( String reqBody, Map<String, String> headers, String url); static Map<String, String> getHeader(Map<String, String> input); }### Answer: @Test public void testGetHeaderWithInput() throws Exception { PowerMockito.mockStatic(KeycloakRequiredActionLinkUtil.class); when(KeycloakRequiredActionLinkUtil.getAdminAccessToken()).thenReturn("testAuthToken"); Map<String, String> input = new HashMap<String, String>(){{ put("x-channel-id", "test-channel"); put("x-device-id", "test-device"); }}; Map<String, String> headers = HttpUtil.getHeader(input); assertTrue(!headers.isEmpty()); assertTrue(headers.size()==4); assertTrue(headers.containsKey("x-authenticated-user-token")); assertTrue(headers.containsKey("Content-Type")); assertTrue(headers.containsKey("x-channel-id")); assertTrue(headers.containsKey("x-device-id")); } @Test public void testGetHeaderWithoutInput() throws Exception { PowerMockito.mockStatic(KeycloakRequiredActionLinkUtil.class); when(KeycloakRequiredActionLinkUtil.getAdminAccessToken()).thenReturn("testAuthToken"); Map<String, String> headers = HttpUtil.getHeader(null); assertTrue(!headers.isEmpty()); assertTrue(headers.size()==2); assertTrue(headers.containsKey("x-authenticated-user-token")); assertTrue(headers.containsKey("Content-Type")); }
### Question: MigrationVersion implements Comparable<MigrationVersion> { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MigrationVersion version1 = (MigrationVersion) o; return compareTo(version1) == 0; } MigrationVersion(BigInteger version, String displayText); private MigrationVersion(String version); static MigrationVersion fromVersion(String version); String getVersion(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(MigrationVersion o); String getTable(); static final MigrationVersion EMPTY; static final MigrationVersion LATEST; static final MigrationVersion CURRENT; }### Answer: @Test public void testEquals() { final MigrationVersion a1 = MigrationVersion.fromVersion("1.2.3.3"); final MigrationVersion a2 = MigrationVersion.fromVersion("1.2.3.3"); assertTrue(a1.compareTo(a2) == 0); assertEquals(a1.hashCode(), a2.hashCode()); }
### Question: MigrationVersion implements Comparable<MigrationVersion> { public static MigrationVersion fromVersion(String version) { if ("current".equalsIgnoreCase(version)) return CURRENT; if (LATEST.getVersion().equals(version)) return LATEST; if (version == null) return EMPTY; return new MigrationVersion(version); } MigrationVersion(BigInteger version, String displayText); private MigrationVersion(String version); static MigrationVersion fromVersion(String version); String getVersion(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override int compareTo(MigrationVersion o); String getTable(); static final MigrationVersion EMPTY; static final MigrationVersion LATEST; static final MigrationVersion CURRENT; }### Answer: @Test(expected = CassandraMigrationException.class) public void missingNumber() { MigrationVersion.fromVersion("1..1"); } @Test(expected = CassandraMigrationException.class) public void dot() { MigrationVersion.fromVersion("."); } @Test(expected = CassandraMigrationException.class) public void startDot() { MigrationVersion.fromVersion(".1"); } @Test(expected = CassandraMigrationException.class) public void endDot() { MigrationVersion.fromVersion("1."); } @Test(expected = CassandraMigrationException.class) public void letters() { MigrationVersion.fromVersion("abc1.0"); } @Test(expected = CassandraMigrationException.class) public void dash() { MigrationVersion.fromVersion("1.2.1-3"); } @Test(expected = CassandraMigrationException.class) public void alphaNumeric() { MigrationVersion.fromVersion("1.2.1a-3"); }
### Question: MigrationInfo implements Comparable<MigrationInfo> { public String validate() { if (!context.pendingOrFuture && (resolvedMigration == null) && (appliedMigration.getType() != MigrationType.SCHEMA) && (appliedMigration.getType() != MigrationType.BASELINE)) { return "Detected applied migration not resolved locally: " + getVersion(); } if ((!context.pendingOrFuture && (MigrationState.PENDING == getState())) || (MigrationState.IGNORED == getState())) { return "Detected resolved migration not applied to database: " + getVersion(); } if (resolvedMigration != null && appliedMigration != null) { if (getVersion().compareTo(context.baseline) > 0) { if (resolvedMigration.getType() != appliedMigration.getType()) { return createMismatchMessage( "Type", appliedMigration.getVersion(), appliedMigration.getType(), resolvedMigration.getType()); } if (!ObjectUtils.nullSafeEquals( resolvedMigration.getChecksum(), appliedMigration.getChecksum())) { return createMismatchMessage( "Checksum", appliedMigration.getVersion(), appliedMigration.getChecksum(), resolvedMigration.getChecksum()); } if (!resolvedMigration.getDescription().equals(appliedMigration.getDescription())) { return createMismatchMessage( "Description", appliedMigration.getVersion(), appliedMigration.getDescription(), resolvedMigration.getDescription()); } } } return null; } MigrationInfo( ResolvedMigration resolvedMigration, AppliedMigration appliedMigration, MigrationInfoContext context); ResolvedMigration getResolvedMigration(); AppliedMigration getAppliedMigration(); MigrationType getType(); Integer getChecksum(); MigrationVersion getVersion(); String getDescription(); String getScript(); MigrationState getState(); Date getInstalledOn(); Integer getExecutionTime(); String validate(); @SuppressWarnings("NullableProblems") int compareTo(MigrationInfo o); @SuppressWarnings("SimplifiableIfStatement") @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void validate() { MigrationVersion version = MigrationVersion.fromVersion("1"); String description = "test"; String user = "testUser"; MigrationType type = MigrationType.CQL; ResolvedMigration resolvedMigration = new ResolvedMigration(); resolvedMigration.setVersion(version); resolvedMigration.setDescription(description); resolvedMigration.setType(type); resolvedMigration.setChecksum(456); AppliedMigration appliedMigration = new AppliedMigration(version, description, type, null, 123, user, 0, true); MigrationInfo migrationInfo = new MigrationInfo(resolvedMigration, appliedMigration, new MigrationInfoContext()); String message = migrationInfo.validate(); assertTrue(message.contains("123")); assertTrue(message.contains("456")); }
### Question: MigrationInfoDumper { public static String dumpToAsciiTable(final MigrationInfo[] migrationInfos) { int versionWidth = VERSION_TITLE.length(); int descriptionWidth = DESCRIPTION_TITLE.length(); for (MigrationInfo migrationInfo : migrationInfos) { versionWidth = Math.max(versionWidth, migrationInfo.getVersion().toString().length()); descriptionWidth = Math.max(descriptionWidth, migrationInfo.getDescription().length()); } String ruler = "+-" + StringUtils.trimOrPad("", versionWidth, '-') + "-+-" + StringUtils.trimOrPad("", descriptionWidth, '-') + "-+---------------------+---------+\n"; StringBuilder table = new StringBuilder(); table.append(ruler); table .append("| ") .append(StringUtils.trimOrPad(VERSION_TITLE, versionWidth, ' ')) .append(" | ") .append(StringUtils.trimOrPad(DESCRIPTION_TITLE, descriptionWidth)) .append(" | Installed on | State |\n"); table.append(ruler); if (migrationInfos.length == 0) { table .append(StringUtils.trimOrPad("| No migrations found", ruler.length() - 2, ' ')) .append("|\n"); } else { for (MigrationInfo migrationInfo : migrationInfos) { table .append("| ") .append(StringUtils.trimOrPad(migrationInfo.getVersion().toString(), versionWidth)); table .append(" | ") .append(StringUtils.trimOrPad(migrationInfo.getDescription(), descriptionWidth)); table .append(" | ") .append( StringUtils.trimOrPad( DateUtils.formatDateAsIsoString(migrationInfo.getInstalledOn()), 19)); table .append(" | ") .append(StringUtils.trimOrPad(migrationInfo.getState().getDisplayName(), 7)); table.append(" |\n"); } } table.append(ruler); return table.toString(); } private MigrationInfoDumper(); static String dumpToAsciiTable(final MigrationInfo[] migrationInfos); }### Answer: @Test public void dumpEmpty() { String table = MigrationInfoDumper.dumpToAsciiTable(new MigrationInfo[0]); String[] lines = StringUtils.tokenizeToStringArray(table, "\n"); assertEquals(5, lines.length); for (String line : lines) { assertEquals(lines[0].length(), line.length()); } } @Test public void dump2pending() { MigrationInfoService migrationInfoService = new MigrationInfoService( createMigrationResolver( createAvailableMigration("1"), createAvailableMigration("2.2014.09.11.55.45613")), createSchemaVersionDAO(), MigrationVersion.LATEST, false, true); migrationInfoService.refresh(); String table = MigrationInfoDumper.dumpToAsciiTable(migrationInfoService.all()); String[] lines = StringUtils.tokenizeToStringArray(table, "\n"); assertEquals(6, lines.length); for (String line : lines) { assertEquals(lines[0].length(), line.length()); } }
### Question: Keyspace { public String getName() { return name; } Keyspace(); Cluster getCluster(); void setCluster(Cluster cluster); String getName(); void setName(String name); }### Answer: @Test public void shouldDefaultToNoKeyspaceButCanBeOverridden() { assertThat(new Keyspace().getName(), is(nullValue())); System.setProperty(Keyspace.KeyspaceProperty.NAME.getName(), "myspace"); assertThat(new Keyspace().getName(), is("myspace")); }
### Question: Keyspace { public Cluster getCluster() { return cluster; } Keyspace(); Cluster getCluster(); void setCluster(Cluster cluster); String getName(); void setName(String name); }### Answer: @Test public void shouldHaveDefaultClusterObject() { assertThat(new Keyspace().getCluster(), is(notNullValue())); }
### Question: ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); }### Answer: @Test public void mergeLocations() { ScriptsLocations locations = new ScriptsLocations("db/locations", "db/files", "db/classes"); List<ScriptsLocation> locationList = locations.getLocations(); assertEquals(3, locationList.size()); Iterator<ScriptsLocation> iterator = locationList.iterator(); assertEquals("db/classes", iterator.next().getPath()); assertEquals("db/files", iterator.next().getPath()); assertEquals("db/locations", iterator.next().getPath()); } @Test public void mergeLocationsDuplicate() { ScriptsLocations locations = new ScriptsLocations("db/locations", "db/migration", "db/migration"); List<ScriptsLocation> locationList = locations.getLocations(); assertEquals(2, locationList.size()); Iterator<ScriptsLocation> iterator = locationList.iterator(); assertEquals("db/locations", iterator.next().getPath()); assertEquals("db/migration", iterator.next().getPath()); } @Test public void mergeLocationsOverlap() { ScriptsLocations locations = new ScriptsLocations("db/migration/oracle", "db/migration", "db/migration"); List<ScriptsLocation> locationList = locations.getLocations(); assertEquals(1, locationList.size()); assertEquals("db/migration", locationList.get(0).getPath()); } @Test public void mergeLocationsSimilarButNoOverlap() { ScriptsLocations locations = new ScriptsLocations("db/migration/oracle", "db/migration", "db/migrationtest"); List<ScriptsLocation> locationList = locations.getLocations(); assertEquals(2, locationList.size()); assertTrue(locationList.contains(new ScriptsLocation("db/migration"))); assertTrue(locationList.contains(new ScriptsLocation("db/migrationtest"))); } @Test public void mergeLocationsSimilarButNoOverlapCamelCase() { ScriptsLocations locations = new ScriptsLocations("/com/xxx/Star/", "/com/xxx/StarTrack/"); List<ScriptsLocation> locationList = locations.getLocations(); assertEquals(2, locationList.size()); assertTrue(locationList.contains(new ScriptsLocation("com/xxx/Star"))); assertTrue(locationList.contains(new ScriptsLocation("com/xxx/StarTrack"))); } @Test public void mergeLocationsSimilarButNoOverlapHyphen() { ScriptsLocations locations = new ScriptsLocations("db/migration/oracle", "db/migration", "db/migration-test"); List<ScriptsLocation> locationList = locations.getLocations(); assertEquals(2, locationList.size()); assertTrue(locationList.contains(new ScriptsLocation("db/migration"))); assertTrue(locationList.contains(new ScriptsLocation("db/migration-test"))); }
### Question: StringUtils { public static String trimOrPad(String str, int length) { return trimOrPad(str, length, ' '); } private StringUtils(); static String trimOrPad(String str, int length); static String trimOrPad(String str, int length, char padChar); static boolean isNumeric(String str); static String collapseWhitespace(String str); static String left(String str, int count); static String replaceAll(String str, String originalToken, String replacementToken); static boolean hasLength(String str); static String arrayToCommaDelimitedString(Object[] strings); static boolean hasText(String s); static String[] tokenizeToStringArray(String str, String delimiters); static int countOccurrencesOf(String str, String token); static String replace(String inString, String oldPattern, String newPattern); static String collectionToCommaDelimitedString(Collection<?> collection); static String collectionToDelimitedString(Collection<?> collection, String delimiter); static String trimLeadingWhitespace(String str); static String trimTrailingWhitespace(String str); }### Answer: @Test public void trimOrPad() { assertEquals("Hello World ", StringUtils.trimOrPad("Hello World", 15)); assertEquals("Hello Worl", StringUtils.trimOrPad("Hello World", 10)); assertEquals(" ", StringUtils.trimOrPad(null, 10)); }
### Question: StringUtils { public static boolean isNumeric(String str) { return str != null && str.matches("\\d*"); } private StringUtils(); static String trimOrPad(String str, int length); static String trimOrPad(String str, int length, char padChar); static boolean isNumeric(String str); static String collapseWhitespace(String str); static String left(String str, int count); static String replaceAll(String str, String originalToken, String replacementToken); static boolean hasLength(String str); static String arrayToCommaDelimitedString(Object[] strings); static boolean hasText(String s); static String[] tokenizeToStringArray(String str, String delimiters); static int countOccurrencesOf(String str, String token); static String replace(String inString, String oldPattern, String newPattern); static String collectionToCommaDelimitedString(Collection<?> collection); static String collectionToDelimitedString(Collection<?> collection, String delimiter); static String trimLeadingWhitespace(String str); static String trimTrailingWhitespace(String str); }### Answer: @Test public void isNumeric() { assertFalse(StringUtils.isNumeric(null)); assertTrue(StringUtils.isNumeric("")); assertFalse(StringUtils.isNumeric(" ")); assertTrue(StringUtils.isNumeric("123")); assertFalse(StringUtils.isNumeric("12 3")); assertFalse(StringUtils.isNumeric("ab2c")); assertFalse(StringUtils.isNumeric("12-3")); assertFalse(StringUtils.isNumeric("12.3")); }
### Question: StringUtils { public static String collapseWhitespace(String str) { return str.replaceAll("\\s+", " "); } private StringUtils(); static String trimOrPad(String str, int length); static String trimOrPad(String str, int length, char padChar); static boolean isNumeric(String str); static String collapseWhitespace(String str); static String left(String str, int count); static String replaceAll(String str, String originalToken, String replacementToken); static boolean hasLength(String str); static String arrayToCommaDelimitedString(Object[] strings); static boolean hasText(String s); static String[] tokenizeToStringArray(String str, String delimiters); static int countOccurrencesOf(String str, String token); static String replace(String inString, String oldPattern, String newPattern); static String collectionToCommaDelimitedString(Collection<?> collection); static String collectionToDelimitedString(Collection<?> collection, String delimiter); static String trimLeadingWhitespace(String str); static String trimTrailingWhitespace(String str); }### Answer: @Test public void collapseWhitespace() { assertEquals("", StringUtils.collapseWhitespace("")); assertEquals("abc", StringUtils.collapseWhitespace("abc")); assertEquals("a b", StringUtils.collapseWhitespace("a b")); assertEquals(" a ", StringUtils.collapseWhitespace(" a ")); assertEquals(" a ", StringUtils.collapseWhitespace(" a ")); assertEquals("a b", StringUtils.collapseWhitespace("a b")); assertEquals("a b c", StringUtils.collapseWhitespace("a b c")); assertEquals(" a b c ", StringUtils.collapseWhitespace(" a b c ")); }
### Question: StringUtils { public static String[] tokenizeToStringArray(String str, String delimiters) { if (str == null) { return null; } String[] tokens = str.split("[" + delimiters + "]"); for (int i = 0; i < tokens.length; i++) { tokens[i] = tokens[i].trim(); } return tokens; } private StringUtils(); static String trimOrPad(String str, int length); static String trimOrPad(String str, int length, char padChar); static boolean isNumeric(String str); static String collapseWhitespace(String str); static String left(String str, int count); static String replaceAll(String str, String originalToken, String replacementToken); static boolean hasLength(String str); static String arrayToCommaDelimitedString(Object[] strings); static boolean hasText(String s); static String[] tokenizeToStringArray(String str, String delimiters); static int countOccurrencesOf(String str, String token); static String replace(String inString, String oldPattern, String newPattern); static String collectionToCommaDelimitedString(Collection<?> collection); static String collectionToDelimitedString(Collection<?> collection, String delimiter); static String trimLeadingWhitespace(String str); static String trimTrailingWhitespace(String str); }### Answer: @Test public void tokenizeToStringArray() { assertArrayEquals(new String[] {"abc"}, StringUtils.tokenizeToStringArray("abc", ",")); assertArrayEquals( new String[] {"abc", "def"}, StringUtils.tokenizeToStringArray("abc,def", ",")); assertArrayEquals( new String[] {"abc", "def"}, StringUtils.tokenizeToStringArray(" abc ,def ", ",")); assertArrayEquals(new String[] {"", "abc"}, StringUtils.tokenizeToStringArray(",abc", ",")); assertArrayEquals(new String[] {"", "abc"}, StringUtils.tokenizeToStringArray(" , abc", ",")); }
### Question: ClassUtils { public static boolean isPresent(String className, ClassLoader classLoader) { try { classLoader.loadClass(className); return true; } catch (Throwable ex) { return false; } } private ClassUtils(); @SuppressWarnings({"unchecked"}) // Must be synchronized for the Maven Parallel Junit runner to work static synchronized T instantiate(String className, ClassLoader classLoader); static List<T> instantiateAll(String[] classes, ClassLoader classLoader); static boolean isPresent(String className, ClassLoader classLoader); static String getShortName(Class<?> aClass); static String getLocationOnDisk(Class<?> aClass); }### Answer: @Test public void isPresent() { assertTrue( ClassUtils.isPresent( "com.contrastsecurity.cassandra.migration.CassandraMigration", Thread.currentThread().getContextClassLoader())); } @Test public void isPresentNot() { assertFalse( ClassUtils.isPresent( "com.example.FakeClass", Thread.currentThread().getContextClassLoader())); }
### Question: FeatureDetector { public boolean isSlf4jAvailable() { if (slf4jAvailable == null) { slf4jAvailable = isPresent("org.slf4j.Logger", classLoader); } return slf4jAvailable; } FeatureDetector(ClassLoader classLoader); boolean isApacheCommonsLoggingAvailable(); boolean isSlf4jAvailable(); }### Answer: @Test public void shouldDetectSlf4j() { assertThat( new FeatureDetector(Thread.currentThread().getContextClassLoader()).isSlf4jAvailable(), is(true)); }
### Question: FeatureDetector { public boolean isApacheCommonsLoggingAvailable() { if (apacheCommonsLoggingAvailable == null) { apacheCommonsLoggingAvailable = isPresent("org.apache.commons.logging.Log", classLoader); } return apacheCommonsLoggingAvailable; } FeatureDetector(ClassLoader classLoader); boolean isApacheCommonsLoggingAvailable(); boolean isSlf4jAvailable(); }### Answer: @Test public void shouldDetectCommonsLogging() { assertThat( new FeatureDetector(Thread.currentThread().getContextClassLoader()) .isApacheCommonsLoggingAvailable(), is(true)); }
### Question: TimeFormat { public static String format(long millis) { return String.format( "%02d:%02d.%03ds", millis / 60000, (millis % 60000) / 1000, (millis % 1000)); } private TimeFormat(); static String format(long millis); }### Answer: @Test public void format() { assertEquals("00:00.001s", TimeFormat.format(1)); assertEquals("00:00.012s", TimeFormat.format(12)); assertEquals("00:00.123s", TimeFormat.format(123)); assertEquals("00:01.234s", TimeFormat.format(1234)); assertEquals("00:12.345s", TimeFormat.format(12345)); assertEquals("01:23.456s", TimeFormat.format(60000 + 23456)); assertEquals("12:34.567s", TimeFormat.format((60000 * 12) + 34567)); assertEquals("123:45.678s", TimeFormat.format((60000 * 123) + 45678)); }
### Question: Email { public void sendAttachment( List<String> emailList, String emailBody, String subject, String filePath) { try { Session session = getSession(); MimeMessage message = new MimeMessage(session); addRecipient(message, Message.RecipientType.TO, emailList); message.setSubject(subject); Multipart multipart = createMultipartData(emailBody, filePath); setMessageAttribute(message, fromEmail, subject, multipart); sendEmail(session, message); } catch (Exception e) { logger.error("Exception occured during email sending " + e, e); } } 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 sendEmailWithAttachmentTest() throws MessagingException { List<String> to = new ArrayList<String>(); to.add("[email protected]"); to.add("[email protected]"); emailService.sendAttachment(to, "Test email as attached.", subject, "emailtemplate.vm"); List<Message> inbox = Mailbox.get("[email protected]"); Assert.assertTrue(inbox.size() > 0); Assert.assertEquals(subject, inbox.get(0).getSubject()); }
### Question: FileSystemResource implements Resource, Comparable<FileSystemResource> { public String getFilename() { return location.getName(); } FileSystemResource(String location); String getLocation(); String getLocationOnDisk(); String loadAsString(String encoding); byte[] loadAsBytes(); String getFilename(); @SuppressWarnings("NullableProblems") int compareTo(FileSystemResource o); }### Answer: @Test public void getFilename() throws Exception { assertEquals("Mig777__Test.cql", new FileSystemResource("Mig777__Test.cql").getFilename()); assertEquals( "Mig777__Test.cql", new FileSystemResource("folder/Mig777__Test.cql").getFilename()); }
### Question: FileSystemResource implements Resource, Comparable<FileSystemResource> { public String getLocation() { return StringUtils.replaceAll(location.getPath(), "\\", "/"); } FileSystemResource(String location); String getLocation(); String getLocationOnDisk(); String loadAsString(String encoding); byte[] loadAsBytes(); String getFilename(); @SuppressWarnings("NullableProblems") int compareTo(FileSystemResource o); }### Answer: @Test public void getPath() throws Exception { assertEquals("Mig777__Test.cql", new FileSystemResource("Mig777__Test.cql").getLocation()); assertEquals( "folder/Mig777__Test.cql", new FileSystemResource("folder/Mig777__Test.cql").getLocation()); }
### Question: ClassPathResource implements Comparable<ClassPathResource>, Resource { public String getFilename() { return location.substring(location.lastIndexOf("/") + 1); } ClassPathResource(String location, ClassLoader classLoader); String getLocation(); String getLocationOnDisk(); String loadAsString(String encoding); byte[] loadAsBytes(); String getFilename(); boolean exists(); @SuppressWarnings({"RedundantIfStatement"}) @Override boolean equals(Object o); @Override int hashCode(); @SuppressWarnings("NullableProblems") int compareTo(ClassPathResource o); }### Answer: @Test public void getFilename() throws Exception { assertEquals( "Mig777__Test.cql", new ClassPathResource("Mig777__Test.cql", Thread.currentThread().getContextClassLoader()) .getFilename()); assertEquals( "Mig777__Test.cql", new ClassPathResource( "folder/Mig777__Test.cql", Thread.currentThread().getContextClassLoader()) .getFilename()); }
### Question: ClassPathResource implements Comparable<ClassPathResource>, Resource { public String loadAsString(String encoding) { try { InputStream inputStream = classLoader.getResourceAsStream(location); if (inputStream == null) { throw new CassandraMigrationException( "Unable to obtain inputstream for resource: " + location); } Reader reader = new InputStreamReader(inputStream, Charset.forName(encoding)); return FileCopyUtils.copyToString(reader); } catch (IOException e) { throw new CassandraMigrationException( "Unable to load resource: " + location + " (encoding: " + encoding + ")", e); } } ClassPathResource(String location, ClassLoader classLoader); String getLocation(); String getLocationOnDisk(); String loadAsString(String encoding); byte[] loadAsBytes(); String getFilename(); boolean exists(); @SuppressWarnings({"RedundantIfStatement"}) @Override boolean equals(Object o); @Override int hashCode(); @SuppressWarnings("NullableProblems") int compareTo(ClassPathResource o); }### Answer: @Test public void loadAsStringUtf8WithoutBOM() { assertEquals( "SELECT * FROM contents;", new ClassPathResource( "com/contrastsecurity/cassandra/migration/utils/scanner/classpath/utf8.nofilter", Thread.currentThread().getContextClassLoader()) .loadAsString("UTF-8")); } @Test public void loadAsStringUtf8WithBOM() { assertEquals( "SELECT * FROM contents;", new ClassPathResource( "com/contrastsecurity/cassandra/migration/utils/scanner/classpath/utf8bom.nofilter", Thread.currentThread().getContextClassLoader()) .loadAsString("UTF-8")); }
### Question: UrlUtils { public static String toFilePath(URL url) { try { String filePath = new File(URLDecoder.decode(url.getPath().replace("+", "%2b"), "UTF-8")).getAbsolutePath(); if (filePath.endsWith("/")) { return filePath.substring(0, filePath.length() - 1); } return filePath; } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Can never happen", e); } } private UrlUtils(); static String toFilePath(URL url); }### Answer: @Test public void toFilePath() throws MalformedURLException { File file = new File("/test dir/a+b"); assertEquals(file.getAbsolutePath(), UrlUtils.toFilePath(file.toURI().toURL())); }
### Question: EsClientFactory { private static ElasticSearchService getTcpClient() { if (tcpClient == null) { tcpClient = new ElasticSearchTcpImpl(); } return tcpClient; } static ElasticSearchService getInstance(String type); }### Answer: @Test public void testGetTcpClient() { ElasticSearchService service = EsClientFactory.getInstance("tcp"); Assert.assertTrue(service instanceof ElasticSearchTcpImpl); }
### Question: EsClientFactory { private static ElasticSearchService getRestClient() { 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.TCP.equals(type)) { return getTcpClient(); } else 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) { long startTime = System.currentTimeMillis(); Promise<String> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchUtilRest:save: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); if (StringUtils.isBlank(identifier) || StringUtils.isBlank(index)) { ProjectLogger.log( "ElasticSearchRestHighImpl:save: " + "Identifier or Index value is null or empty, identifier : " + "" + identifier + ",index: " + index + ",not able to save data.", LoggerEnum.INFO.name()); promise.success(ERROR); return promise.future(); } data.put("identifier", identifier); IndexRequest indexRequest = new IndexRequest(index, _DOC, identifier).source(data); ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() { @Override public void onResponse(IndexResponse indexResponse) { ProjectLogger.log( "ElasticSearchRestHighImpl:save: Success for index : " + index + ", identifier :" + identifier, LoggerEnum.INFO.name()); promise.success(indexResponse.getId()); ProjectLogger.log( "ElasticSearchRestHighImpl:save: method end at ==" + System.currentTimeMillis() + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { promise.failure(e); ProjectLogger.log( "ElasticSearchRestHighImpl:save: " + "Error while saving " + index + " id : " + identifier + " with error :" + e, LoggerEnum.ERROR.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:save: method end at ==" + System.currentTimeMillis() + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } }; ConnectionManager.getRestClient().indexAsync(indexRequest, listener); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> delete(String index, String identifier); @Override @SuppressWarnings({"unchecked", "rawtypes"}) Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Boolean> healthCheck(); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds( List<String> ids, List<String> fields, String index); }### Answer: @Test public void testSaveSuccess() { mockRulesForSave(false); Future<String> result = esService.save("test", "001", new HashMap<>()); String res = (String) ElasticSearchHelper.getResponseFromFuture(result); assertEquals("001", res); } @Test public void testSaveFailureWithEmptyIndex() { Future<String> result = esService.save("", "001", new HashMap<>()); String res = (String) ElasticSearchHelper.getResponseFromFuture(result); assertEquals("ERROR", res); } @Test public void testSaveFailureWithEmptyIdentifier() { Future<String> result = esService.save("test", "", new HashMap<>()); String res = (String) ElasticSearchHelper.getResponseFromFuture(result); assertEquals("ERROR", res); } @Test public void testSaveFailure() { mockRulesForSave(true); Future<String> result = esService.save("test", "001", new HashMap<>()); String res = (String) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(null, res); }
### Question: SmtpEMailServiceImpl implements IEmailService { @Override public boolean sendEmail(EmailRequest emailReq) { if (emailReq == null) { logger.info("Email request is null or empty:"); return false; } else if (CollectionUtils.isNotEmpty(emailReq.getBcc()) || emailReq.getTo().size() > 1) { return email.sendEmail( email.getFromEmail(), emailReq.getSubject(), emailReq.getBody(), CollectionUtils.isEmpty(emailReq.getBcc()) ? emailReq.getTo() : emailReq.getBcc()); } else if (CollectionUtils.isNotEmpty(emailReq.getCc())) { return email.sendMail( emailReq.getTo(), emailReq.getSubject(), emailReq.getBody(), emailReq.getCc()); } else { return email.sendMail(emailReq.getTo(), emailReq.getSubject(), emailReq.getBody()); } } SmtpEMailServiceImpl(); SmtpEMailServiceImpl(EmailConfig config); @Override boolean sendEmail(EmailRequest emailReq); }### Answer: @Test public void sendEmailFailure () { List<String> to = new ArrayList<String>(); Map<String,String> param = new HashMap<String, String>(); param.put("name", "test"); EmailRequest emailReq = new EmailRequest("testEmail", to, null, null, "emailtemplate", null, param); boolean response = service.sendEmail(emailReq); assertFalse(response); }
### Question: ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); if (StringUtils.isNotEmpty(identifier) && StringUtils.isNotEmpty(index)) { ProjectLogger.log( "ElasticSearchRestHighImpl:getDataByIdentifier: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); GetRequest getRequest = new GetRequest(index, _DOC, identifier); ActionListener<GetResponse> listener = new ActionListener<GetResponse>() { @Override public void onResponse(GetResponse getResponse) { if (getResponse.isExists()) { Map<String, Object> sourceAsMap = getResponse.getSourceAsMap(); if (MapUtils.isNotEmpty(sourceAsMap)) { promise.success(sourceAsMap); ProjectLogger.log( "ElasticSearchRestHighImpl:getDataByIdentifier: method end ==" + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } else { promise.success(new HashMap<>()); } } else { promise.success(new HashMap<>()); } } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:getDataByIdentifier: method Failed with error == " + e, LoggerEnum.INFO.name()); promise.failure(e); } }; ConnectionManager.getRestClient().getAsync(getRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:getDataByIdentifier: " + "provided index or identifier is null, index = " + index + "," + " identifier = " + identifier, LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> delete(String index, String identifier); @Override @SuppressWarnings({"unchecked", "rawtypes"}) Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Boolean> healthCheck(); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds( List<String> ids, List<String> fields, String index); }### Answer: @Test public void testGetDataByIdentifierFailureWithEmptyIndex() { try { esService.getDataByIdentifier("", "001"); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } } @Test public void testGetDataByIdentifierFailureWithEmptyIdentifier() { try { esService.getDataByIdentifier("test", ""); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } } @Test public void testGetDataByIdentifierFailure() { mockRulesForGet(true); Future<Map<String, Object>> result = esService.getDataByIdentifier("test", "001"); Object res = ElasticSearchHelper.getResponseFromFuture(result); assertEquals(null, res); }
### Question: JavaMigrationResolver implements MigrationResolver { public List<ResolvedMigration> resolveMigrations() { List<ResolvedMigration> migrations = new ArrayList<ResolvedMigration>(); if (!location.isClassPath()) { return migrations; } try { Class<?>[] classes = new Scanner(classLoader).scanForClasses(location, JavaMigration.class); for (Class<?> clazz : classes) { JavaMigration javaMigration = ClassUtils.instantiate(clazz.getName(), classLoader); ResolvedMigration migrationInfo = extractMigrationInfo(javaMigration); migrationInfo.setPhysicalLocation(ClassUtils.getLocationOnDisk(clazz)); migrationInfo.setExecutor(new JavaMigrationExecutor(javaMigration)); migrations.add(migrationInfo); } } catch (Exception e) { throw new CassandraMigrationException( "Unable to resolve Java migrations in location: " + location, e); } Collections.sort(migrations, new ResolvedMigrationComparator()); return migrations; } JavaMigrationResolver(ClassLoader classLoader, ScriptsLocation location); List<ResolvedMigration> resolveMigrations(); }### Answer: @Test(expected = CassandraMigrationException.class) public void broken() { new JavaMigrationResolver( Thread.currentThread().getContextClassLoader(), new ScriptsLocation("com/contrastsecurity/cassandra/migration/resolver/java/error")) .resolveMigrations(); } @Test public void resolveMigrations() { JavaMigrationResolver jdbcMigrationResolver = new JavaMigrationResolver( Thread.currentThread().getContextClassLoader(), new ScriptsLocation("com/contrastsecurity/cassandra/migration/resolver/java/dummy")); Collection<ResolvedMigration> migrations = jdbcMigrationResolver.resolveMigrations(); assertEquals(3, migrations.size()); List<ResolvedMigration> migrationList = new ArrayList<ResolvedMigration>(migrations); ResolvedMigration migrationInfo = migrationList.get(0); assertEquals("2", migrationInfo.getVersion().toString()); assertEquals("InterfaceBasedMigration", migrationInfo.getDescription()); assertNull(migrationInfo.getChecksum()); ResolvedMigration migrationInfo1 = migrationList.get(1); assertEquals("3.5", migrationInfo1.getVersion().toString()); assertEquals("Three Dot Five", migrationInfo1.getDescription()); assertEquals(35, migrationInfo1.getChecksum().intValue()); ResolvedMigration migrationInfo2 = migrationList.get(2); assertEquals("4", migrationInfo2.getVersion().toString()); }
### Question: ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<Boolean> delete(String index, String identifier) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:delete: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); if (StringUtils.isNotEmpty(identifier) && StringUtils.isNotEmpty(index)) { DeleteRequest delRequest = new DeleteRequest(index, _DOC, identifier); ActionListener<DeleteResponse> listener = new ActionListener<DeleteResponse>() { @Override public void onResponse(DeleteResponse deleteResponse) { if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) { ProjectLogger.log( "ElasticSearchRestHighImpl:delete:OnResponse: Document not found for index : " + index + " , identifier : " + identifier, LoggerEnum.INFO.name()); promise.success(false); } else { promise.success(true); } } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:delete: Async Failed due to error :" + e, LoggerEnum.INFO.name()); promise.failure(e); } }; ConnectionManager.getRestClient().deleteAsync(delRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:delete: " + "provided index or identifier is null, index = " + index + "," + " identifier = " + identifier, LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } ProjectLogger.log( "ElasticSearchRestHighImpl:delete: method end ==" + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> delete(String index, String identifier); @Override @SuppressWarnings({"unchecked", "rawtypes"}) Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Boolean> healthCheck(); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds( List<String> ids, List<String> fields, String index); }### Answer: @Test public void testDeleteSuccess() { mockRulesForDelete(false, false); Future<Boolean> result = esService.delete("test", "001"); boolean res = (boolean) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(true, res); } @Test public void testDeleteSuccessWithoutDelete() { mockRulesForDelete(false, true); Future<Boolean> result = esService.delete("test", "001"); boolean res = (boolean) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(false, res); } @Test public void testDeleteFailure() { mockRulesForDelete(true, false); Future<Boolean> result = esService.delete("test", "001"); Object res = ElasticSearchHelper.getResponseFromFuture(result); assertEquals(null, res); } @Test public void testDeleteFailureWithEmptyIdentifier() { try { esService.delete("test", ""); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } } @Test public void testDeleteFailureWithEmptyIndex() { try { esService.delete("", "001"); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } }
### Question: ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); BulkRequest request = new BulkRequest(); Promise<Boolean> promise = Futures.promise(); for (Map<String, Object> data : dataList) { request.add(new IndexRequest(index, _DOC, (String) data.get(JsonKey.ID)).source(data)); } ActionListener<BulkResponse> listener = new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkResponse) { Iterator<BulkItemResponse> responseItr = bulkResponse.iterator(); if (responseItr != null) { promise.success(true); while (responseItr.hasNext()) { BulkItemResponse bResponse = responseItr.next(); if (bResponse.isFailed()) { ProjectLogger.log( "ElasticSearchRestHighImpl:bulkinsert: api response===" + bResponse.getId() + " " + bResponse.getFailureMessage(), LoggerEnum.INFO.name()); } } } } @Override public void onFailure(Exception e) { ProjectLogger.log("ElasticSearchRestHighImpl:bulkinsert: Bulk upload error block", e); promise.success(false); } }; ConnectionManager.getRestClient().bulkAsync(request, listener); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method end ==" + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> delete(String index, String identifier); @Override @SuppressWarnings({"unchecked", "rawtypes"}) Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Boolean> healthCheck(); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds( List<String> ids, List<String> fields, String index); }### Answer: @Test public void testBuilInsertSuccess() { mockRulesForBulk(false); List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> map = new HashMap<>(); map.put(JsonKey.IDENTIFIER, "0001"); list.add(map); Future<Boolean> result = esService.bulkInsert("test", list); boolean res = (boolean) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(true, res); } @Test public void testBuilInsertFailure() { mockRulesForBulk(true); List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> map = new HashMap<>(); map.put(JsonKey.IDENTIFIER, "0001"); list.add(map); Future<Boolean> result = esService.bulkInsert("test", list); boolean res = (boolean) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(false, res); }
### Question: RDAPCLI { public static Type guessQueryType(String query) { try { if (query.matches("^\\d+$")) { return Type.AUTNUM; } if (query.matches("^[\\d\\.:/]+$")) { return Type.IP; } if (DomainName.of(query).getLevelSize() > 1) { return Type.DOMAIN; } return Type.ENTITY; } catch (IllegalArgumentException iae) { LOGGER.debug("Not a domain name, defaulting to entity", iae); return Type.ENTITY; } } private RDAPCLI(); static void main(String[] args); static Type guessQueryType(String query); }### Answer: @Test public void testGuess() { assertEquals(RDAPCLI.Type.AUTNUM,RDAPCLI.guessQueryType("12345")); assertEquals(RDAPCLI.Type.IP,RDAPCLI.guessQueryType("127.0.0.0/8")); assertEquals(RDAPCLI.Type.DOMAIN, RDAPCLI.guessQueryType("foo.example")); assertEquals(RDAPCLI.Type.ENTITY,RDAPCLI.guessQueryType("handle")); }
### Question: DomainName { public boolean isFQDN() { return labels.get(labels.size() - 1) instanceof Label.RootLabel; } DomainName(List<Label> labels); static DomainName of(String domainName); DomainName toFQDN(); boolean isFQDN(); int getLevelSize(); List<Label> getLabels(); Label getTLDLabel(); String getStringValue(); Label getLevel(int level); DomainName toLDH(); DomainName toUnicode(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testIsFQDN() { assertFalse(DomainName.of("www.example.com").isFQDN()); assertTrue(DomainName.of("www.example.com.").isFQDN()); }
### Question: DomainName { public DomainName toFQDN() { if (isFQDN()) { return this; } return new DomainName(new ImmutableList.Builder<Label>().addAll(labels).add(Label.RootLabel.getInstance()).build()); } DomainName(List<Label> labels); static DomainName of(String domainName); DomainName toFQDN(); boolean isFQDN(); int getLevelSize(); List<Label> getLabels(); Label getTLDLabel(); String getStringValue(); Label getLevel(int level); DomainName toLDH(); DomainName toUnicode(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testToFQDN() { DomainName dn = DomainName.of("www.example.com"); assertEquals(4, dn.toFQDN().getLabels().size()); assertEquals("www.example.com.", dn.toFQDN().getStringValue()); }
### Question: Tel extends URIValue { public static Tel unvalidatedTel(String telephoneNumber) throws URISyntaxException { return new Tel(new URI("tel:" + telephoneNumber)); } private Tel(URI uri); Tel(TelephoneNumber telephoneNumber); Tel(String telephoneNumber); static Tel unvalidatedTel(String telephoneNumber); }### Answer: @Test public void shouldBePossibleToCreateUnvalidedPhoneNumber() throws URISyntaxException { Tel tel = Tel.unvalidatedTel("+29716"); assertNotNull(tel); assertEquals("tel:+29716", tel.getStringValue()); }
### Question: Label { public static Label of(final String label) { if (StringUtils.isEmpty(label)) { return RootLabel.getInstance(); } if (!ASCIILabel.ASCII_SET.containsAll(label)) { IDNA.Info info = new IDNA.Info(); StringBuilder result = new StringBuilder(); IDNA.labelToUnicode(label, result, info); if (info.hasErrors()) { throw new LabelException.IDNParseException(info.getErrors()); } return new NonASCIILabel.ULabel(result.toString()); } if (!ASCIILabel.LDHLabel.LDH_SET.containsAll(label) || label.startsWith(HYPHEN) || label.endsWith(HYPHEN)) { return new ASCIILabel.NONLDHLabel(label); } if (!label.matches("^..--.*")) { return new ASCIILabel.LDHLabel.NonReservedLDHLabel(label); } if (label.startsWith("xn")) { Label aLabel = new ASCIILabel.LDHLabel.ReservedLDHLabel.ALabel(label); try { aLabel.toUnicode(); return aLabel; } catch (LabelException.IDNParseException e) { LOGGER.debug("Fake A-Label", e); return new ASCIILabel.LDHLabel.ReservedLDHLabel.FakeALabel(label, e.getErrors()); } } return new ASCIILabel.LDHLabel.ReservedLDHLabel(label); } Label(String value); static Label of(final String label); String getStringValue(); Label toLDH(); Label toUnicode(); static final Logger LOGGER; static final int IDNA_OPTIONS; }### Answer: @Test public void testLabelInstances() { Label label = Label.of("example"); assertTrue(label instanceof Label.ASCIILabel.LDHLabel.NonReservedLDHLabel); label = Label.of(""); assertTrue(label instanceof Label.RootLabel); label = Label.of("xn--bcher-kva"); assertTrue(label instanceof Label.ASCIILabel.LDHLabel.ReservedLDHLabel.ALabel); label = Label.of("xn--bcher-aaa"); assertTrue(label instanceof Label.ASCIILabel.LDHLabel.ReservedLDHLabel.FakeALabel); label = Label.of("_tcp"); assertTrue(label instanceof Label.ASCIILabel.NONLDHLabel); label = Label.of("-example"); assertTrue(label instanceof Label.ASCIILabel.NONLDHLabel); label = Label.of("example-"); assertTrue(label instanceof Label.ASCIILabel.NONLDHLabel); } @Test public void testControlCharacters() { for (final String s : new UnicodeSet(0, 31)) { Assert.assertThrows(new Assert.Closure() { @Override public void execute() throws Throwable { Label.of(s); } }, LabelException.IDNParseException.class, "expects LabelException"); } }
### Question: Label { public Label toUnicode() { return this; } Label(String value); static Label of(final String label); String getStringValue(); Label toLDH(); Label toUnicode(); static final Logger LOGGER; static final int IDNA_OPTIONS; }### Answer: @Test public void testToUnicode() { Label label = Label.of("xn--bcher-kva"); assertEquals("b\u00FCcher", label.toUnicode().getStringValue()); }
### Question: Label { public Label toLDH() { return this; } Label(String value); static Label of(final String label); String getStringValue(); Label toLDH(); Label toUnicode(); static final Logger LOGGER; static final int IDNA_OPTIONS; }### Answer: @Test public void testToLDH() { Label label = Label.of("b\u00FCcher"); assertEquals("xn--bcher-kva", label.toLDH().getStringValue()); label = Label.of("Bu\u0308cher"); assertEquals("xn--bcher-kva", label.toLDH().getStringValue()); assertEquals("b\u00FCcher", label.getStringValue()); }