target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@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"))); } | String extractScriptName(Resource resource) { if (location.getPath().isEmpty()) { return resource.getLocation(); } return resource.getLocation().substring(location.getPath().length() + 1); } | CqlMigrationResolver implements MigrationResolver { String extractScriptName(Resource resource) { if (location.getPath().isEmpty()) { return resource.getLocation(); } return resource.getLocation().substring(location.getPath().length() + 1); } } | 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); } | 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(); } | 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(); } |
@Test public void testMigrateActionAcceptValueFailure() { Assert.assertNotEquals("ok", ProjectUtil.MigrateAction.ACCEPT.getValue()); } | private static Object getValue(Map<String, Object> map, String key) { Object value = map.get(key); map.remove(key); return value; } | ProjectUtil { private static Object getValue(Map<String, Object> map, String key) { Object value = map.get(key); map.remove(key); return value; } } | ProjectUtil { private static Object getValue(Map<String, Object> map, String key) { Object value = map.get(key); map.remove(key); return value; } } | 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); 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); } | 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); 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; } |
@Test public void testMigrateActionRejectValueFailure() { Assert.assertNotEquals("no", ProjectUtil.MigrateAction.REJECT.getValue()); } | private static Object getValue(Map<String, Object> map, String key) { Object value = map.get(key); map.remove(key); return value; } | ProjectUtil { private static Object getValue(Map<String, Object> map, String key) { Object value = map.get(key); map.remove(key); return value; } } | ProjectUtil { private static Object getValue(Map<String, Object> map, String key) { Object value = map.get(key); map.remove(key); return value; } } | 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); 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); } | 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); 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; } |
@Test public void testMigrateActionAcceptValueSuccess() { Assert.assertEquals("accept", ProjectUtil.MigrateAction.ACCEPT.getValue()); } | private static Object getValue(Map<String, Object> map, String key) { Object value = map.get(key); map.remove(key); return value; } | ProjectUtil { private static Object getValue(Map<String, Object> map, String key) { Object value = map.get(key); map.remove(key); return value; } } | ProjectUtil { private static Object getValue(Map<String, Object> map, String key) { Object value = map.get(key); map.remove(key); return value; } } | 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); 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); } | 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); 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; } |
@Test public void testMigrateActionRejectValueSuccess() { Assert.assertEquals("reject", ProjectUtil.MigrateAction.REJECT.getValue()); } | private static Object getValue(Map<String, Object> map, String key) { Object value = map.get(key); map.remove(key); return value; } | ProjectUtil { private static Object getValue(Map<String, Object> map, String key) { Object value = map.get(key); map.remove(key); return value; } } | ProjectUtil { private static Object getValue(Map<String, Object> map, String key) { Object value = map.get(key); map.remove(key); return value; } } | 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); 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); } | 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); 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; } |
@Test public void testValidateCountryCode() { boolean isValid = ProjectUtil.validateCountryCode("+91"); assertTrue(isValid); } | 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; } } | 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; } } } | 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; } } } | 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); } | 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; } |
@Test public void testValidateUUID() { boolean isValid = ProjectUtil.validateUUID("1df03f56-ceba-4f2d-892c-2b1609e7b05f"); assertTrue(isValid); } | public static boolean validateUUID(String uuidStr) { try { UUID.fromString(uuidStr); return true; } catch (Exception ex) { return false; } } | ProjectUtil { public static boolean validateUUID(String uuidStr) { try { UUID.fromString(uuidStr); return true; } catch (Exception ex) { return false; } } } | ProjectUtil { public static boolean validateUUID(String uuidStr) { try { UUID.fromString(uuidStr); return true; } catch (Exception ex) { return false; } } } | 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); } | 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; } |
@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("Authorization", "123456"); String url = "http: try { String response = (String) HttpUtil.postFormData(reqData, fileData, headers, url).getBody(); assertTrue("{\"message\":\"success\"}".equals(response)); } catch (IOException e) { ProjectLogger.log(e.getMessage()); } } | 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); ProjectLogger.log( "HttpUtil postFormData method started at ==" + startTime + " for requestURL " + url, LoggerEnum.PERF_LOG); try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(url); Set<Entry<String, String>> headerEntry = headers.entrySet(); for (Entry<String, String> headerObj : headerEntry) { httpPost.addHeader(headerObj.getKey(), headerObj.getValue()); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); Set<Entry<String, String>> entry = reqData.entrySet(); for (Entry<String, String> entryObj : entry) { builder.addTextBody( entryObj.getKey(), entryObj.getValue(), ContentType.create("text/plain", MIME.UTF8_CHARSET)); } Set<Entry<String, byte[]>> fileEntry = fileData.entrySet(); for (Entry<String, byte[]> entryObj : fileEntry) { if (!StringUtils.isBlank(entryObj.getKey()) && null != entryObj.getValue()) { builder.addBinaryBody( entryObj.getKey(), entryObj.getValue(), ContentType.APPLICATION_OCTET_STREAM, entryObj.getKey()); } } HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "HttpUtil postFormData method end at ==" + stopTime + " for requestURL " + url + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); HttpResponse httpResponse = client.execute(httpPost); HttpUtilResponse response = null; String body = ""; try { body = generateResponse(httpResponse); } catch (Exception ex) { ProjectLogger.log("Exception occurred while reading body" + ex); } response = new HttpUtilResponse(body, httpResponse.getStatusLine().getStatusCode()); telemetryProcessingCall(logInfo); return response; } catch (Exception ex) { ProjectLogger.log("Exception occurred while calling postFormData method.", ex); throw ex; } } | 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); ProjectLogger.log( "HttpUtil postFormData method started at ==" + startTime + " for requestURL " + url, LoggerEnum.PERF_LOG); try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(url); Set<Entry<String, String>> headerEntry = headers.entrySet(); for (Entry<String, String> headerObj : headerEntry) { httpPost.addHeader(headerObj.getKey(), headerObj.getValue()); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); Set<Entry<String, String>> entry = reqData.entrySet(); for (Entry<String, String> entryObj : entry) { builder.addTextBody( entryObj.getKey(), entryObj.getValue(), ContentType.create("text/plain", MIME.UTF8_CHARSET)); } Set<Entry<String, byte[]>> fileEntry = fileData.entrySet(); for (Entry<String, byte[]> entryObj : fileEntry) { if (!StringUtils.isBlank(entryObj.getKey()) && null != entryObj.getValue()) { builder.addBinaryBody( entryObj.getKey(), entryObj.getValue(), ContentType.APPLICATION_OCTET_STREAM, entryObj.getKey()); } } HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "HttpUtil postFormData method end at ==" + stopTime + " for requestURL " + url + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); HttpResponse httpResponse = client.execute(httpPost); HttpUtilResponse response = null; String body = ""; try { body = generateResponse(httpResponse); } catch (Exception ex) { ProjectLogger.log("Exception occurred while reading body" + ex); } response = new HttpUtilResponse(body, httpResponse.getStatusLine().getStatusCode()); telemetryProcessingCall(logInfo); return response; } catch (Exception ex) { ProjectLogger.log("Exception occurred while calling postFormData method.", ex); throw ex; } } } | 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); ProjectLogger.log( "HttpUtil postFormData method started at ==" + startTime + " for requestURL " + url, LoggerEnum.PERF_LOG); try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(url); Set<Entry<String, String>> headerEntry = headers.entrySet(); for (Entry<String, String> headerObj : headerEntry) { httpPost.addHeader(headerObj.getKey(), headerObj.getValue()); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); Set<Entry<String, String>> entry = reqData.entrySet(); for (Entry<String, String> entryObj : entry) { builder.addTextBody( entryObj.getKey(), entryObj.getValue(), ContentType.create("text/plain", MIME.UTF8_CHARSET)); } Set<Entry<String, byte[]>> fileEntry = fileData.entrySet(); for (Entry<String, byte[]> entryObj : fileEntry) { if (!StringUtils.isBlank(entryObj.getKey()) && null != entryObj.getValue()) { builder.addBinaryBody( entryObj.getKey(), entryObj.getValue(), ContentType.APPLICATION_OCTET_STREAM, entryObj.getKey()); } } HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "HttpUtil postFormData method end at ==" + stopTime + " for requestURL " + url + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); HttpResponse httpResponse = client.execute(httpPost); HttpUtilResponse response = null; String body = ""; try { body = generateResponse(httpResponse); } catch (Exception ex) { ProjectLogger.log("Exception occurred while reading body" + ex); } response = new HttpUtilResponse(body, httpResponse.getStatusLine().getStatusCode()); telemetryProcessingCall(logInfo); return response; } catch (Exception ex) { ProjectLogger.log("Exception occurred while calling postFormData method.", ex); throw ex; } } private HttpUtil(); } | 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); ProjectLogger.log( "HttpUtil postFormData method started at ==" + startTime + " for requestURL " + url, LoggerEnum.PERF_LOG); try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(url); Set<Entry<String, String>> headerEntry = headers.entrySet(); for (Entry<String, String> headerObj : headerEntry) { httpPost.addHeader(headerObj.getKey(), headerObj.getValue()); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); Set<Entry<String, String>> entry = reqData.entrySet(); for (Entry<String, String> entryObj : entry) { builder.addTextBody( entryObj.getKey(), entryObj.getValue(), ContentType.create("text/plain", MIME.UTF8_CHARSET)); } Set<Entry<String, byte[]>> fileEntry = fileData.entrySet(); for (Entry<String, byte[]> entryObj : fileEntry) { if (!StringUtils.isBlank(entryObj.getKey()) && null != entryObj.getValue()) { builder.addBinaryBody( entryObj.getKey(), entryObj.getValue(), ContentType.APPLICATION_OCTET_STREAM, entryObj.getKey()); } } HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "HttpUtil postFormData method end at ==" + stopTime + " for requestURL " + url + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); HttpResponse httpResponse = client.execute(httpPost); HttpUtilResponse response = null; String body = ""; try { body = generateResponse(httpResponse); } catch (Exception ex) { ProjectLogger.log("Exception occurred while reading body" + ex); } response = new HttpUtilResponse(body, httpResponse.getStatusLine().getStatusCode()); telemetryProcessingCall(logInfo); return response; } catch (Exception ex) { ProjectLogger.log("Exception occurred while calling postFormData method.", ex); throw ex; } } 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); } | 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); ProjectLogger.log( "HttpUtil postFormData method started at ==" + startTime + " for requestURL " + url, LoggerEnum.PERF_LOG); try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(url); Set<Entry<String, String>> headerEntry = headers.entrySet(); for (Entry<String, String> headerObj : headerEntry) { httpPost.addHeader(headerObj.getKey(), headerObj.getValue()); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); Set<Entry<String, String>> entry = reqData.entrySet(); for (Entry<String, String> entryObj : entry) { builder.addTextBody( entryObj.getKey(), entryObj.getValue(), ContentType.create("text/plain", MIME.UTF8_CHARSET)); } Set<Entry<String, byte[]>> fileEntry = fileData.entrySet(); for (Entry<String, byte[]> entryObj : fileEntry) { if (!StringUtils.isBlank(entryObj.getKey()) && null != entryObj.getValue()) { builder.addBinaryBody( entryObj.getKey(), entryObj.getValue(), ContentType.APPLICATION_OCTET_STREAM, entryObj.getKey()); } } HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "HttpUtil postFormData method end at ==" + stopTime + " for requestURL " + url + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); HttpResponse httpResponse = client.execute(httpPost); HttpUtilResponse response = null; String body = ""; try { body = generateResponse(httpResponse); } catch (Exception ex) { ProjectLogger.log("Exception occurred while reading body" + ex); } response = new HttpUtilResponse(body, httpResponse.getStatusLine().getStatusCode()); telemetryProcessingCall(logInfo); return response; } catch (Exception ex) { ProjectLogger.log("Exception occurred while calling postFormData method.", ex); throw ex; } } 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); } |
@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); PowerMockito.when(closeableHttpResponseMock.getStatusLine()) .thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!")); PowerMockito.when(closeableHttpResponseMock.getEntity()).thenReturn(httpEntity); closeableHttpResponseMock.setEntity(httpEntity); PowerMockito.when(closeableHttpResponseMock.getEntity()).thenReturn(httpEntity); PowerMockito.when(closeableHttpResponseMock.getEntity().getContent()) .thenReturn(new ByteArrayInputStream("{\"message\":\"success\"}".getBytes())); CloseableHttpClient closeableHttpClientMocked = PowerMockito.mock(CloseableHttpClient.class); PowerMockito.mockStatic(HttpClients.class); PowerMockito.when(HttpClients.createDefault()).thenReturn(closeableHttpClientMocked); PowerMockito.when(closeableHttpClientMocked.execute(Mockito.any(HttpPost.class))) .thenReturn(closeableHttpResponseMock); String response = HttpUtil.sendPatchRequest(url, "{\"message\":\"success\"}", headers); assertTrue("SUCCESS".equals(response)); } catch (IOException e) { ProjectLogger.log(e.getMessage()); } } | 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 method started at ==" + startTime + " for requestURL and params " + requestURL + " param==" + params, LoggerEnum.PERF_LOG); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPatch patch = new HttpPatch(requestURL); setHeaders(patch, headers); StringEntity entity = new StringEntity(params); patch.setEntity(entity); CloseableHttpResponse response = httpClient.execute(patch); if (response.getStatusLine().getStatusCode() == ResponseCode.OK.getResponseCode()) { long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "HttpUtil sendPatchRequest method end at ==" + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return ResponseCode.success.getErrorCode(); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "Patch request failure status code ==" + response.getStatusLine().getStatusCode() + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return "Failure"; } catch (Exception e) { ProjectLogger.log("HttpUtil call fails == " + e.getMessage(), e); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; telemetryProcessingCall(logInfo); ProjectLogger.log( "HttpUtil sendPatchRequest method end at ==" + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return "Failure"; } | 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 method started at ==" + startTime + " for requestURL and params " + requestURL + " param==" + params, LoggerEnum.PERF_LOG); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPatch patch = new HttpPatch(requestURL); setHeaders(patch, headers); StringEntity entity = new StringEntity(params); patch.setEntity(entity); CloseableHttpResponse response = httpClient.execute(patch); if (response.getStatusLine().getStatusCode() == ResponseCode.OK.getResponseCode()) { long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "HttpUtil sendPatchRequest method end at ==" + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return ResponseCode.success.getErrorCode(); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "Patch request failure status code ==" + response.getStatusLine().getStatusCode() + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return "Failure"; } catch (Exception e) { ProjectLogger.log("HttpUtil call fails == " + e.getMessage(), e); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; telemetryProcessingCall(logInfo); ProjectLogger.log( "HttpUtil sendPatchRequest method end at ==" + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return "Failure"; } } | 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 method started at ==" + startTime + " for requestURL and params " + requestURL + " param==" + params, LoggerEnum.PERF_LOG); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPatch patch = new HttpPatch(requestURL); setHeaders(patch, headers); StringEntity entity = new StringEntity(params); patch.setEntity(entity); CloseableHttpResponse response = httpClient.execute(patch); if (response.getStatusLine().getStatusCode() == ResponseCode.OK.getResponseCode()) { long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "HttpUtil sendPatchRequest method end at ==" + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return ResponseCode.success.getErrorCode(); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "Patch request failure status code ==" + response.getStatusLine().getStatusCode() + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return "Failure"; } catch (Exception e) { ProjectLogger.log("HttpUtil call fails == " + e.getMessage(), e); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; telemetryProcessingCall(logInfo); ProjectLogger.log( "HttpUtil sendPatchRequest method end at ==" + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return "Failure"; } private HttpUtil(); } | 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 method started at ==" + startTime + " for requestURL and params " + requestURL + " param==" + params, LoggerEnum.PERF_LOG); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPatch patch = new HttpPatch(requestURL); setHeaders(patch, headers); StringEntity entity = new StringEntity(params); patch.setEntity(entity); CloseableHttpResponse response = httpClient.execute(patch); if (response.getStatusLine().getStatusCode() == ResponseCode.OK.getResponseCode()) { long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "HttpUtil sendPatchRequest method end at ==" + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return ResponseCode.success.getErrorCode(); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "Patch request failure status code ==" + response.getStatusLine().getStatusCode() + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return "Failure"; } catch (Exception e) { ProjectLogger.log("HttpUtil call fails == " + e.getMessage(), e); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; telemetryProcessingCall(logInfo); ProjectLogger.log( "HttpUtil sendPatchRequest method end at ==" + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return "Failure"; } 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); } | 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 method started at ==" + startTime + " for requestURL and params " + requestURL + " param==" + params, LoggerEnum.PERF_LOG); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPatch patch = new HttpPatch(requestURL); setHeaders(patch, headers); StringEntity entity = new StringEntity(params); patch.setEntity(entity); CloseableHttpResponse response = httpClient.execute(patch); if (response.getStatusLine().getStatusCode() == ResponseCode.OK.getResponseCode()) { long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "HttpUtil sendPatchRequest method end at ==" + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return ResponseCode.success.getErrorCode(); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; ProjectLogger.log( "Patch request failure status code ==" + response.getStatusLine().getStatusCode() + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return "Failure"; } catch (Exception e) { ProjectLogger.log("HttpUtil call fails == " + e.getMessage(), e); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; telemetryProcessingCall(logInfo); ProjectLogger.log( "HttpUtil sendPatchRequest method end at ==" + stopTime + " for requestURL " + requestURL + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG); return "Failure"; } 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); } |
@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()); } } | 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; } | 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; } } | 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(); } | 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); } | 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); } |
@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()); } } | 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; } | 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; } } | 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(); } | 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); } | 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); } |
@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); } | @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 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 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); } | 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(); } | 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; } |
@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()); } | public boolean sendMail(List<String> emailList, String subject, String body) { return sendMail(emailList, subject, body, null); } | Email { public boolean sendMail(List<String> emailList, String subject, String body) { return sendMail(emailList, subject, body, null); } } | Email { public boolean sendMail(List<String> emailList, String subject, String body) { return sendMail(emailList, subject, body, null); } Email(); Email(EmailConfig config); } | 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(); } | 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(); } |
@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")); } | 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); }}; } | 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); }}; } } | 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(); } | 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); } | 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); } |
@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")); } | 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); }}; } | 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); }}; } } | 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(); } | 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); } | 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); } |
@Test public void maskEmail() { HashMap<String, String> emailMaskExpectations = new HashMap<String, String>(){ { put("[email protected]", "ab*@gmail.com"); put("[email protected]", "ab**@yahoo.com"); put("[email protected]", "abcd****@testmail.org"); } }; emailMaskExpectations.forEach((email, expectedResult) -> { assertEquals(expectedResult, logMaskService.maskEmail(email)); }); } | public String maskEmail(String email) { if (email.indexOf("@") > 4) { return email.replaceAll("(^[^@]{4}|(?!^)\\G)[^@]", "$1*"); } else { return email.replaceAll("(^[^@]{2}|(?!^)\\G)[^@]", "$1*"); } } | LogMaskServiceImpl implements DataMaskingService { public String maskEmail(String email) { if (email.indexOf("@") > 4) { return email.replaceAll("(^[^@]{4}|(?!^)\\G)[^@]", "$1*"); } else { return email.replaceAll("(^[^@]{2}|(?!^)\\G)[^@]", "$1*"); } } } | LogMaskServiceImpl implements DataMaskingService { public String maskEmail(String email) { if (email.indexOf("@") > 4) { return email.replaceAll("(^[^@]{4}|(?!^)\\G)[^@]", "$1*"); } else { return email.replaceAll("(^[^@]{2}|(?!^)\\G)[^@]", "$1*"); } } } | LogMaskServiceImpl implements DataMaskingService { public String maskEmail(String email) { if (email.indexOf("@") > 4) { return email.replaceAll("(^[^@]{4}|(?!^)\\G)[^@]", "$1*"); } else { return email.replaceAll("(^[^@]{2}|(?!^)\\G)[^@]", "$1*"); } } String maskEmail(String email); String maskPhone(String phone); } | LogMaskServiceImpl implements DataMaskingService { public String maskEmail(String email) { if (email.indexOf("@") > 4) { return email.replaceAll("(^[^@]{4}|(?!^)\\G)[^@]", "$1*"); } else { return email.replaceAll("(^[^@]{2}|(?!^)\\G)[^@]", "$1*"); } } String maskEmail(String email); String maskPhone(String phone); } |
@Test public void maskPhone() { HashMap<String, String> phoneMaskExpectations = new HashMap<String, String>(){ { put("0123456789", "012345678*"); put("123-456-789", "123-456-7**"); put("123", "123"); } }; phoneMaskExpectations.forEach((phone, expectedResult) -> { assertEquals(expectedResult, logMaskService.maskPhone(phone)); }); } | public String maskPhone(String phone) { return phone.replaceAll("(^[^*]{9}|(?!^)\\G)[^*]", "$1*"); } | LogMaskServiceImpl implements DataMaskingService { public String maskPhone(String phone) { return phone.replaceAll("(^[^*]{9}|(?!^)\\G)[^*]", "$1*"); } } | LogMaskServiceImpl implements DataMaskingService { public String maskPhone(String phone) { return phone.replaceAll("(^[^*]{9}|(?!^)\\G)[^*]", "$1*"); } } | LogMaskServiceImpl implements DataMaskingService { public String maskPhone(String phone) { return phone.replaceAll("(^[^*]{9}|(?!^)\\G)[^*]", "$1*"); } String maskEmail(String email); String maskPhone(String phone); } | LogMaskServiceImpl implements DataMaskingService { public String maskPhone(String phone) { return phone.replaceAll("(^[^*]{9}|(?!^)\\G)[^*]", "$1*"); } String maskEmail(String email); String maskPhone(String phone); } |
@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(), response.get("response")); } | @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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } | 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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } } | 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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } CassandraOperationImpl(); } | 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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@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, "[email protected]"); when(session.execute(update)).thenReturn(resultSet); Response response = operation.updateRecordWithTTL(cassandraKeySpace, "otp", otp, compositeKey, 120); assertNotNull(response.get("response")); } | @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); Update update = QueryBuilder.update(keyspaceName, tableName); Assignments assignments = update.with(); Update.Where where = update.where(); request .entrySet() .stream() .forEach( x -> { assignments.and(QueryBuilder.set(x.getKey(), x.getValue())); }); compositeKey .entrySet() .stream() .forEach( x -> { where.and(eq(x.getKey(), x.getValue())); }); update.using(QueryBuilder.ttl(ttl)); ProjectLogger.log( "CassandraOperationImpl:updateRecordWithTTL: query = " + update.getQueryString(), LoggerEnum.INFO.name()); ResultSet results = session.execute(update); Response response = CassandraUtil.createResponse(results); logQueryElapseTime("updateRecordWithTTL", startTime); return response; } | 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); Update update = QueryBuilder.update(keyspaceName, tableName); Assignments assignments = update.with(); Update.Where where = update.where(); request .entrySet() .stream() .forEach( x -> { assignments.and(QueryBuilder.set(x.getKey(), x.getValue())); }); compositeKey .entrySet() .stream() .forEach( x -> { where.and(eq(x.getKey(), x.getValue())); }); update.using(QueryBuilder.ttl(ttl)); ProjectLogger.log( "CassandraOperationImpl:updateRecordWithTTL: query = " + update.getQueryString(), LoggerEnum.INFO.name()); ResultSet results = session.execute(update); Response response = CassandraUtil.createResponse(results); logQueryElapseTime("updateRecordWithTTL", startTime); return response; } } | 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); Update update = QueryBuilder.update(keyspaceName, tableName); Assignments assignments = update.with(); Update.Where where = update.where(); request .entrySet() .stream() .forEach( x -> { assignments.and(QueryBuilder.set(x.getKey(), x.getValue())); }); compositeKey .entrySet() .stream() .forEach( x -> { where.and(eq(x.getKey(), x.getValue())); }); update.using(QueryBuilder.ttl(ttl)); ProjectLogger.log( "CassandraOperationImpl:updateRecordWithTTL: query = " + update.getQueryString(), LoggerEnum.INFO.name()); ResultSet results = session.execute(update); Response response = CassandraUtil.createResponse(results); logQueryElapseTime("updateRecordWithTTL", startTime); return response; } CassandraOperationImpl(); } | 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); Update update = QueryBuilder.update(keyspaceName, tableName); Assignments assignments = update.with(); Update.Where where = update.where(); request .entrySet() .stream() .forEach( x -> { assignments.and(QueryBuilder.set(x.getKey(), x.getValue())); }); compositeKey .entrySet() .stream() .forEach( x -> { where.and(eq(x.getKey(), x.getValue())); }); update.using(QueryBuilder.ttl(ttl)); ProjectLogger.log( "CassandraOperationImpl:updateRecordWithTTL: query = " + update.getQueryString(), LoggerEnum.INFO.name()); ResultSet results = session.execute(update); Response response = CassandraUtil.createResponse(results); logQueryElapseTime("updateRecordWithTTL", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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); Update update = QueryBuilder.update(keyspaceName, tableName); Assignments assignments = update.with(); Update.Where where = update.where(); request .entrySet() .stream() .forEach( x -> { assignments.and(QueryBuilder.set(x.getKey(), x.getValue())); }); compositeKey .entrySet() .stream() .forEach( x -> { where.and(eq(x.getKey(), x.getValue())); }); update.using(QueryBuilder.ttl(ttl)); ProjectLogger.log( "CassandraOperationImpl:updateRecordWithTTL: query = " + update.getQueryString(), LoggerEnum.INFO.name()); ResultSet results = session.execute(update); Response response = CassandraUtil.createResponse(results); logQueryElapseTime("updateRecordWithTTL", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@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()); } | @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 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 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); } | 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(); } | 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; } |
@Test public void testUpdateRecordFailure() throws Exception { dummyAddress.put(JsonKey.CITY, "city"); dummyAddress.put(JsonKey.ADD_TYPE, "addrType"); when(session.prepare(Mockito.anyString())) .thenThrow( new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode())); Throwable exception = null; try { operation.updateRecord(cassandraKeySpace, "address", dummyAddress); } catch (Exception ex) { exception = ex; } assertEquals(ResponseCode.dbUpdateError.getErrorMessage(), exception.getMessage()); } | @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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } | 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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } } | 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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } CassandraOperationImpl(); } | 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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@Test public void testUpdateRecordFailureWithInvalidProperty() throws Exception { dummyAddress.put(JsonKey.CITY, "city"); dummyAddress.put(JsonKey.ADD_TYPE, "addrType"); when(session.prepare(Mockito.anyString())) .thenThrow( new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), JsonKey.UNKNOWN_IDENTIFIER, ResponseCode.CLIENT_ERROR.getResponseCode())); Throwable exception = null; try { operation.updateRecord(cassandraKeySpace, "address", dummyAddress); } catch (Exception exp) { exception = exp; } Object[] args = {""}; assertEquals( new MessageFormat(ResponseCode.invalidPropertyError.getErrorMessage()).format(args), exception.getMessage()); } | @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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } | 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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } } | 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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } CassandraOperationImpl(); } | 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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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); Response response = new Response(); try { String query = CassandraUtil.getUpdateQueryStatement(keyspaceName, tableName, request); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(query); Object[] array = new Object[request.size()]; int i = 0; String str = ""; int index = query.lastIndexOf(Constants.SET.trim()); str = query.substring(index + 4); str = str.replace(Constants.EQUAL_WITH_QUE_MARK, ""); str = str.replace(Constants.WHERE_ID, ""); str = str.replace(Constants.SEMICOLON, ""); String[] arr = str.split(","); for (String key : arr) { array[i++] = request.get(key.trim()); } array[i] = request.get(Constants.IDENTIFIER); BoundStatement boundStatement = statement.bind(array); connectionManager.getSession(keyspaceName).execute(boundStatement); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { e.printStackTrace(); if (e.getMessage().contains(JsonKey.UNKNOWN_IDENTIFIER)) { ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.invalidPropertyError.getErrorCode(), CassandraUtil.processExceptionForUnknownIdentifier(e), ResponseCode.CLIENT_ERROR.getResponseCode()); } ProjectLogger.log( Constants.EXCEPTION_MSG_UPDATE + tableName + " : " + e.getMessage(), e, LoggerEnum.ERROR.name()); throw new ProjectCommonException( ResponseCode.dbUpdateError.getErrorCode(), ResponseCode.dbUpdateError.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("updateRecord", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@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 = operation.getAllRecords(cassandraKeySpace, "address"); assertTrue(response.getResult().size() > 0); } | @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(); try { Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName); ResultSet results = connectionManager.getSession(keyspaceName).execute(selectQuery); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getAllRecords", startTime); return response; } | 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(); try { Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName); ResultSet results = connectionManager.getSession(keyspaceName).execute(selectQuery); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getAllRecords", startTime); return response; } } | 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(); try { Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName); ResultSet results = connectionManager.getSession(keyspaceName).execute(selectQuery); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getAllRecords", startTime); return response; } CassandraOperationImpl(); } | 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(); try { Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName); ResultSet results = connectionManager.getSession(keyspaceName).execute(selectQuery); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getAllRecords", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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(); try { Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName); ResultSet results = connectionManager.getSession(keyspaceName).execute(selectQuery); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getAllRecords", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@Test public void testGetAllRecordsFailure() throws Exception { when(session.execute(selectQuery)) .thenThrow( new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode())); List<Row> rows = new ArrayList<>(); Row row = Mockito.mock(Row.class); rows.add(row); when(resultSet.all()).thenReturn(rows); PowerMockito.whenNew(BoundStatement.class) .withArguments(Mockito.any(PreparedStatement.class)) .thenReturn(boundStatement); Throwable exception = null; try { operation.getAllRecords(cassandraKeySpace, "address"); } catch (Exception ex) { exception = ex; } assertTrue( (((ProjectCommonException) exception).getResponseCode()) == ResponseCode.SERVER_ERROR.getResponseCode()); } | @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(); try { Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName); ResultSet results = connectionManager.getSession(keyspaceName).execute(selectQuery); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getAllRecords", startTime); return response; } | 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(); try { Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName); ResultSet results = connectionManager.getSession(keyspaceName).execute(selectQuery); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getAllRecords", startTime); return response; } } | 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(); try { Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName); ResultSet results = connectionManager.getSession(keyspaceName).execute(selectQuery); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getAllRecords", startTime); return response; } CassandraOperationImpl(); } | 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(); try { Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName); ResultSet results = connectionManager.getSession(keyspaceName).execute(selectQuery); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getAllRecords", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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(); try { Select selectQuery = QueryBuilder.select().all().from(keyspaceName, tableName); ResultSet results = connectionManager.getSession(keyspaceName).execute(selectQuery); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getAllRecords", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@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(), ResponseCode.SERVER_ERROR.getResponseCode())); try { operation.getPropertiesValueById( cassandraKeySpace, "address", "123", JsonKey.ID, JsonKey.CITY, JsonKey.ADD_TYPE); } catch (Exception ex) { exception = ex; } assertTrue( (((ProjectCommonException) exception).getResponseCode()) == ResponseCode.SERVER_ERROR.getResponseCode()); } | @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, LoggerEnum.INFO); Response response = new Response(); try { String selectQuery = CassandraUtil.getSelectStatement(keyspaceName, tableName, properties); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(selectQuery); BoundStatement boundStatement = new BoundStatement(statement); ResultSet results = connectionManager.getSession(keyspaceName).execute(boundStatement.bind(id)); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getPropertiesValueById", startTime); return response; } | 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, LoggerEnum.INFO); Response response = new Response(); try { String selectQuery = CassandraUtil.getSelectStatement(keyspaceName, tableName, properties); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(selectQuery); BoundStatement boundStatement = new BoundStatement(statement); ResultSet results = connectionManager.getSession(keyspaceName).execute(boundStatement.bind(id)); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getPropertiesValueById", startTime); return response; } } | 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, LoggerEnum.INFO); Response response = new Response(); try { String selectQuery = CassandraUtil.getSelectStatement(keyspaceName, tableName, properties); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(selectQuery); BoundStatement boundStatement = new BoundStatement(statement); ResultSet results = connectionManager.getSession(keyspaceName).execute(boundStatement.bind(id)); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getPropertiesValueById", startTime); return response; } CassandraOperationImpl(); } | 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, LoggerEnum.INFO); Response response = new Response(); try { String selectQuery = CassandraUtil.getSelectStatement(keyspaceName, tableName, properties); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(selectQuery); BoundStatement boundStatement = new BoundStatement(statement); ResultSet results = connectionManager.getSession(keyspaceName).execute(boundStatement.bind(id)); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getPropertiesValueById", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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, LoggerEnum.INFO); Response response = new Response(); try { String selectQuery = CassandraUtil.getSelectStatement(keyspaceName, tableName, properties); PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(selectQuery); BoundStatement boundStatement = new BoundStatement(statement); ResultSet results = connectionManager.getSession(keyspaceName).execute(boundStatement.bind(id)); response = CassandraUtil.createResponse(results); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("getPropertiesValueById", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@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.anyString(), Mockito.anyString())).thenReturn(selectQuery); when(selectSelection.all()).thenReturn(selectBuilder); Response response = operation.getRecordById(cassandraKeySpace, "address", "123"); assertTrue(response.getResult().size() > 0); } | @Override public Response getRecordById(String keyspaceName, String tableName, String key) { return getRecordByIdentifier(keyspaceName, tableName, key, null); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordById(String keyspaceName, String tableName, String key) { return getRecordByIdentifier(keyspaceName, tableName, key, null); } } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordById(String keyspaceName, String tableName, String key) { return getRecordByIdentifier(keyspaceName, tableName, key, null); } CassandraOperationImpl(); } | 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<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@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")).thenReturn(alias); when(alias.as("otp_ttl")).thenReturn(selectSelection); Iterator<Row> rowItr = Mockito.mock(Iterator.class); Mockito.when(resultSet.iterator()).thenReturn(rowItr); when(session.execute(where)).thenReturn(resultSet); when(selectBuilder.from(Mockito.anyString(), Mockito.anyString())).thenReturn(selectQuery); when(selectSelection.all()).thenReturn(selectBuilder); Map<String, Object> key = new HashMap<>(); key.put(JsonKey.TYPE, JsonKey.EMAIL); key.put(JsonKey.KEY, "[email protected]"); List<String> ttlFields = new ArrayList<>(); ttlFields.add(JsonKey.OTP); List<String> fields = new ArrayList<>(); fields.add(JsonKey.CREATED_ON); fields.add(JsonKey.TYPE); fields.add(JsonKey.OTP); fields.add(JsonKey.KEY); Response response = operation.getRecordWithTTLById(cassandraKeySpace, "otp", key, ttlFields, fields); assertTrue(response.getResult().size() > 0); } | @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); } | 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); } } | 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); } CassandraOperationImpl(); } | 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); } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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); } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@Test public void testGetRecordFailureById() 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(), ResponseCode.SERVER_ERROR.getResponseCode())); try { operation.getRecordById(cassandraKeySpace, "address", "123"); } catch (Exception ex) { exception = ex; } assertTrue( (((ProjectCommonException) exception).getResponseCode()) == ResponseCode.SERVER_ERROR.getResponseCode()); } | @Override public Response getRecordById(String keyspaceName, String tableName, String key) { return getRecordByIdentifier(keyspaceName, tableName, key, null); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordById(String keyspaceName, String tableName, String key) { return getRecordByIdentifier(keyspaceName, tableName, key, null); } } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordById(String keyspaceName, String tableName, String key) { return getRecordByIdentifier(keyspaceName, tableName, key, null); } CassandraOperationImpl(); } | 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<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@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); Mockito.when(resultSet.iterator()).thenReturn(rowItr); Response response = operation.getRecordsByProperties(cassandraKeySpace, "address", map); assertTrue(response.getResult().size() > 0); } | @Override public Response getRecordsByProperties( String keyspaceName, String tableName, Map<String, Object> propertyMap) { return getRecordsByProperties(keyspaceName, tableName, propertyMap, null); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperties( String keyspaceName, String tableName, Map<String, Object> propertyMap) { return getRecordsByProperties(keyspaceName, tableName, propertyMap, null); } } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperties( String keyspaceName, String tableName, Map<String, Object> propertyMap) { return getRecordsByProperties(keyspaceName, tableName, propertyMap, null); } CassandraOperationImpl(); } | 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 keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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 keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@Test public void testGetRecordFailureByProperties() throws Exception { Map<String, Object> map = new HashMap<>(); map.put(JsonKey.USER_ID, "USR1"); map.put(JsonKey.ADD_TYPE, "addrType"); List<Row> rows = new ArrayList<>(); Row row = Mockito.mock(Row.class); rows.add(row); when(resultSet.all()).thenReturn(rows); when(selectSelection.all()) .thenThrow( new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode())); Throwable exception = null; try { operation.getRecordsByProperties(cassandraKeySpace, "address", map); } catch (Exception ex) { exception = ex; } assertTrue( (((ProjectCommonException) exception).getResponseCode()) == ResponseCode.SERVER_ERROR.getResponseCode()); } | @Override public Response getRecordsByProperties( String keyspaceName, String tableName, Map<String, Object> propertyMap) { return getRecordsByProperties(keyspaceName, tableName, propertyMap, null); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperties( String keyspaceName, String tableName, Map<String, Object> propertyMap) { return getRecordsByProperties(keyspaceName, tableName, propertyMap, null); } } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperties( String keyspaceName, String tableName, Map<String, Object> propertyMap) { return getRecordsByProperties(keyspaceName, tableName, propertyMap, null); } CassandraOperationImpl(); } | 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 keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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 keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@Test public void empty() { assertEquals(MigrationVersion.EMPTY, MigrationVersion.EMPTY); assertTrue(MigrationVersion.EMPTY.compareTo(MigrationVersion.EMPTY) == 0); } | @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 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 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); } | 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(); } | 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; } |
@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()).thenReturn(rowItr); Response response = operation.getRecordsByProperty(cassandraKeySpace, "address", JsonKey.ID, list); assertTrue(response.getResult().size() > 0); } | @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } CassandraOperationImpl(); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@Test public void testGetRecordForListFailreByProperties() throws Exception { List<Object> list = new ArrayList<>(); list.add("123"); list.add("321"); List<Row> rows = new ArrayList<>(); Row row = Mockito.mock(Row.class); rows.add(row); when(resultSet.all()).thenReturn(rows); when(selectSelection.all()) .thenThrow( new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode())); Throwable exception = null; try { operation.getRecordsByProperty(cassandraKeySpace, "address", JsonKey.ID, list); } catch (Exception ex) { exception = ex; } assertTrue( (((ProjectCommonException) exception).getResponseCode()) == ResponseCode.SERVER_ERROR.getResponseCode()); } | @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } CassandraOperationImpl(); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@Test public void testGetRecordsSuccessByProperty() throws Exception { List<Row> rows = new ArrayList<>(); Row row = Mockito.mock(Row.class); rows.add(row); when(resultSet.all()).thenReturn(rows); Iterator<Row> rowItr = Mockito.mock(Iterator.class); Mockito.when(resultSet.iterator()).thenReturn(rowItr); when(session.execute(boundStatement.bind("123"))).thenReturn(resultSet); Response response = operation.getRecordsByProperty(cassandraKeySpace, "address", JsonKey.ADD_TYPE, "addrType"); assertTrue(response.getResult().size() > 0); } | @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } CassandraOperationImpl(); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@Test public void testGetRecordsFailureByProperty() throws Exception { List<Row> rows = new ArrayList<>(); Row row = Mockito.mock(Row.class); rows.add(row); when(resultSet.all()).thenReturn(rows); when(selectSelection.all()) .thenThrow( new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode())); Throwable exception = null; try { operation.getRecordsByProperty(cassandraKeySpace, "address", JsonKey.ADD_TYPE, "addrType"); } catch (Exception ex) { exception = ex; } assertTrue( (((ProjectCommonException) exception).getResponseCode()) == ResponseCode.SERVER_ERROR.getResponseCode()); } | @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } CassandraOperationImpl(); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordsByProperty( String keyspaceName, String tableName, String propertyName, Object propertyValue) { return getRecordsByProperty(keyspaceName, tableName, propertyName, propertyValue, null); } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@Test public void testGetRecordsSuccessById() { Iterator<Row> rowItr = Mockito.mock(Iterator.class); Mockito.when(resultSet.iterator()).thenReturn(rowItr); when(session.execute(where)).thenReturn(resultSet); when(selectSelection.all()).thenReturn(selectBuilder); Response response = operation.getRecordById(cassandraKeySpace, "address", "123"); assertTrue(response.getResult().size() > 0); } | @Override public Response getRecordById(String keyspaceName, String tableName, String key) { return getRecordByIdentifier(keyspaceName, tableName, key, null); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordById(String keyspaceName, String tableName, String key) { return getRecordByIdentifier(keyspaceName, tableName, key, null); } } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordById(String keyspaceName, String tableName, String key) { return getRecordByIdentifier(keyspaceName, tableName, key, null); } CassandraOperationImpl(); } | 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<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@Test public void testGetRecordsFailureById() throws Exception { List<Row> rows = new ArrayList<>(); Row row = Mockito.mock(Row.class); rows.add(row); when(resultSet.all()).thenReturn(rows); when(selectSelection.all()) .thenThrow( new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode())); Throwable exception = null; try { operation.getRecordById(cassandraKeySpace, "address1", "123"); } catch (Exception ex) { exception = ex; } assertTrue( (((ProjectCommonException) exception).getResponseCode()) == ResponseCode.SERVER_ERROR.getResponseCode()); } | @Override public Response getRecordById(String keyspaceName, String tableName, String key) { return getRecordByIdentifier(keyspaceName, tableName, key, null); } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordById(String keyspaceName, String tableName, String key) { return getRecordByIdentifier(keyspaceName, tableName, key, null); } } | CassandraOperationImpl implements CassandraOperation { @Override public Response getRecordById(String keyspaceName, String tableName, String key) { return getRecordByIdentifier(keyspaceName, tableName, key, null); } CassandraOperationImpl(); } | 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<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@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")); } | @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 = new Response(); try { Delete.Where delete = QueryBuilder.delete() .from(keyspaceName, tableName) .where(eq(Constants.IDENTIFIER, identifier)); connectionManager.getSession(keyspaceName).execute(delete); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_DELETE + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("deleteRecord", startTime); return response; } | 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 = new Response(); try { Delete.Where delete = QueryBuilder.delete() .from(keyspaceName, tableName) .where(eq(Constants.IDENTIFIER, identifier)); connectionManager.getSession(keyspaceName).execute(delete); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_DELETE + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("deleteRecord", startTime); return response; } } | 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 = new Response(); try { Delete.Where delete = QueryBuilder.delete() .from(keyspaceName, tableName) .where(eq(Constants.IDENTIFIER, identifier)); connectionManager.getSession(keyspaceName).execute(delete); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_DELETE + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("deleteRecord", startTime); return response; } CassandraOperationImpl(); } | 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 = new Response(); try { Delete.Where delete = QueryBuilder.delete() .from(keyspaceName, tableName) .where(eq(Constants.IDENTIFIER, identifier)); connectionManager.getSession(keyspaceName).execute(delete); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_DELETE + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("deleteRecord", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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 = new Response(); try { Delete.Where delete = QueryBuilder.delete() .from(keyspaceName, tableName) .where(eq(Constants.IDENTIFIER, identifier)); connectionManager.getSession(keyspaceName).execute(delete); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_DELETE + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("deleteRecord", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@Test public void testDeleteRecordFailure() { when(QueryBuilder.delete()) .thenThrow( new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode())); Throwable exception = null; try { operation.deleteRecord(cassandraKeySpace, "address", "123"); } catch (Exception ex) { exception = ex; } assertTrue( (((ProjectCommonException) exception).getResponseCode()) == ResponseCode.SERVER_ERROR.getResponseCode()); } | @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 = new Response(); try { Delete.Where delete = QueryBuilder.delete() .from(keyspaceName, tableName) .where(eq(Constants.IDENTIFIER, identifier)); connectionManager.getSession(keyspaceName).execute(delete); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_DELETE + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("deleteRecord", startTime); return response; } | 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 = new Response(); try { Delete.Where delete = QueryBuilder.delete() .from(keyspaceName, tableName) .where(eq(Constants.IDENTIFIER, identifier)); connectionManager.getSession(keyspaceName).execute(delete); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_DELETE + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("deleteRecord", startTime); return response; } } | 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 = new Response(); try { Delete.Where delete = QueryBuilder.delete() .from(keyspaceName, tableName) .where(eq(Constants.IDENTIFIER, identifier)); connectionManager.getSession(keyspaceName).execute(delete); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_DELETE + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("deleteRecord", startTime); return response; } CassandraOperationImpl(); } | 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 = new Response(); try { Delete.Where delete = QueryBuilder.delete() .from(keyspaceName, tableName) .where(eq(Constants.IDENTIFIER, identifier)); connectionManager.getSession(keyspaceName).execute(delete); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_DELETE + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("deleteRecord", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } | 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 = new Response(); try { Delete.Where delete = QueryBuilder.delete() .from(keyspaceName, tableName) .where(eq(Constants.IDENTIFIER, identifier)); connectionManager.getSession(keyspaceName).execute(delete); response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { ProjectLogger.log(Constants.EXCEPTION_MSG_DELETE + tableName + " : " + e.getMessage(), e); throw new ProjectCommonException( ResponseCode.SERVER_ERROR.getErrorCode(), ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode()); } logQueryElapseTime("deleteRecord", startTime); return response; } CassandraOperationImpl(); @Override Response insertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response deleteRecord(String keyspaceName, String tableName, String identifier); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
Object propertyValue,
List<String> fields); @Override Response getRecordsByProperty(
String keyspaceName, String tableName, String propertyName, List<Object> propertyValueList); @Override Response getRecordsByProperty(
String keyspaceName,
String tableName,
String propertyName,
List<Object> propertyValueList,
List<String> fields); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap); @Override Response getRecordsByProperties(
String keyspaceName, String tableName, Map<String, Object> propertyMap, List<String> fields); @Override Response getPropertiesValueById(
String keyspaceName, String tableName, String id, String... properties); @Override Response getAllRecords(String keyspaceName, String tableName); @Override Response upsertRecord(String keyspaceName, String tableName, Map<String, Object> request); @Override Response updateRecord(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey); @Override Response getRecordById(String keyspaceName, String tableName, String key); @Override Response getRecordById(String keyspaceName, String tableName, Map<String, Object> key); @Override Response getRecordById(
String keyspaceName, String tableName, String key, List<String> fields); @Override Response getRecordById(
String keyspaceName, String tableName, Map<String, Object> key, List<String> fields); @Override Response getRecordWithTTLById(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); Response getRecordWithTTLByIdentifier(
String keyspaceName,
String tableName,
Map<String, Object> key,
List<String> ttlFields,
List<String> fields); @Override Response batchInsert(
String keyspaceName, String tableName, List<Map<String, Object>> records); Response batchUpdateById(
String keyspaceName, String tableName, List<Map<String, Object>> records); @Override Response performBatchAction(
String keySpaceName, String tableName, Map<String, Object> inputData); @Override Response batchUpdate(
String keyspaceName, String tableName, List<Map<String, Map<String, Object>>> list); @Override Response getRecordsByIndexedProperty(
String keyspaceName, String tableName, String propertyName, Object propertyValue); @Override void deleteRecord(
String keyspaceName, String tableName, Map<String, String> compositeKeyMap); @Override boolean deleteRecords(String keyspaceName, String tableName, List<String> identifierList); @Override Response getRecordsByCompositeKey(
String keyspaceName, String tableName, Map<String, Object> compositeKeyMap); @Override Response getRecordsByIdsWithSpecifiedColumns(
String keyspaceName, String tableName, List<String> properties, List<String> ids); @Override Response getRecordsByPrimaryKeys(
String keyspaceName,
String tableName,
List<String> primaryKeys,
String primaryKeyColumnName); @Override Response insertRecordWithTTL(
String keyspaceName, String tableName, Map<String, Object> request, int ttl); @Override Response updateRecordWithTTL(
String keyspaceName,
String tableName,
Map<String, Object> request,
Map<String, Object> compositeKey,
int ttl); @Override Response getRecordsByIdsWithSpecifiedColumnsAndTTL(
String keyspaceName,
String tableName,
Map<String, Object> primaryKeys,
List<String> properties,
Map<String, String> ttlPropertiesWithAlias); @Override Response batchInsertWithTTL(
String keyspaceName,
String tableName,
List<Map<String, Object>> records,
List<Integer> ttls); @Override Response getRecordByObjectType(
String keyspace,
String tableName,
String columnName,
String key,
int value,
String objectType); @Override Response getRecords(
String keyspace, String table, Map<String, Object> filters, List<String> fields); @Override void applyOperationOnRecordsAsync(
String keySpace,
String table,
Map<String, Object> filters,
List<String> fields,
FutureCallback<ResultSet> callback); @Override Response searchValueInList(String keyspace, String tableName, String key, String value); @Override Response searchValueInList(
String keyspace,
String tableName,
String key,
String value,
Map<String, Object> propertyMap); } |
@Test public void latest() { assertEquals(MigrationVersion.LATEST, MigrationVersion.LATEST); assertTrue(MigrationVersion.LATEST.compareTo(MigrationVersion.LATEST) == 0); } | @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 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 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); } | 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(); } | 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; } |
@Test(expected = CassandraMigrationException.class) public void missingNumber() { MigrationVersion.fromVersion("1..1"); } | 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 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 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); } | 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(); } | 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; } |
@Test(expected = CassandraMigrationException.class) public void dot() { MigrationVersion.fromVersion("."); } | 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 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 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); } | 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(); } | 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; } |
@Test(expected = CassandraMigrationException.class) public void startDot() { MigrationVersion.fromVersion(".1"); } | 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 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 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); } | 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(); } | 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; } |
@Test(expected = CassandraMigrationException.class) public void endDot() { MigrationVersion.fromVersion("1."); } | 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 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 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); } | 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(); } | 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; } |
@Test(expected = CassandraMigrationException.class) public void letters() { MigrationVersion.fromVersion("abc1.0"); } | 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 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 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); } | 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(); } | 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; } |
@Test(expected = CassandraMigrationException.class) public void dash() { MigrationVersion.fromVersion("1.2.1-3"); } | 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 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 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); } | 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(); } | 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; } |
@Test(expected = CassandraMigrationException.class) public void alphaNumeric() { MigrationVersion.fromVersion("1.2.1a-3"); } | 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 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 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); } | 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(); } | 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; } |
@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()); } | public boolean sendMail(List<String> emailList, String subject, String body) { return sendMail(emailList, subject, body, null); } | Email { public boolean sendMail(List<String> emailList, String subject, String body) { return sendMail(emailList, subject, body, null); } } | Email { public boolean sendMail(List<String> emailList, String subject, String body) { return sendMail(emailList, subject, body, null); } Email(); Email(EmailConfig config); } | 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(); } | 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(); } |
@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")); } | 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 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 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); } | 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(); } | 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(); } |
@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()); } } | 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(); } | 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(); } } | 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(); } | 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); } | 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); } |
@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()); } } | 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(); } | 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(); } } | 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(); } | 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); } | 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); } |
@Test public void shouldDefaultToNoKeyspaceButCanBeOverridden() { assertThat(new Keyspace().getName(), is(nullValue())); System.setProperty(Keyspace.KeyspaceProperty.NAME.getName(), "myspace"); assertThat(new Keyspace().getName(), is("myspace")); } | public String getName() { return name; } | Keyspace { public String getName() { return name; } } | Keyspace { public String getName() { return name; } Keyspace(); } | Keyspace { public String getName() { return name; } Keyspace(); Cluster getCluster(); void setCluster(Cluster cluster); String getName(); void setName(String name); } | Keyspace { public String getName() { return name; } Keyspace(); Cluster getCluster(); void setCluster(Cluster cluster); String getName(); void setName(String name); } |
@Test public void shouldHaveDefaultClusterObject() { assertThat(new Keyspace().getCluster(), is(notNullValue())); } | public Cluster getCluster() { return cluster; } | Keyspace { public Cluster getCluster() { return cluster; } } | Keyspace { public Cluster getCluster() { return cluster; } Keyspace(); } | Keyspace { public Cluster getCluster() { return cluster; } Keyspace(); Cluster getCluster(); void setCluster(Cluster cluster); String getName(); void setName(String name); } | Keyspace { public Cluster getCluster() { return cluster; } Keyspace(); Cluster getCluster(); void setCluster(Cluster cluster); String getName(); void setName(String name); } |
@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()); } | public List<ScriptsLocation> getLocations() { return locations; } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); } |
@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()); } | public List<ScriptsLocation> getLocations() { return locations; } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); } |
@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()); } | public List<ScriptsLocation> getLocations() { return locations; } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); } |
@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"))); } | public List<ScriptsLocation> getLocations() { return locations; } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); } |
@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"))); } | public List<ScriptsLocation> getLocations() { return locations; } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); } |
@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()); } | 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 { 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 { 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); } | 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(); } | 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(); } |
@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"))); } | public List<ScriptsLocation> getLocations() { return locations; } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); } | ScriptsLocations { public List<ScriptsLocation> getLocations() { return locations; } ScriptsLocations(String... rawLocations); List<ScriptsLocation> getLocations(); } |
@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)); } | public static String trimOrPad(String str, int length) { return trimOrPad(str, length, ' '); } | StringUtils { public static String trimOrPad(String str, int length) { return trimOrPad(str, length, ' '); } } | StringUtils { public static String trimOrPad(String str, int length) { return trimOrPad(str, length, ' '); } private StringUtils(); } | 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); } | 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); } |
@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")); } | public static boolean isNumeric(String str) { return str != null && str.matches("\\d*"); } | StringUtils { public static boolean isNumeric(String str) { return str != null && str.matches("\\d*"); } } | StringUtils { public static boolean isNumeric(String str) { return str != null && str.matches("\\d*"); } private StringUtils(); } | 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); } | 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); } |
@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 ")); } | public static String collapseWhitespace(String str) { return str.replaceAll("\\s+", " "); } | StringUtils { public static String collapseWhitespace(String str) { return str.replaceAll("\\s+", " "); } } | StringUtils { public static String collapseWhitespace(String str) { return str.replaceAll("\\s+", " "); } private StringUtils(); } | 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); } | 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); } |
@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", ",")); } | 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; } | 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; } } | 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(); } | 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); } | 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); } |
@Test public void isPresent() { assertTrue( ClassUtils.isPresent( "com.contrastsecurity.cassandra.migration.CassandraMigration", Thread.currentThread().getContextClassLoader())); } | public static boolean isPresent(String className, ClassLoader classLoader) { try { classLoader.loadClass(className); return true; } catch (Throwable ex) { return false; } } | ClassUtils { public static boolean isPresent(String className, ClassLoader classLoader) { try { classLoader.loadClass(className); return true; } catch (Throwable ex) { return false; } } } | ClassUtils { public static boolean isPresent(String className, ClassLoader classLoader) { try { classLoader.loadClass(className); return true; } catch (Throwable ex) { return false; } } private ClassUtils(); } | 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); } | 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); } |
@Test public void isPresentNot() { assertFalse( ClassUtils.isPresent( "com.example.FakeClass", Thread.currentThread().getContextClassLoader())); } | public static boolean isPresent(String className, ClassLoader classLoader) { try { classLoader.loadClass(className); return true; } catch (Throwable ex) { return false; } } | ClassUtils { public static boolean isPresent(String className, ClassLoader classLoader) { try { classLoader.loadClass(className); return true; } catch (Throwable ex) { return false; } } } | ClassUtils { public static boolean isPresent(String className, ClassLoader classLoader) { try { classLoader.loadClass(className); return true; } catch (Throwable ex) { return false; } } private ClassUtils(); } | 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); } | 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); } |
@Test public void shouldDetectSlf4j() { assertThat( new FeatureDetector(Thread.currentThread().getContextClassLoader()).isSlf4jAvailable(), is(true)); } | public boolean isSlf4jAvailable() { if (slf4jAvailable == null) { slf4jAvailable = isPresent("org.slf4j.Logger", classLoader); } return slf4jAvailable; } | FeatureDetector { public boolean isSlf4jAvailable() { if (slf4jAvailable == null) { slf4jAvailable = isPresent("org.slf4j.Logger", classLoader); } return slf4jAvailable; } } | FeatureDetector { public boolean isSlf4jAvailable() { if (slf4jAvailable == null) { slf4jAvailable = isPresent("org.slf4j.Logger", classLoader); } return slf4jAvailable; } FeatureDetector(ClassLoader classLoader); } | FeatureDetector { public boolean isSlf4jAvailable() { if (slf4jAvailable == null) { slf4jAvailable = isPresent("org.slf4j.Logger", classLoader); } return slf4jAvailable; } FeatureDetector(ClassLoader classLoader); boolean isApacheCommonsLoggingAvailable(); boolean isSlf4jAvailable(); } | 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 shouldDetectCommonsLogging() { assertThat( new FeatureDetector(Thread.currentThread().getContextClassLoader()) .isApacheCommonsLoggingAvailable(), is(true)); } | public boolean isApacheCommonsLoggingAvailable() { if (apacheCommonsLoggingAvailable == null) { apacheCommonsLoggingAvailable = isPresent("org.apache.commons.logging.Log", classLoader); } return apacheCommonsLoggingAvailable; } | FeatureDetector { public boolean isApacheCommonsLoggingAvailable() { if (apacheCommonsLoggingAvailable == null) { apacheCommonsLoggingAvailable = isPresent("org.apache.commons.logging.Log", classLoader); } return apacheCommonsLoggingAvailable; } } | FeatureDetector { public boolean isApacheCommonsLoggingAvailable() { if (apacheCommonsLoggingAvailable == null) { apacheCommonsLoggingAvailable = isPresent("org.apache.commons.logging.Log", classLoader); } return apacheCommonsLoggingAvailable; } FeatureDetector(ClassLoader classLoader); } | FeatureDetector { public boolean isApacheCommonsLoggingAvailable() { if (apacheCommonsLoggingAvailable == null) { apacheCommonsLoggingAvailable = isPresent("org.apache.commons.logging.Log", classLoader); } return apacheCommonsLoggingAvailable; } FeatureDetector(ClassLoader classLoader); boolean isApacheCommonsLoggingAvailable(); boolean isSlf4jAvailable(); } | FeatureDetector { public boolean isApacheCommonsLoggingAvailable() { if (apacheCommonsLoggingAvailable == null) { apacheCommonsLoggingAvailable = isPresent("org.apache.commons.logging.Log", classLoader); } return apacheCommonsLoggingAvailable; } FeatureDetector(ClassLoader classLoader); boolean isApacheCommonsLoggingAvailable(); boolean isSlf4jAvailable(); } |
@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)); } | public static String format(long millis) { return String.format( "%02d:%02d.%03ds", millis / 60000, (millis % 60000) / 1000, (millis % 1000)); } | TimeFormat { public static String format(long millis) { return String.format( "%02d:%02d.%03ds", millis / 60000, (millis % 60000) / 1000, (millis % 1000)); } } | TimeFormat { public static String format(long millis) { return String.format( "%02d:%02d.%03ds", millis / 60000, (millis % 60000) / 1000, (millis % 1000)); } private TimeFormat(); } | 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); } | 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 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()); } | 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 { 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 { 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); } | 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(); } | 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(); } |
@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()); } | public String getFilename() { return location.getName(); } | FileSystemResource implements Resource, Comparable<FileSystemResource> { public String getFilename() { return location.getName(); } } | FileSystemResource implements Resource, Comparable<FileSystemResource> { public String getFilename() { return location.getName(); } FileSystemResource(String location); } | 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); } | 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); } |
@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()); } | public String getLocation() { return StringUtils.replaceAll(location.getPath(), "\\", "/"); } | FileSystemResource implements Resource, Comparable<FileSystemResource> { public String getLocation() { return StringUtils.replaceAll(location.getPath(), "\\", "/"); } } | FileSystemResource implements Resource, Comparable<FileSystemResource> { public String getLocation() { return StringUtils.replaceAll(location.getPath(), "\\", "/"); } FileSystemResource(String location); } | 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); } | 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); } |
@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()); } | public String getFilename() { return location.substring(location.lastIndexOf("/") + 1); } | ClassPathResource implements Comparable<ClassPathResource>, Resource { public String getFilename() { return location.substring(location.lastIndexOf("/") + 1); } } | ClassPathResource implements Comparable<ClassPathResource>, Resource { public String getFilename() { return location.substring(location.lastIndexOf("/") + 1); } ClassPathResource(String location, ClassLoader classLoader); } | 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); } | 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); } |
@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")); } | 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 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 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); } | 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); } | 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); } |
@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")); } | 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 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 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); } | 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); } | 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); } |
@Test public void toFilePath() throws MalformedURLException { File file = new File("/test dir/a+b"); assertEquals(file.getAbsolutePath(), UrlUtils.toFilePath(file.toURI().toURL())); } | 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); } } | 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); } } } | 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(); } | 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); } | 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); } |
@Test public void testGetTcpClient() { ElasticSearchService service = EsClientFactory.getInstance("tcp"); Assert.assertTrue(service instanceof ElasticSearchTcpImpl); } | private static ElasticSearchService getTcpClient() { if (tcpClient == null) { tcpClient = new ElasticSearchTcpImpl(); } return tcpClient; } | EsClientFactory { private static ElasticSearchService getTcpClient() { if (tcpClient == null) { tcpClient = new ElasticSearchTcpImpl(); } return tcpClient; } } | EsClientFactory { private static ElasticSearchService getTcpClient() { if (tcpClient == null) { tcpClient = new ElasticSearchTcpImpl(); } return tcpClient; } } | EsClientFactory { private static ElasticSearchService getTcpClient() { if (tcpClient == null) { tcpClient = new ElasticSearchTcpImpl(); } return tcpClient; } static ElasticSearchService getInstance(String type); } | EsClientFactory { private static ElasticSearchService getTcpClient() { if (tcpClient == null) { tcpClient = new ElasticSearchTcpImpl(); } return tcpClient; } static ElasticSearchService getInstance(String type); } |
@Test public void testGetRestClient() { ElasticSearchService service = EsClientFactory.getInstance("rest"); Assert.assertTrue(service instanceof ElasticSearchRestHighImpl); } | private static ElasticSearchService getRestClient() { if (restClient == null) { restClient = new ElasticSearchRestHighImpl(); } return restClient; } | EsClientFactory { private static ElasticSearchService getRestClient() { if (restClient == null) { restClient = new ElasticSearchRestHighImpl(); } return restClient; } } | EsClientFactory { private static ElasticSearchService getRestClient() { if (restClient == null) { restClient = new ElasticSearchRestHighImpl(); } return restClient; } } | EsClientFactory { private static ElasticSearchService getRestClient() { if (restClient == null) { restClient = new ElasticSearchRestHighImpl(); } return restClient; } static ElasticSearchService getInstance(String type); } | EsClientFactory { private static ElasticSearchService getRestClient() { if (restClient == null) { restClient = new ElasticSearchRestHighImpl(); } return restClient; } static ElasticSearchService getInstance(String type); } |
@Test public void testInstanceNull() { ElasticSearchService service = EsClientFactory.getInstance("test"); Assert.assertNull(service); } | 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; } | 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; } } | 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; } } | 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); } | 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); } |
@Test public void testSaveSuccess() { mockRulesForSave(false); Future<String> result = esService.save("test", "001", new HashMap<>()); String res = (String) ElasticSearchHelper.getResponseFromFuture(result); assertEquals("001", res); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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); } |
@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); } | @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 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 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); } | 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); } | 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); } |
@Test public void testSaveFailureWithEmptyIndex() { Future<String> result = esService.save("", "001", new HashMap<>()); String res = (String) ElasticSearchHelper.getResponseFromFuture(result); assertEquals("ERROR", res); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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); } |
@Test public void testSaveFailureWithEmptyIdentifier() { Future<String> result = esService.save("test", "", new HashMap<>()); String res = (String) ElasticSearchHelper.getResponseFromFuture(result); assertEquals("ERROR", res); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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); } |
@Test public void testSaveFailure() { mockRulesForSave(true); Future<String> result = esService.save("test", "001", new HashMap<>()); String res = (String) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(null, res); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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); } |
@Test public void testUpdateSuccess() { mockRulesForUpdate(false); Future<Boolean> result = esService.update("test", "001", new HashMap<>()); boolean res = (boolean) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(true, res); } | @Override public Future<Boolean> update(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } |
@Test public void testUpdateFailure() { mockRulesForUpdate(true); Future<Boolean> result = esService.update("test", "001", new HashMap<>()); Object res = ElasticSearchHelper.getResponseFromFuture(result); assertEquals(null, res); } | @Override public Future<Boolean> update(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } |
@Test public void testUpdateFailureWithEmptyIndex() { try { esService.update("", "001", new HashMap<>()); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } } | @Override public Future<Boolean> update(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } |
@Test public void testUpdateFailureWithEmptyIdentifier() { try { esService.update("test", "", new HashMap<>()); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } } | @Override public Future<Boolean> update(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } |
@Test public void testGetDataByIdentifierFailureWithEmptyIndex() { try { esService.getDataByIdentifier("", "001"); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } } | @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(); } | 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(); } } | 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(); } } | 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); } | 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); } |
@Test public void testGetDataByIdentifierFailureWithEmptyIdentifier() { try { esService.getDataByIdentifier("test", ""); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } } | @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(); } | 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(); } } | 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(); } } | 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); } | 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); } |
@Test public void testGetDataByIdentifierFailure() { mockRulesForGet(true); Future<Map<String, Object>> result = esService.getDataByIdentifier("test", "001"); Object res = ElasticSearchHelper.getResponseFromFuture(result); assertEquals(null, res); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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); } |
@Test(expected = CassandraMigrationException.class) public void broken() { new JavaMigrationResolver( Thread.currentThread().getContextClassLoader(), new ScriptsLocation("com/contrastsecurity/cassandra/migration/resolver/java/error")) .resolveMigrations(); } | 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 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 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); } | 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(); } | 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(); } |
@Test public void testDeleteSuccess() { mockRulesForDelete(false, false); Future<Boolean> result = esService.delete("test", "001"); boolean res = (boolean) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(true, res); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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); } |
@Test public void testDeleteSuccessWithoutDelete() { mockRulesForDelete(false, true); Future<Boolean> result = esService.delete("test", "001"); boolean res = (boolean) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(false, res); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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); } |
@Test public void testDeleteFailure() { mockRulesForDelete(true, false); Future<Boolean> result = esService.delete("test", "001"); Object res = ElasticSearchHelper.getResponseFromFuture(result); assertEquals(null, res); } | @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(); } | 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(); } } | 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(); } } | 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); } | 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); } |
@Test public void testDeleteFailureWithEmptyIdentifier() { try { esService.delete("test", ""); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } } | @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(); } | 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(); } } | 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(); } } | 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); } | 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); } |
@Test public void testDeleteFailureWithEmptyIndex() { try { esService.delete("", "001"); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } } | @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(); } | 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(); } } | 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(); } } | 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); } | 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); } |
@Test public void testUpsertSuccess() { mockRulesForUpdate(false); Future<Boolean> result = esService.update("test", "001", new HashMap<>()); boolean res = (boolean) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(true, res); } | @Override public Future<Boolean> update(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } |
@Test public void testUpsertFailure() { mockRulesForUpdate(true); Future<Boolean> result = esService.update("test", "001", new HashMap<>()); Object res = ElasticSearchHelper.getResponseFromFuture(result); assertEquals(null, res); } | @Override public Future<Boolean> update(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } |
@Test public void testUpsertFailureWithEmptyIndex() { try { esService.update("", "001", new HashMap<>()); } catch (ProjectCommonException e) { assertEquals(e.getResponseCode(), ResponseCode.invalidData.getResponseCode()); } } | @Override public Future<Boolean> update(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } | 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, LoggerEnum.PERF_LOG.name()); Promise<Boolean> promise = Futures.promise(); ; if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { UpdateRequest updateRequest = new UpdateRequest(index, _DOC, identifier).doc(data); ActionListener<UpdateResponse> listener = new ActionListener<UpdateResponse>() { @Override public void onResponse(UpdateResponse updateResponse) { promise.success(true); ProjectLogger.log( "ElasticSearchRestHighImpl:update: Success with " + updateResponse.getResult() + " response from elastic search for index" + index + ",identifier : " + identifier, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchRestHighImpl:update: method end ==" + " for INdex " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); } @Override public void onFailure(Exception e) { ProjectLogger.log( "ElasticSearchRestHighImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } }; ConnectionManager.getRestClient().updateAsync(updateRequest, listener); } else { ProjectLogger.log( "ElasticSearchRestHighImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); promise.failure(ProjectUtil.createClientException(ResponseCode.invalidData)); } return promise.future(); } @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); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.