src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
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.g...
@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_...
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 CredentialRepresenta...
@Test public void testUpdatePassword() throws Exception { boolean updated = keyCloakService.updatePassword(userId.get(JsonKey.USER_ID), "password"); Assert.assertTrue(updated); }
RequestValidator { @SuppressWarnings("unchecked") public static void validateUpdateContent(Request contentRequestDto) { List<Map<String, Object>> list = (List<Map<String, Object>>) (contentRequestDto.getRequest().get(JsonKey.CONTENTS)); if(CollectionUtils.isNotEmpty(list)) { for (Map<String, Object> map : list) { if (n...
@Test public void testValidateUpdateContentSuccess() { Request request = new Request(); boolean response = false; List<Map<String, Object>> listOfMap = new ArrayList<>(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.CONTENT_ID, "do_1233343"); requestObj.put(JsonKey.STATUS, "Completed"); list...
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 val...
@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...
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...
@Test(expected = CassandraMigrationException.class) public void extractSchemaVersionNoDescription() { MigrationInfoHelper.extractVersionAndDescription("9_4", "", "__", ""); } @Test public void extractSchemaVersionDefaults() { Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription("V9_4__...
RequestValidator { public static void validateUpdateClientKey(String clientId, String masterAccessToken) { validateClientId(clientId); if (StringUtils.isBlank(masterAccessToken)) { throw createExceptionInstance(ResponseCode.invalidRequestData.getErrorCode()); } } private RequestValidator(); @SuppressWarnings("unchecke...
@Test public void testValidateUpdateClientKeyFailureWithEmptyToken() { try { RequestValidator.validateUpdateClientKey("1234", ""); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidRequestData.getErrorCode(), e.getCode()...
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 ...
@Test public void testValidateClientIdFailureWithEmptyId() { try { RequestValidator.validateClientId(""); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidClientId.getErrorCode(), e.getCode()); } }
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); } } privat...
@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) { asser...
RequestValidator { public static void validateSendMail(Request request) { if (StringUtils.isBlank((String) request.getRequest().get(JsonKey.SUBJECT))) { throw new ProjectCommonException( ResponseCode.emailSubjectError.getErrorCode(), ResponseCode.emailSubjectError.getErrorMessage(), ERROR_CODE); } if (StringUtils.isBla...
@Test public void testValidateSendEmailSuccess() { boolean response = false; Request request = new Request(); Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.SUBJECT, "test123"); requestObj.put(JsonKey.BODY, "test"); List<String> data = new ArrayList<>(); data.add("test123@gmail.com"); requestO...
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.get...
@Test public void testValidateEnrolmentTypeFailureWithEmptyType() { try { RequestValidator.validateEnrolmentType(""); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.enrolmentTypeRequired.getErrorCode(), e.getCode()); } } @Te...
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(...
@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.v...
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 createExc...
@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.validateUpdateOrg...
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 validateUpdate...
@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...
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(Req...
@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 testValidateGetClientKeyFailureWithEmptyCl...
UserRequestValidator extends BaseRequestValidator { public void validateCreateUserRequest(Request userRequest) { externalIdsValidation(userRequest, JsonKey.CREATE); fieldsNotAllowed( Arrays.asList( JsonKey.REGISTERED_ORG_ID, JsonKey.ROOT_ORG_ID, JsonKey.PROVIDER, JsonKey.EXTERNAL_ID, JsonKey.EXTERNAL_ID_PROVIDER, JsonK...
@Test public void testValidatePasswordFailure() { Request request = initailizeRequest(); Map<String, Object> requestObj = request.getRequest(); requestObj.put(JsonKey.PASSWORD, "password"); request.setRequest(requestObj); try { userRequestValidator.validateCreateUserRequest(request); } catch (ProjectCommonException e) ...
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(R...
@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);...
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.R...
@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 (ProjectCommonEx...
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.getRequ...
@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.R...
UserRequestValidator extends BaseRequestValidator { public void validateCreateUserV3Request(Request userRequest) { validateCreateUserRequest(userRequest); } void validateCreateUserRequest(Request userRequest); static boolean isGoodPassword(String password); void validateUserCreateV3(Request userRequest); void validate...
@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.validateCreateUserV3Requ...
UserRequestValidator extends BaseRequestValidator { public void validateUserCreateV3(Request userRequest) { validateParam( (String) userRequest.getRequest().get(JsonKey.FIRST_NAME), ResponseCode.mandatoryParamsMissing, JsonKey.FIRST_NAME); if (StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.EMAIL)) &&...
@Test public void testValidateUserCreateV3Success() { boolean response = false; Request request = initailizeRequest(); Map<String, Object> requestObj = request.getRequest(); requestObj.put(JsonKey.PASSWORD, "Password@1"); request.setRequest(requestObj); try { userRequestValidator.validateUserCreateV3(request); response...
UserRequestValidator extends BaseRequestValidator { public void validateCreateUserV1Request(Request userRequest) { validateUserName(userRequest); validateCreateUserV3Request(userRequest); } void validateCreateUserRequest(Request userRequest); static boolean isGoodPassword(String password); void validateUserCreateV3(Re...
@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) { asse...
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, subj...
@Test public void sendEmailTest() throws MessagingException { List<String> to = new ArrayList<String>(); to.add("testmail@test.com"); to.add("test1@test.com"); emailService.sendEmail("testmail@test.com", subject, "Hi how are you", to); List<Message> inbox = Mailbox.get("testmail@test.com"); Assert.assertTrue(inbox.size...
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(), ...
@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...
UserRequestValidator extends BaseRequestValidator { public void validateChangePassword(Request userRequest) { if (userRequest.getRequest().get(JsonKey.PASSWORD) == null || (StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.PASSWORD)))) { ProjectCommonException.throwClientErrorException(ResponseCode.pass...
@Test public void testValidateChangePasswordSuccess() { Request request = new Request(); boolean response = false; Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.NEW_PASSWORD, "password1"); requestObj.put(JsonKey.PASSWORD, "password"); request.setRequest(requestObj); try { userRequestValidator...
UserRequestValidator extends BaseRequestValidator { public void phoneValidation(Request userRequest) { if (!StringUtils.isBlank((String) userRequest.getRequest().get(JsonKey.COUNTRY_CODE))) { boolean bool = ProjectUtil.validateCountryCode( (String) userRequest.getRequest().get(JsonKey.COUNTRY_CODE)); if (!bool) { Proje...
@Test public void testPhoneValidationSuccess() { Request request = new Request(); boolean response = false; Map<String, Object> requestObj = new HashMap<>(); requestObj.put(JsonKey.PHONE, "9321234123"); requestObj.put(JsonKey.COUNTRY_CODE, "+91"); requestObj.put(JsonKey.PROVIDER, "sunbird"); requestObj.put(JsonKey.PHON...
UserRequestValidator extends BaseRequestValidator { public void validateUpdateUserRequest(Request userRequest) { if (userRequest.getRequest().containsKey(JsonKey.MANAGED_BY)) { ProjectCommonException.throwClientErrorException(ResponseCode.managedByNotAllowed); } externalIdsValidation(userRequest, JsonKey.UPDATE); phone...
@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"); reque...
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 || !(r...
@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.p...
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...
@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 (ProjectCommonExceptio...
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 userRe...
@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 =...
UserRequestValidator extends BaseRequestValidator { @SuppressWarnings("unchecked") public void validateMandatoryFrameworkFields( Map<String, Object> userMap, List<String> frameworkFields, List<String> frameworkMandatoryFields) { if (userMap.containsKey(JsonKey.FRAMEWORK)) { Map<String, Object> frameworkRequest = (Map<S...
@Test public void testValidateMandatoryFrameworkFieldsSuccess() { Request request = initailizeRequest(); request.getRequest().put(JsonKey.FRAMEWORK, createFrameWork()); boolean response = false; try { new UserRequestValidator() .validateMandatoryFrameworkFields( request.getRequest(), getSupportedFileds(), getMandatoryF...
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 ...
@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...
ProjectUtil { public static VelocityContext getContext(Map<String, Object> map) { propertiesCache = PropertiesCache.getInstance(); VelocityContext context = new VelocityContext(); if (StringUtils.isNotBlank((String) map.get(JsonKey.ACTION_URL))) { context.put(JsonKey.ACTION_URL, getValue(map, JsonKey.ACTION_URL)); } if...
@Test public void testGetContextFailureWithoutActionUrl() { Map<String, Object> templateMap = new HashMap<>(); templateMap.put(JsonKey.NAME, "userName"); VelocityContext context = ProjectUtil.getContext(templateMap); assertEquals(false, context.internalContainsKey(JsonKey.ACTION_URL)); } @Test public void testGetContex...
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 getFormatte...
@Test public void testCreateAuthTokenSuccess() { String authToken = ProjectUtil.createAuthToken("test", "tset1234"); assertNotNull(authToken); }
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}"))...
@Test public void testValidatePhoneNumberFailureWithInvalidPhoneNumber() { assertFalse(ProjectUtil.validatePhoneNumber("312")); } @Test public void testValidatePhoneNumberSuccess() { assertTrue(ProjectUtil.validatePhoneNumber("9844016699")); }
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()); ...
@Test public void testGenerateRandomPasswordSuccess() { assertNotNull(ProjectUtil.generateRandomPassword()); }
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....
@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.c...
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)...
@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); }
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 ...
@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 testIsEmailVali...
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 ...
@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 testIsDa...
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, Strin...
@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__...
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...
@Test public void testGetEkstepHeaderSuccess() { Map<String, String> map = ProjectUtil.getEkstepHeader(); assertEquals(map.get("Content-Type"), "application/json"); assertNotNull(map.get(JsonKey.AUTHORIZATION)); }
ProjectUtil { private static Object getValue(Map<String, Object> map, String key) { Object value = map.get(key); map.remove(key); return value; } static boolean isStringNullOREmpty(String value); static String getFormattedDate(); static String formatDate(Date date); static boolean isEmailvalid(final String email); sta...
@Test public void testReportTrackingStatusSuccess() { assertEquals(0, ProjectUtil.ReportTrackingStatus.NEW.getValue()); assertEquals(1, ProjectUtil.ReportTrackingStatus.GENERATING_DATA.getValue()); assertEquals(2, ProjectUtil.ReportTrackingStatus.UPLOADING_FILE.getValue()); assertEquals(3, ProjectUtil.ReportTrackingSta...
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(); sta...
@Test public void testCreateAndThrowServerErrorSuccess() { try { ProjectUtil.createAndThrowServerError(); } catch (ProjectCommonException e) { assertEquals(ResponseCode.SERVER_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.SERVER_ERROR.getErrorCode(), e.getCode()); } }
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 getFor...
@Test public void testCreateAndThrowInvalidUserDataExceptionSuccess() { try { ProjectUtil.createAndThrowInvalidUserDataException(); } catch (ProjectCommonException e) { assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), e.getResponseCode()); assertEquals(ResponseCode.invalidUsrData.getErrorCode(), e.getCode()); ...
ProjectUtil { public static Map<String, String> getDateRange(int numDays) { Map<String, String> map = new HashMap<>(); if (numDays <= 0) { return map; } Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.add(Calendar.DATE, -numDays); map.put(STARTDATE, new SimpleDateFormat(YYYY_MM_DD_FORMATTER).forma...
@Test public void testGetDateRangeSuccess() { int noOfDays = 7; Map<String, String> map = ProjectUtil.getDateRange(noOfDays); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.add(Calendar.DATE, -noOfDays); assertEquals(map.get("startDate"), new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));...
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 user...
@Test public void testGetLmsUserIdSuccessWithoutFedUserId() { String userid = ProjectUtil.getLmsUserId("1234567890"); assertEquals("1234567890", userid); }
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 isStrin...
@Test public void testValidateCountryCode() { boolean isValid = ProjectUtil.validateCountryCode("+91"); assertTrue(isValid); }
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 em...
@Test public void testValidateUUID() { boolean isValid = ProjectUtil.validateUUID("1df03f56-ceba-4f2d-892c-2b1609e7b05f"); assertTrue(isValid); }
HttpUtil { public static HttpUtilResponse postFormData( Map<String, String> reqData, Map<String, byte[]> fileData, Map<String, String> headers, String url) throws IOException { long startTime = System.currentTimeMillis(); Map<String, Object> logInfo = genarateLogInfo(JsonKey.API_CALL, "API CALL : " + url); ProjectLogge...
@Test public void testPostFormDataSuccess() { Map<String, String> reqData = new HashMap<>(); reqData.put("field1", "value1"); reqData.put("field2", "value2"); Map<String, byte[]> fileData = new HashMap<>(); fileData.put("file1", ("asd".getBytes())); Map<String, String> headers = new HashMap<>(); headers.put("Authorizat...
HttpUtil { public static String sendPatchRequest( String requestURL, String params, Map<String, String> headers) throws IOException { long startTime = System.currentTimeMillis(); Map<String, Object> logInfo = genarateLogInfo(JsonKey.API_CALL, "API CALL : " + requestURL); ProjectLogger.log( "HttpUtil sendPatchRequest me...
@Test public void testSendPatchRequestSuccess() { Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "123456"); String url = "http: try { CloseableHttpResponse closeableHttpResponseMock = PowerMockito.mock(CloseableHttpResponse.class); HttpEntity httpEntity = PowerMockito.mock(HttpEntity.class)...
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 ...
@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 (IOEx...
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, heade...
@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) { ProjectL...
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 ? ...
@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.fro...
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 bod...
@Test public void sendEmailToMultipleUser() throws MessagingException { List<String> to = new ArrayList<String>(); to.add("testmail@test.com"); to.add("test1@test.com"); emailService.sendMail(to, subject, "Test email body"); List<Message> inbox = Mailbox.get("testmail@test.com"); Assert.assertTrue(inbox.size() > 0); As...
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...
@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-dev...
CassandraOperationImpl implements CassandraOperation { @Override public Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "Cassandra Service updateRecord method started at ==" + startTime, LoggerEnum.INFO); Respons...
@Test public void testUpdateRecordSuccess() { address.put(JsonKey.CITY, "city"); address.put(JsonKey.ADD_TYPE, "addrType"); when(session.execute(boundStatement)).thenReturn(resultSet); Response response = operation.updateRecord(cassandraKeySpace, "address", address); assertEquals(ResponseCode.success.getErrorCode(), re...
CassandraOperationImpl implements CassandraOperation { @Override public Response updateRecordWithTTL( String keyspaceName, String tableName, Map<String, Object> request, Map<String, Object> compositeKey, int ttl) { long startTime = System.currentTimeMillis(); Session session = connectionManager.getSession(keyspaceName)...
@Test public void testUpdateRecordWithTTLSuccess() { when(resultSet.iterator()).thenReturn(iterator); Map<String, Object> compositeKey = new HashMap<>(); compositeKey.put(JsonKey.TYPE, JsonKey.EMAIL); compositeKey.put(JsonKey.KEY, "amit@example.com"); when(session.execute(update)).thenReturn(resultSet); Response respon...
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 d...
@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()); }
CassandraOperationImpl implements CassandraOperation { @Override public Response getAllRecords(String keyspaceName, String tableName) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "Cassandra Service getAllRecords method started at ==" + startTime, LoggerEnum.INFO); Response response = new Response()...
@Test public void testGetAllRecordsSuccess() throws Exception { Iterator<Row> rowItr = Mockito.mock(Iterator.class); Mockito.when(resultSet.iterator()).thenReturn(rowItr); PowerMockito.whenNew(BoundStatement.class) .withArguments(Mockito.any(PreparedStatement.class)) .thenReturn(boundStatement); Response response = ope...
CassandraOperationImpl implements CassandraOperation { @Override public Response getPropertiesValueById( String keyspaceName, String tableName, String id, String... properties) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "Cassandra Service getPropertiesValueById method started at ==" + startTime, ...
@Test public void testGetPropertiesValueFailureById() throws Exception { Throwable exception = null; PowerMockito.whenNew(BoundStatement.class) .withArguments(Mockito.any(PreparedStatement.class)) .thenThrow( new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage...
CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordById(String keyspaceName, String tableName, String key) { return getRecordByIdentifier(keyspaceName, tableName, key, null); } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<Str...
@Test public void testGetRecordSuccessById() { Iterator<Row> rowItr = Mockito.mock(Iterator.class); Mockito.when(resultSet.iterator()).thenReturn(rowItr); when(session.execute(boundStatement.bind("123"))).thenReturn(resultSet); when(session.execute(where)).thenReturn(resultSet); when(selectBuilder.from(Mockito.anyStrin...
CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordWithTTLById( String keyspaceName, String tableName, Map<String, Object> key, List<String> ttlFields, List<String> fields) { return getRecordWithTTLByIdentifier(keyspaceName, tableName, key, ttlFields, fields); } CassandraOperation...
@Test public void testGetRecordWithTTLById() { Select.SelectionOrAlias alias = PowerMockito.mock(Select.SelectionOrAlias.class); Select select = PowerMockito.mock(Select.class); when(selectSelection.from("sunbird", "otp")).thenReturn(select); when(select.where()).thenReturn(where); when(selectSelection.ttl("otp")).then...
CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperties( String keyspaceName, String tableName, Map<String, Object> propertyMap) { return getRecordsByProperties(keyspaceName, tableName, propertyMap, null); } CassandraOperationImpl(); @Override Response insertRecord(String...
@Test public void testGetRecordSuccessByProperties() throws Exception { Map<String, Object> map = new HashMap<>(); map.put(JsonKey.USER_ID, "USR1"); map.put(JsonKey.ADD_TYPE, "addrType"); when(session.execute(boundStatement.bind("123"))).thenReturn(resultSet); Iterator<Row> rowItr = Mockito.mock(Iterator.class); Mockit...
CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } CassandraOperationImpl(); @Override Respon...
@Test public void testGetRecordForListSuccessByProperties() throws Exception { List<Object> list = new ArrayList<>(); list.add("123"); list.add("321"); when(session.execute(boundStatement.bind("123"))).thenReturn(resultSet); Iterator<Row> rowItr = Mockito.mock(Iterator.class); Mockito.when(resultSet.iterator()).thenRet...
CassandraOperationImpl implements CassandraOperation { @Override public Response deleteRecord(String keyspaceName, String tableName, String identifier) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "Cassandra Service deleteRecord method started at ==" + startTime, LoggerEnum.INFO); Response response...
@Test public void testDeleteRecordSuccess() throws Exception { when(QueryBuilder.delete()).thenReturn(deleteSelection); Response response = new Response(); response.put(JsonKey.RESPONSE, Constants.SUCCESS); operation.deleteRecord(cassandraKeySpace, "address", "123"); assertEquals("SUCCESS", response.get("response")); }...
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); } MigrationVer...
@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() { MigrationVer...
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: " + ge...
@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.setDescripti...
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...
@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() { Mi...
Keyspace { public String getName() { return name; } Keyspace(); Cluster getCluster(); void setCluster(Cluster cluster); String getName(); void setName(String name); }
@Test public void shouldDefaultToNoKeyspaceButCanBeOverridden() { assertThat(new Keyspace().getName(), is(nullValue())); System.setProperty(Keyspace.KeyspaceProperty.NAME.getName(), "myspace"); assertThat(new Keyspace().getName(), is("myspace")); }
Keyspace { public Cluster getCluster() { return cluster; } Keyspace(); Cluster getCluster(); void setCluster(Cluster cluster); String getName(); void setName(String name); }
@Test public void shouldHaveDefaultClusterObject() { assertThat(new Keyspace().getCluster(), is(notNullValue())); }
ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); }
@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", ...
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(Stri...
@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)); }
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 s...
@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("1...
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 ...
@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.collapseWhite...
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(St...
@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 ...
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 syn...
@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...
FeatureDetector { public boolean isSlf4jAvailable() { if (slf4jAvailable == null) { slf4jAvailable = isPresent("org.slf4j.Logger", classLoader); } return slf4jAvailable; } FeatureDetector(ClassLoader classLoader); boolean isApacheCommonsLoggingAvailable(); boolean isSlf4jAvailable(); }
@Test public void shouldDetectSlf4j() { assertThat( new FeatureDetector(Thread.currentThread().getContextClassLoader()).isSlf4jAvailable(), is(true)); }
FeatureDetector { public boolean isApacheCommonsLoggingAvailable() { if (apacheCommonsLoggingAvailable == null) { apacheCommonsLoggingAvailable = isPresent("org.apache.commons.logging.Log", classLoader); } return apacheCommonsLoggingAvailable; } FeatureDetector(ClassLoader classLoader); boolean isApacheCommonsLoggingAv...
@Test public void shouldDetectCommonsLogging() { assertThat( new FeatureDetector(Thread.currentThread().getContextClassLoader()) .isApacheCommonsLoggingAvailable(), is(true)); }
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); }
@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", Time...
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 = createMult...
@Test public void sendEmailWithAttachmentTest() throws MessagingException { List<String> to = new ArrayList<String>(); to.add("testmail@test.com"); to.add("test1@test.com"); emailService.sendAttachment(to, "Test email as attached.", subject, "emailtemplate.vm"); List<Message> inbox = Mailbox.get("testmail@test.com"); A...
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("...
@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()); }
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...
@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()); }
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[] loa...
@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...
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); } R...
@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() { asse...
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 ...
@Test public void toFilePath() throws MalformedURLException { File file = new File("/test dir/a+b"); assertEquals(file.getAbsolutePath(), UrlUtils.toFilePath(file.toURI().toURL())); }
EsClientFactory { private static ElasticSearchService getTcpClient() { if (tcpClient == null) { tcpClient = new ElasticSearchTcpImpl(); } return tcpClient; } static ElasticSearchService getInstance(String type); }
@Test public void testGetTcpClient() { ElasticSearchService service = EsClientFactory.getInstance("tcp"); Assert.assertTrue(service instanceof ElasticSearchTcpImpl); }
EsClientFactory { private static ElasticSearchService getRestClient() { if (restClient == null) { restClient = new ElasticSearchRestHighImpl(); } return restClient; } static ElasticSearchService getInstance(String type); }
@Test public void testGetRestClient() { ElasticSearchService service = EsClientFactory.getInstance("rest"); Assert.assertTrue(service instanceof ElasticSearchRestHighImpl); }
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); } ret...
@Test public void testInstanceNull() { ElasticSearchService service = EsClientFactory.getInstance("test"); Assert.assertNull(service); }
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 ==" + ...
@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 = esServic...
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.getFr...
@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); ass...
ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<Boolean> update(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method started at ==" + startTime + " for Index " + index, L...
@Test public void testUpdateSuccess() { mockRulesForUpdate(false); Future<Boolean> result = esService.update("test", "001", new HashMap<>()); boolean res = (boolean) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(true, res); } @Test public void testUpdateFailure() { mockRulesForUpdate(true); Future<Boo...
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.isN...
@Test public void testGetDataByIdentifierFailureWithEmptyIndex() { try { esService.getDataByIdentifier("", "001"); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } } @Test public void testGetDataByIdentifierFailureWithEmptyIdentifier() { try { esServi...
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, JavaMigratio...
@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...
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> promi...
@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); ...
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, Lo...
@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...
ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:sear...
@Test @Ignore public void testComplexSearchSuccess() throws Exception { SearchDTO searchDTO = new SearchDTO(); List<String> fields = new ArrayList<String>(); fields.add("courseId"); fields.add("courseType"); fields.add("createdOn"); fields.add("description"); Map<String, Object> sortMap = new HashMap<>(); sortMap.put("...
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("N...
@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")); }
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 getLe...
@Test public void testIsFQDN() { assertFalse(DomainName.of("www.example.com").isFQDN()); assertTrue(DomainName.of("www.example.com.").isFQDN()); }
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...
@Test public void testToFQDN() { DomainName dn = DomainName.of("www.example.com"); assertEquals(4, dn.toFQDN().getLabels().size()); assertEquals("www.example.com.", dn.toFQDN().getStringValue()); }
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); }
@Test public void shouldBePossibleToCreateUnvalidedPhoneNumber() throws URISyntaxException { Tel tel = Tel.unvalidatedTel("+29716"); assertNotNull(tel); assertEquals("tel:+29716", tel.getStringValue()); }