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 testUpsertFailureWithEmptyIdentifier() { 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 testBuilInsertSuccess() { mockRulesForBulk(false); List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> map = new HashMap<>(); map.put(JsonKey.IDENTIFIER, "0001"); list.add(map); Future<Boolean> result = esService.bulkInsert("test", list); boolean res = (boolean) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(true, res); } | @Override public Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); BulkRequest request = new BulkRequest(); Promise<Boolean> promise = Futures.promise(); for (Map<String, Object> data : dataList) { request.add(new IndexRequest(index, _DOC, (String) data.get(JsonKey.ID)).source(data)); } ActionListener<BulkResponse> listener = new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkResponse) { Iterator<BulkItemResponse> responseItr = bulkResponse.iterator(); if (responseItr != null) { promise.success(true); while (responseItr.hasNext()) { BulkItemResponse bResponse = responseItr.next(); if (bResponse.isFailed()) { ProjectLogger.log( "ElasticSearchRestHighImpl:bulkinsert: api response===" + bResponse.getId() + " " + bResponse.getFailureMessage(), LoggerEnum.INFO.name()); } } } } @Override public void onFailure(Exception e) { ProjectLogger.log("ElasticSearchRestHighImpl:bulkinsert: Bulk upload error block", e); promise.success(false); } }; ConnectionManager.getRestClient().bulkAsync(request, listener); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method end ==" + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); return promise.future(); } | ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); BulkRequest request = new BulkRequest(); Promise<Boolean> promise = Futures.promise(); for (Map<String, Object> data : dataList) { request.add(new IndexRequest(index, _DOC, (String) data.get(JsonKey.ID)).source(data)); } ActionListener<BulkResponse> listener = new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkResponse) { Iterator<BulkItemResponse> responseItr = bulkResponse.iterator(); if (responseItr != null) { promise.success(true); while (responseItr.hasNext()) { BulkItemResponse bResponse = responseItr.next(); if (bResponse.isFailed()) { ProjectLogger.log( "ElasticSearchRestHighImpl:bulkinsert: api response===" + bResponse.getId() + " " + bResponse.getFailureMessage(), LoggerEnum.INFO.name()); } } } } @Override public void onFailure(Exception e) { ProjectLogger.log("ElasticSearchRestHighImpl:bulkinsert: Bulk upload error block", e); promise.success(false); } }; ConnectionManager.getRestClient().bulkAsync(request, listener); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method end ==" + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); return promise.future(); } } | ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); BulkRequest request = new BulkRequest(); Promise<Boolean> promise = Futures.promise(); for (Map<String, Object> data : dataList) { request.add(new IndexRequest(index, _DOC, (String) data.get(JsonKey.ID)).source(data)); } ActionListener<BulkResponse> listener = new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkResponse) { Iterator<BulkItemResponse> responseItr = bulkResponse.iterator(); if (responseItr != null) { promise.success(true); while (responseItr.hasNext()) { BulkItemResponse bResponse = responseItr.next(); if (bResponse.isFailed()) { ProjectLogger.log( "ElasticSearchRestHighImpl:bulkinsert: api response===" + bResponse.getId() + " " + bResponse.getFailureMessage(), LoggerEnum.INFO.name()); } } } } @Override public void onFailure(Exception e) { ProjectLogger.log("ElasticSearchRestHighImpl:bulkinsert: Bulk upload error block", e); promise.success(false); } }; ConnectionManager.getRestClient().bulkAsync(request, listener); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method end ==" + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); return promise.future(); } } | ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); BulkRequest request = new BulkRequest(); Promise<Boolean> promise = Futures.promise(); for (Map<String, Object> data : dataList) { request.add(new IndexRequest(index, _DOC, (String) data.get(JsonKey.ID)).source(data)); } ActionListener<BulkResponse> listener = new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkResponse) { Iterator<BulkItemResponse> responseItr = bulkResponse.iterator(); if (responseItr != null) { promise.success(true); while (responseItr.hasNext()) { BulkItemResponse bResponse = responseItr.next(); if (bResponse.isFailed()) { ProjectLogger.log( "ElasticSearchRestHighImpl:bulkinsert: api response===" + bResponse.getId() + " " + bResponse.getFailureMessage(), LoggerEnum.INFO.name()); } } } } @Override public void onFailure(Exception e) { ProjectLogger.log("ElasticSearchRestHighImpl:bulkinsert: Bulk upload error block", e); promise.success(false); } }; ConnectionManager.getRestClient().bulkAsync(request, listener); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method end ==" + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> delete(String index, String identifier); @Override @SuppressWarnings({"unchecked", "rawtypes"}) Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Boolean> healthCheck(); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); } | ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); BulkRequest request = new BulkRequest(); Promise<Boolean> promise = Futures.promise(); for (Map<String, Object> data : dataList) { request.add(new IndexRequest(index, _DOC, (String) data.get(JsonKey.ID)).source(data)); } ActionListener<BulkResponse> listener = new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkResponse) { Iterator<BulkItemResponse> responseItr = bulkResponse.iterator(); if (responseItr != null) { promise.success(true); while (responseItr.hasNext()) { BulkItemResponse bResponse = responseItr.next(); if (bResponse.isFailed()) { ProjectLogger.log( "ElasticSearchRestHighImpl:bulkinsert: api response===" + bResponse.getId() + " " + bResponse.getFailureMessage(), LoggerEnum.INFO.name()); } } } } @Override public void onFailure(Exception e) { ProjectLogger.log("ElasticSearchRestHighImpl:bulkinsert: Bulk upload error block", e); promise.success(false); } }; ConnectionManager.getRestClient().bulkAsync(request, listener); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method end ==" + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> delete(String index, String identifier); @Override @SuppressWarnings({"unchecked", "rawtypes"}) Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Boolean> healthCheck(); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); } |
@Test public void resolveMigrations() { JavaMigrationResolver jdbcMigrationResolver = new JavaMigrationResolver( Thread.currentThread().getContextClassLoader(), new ScriptsLocation("com/contrastsecurity/cassandra/migration/resolver/java/dummy")); Collection<ResolvedMigration> migrations = jdbcMigrationResolver.resolveMigrations(); assertEquals(3, migrations.size()); List<ResolvedMigration> migrationList = new ArrayList<ResolvedMigration>(migrations); ResolvedMigration migrationInfo = migrationList.get(0); assertEquals("2", migrationInfo.getVersion().toString()); assertEquals("InterfaceBasedMigration", migrationInfo.getDescription()); assertNull(migrationInfo.getChecksum()); ResolvedMigration migrationInfo1 = migrationList.get(1); assertEquals("3.5", migrationInfo1.getVersion().toString()); assertEquals("Three Dot Five", migrationInfo1.getDescription()); assertEquals(35, migrationInfo1.getChecksum().intValue()); ResolvedMigration migrationInfo2 = migrationList.get(2); assertEquals("4", migrationInfo2.getVersion().toString()); } | 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 testBuilInsertFailure() { mockRulesForBulk(true); List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> map = new HashMap<>(); map.put(JsonKey.IDENTIFIER, "0001"); list.add(map); Future<Boolean> result = esService.bulkInsert("test", list); boolean res = (boolean) ElasticSearchHelper.getResponseFromFuture(result); assertEquals(false, res); } | @Override public Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); BulkRequest request = new BulkRequest(); Promise<Boolean> promise = Futures.promise(); for (Map<String, Object> data : dataList) { request.add(new IndexRequest(index, _DOC, (String) data.get(JsonKey.ID)).source(data)); } ActionListener<BulkResponse> listener = new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkResponse) { Iterator<BulkItemResponse> responseItr = bulkResponse.iterator(); if (responseItr != null) { promise.success(true); while (responseItr.hasNext()) { BulkItemResponse bResponse = responseItr.next(); if (bResponse.isFailed()) { ProjectLogger.log( "ElasticSearchRestHighImpl:bulkinsert: api response===" + bResponse.getId() + " " + bResponse.getFailureMessage(), LoggerEnum.INFO.name()); } } } } @Override public void onFailure(Exception e) { ProjectLogger.log("ElasticSearchRestHighImpl:bulkinsert: Bulk upload error block", e); promise.success(false); } }; ConnectionManager.getRestClient().bulkAsync(request, listener); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method end ==" + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); return promise.future(); } | ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); BulkRequest request = new BulkRequest(); Promise<Boolean> promise = Futures.promise(); for (Map<String, Object> data : dataList) { request.add(new IndexRequest(index, _DOC, (String) data.get(JsonKey.ID)).source(data)); } ActionListener<BulkResponse> listener = new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkResponse) { Iterator<BulkItemResponse> responseItr = bulkResponse.iterator(); if (responseItr != null) { promise.success(true); while (responseItr.hasNext()) { BulkItemResponse bResponse = responseItr.next(); if (bResponse.isFailed()) { ProjectLogger.log( "ElasticSearchRestHighImpl:bulkinsert: api response===" + bResponse.getId() + " " + bResponse.getFailureMessage(), LoggerEnum.INFO.name()); } } } } @Override public void onFailure(Exception e) { ProjectLogger.log("ElasticSearchRestHighImpl:bulkinsert: Bulk upload error block", e); promise.success(false); } }; ConnectionManager.getRestClient().bulkAsync(request, listener); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method end ==" + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); return promise.future(); } } | ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); BulkRequest request = new BulkRequest(); Promise<Boolean> promise = Futures.promise(); for (Map<String, Object> data : dataList) { request.add(new IndexRequest(index, _DOC, (String) data.get(JsonKey.ID)).source(data)); } ActionListener<BulkResponse> listener = new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkResponse) { Iterator<BulkItemResponse> responseItr = bulkResponse.iterator(); if (responseItr != null) { promise.success(true); while (responseItr.hasNext()) { BulkItemResponse bResponse = responseItr.next(); if (bResponse.isFailed()) { ProjectLogger.log( "ElasticSearchRestHighImpl:bulkinsert: api response===" + bResponse.getId() + " " + bResponse.getFailureMessage(), LoggerEnum.INFO.name()); } } } } @Override public void onFailure(Exception e) { ProjectLogger.log("ElasticSearchRestHighImpl:bulkinsert: Bulk upload error block", e); promise.success(false); } }; ConnectionManager.getRestClient().bulkAsync(request, listener); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method end ==" + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); return promise.future(); } } | ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); BulkRequest request = new BulkRequest(); Promise<Boolean> promise = Futures.promise(); for (Map<String, Object> data : dataList) { request.add(new IndexRequest(index, _DOC, (String) data.get(JsonKey.ID)).source(data)); } ActionListener<BulkResponse> listener = new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkResponse) { Iterator<BulkItemResponse> responseItr = bulkResponse.iterator(); if (responseItr != null) { promise.success(true); while (responseItr.hasNext()) { BulkItemResponse bResponse = responseItr.next(); if (bResponse.isFailed()) { ProjectLogger.log( "ElasticSearchRestHighImpl:bulkinsert: api response===" + bResponse.getId() + " " + bResponse.getFailureMessage(), LoggerEnum.INFO.name()); } } } } @Override public void onFailure(Exception e) { ProjectLogger.log("ElasticSearchRestHighImpl:bulkinsert: Bulk upload error block", e); promise.success(false); } }; ConnectionManager.getRestClient().bulkAsync(request, listener); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method end ==" + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> delete(String index, String identifier); @Override @SuppressWarnings({"unchecked", "rawtypes"}) Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Boolean> healthCheck(); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); } | ElasticSearchRestHighImpl implements ElasticSearchService { @Override public Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList) { long startTime = System.currentTimeMillis(); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); BulkRequest request = new BulkRequest(); Promise<Boolean> promise = Futures.promise(); for (Map<String, Object> data : dataList) { request.add(new IndexRequest(index, _DOC, (String) data.get(JsonKey.ID)).source(data)); } ActionListener<BulkResponse> listener = new ActionListener<BulkResponse>() { @Override public void onResponse(BulkResponse bulkResponse) { Iterator<BulkItemResponse> responseItr = bulkResponse.iterator(); if (responseItr != null) { promise.success(true); while (responseItr.hasNext()) { BulkItemResponse bResponse = responseItr.next(); if (bResponse.isFailed()) { ProjectLogger.log( "ElasticSearchRestHighImpl:bulkinsert: api response===" + bResponse.getId() + " " + bResponse.getFailureMessage(), LoggerEnum.INFO.name()); } } } } @Override public void onFailure(Exception e) { ProjectLogger.log("ElasticSearchRestHighImpl:bulkinsert: Bulk upload error block", e); promise.success(false); } }; ConnectionManager.getRestClient().bulkAsync(request, listener); ProjectLogger.log( "ElasticSearchRestHighImpl:bulkInsert: method end ==" + " for Index " + index + " ,Total time elapsed = " + calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> delete(String index, String identifier); @Override @SuppressWarnings({"unchecked", "rawtypes"}) Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Boolean> healthCheck(); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); } |
@Test public void testCreateDataSuccess() { mockRulesForInsert(); esService.save(INDEX_NAME, (String) chemistryMap.get("courseId"), chemistryMap); assertNotNull(chemistryMap.get("courseId")); esService.save(INDEX_NAME, (String) physicsMap.get("courseId"), physicsMap); assertNotNull(physicsMap.get("courseId")); } | @Override public Future<String> save(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); Promise<String> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:save: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); if (StringUtils.isBlank(identifier) || StringUtils.isBlank(index)) { ProjectLogger.log( "ElasticSearchTcpImpl:save: Identifier value is null or empty ,not able to save data.", LoggerEnum.ERROR.name()); promise.success("ERROR"); return promise.future(); } try { data.put("identifier", identifier); IndexResponse response = ConnectionManager.getClient().prepareIndex(index, _DOC, identifier).setSource(data).get(); ProjectLogger.log( "ElasticSearchTcpImpl:save: " + "Save value==" + response.getId() + " " + response.status(), LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchTcpImpl:save: method end at ==" + System.currentTimeMillis() + " for INdex " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getId()); return promise.future(); } catch (Exception e) { ProjectLogger.log( "ElasticSearchTcpImpl:save: Error while saving index " + index + " id : " + identifier + " with error :" + e, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchTcpImpl:save: method end at ==" + System.currentTimeMillis() + " for Index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(""); } return promise.future(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<String> save(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); Promise<String> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:save: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); if (StringUtils.isBlank(identifier) || StringUtils.isBlank(index)) { ProjectLogger.log( "ElasticSearchTcpImpl:save: Identifier value is null or empty ,not able to save data.", LoggerEnum.ERROR.name()); promise.success("ERROR"); return promise.future(); } try { data.put("identifier", identifier); IndexResponse response = ConnectionManager.getClient().prepareIndex(index, _DOC, identifier).setSource(data).get(); ProjectLogger.log( "ElasticSearchTcpImpl:save: " + "Save value==" + response.getId() + " " + response.status(), LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchTcpImpl:save: method end at ==" + System.currentTimeMillis() + " for INdex " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getId()); return promise.future(); } catch (Exception e) { ProjectLogger.log( "ElasticSearchTcpImpl:save: Error while saving index " + index + " id : " + identifier + " with error :" + e, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchTcpImpl:save: method end at ==" + System.currentTimeMillis() + " for Index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(""); } return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<String> save(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); Promise<String> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:save: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); if (StringUtils.isBlank(identifier) || StringUtils.isBlank(index)) { ProjectLogger.log( "ElasticSearchTcpImpl:save: Identifier value is null or empty ,not able to save data.", LoggerEnum.ERROR.name()); promise.success("ERROR"); return promise.future(); } try { data.put("identifier", identifier); IndexResponse response = ConnectionManager.getClient().prepareIndex(index, _DOC, identifier).setSource(data).get(); ProjectLogger.log( "ElasticSearchTcpImpl:save: " + "Save value==" + response.getId() + " " + response.status(), LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchTcpImpl:save: method end at ==" + System.currentTimeMillis() + " for INdex " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getId()); return promise.future(); } catch (Exception e) { ProjectLogger.log( "ElasticSearchTcpImpl:save: Error while saving index " + index + " id : " + identifier + " with error :" + e, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchTcpImpl:save: method end at ==" + System.currentTimeMillis() + " for Index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(""); } return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<String> save(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); Promise<String> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:save: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); if (StringUtils.isBlank(identifier) || StringUtils.isBlank(index)) { ProjectLogger.log( "ElasticSearchTcpImpl:save: Identifier value is null or empty ,not able to save data.", LoggerEnum.ERROR.name()); promise.success("ERROR"); return promise.future(); } try { data.put("identifier", identifier); IndexResponse response = ConnectionManager.getClient().prepareIndex(index, _DOC, identifier).setSource(data).get(); ProjectLogger.log( "ElasticSearchTcpImpl:save: " + "Save value==" + response.getId() + " " + response.status(), LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchTcpImpl:save: method end at ==" + System.currentTimeMillis() + " for INdex " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getId()); return promise.future(); } catch (Exception e) { ProjectLogger.log( "ElasticSearchTcpImpl:save: Error while saving index " + index + " id : " + identifier + " with error :" + e, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchTcpImpl:save: method end at ==" + System.currentTimeMillis() + " for Index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(""); } return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<String> save(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); Promise<String> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:save: method started at ==" + startTime + " for Index " + index, LoggerEnum.PERF_LOG.name()); if (StringUtils.isBlank(identifier) || StringUtils.isBlank(index)) { ProjectLogger.log( "ElasticSearchTcpImpl:save: Identifier value is null or empty ,not able to save data.", LoggerEnum.ERROR.name()); promise.success("ERROR"); return promise.future(); } try { data.put("identifier", identifier); IndexResponse response = ConnectionManager.getClient().prepareIndex(index, _DOC, identifier).setSource(data).get(); ProjectLogger.log( "ElasticSearchTcpImpl:save: " + "Save value==" + response.getId() + " " + response.status(), LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchTcpImpl:save: method end at ==" + System.currentTimeMillis() + " for INdex " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getId()); return promise.future(); } catch (Exception e) { ProjectLogger.log( "ElasticSearchTcpImpl:save: Error while saving index " + index + " id : " + identifier + " with error :" + e, LoggerEnum.INFO.name()); ProjectLogger.log( "ElasticSearchTcpImpl:save: method end at ==" + System.currentTimeMillis() + " for Index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(""); } return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); static final int WAIT_TIME; static Timeout timeout; } |
@Test public void testGetByIdentifierSuccess() { Future<Map<String, Object>> responseMapF = esService.getDataByIdentifier(INDEX_NAME, (String) chemistryMap.get("courseId")); Map<String, Object> responseMap = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(responseMapF); assertEquals(responseMap.get("courseId"), chemistryMap.get("courseId")); } | @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); static final int WAIT_TIME; static Timeout timeout; } |
@Test public void testUpdateDataSuccess() { Map<String, Object> innermap = new HashMap<>(); innermap.put("courseName", "Updated course name"); innermap.put("organisationId", "updatedOrgId"); GetRequestBuilder grb = mock(GetRequestBuilder.class); GetResponse getResponse = mock(GetResponse.class); when(client.prepareGet( Mockito.anyString(), Mockito.anyString(), Mockito.eq((String) chemistryMap.get("courseId")))) .thenReturn(grb); when(grb.get()).thenReturn(getResponse); when(getResponse.getSource()).thenReturn(innermap); Future<Boolean> responseF = esService.update(INDEX_NAME, (String) chemistryMap.get("courseId"), innermap); boolean response = (boolean) ElasticSearchHelper.getResponseFromFuture(responseF); assertTrue(response); } | @Override public Future<Boolean> update(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); Promise<Boolean> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:update: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { try { UpdateResponse response = ConnectionManager.getClient().prepareUpdate(index, _DOC, identifier).setDoc(data).get(); ProjectLogger.log( "ElasticSearchTcpImpl:update: " + "updated response==" + response.getResult().name(), LoggerEnum.INFO.name()); if (response.getResult().name().equals("UPDATED")) { ProjectLogger.log( "ElasticSearchTcpImpl:update: method end ==" + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(true); return promise.future(); } else { ProjectLogger.log( "ElasticSearchTcpImpl:update: update was not success:" + response.getResult(), LoggerEnum.INFO.name()); } } catch (Exception e) { ProjectLogger.log( "ElasticSearchTcpImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } } else { ProjectLogger.log( "ElasticSearchTcpImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); } ProjectLogger.log( "ElasticSearchTcpImpl:update: method end ==" + " for Index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(false); return promise.future(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Boolean> update(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); Promise<Boolean> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:update: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { try { UpdateResponse response = ConnectionManager.getClient().prepareUpdate(index, _DOC, identifier).setDoc(data).get(); ProjectLogger.log( "ElasticSearchTcpImpl:update: " + "updated response==" + response.getResult().name(), LoggerEnum.INFO.name()); if (response.getResult().name().equals("UPDATED")) { ProjectLogger.log( "ElasticSearchTcpImpl:update: method end ==" + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(true); return promise.future(); } else { ProjectLogger.log( "ElasticSearchTcpImpl:update: update was not success:" + response.getResult(), LoggerEnum.INFO.name()); } } catch (Exception e) { ProjectLogger.log( "ElasticSearchTcpImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } } else { ProjectLogger.log( "ElasticSearchTcpImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); } ProjectLogger.log( "ElasticSearchTcpImpl:update: method end ==" + " for Index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(false); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Boolean> update(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); Promise<Boolean> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:update: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { try { UpdateResponse response = ConnectionManager.getClient().prepareUpdate(index, _DOC, identifier).setDoc(data).get(); ProjectLogger.log( "ElasticSearchTcpImpl:update: " + "updated response==" + response.getResult().name(), LoggerEnum.INFO.name()); if (response.getResult().name().equals("UPDATED")) { ProjectLogger.log( "ElasticSearchTcpImpl:update: method end ==" + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(true); return promise.future(); } else { ProjectLogger.log( "ElasticSearchTcpImpl:update: update was not success:" + response.getResult(), LoggerEnum.INFO.name()); } } catch (Exception e) { ProjectLogger.log( "ElasticSearchTcpImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } } else { ProjectLogger.log( "ElasticSearchTcpImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); } ProjectLogger.log( "ElasticSearchTcpImpl:update: method end ==" + " for Index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(false); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Boolean> update(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); Promise<Boolean> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:update: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { try { UpdateResponse response = ConnectionManager.getClient().prepareUpdate(index, _DOC, identifier).setDoc(data).get(); ProjectLogger.log( "ElasticSearchTcpImpl:update: " + "updated response==" + response.getResult().name(), LoggerEnum.INFO.name()); if (response.getResult().name().equals("UPDATED")) { ProjectLogger.log( "ElasticSearchTcpImpl:update: method end ==" + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(true); return promise.future(); } else { ProjectLogger.log( "ElasticSearchTcpImpl:update: update was not success:" + response.getResult(), LoggerEnum.INFO.name()); } } catch (Exception e) { ProjectLogger.log( "ElasticSearchTcpImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } } else { ProjectLogger.log( "ElasticSearchTcpImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); } ProjectLogger.log( "ElasticSearchTcpImpl:update: method end ==" + " for Index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(false); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Boolean> update(String index, String identifier, Map<String, Object> data) { long startTime = System.currentTimeMillis(); Promise<Boolean> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:update: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); if (!StringUtils.isBlank(index) && !StringUtils.isBlank(identifier) && data != null) { try { UpdateResponse response = ConnectionManager.getClient().prepareUpdate(index, _DOC, identifier).setDoc(data).get(); ProjectLogger.log( "ElasticSearchTcpImpl:update: " + "updated response==" + response.getResult().name(), LoggerEnum.INFO.name()); if (response.getResult().name().equals("UPDATED")) { ProjectLogger.log( "ElasticSearchTcpImpl:update: method end ==" + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(true); return promise.future(); } else { ProjectLogger.log( "ElasticSearchTcpImpl:update: update was not success:" + response.getResult(), LoggerEnum.INFO.name()); } } catch (Exception e) { ProjectLogger.log( "ElasticSearchTcpImpl:update: exception occured:" + e.getMessage(), LoggerEnum.ERROR.name()); promise.failure(e); } } else { ProjectLogger.log( "ElasticSearchTcpImpl:update: Requested data is invalid.", LoggerEnum.INFO.name()); } ProjectLogger.log( "ElasticSearchTcpImpl:update: method end ==" + " for Index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(false); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); static final int WAIT_TIME; static Timeout timeout; } |
@Test @Ignore public void testComplexSearchSuccess() throws Exception { SearchDTO searchDTO = new SearchDTO(); List<String> fields = new ArrayList<String>(); fields.add("courseId"); fields.add("courseType"); fields.add("createdOn"); fields.add("description"); Map<String, Object> sortMap = new HashMap<>(); sortMap.put("courseType", "ASC"); searchDTO.setSortBy(sortMap); List<String> excludedFields = new ArrayList<String>(); excludedFields.add("createdOn"); searchDTO.setExcludedFields(excludedFields); searchDTO.setLimit(20); searchDTO.setOffset(0); Map<String, Object> additionalPro = new HashMap<String, Object>(); searchDTO.addAdditionalProperty("test", additionalPro); List<String> existsList = new ArrayList<String>(); existsList.add("pkgVersion"); existsList.add("size"); Map<String, Object> additionalProperties = new HashMap<String, Object>(); additionalProperties.put(JsonKey.EXISTS, existsList); List<String> description = new ArrayList<String>(); description.add("This is for chemistry"); description.add("Hindi Jii"); List<Integer> sizes = new ArrayList<Integer>(); sizes.add(10); sizes.add(20); Map<String, Object> filterMap = new HashMap<String, Object>(); filterMap.put("description", description); filterMap.put("size", sizes); additionalProperties.put(JsonKey.FILTERS, filterMap); Map<String, Object> rangeMap = new HashMap<String, Object>(); rangeMap.put(">", 0); filterMap.put("pkgVersion", rangeMap); Map<String, Object> lexicalMap = new HashMap<>(); lexicalMap.put(STARTS_WITH, "type"); filterMap.put("courseType", lexicalMap); Map<String, Object> lexicalMap1 = new HashMap<>(); lexicalMap1.put(ENDS_WITH, "sunbird"); filterMap.put("courseAddedByName", lexicalMap1); filterMap.put("orgName", "Name of the organisation"); searchDTO.setAdditionalProperties(additionalProperties); searchDTO.setFields(fields); searchDTO.setQuery("organisation"); List<String> mode = Arrays.asList("soft"); searchDTO.setMode(mode); Map<String, Integer> constraintMap = new HashMap<String, Integer>(); constraintMap.put("grades", 10); constraintMap.put("pkgVersion", 5); searchDTO.setSoftConstraints(constraintMap); searchDTO.setQuery("organisation Name published"); mockRulesForSearch(3); Future<Map<String, Object>> map = esService.search(searchDTO, INDEX_NAME); Map<String, Object> response = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(map); assertEquals(2, response.size()); } | @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); static final int WAIT_TIME; static Timeout timeout; } |
@Test @Ignore public void testComplexSearchSuccessWithRangeGreaterThan() { SearchDTO searchDTO = new SearchDTO(); Map<String, Object> additionalProperties = new HashMap<String, Object>(); List<Integer> sizes = new ArrayList<Integer>(); sizes.add(10); sizes.add(20); Map<String, Object> filterMap = new HashMap<String, Object>(); filterMap.put("size", sizes); Map<String, String> innerMap = new HashMap<>(); innerMap.put("createdOn", "2017-11-06"); filterMap.put(">=", innerMap); additionalProperties.put(JsonKey.FILTERS, filterMap); Map<String, Object> rangeMap = new HashMap<String, Object>(); rangeMap.put(">", 0); filterMap.put("pkgVersion", rangeMap); Map<String, Object> lexicalMap = new HashMap<>(); lexicalMap.put(STARTS_WITH, "type"); filterMap.put("courseType", lexicalMap); Map<String, Object> lexicalMap1 = new HashMap<>(); lexicalMap1.put(ENDS_WITH, "sunbird"); filterMap.put("courseAddedByName", lexicalMap1); filterMap.put("orgName", "Name of the organisation"); searchDTO.setAdditionalProperties(additionalProperties); searchDTO.setQuery("organisation"); mockRulesForSearch(3); Future<Map<String, Object>> map = esService.search(searchDTO, INDEX_NAME); Map<String, Object> response = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(map); assertEquals(2, response.size()); } | @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); static final int WAIT_TIME; static Timeout timeout; } |
@Test @Ignore public void testComplexSearchSuccessWithRangeLessThan() { SearchDTO searchDTO = new SearchDTO(); Map<String, Object> additionalProperties = new HashMap<String, Object>(); List<Integer> sizes = new ArrayList<Integer>(); sizes.add(10); sizes.add(20); Map<String, Object> filterMap = new HashMap<String, Object>(); filterMap.put("size", sizes); Map<String, String> innerMap = new HashMap<>(); innerMap.put("createdOn", "2017-11-06"); filterMap.put("<=", innerMap); additionalProperties.put(JsonKey.FILTERS, filterMap); Map<String, Object> rangeMap = new HashMap<String, Object>(); rangeMap.put(">", 0); filterMap.put("pkgVersion", rangeMap); Map<String, Object> lexicalMap = new HashMap<>(); lexicalMap.put(STARTS_WITH, "type"); filterMap.put("courseType", lexicalMap); Map<String, Object> lexicalMap1 = new HashMap<>(); lexicalMap1.put(ENDS_WITH, "sunbird"); filterMap.put("courseAddedByName", lexicalMap1); filterMap.put("orgName", "Name of the organisation"); searchDTO.setAdditionalProperties(additionalProperties); searchDTO.setQuery("organisation"); mockRulesForSearch(3); Future<Map<String, Object>> map = esService.search(searchDTO, INDEX_NAME); Map<String, Object> response = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(map); assertEquals(2, response.size()); } | @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> search(SearchDTO searchDTO, String index) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); String[] indices = {index}; ProjectLogger.log( "ElasticSearchTcpImpl:search: method started at ==" + startTime, LoggerEnum.PERF_LOG.name()); SearchRequestBuilder searchRequestBuilder = ElasticSearchHelper.getTransportSearchBuilder(ConnectionManager.getClient(), indices); Map<String, Float> constraintsMap = ElasticSearchHelper.getConstraints(searchDTO); BoolQueryBuilder query = new BoolQueryBuilder(); String channel = PropertiesCache.getInstance().getProperty(JsonKey.SUNBIRD_ES_CHANNEL); if (!(StringUtils.isBlank(channel) || JsonKey.SUNBIRD_ES_CHANNEL.equals(channel))) { query.must( ElasticSearchHelper.createMatchQuery( JsonKey.CHANNEL, channel, constraintsMap.get(JsonKey.CHANNEL))); } if (!StringUtils.isBlank(searchDTO.getQuery())) { SimpleQueryStringBuilder sqsb = QueryBuilders.simpleQueryStringQuery(searchDTO.getQuery()); if (CollectionUtils.isEmpty(searchDTO.getQueryFields())) { query.must(sqsb.field("all_fields")); } else { Map<String, Float> searchFields = searchDTO .getQueryFields() .stream() .collect(Collectors.<String, String, Float>toMap(s -> s, v -> 1.0f)); query.must(sqsb.fields(searchFields)); } } if (searchDTO.getSortBy() != null && searchDTO.getSortBy().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getSortBy().entrySet()) { if (!entry.getKey().contains(".")) { searchRequestBuilder.addSort( entry.getKey() + ElasticSearchHelper.RAW_APPEND, ElasticSearchHelper.getSortOrder((String) entry.getValue())); } else { Map<String, Object> map = (Map<String, Object>) entry.getValue(); Map<String, String> dataMap = (Map) map.get(JsonKey.TERM); for (Map.Entry<String, String> dateMapEntry : dataMap.entrySet()) { FieldSortBuilder mySort = SortBuilders.fieldSort(entry.getKey() + ElasticSearchHelper.RAW_APPEND) .setNestedFilter( new TermQueryBuilder(dateMapEntry.getKey(), dateMapEntry.getValue())) .sortMode(SortMode.MIN) .order(ElasticSearchHelper.getSortOrder((String) map.get(JsonKey.ORDER))); searchRequestBuilder.addSort(mySort); } } } } searchRequestBuilder.setFetchSource( searchDTO.getFields() != null ? searchDTO.getFields().stream().toArray(String[]::new) : null, searchDTO.getExcludedFields() != null ? searchDTO.getExcludedFields().stream().toArray(String[]::new) : null); if (searchDTO.getOffset() != null) { searchRequestBuilder.setFrom(searchDTO.getOffset()); } if (searchDTO.getLimit() != null) { searchRequestBuilder.setSize(searchDTO.getLimit()); } if (searchDTO.getAdditionalProperties() != null && searchDTO.getAdditionalProperties().size() > 0) { for (Map.Entry<String, Object> entry : searchDTO.getAdditionalProperties().entrySet()) { ElasticSearchHelper.addAdditionalProperties(query, entry, constraintsMap); } } searchRequestBuilder.setQuery(query); List finalFacetList = new ArrayList(); if (null != searchDTO.getFacets() && !searchDTO.getFacets().isEmpty()) { searchRequestBuilder = ElasticSearchHelper.addAggregations(searchRequestBuilder, searchDTO.getFacets()); } ProjectLogger.log( "ElasticSearchTcpImpl:search: calling search builder ==" + searchRequestBuilder.toString(), LoggerEnum.INFO.name()); SearchResponse response = null; try { response = searchRequestBuilder.execute().actionGet(); } catch (SearchPhaseExecutionException e) { promise.failure(e); ProjectCommonException.throwClientErrorException( ResponseCode.invalidValue, e.getRootCause().getMessage()); } Map<String, Object> responseMap = ElasticSearchHelper.getSearchResponseMap(response, searchDTO, finalFacetList); ProjectLogger.log( "ElasticSearchTcpImpl:search: method end" + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(responseMap); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); static final int WAIT_TIME; static Timeout timeout; } |
@Test public void testGetByIdentifierFailureWithoutIndex() { try { esService.getDataByIdentifier(null, (String) chemistryMap.get("courseId")); } catch (ProjectCommonException ex) { assertEquals(ResponseCode.SERVER_ERROR.getResponseCode(), ex.getResponseCode()); } } | @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); static final int WAIT_TIME; static Timeout timeout; } |
@Test public void testGetByIdentifierFailureWithoutTypeAndIndexIdentifier() { try { esService.getDataByIdentifier(null, ""); } catch (ProjectCommonException ex) { assertEquals(ResponseCode.SERVER_ERROR.getResponseCode(), ex.getResponseCode()); } } | @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); static final int WAIT_TIME; static Timeout timeout; } |
@Test public void testGetDataByIdentifierFailureWithoutIdentifier() { Future<Map<String, Object>> responseMap = esService.getDataByIdentifier(INDEX_NAME, ""); Map<String, Object> map = (Map<String, Object>) ElasticSearchHelper.getResponseFromFuture(responseMap); assertEquals(0, map.size()); } | @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); } | ElasticSearchTcpImpl implements ElasticSearchService { @Override public Future<Map<String, Object>> getDataByIdentifier(String index, String identifier) { long startTime = System.currentTimeMillis(); Promise<Map<String, Object>> promise = Futures.promise(); ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method started at ==" + startTime + " for index " + index, LoggerEnum.PERF_LOG.name()); GetResponse response = null; if (StringUtils.isBlank(index) || StringUtils.isBlank(identifier)) { ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: Invalid request is coming.", LoggerEnum.INFO.name()); promise.success(new HashMap<>()); return promise.future(); } else { response = ConnectionManager.getClient().prepareGet(index, _DOC, identifier).get(); } if (response == null || null == response.getSource()) { promise.success(new HashMap<>()); return promise.future(); } ProjectLogger.log( "ElasticSearchTcpImpl:getDataByIdentifier: method " + " for index " + index + " ,Total time elapsed = " + ElasticSearchHelper.calculateEndTime(startTime), LoggerEnum.PERF_LOG.name()); promise.success(response.getSource()); return promise.future(); } @Override Future<String> save(String index, String identifier, Map<String, Object> data); @Override Future<Map<String, Object>> getDataByIdentifier(String index, String identifier); @Override Future<Boolean> update(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> upsert(String index, String identifier, Map<String, Object> data); @Override Future<Boolean> delete(String index, String identifier); @Override Future<Map<String, Object>> search(SearchDTO searchDTO, String index); @Override Future<Map<String, Map<String, Object>>> getEsResultByListOfIds(
List<String> ids, List<String> fields, String index); @Override Future<Boolean> bulkInsert(String index, List<Map<String, Object>> dataList); @Override Future<Boolean> healthCheck(); static final int WAIT_TIME; static Timeout timeout; } |
@Test public void conventionOverConfiguration() { JavaMigrationResolver jdbcMigrationResolver = new JavaMigrationResolver(Thread.currentThread().getContextClassLoader(), null); ResolvedMigration migrationInfo = jdbcMigrationResolver.extractMigrationInfo(new V2__InterfaceBasedMigration()); assertEquals("2", migrationInfo.getVersion().toString()); assertEquals("InterfaceBasedMigration", migrationInfo.getDescription()); assertNull(migrationInfo.getChecksum()); } | ResolvedMigration extractMigrationInfo(JavaMigration javaMigration) { Integer checksum = null; if (javaMigration instanceof MigrationChecksumProvider) { MigrationChecksumProvider checksumProvider = (MigrationChecksumProvider) javaMigration; checksum = checksumProvider.getChecksum(); } MigrationVersion version; String description; if (javaMigration instanceof MigrationInfoProvider) { MigrationInfoProvider infoProvider = (MigrationInfoProvider) javaMigration; version = infoProvider.getVersion(); description = infoProvider.getDescription(); if (!StringUtils.hasText(description)) { throw new CassandraMigrationException("Missing description for migration " + version); } } else { Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription( ClassUtils.getShortName(javaMigration.getClass()), "V", "__", ""); version = info.getLeft(); description = info.getRight(); } String script = javaMigration.getClass().getName(); ResolvedMigration resolvedMigration = new ResolvedMigration(); resolvedMigration.setVersion(version); resolvedMigration.setDescription(description); resolvedMigration.setScript(script); resolvedMigration.setChecksum(checksum); resolvedMigration.setType(MigrationType.JAVA_DRIVER); return resolvedMigration; } | JavaMigrationResolver implements MigrationResolver { ResolvedMigration extractMigrationInfo(JavaMigration javaMigration) { Integer checksum = null; if (javaMigration instanceof MigrationChecksumProvider) { MigrationChecksumProvider checksumProvider = (MigrationChecksumProvider) javaMigration; checksum = checksumProvider.getChecksum(); } MigrationVersion version; String description; if (javaMigration instanceof MigrationInfoProvider) { MigrationInfoProvider infoProvider = (MigrationInfoProvider) javaMigration; version = infoProvider.getVersion(); description = infoProvider.getDescription(); if (!StringUtils.hasText(description)) { throw new CassandraMigrationException("Missing description for migration " + version); } } else { Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription( ClassUtils.getShortName(javaMigration.getClass()), "V", "__", ""); version = info.getLeft(); description = info.getRight(); } String script = javaMigration.getClass().getName(); ResolvedMigration resolvedMigration = new ResolvedMigration(); resolvedMigration.setVersion(version); resolvedMigration.setDescription(description); resolvedMigration.setScript(script); resolvedMigration.setChecksum(checksum); resolvedMigration.setType(MigrationType.JAVA_DRIVER); return resolvedMigration; } } | JavaMigrationResolver implements MigrationResolver { ResolvedMigration extractMigrationInfo(JavaMigration javaMigration) { Integer checksum = null; if (javaMigration instanceof MigrationChecksumProvider) { MigrationChecksumProvider checksumProvider = (MigrationChecksumProvider) javaMigration; checksum = checksumProvider.getChecksum(); } MigrationVersion version; String description; if (javaMigration instanceof MigrationInfoProvider) { MigrationInfoProvider infoProvider = (MigrationInfoProvider) javaMigration; version = infoProvider.getVersion(); description = infoProvider.getDescription(); if (!StringUtils.hasText(description)) { throw new CassandraMigrationException("Missing description for migration " + version); } } else { Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription( ClassUtils.getShortName(javaMigration.getClass()), "V", "__", ""); version = info.getLeft(); description = info.getRight(); } String script = javaMigration.getClass().getName(); ResolvedMigration resolvedMigration = new ResolvedMigration(); resolvedMigration.setVersion(version); resolvedMigration.setDescription(description); resolvedMigration.setScript(script); resolvedMigration.setChecksum(checksum); resolvedMigration.setType(MigrationType.JAVA_DRIVER); return resolvedMigration; } JavaMigrationResolver(ClassLoader classLoader, ScriptsLocation location); } | JavaMigrationResolver implements MigrationResolver { ResolvedMigration extractMigrationInfo(JavaMigration javaMigration) { Integer checksum = null; if (javaMigration instanceof MigrationChecksumProvider) { MigrationChecksumProvider checksumProvider = (MigrationChecksumProvider) javaMigration; checksum = checksumProvider.getChecksum(); } MigrationVersion version; String description; if (javaMigration instanceof MigrationInfoProvider) { MigrationInfoProvider infoProvider = (MigrationInfoProvider) javaMigration; version = infoProvider.getVersion(); description = infoProvider.getDescription(); if (!StringUtils.hasText(description)) { throw new CassandraMigrationException("Missing description for migration " + version); } } else { Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription( ClassUtils.getShortName(javaMigration.getClass()), "V", "__", ""); version = info.getLeft(); description = info.getRight(); } String script = javaMigration.getClass().getName(); ResolvedMigration resolvedMigration = new ResolvedMigration(); resolvedMigration.setVersion(version); resolvedMigration.setDescription(description); resolvedMigration.setScript(script); resolvedMigration.setChecksum(checksum); resolvedMigration.setType(MigrationType.JAVA_DRIVER); return resolvedMigration; } JavaMigrationResolver(ClassLoader classLoader, ScriptsLocation location); List<ResolvedMigration> resolveMigrations(); } | JavaMigrationResolver implements MigrationResolver { ResolvedMigration extractMigrationInfo(JavaMigration javaMigration) { Integer checksum = null; if (javaMigration instanceof MigrationChecksumProvider) { MigrationChecksumProvider checksumProvider = (MigrationChecksumProvider) javaMigration; checksum = checksumProvider.getChecksum(); } MigrationVersion version; String description; if (javaMigration instanceof MigrationInfoProvider) { MigrationInfoProvider infoProvider = (MigrationInfoProvider) javaMigration; version = infoProvider.getVersion(); description = infoProvider.getDescription(); if (!StringUtils.hasText(description)) { throw new CassandraMigrationException("Missing description for migration " + version); } } else { Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription( ClassUtils.getShortName(javaMigration.getClass()), "V", "__", ""); version = info.getLeft(); description = info.getRight(); } String script = javaMigration.getClass().getName(); ResolvedMigration resolvedMigration = new ResolvedMigration(); resolvedMigration.setVersion(version); resolvedMigration.setDescription(description); resolvedMigration.setScript(script); resolvedMigration.setChecksum(checksum); resolvedMigration.setType(MigrationType.JAVA_DRIVER); return resolvedMigration; } JavaMigrationResolver(ClassLoader classLoader, ScriptsLocation location); List<ResolvedMigration> resolveMigrations(); } |
@Test public void testGuess() { assertEquals(RDAPCLI.Type.AUTNUM,RDAPCLI.guessQueryType("12345")); assertEquals(RDAPCLI.Type.IP,RDAPCLI.guessQueryType("127.0.0.0/8")); assertEquals(RDAPCLI.Type.DOMAIN, RDAPCLI.guessQueryType("foo.example")); assertEquals(RDAPCLI.Type.ENTITY,RDAPCLI.guessQueryType("handle")); } | public static Type guessQueryType(String query) { try { if (query.matches("^\\d+$")) { return Type.AUTNUM; } if (query.matches("^[\\d\\.:/]+$")) { return Type.IP; } if (DomainName.of(query).getLevelSize() > 1) { return Type.DOMAIN; } return Type.ENTITY; } catch (IllegalArgumentException iae) { LOGGER.debug("Not a domain name, defaulting to entity", iae); return Type.ENTITY; } } | RDAPCLI { public static Type guessQueryType(String query) { try { if (query.matches("^\\d+$")) { return Type.AUTNUM; } if (query.matches("^[\\d\\.:/]+$")) { return Type.IP; } if (DomainName.of(query).getLevelSize() > 1) { return Type.DOMAIN; } return Type.ENTITY; } catch (IllegalArgumentException iae) { LOGGER.debug("Not a domain name, defaulting to entity", iae); return Type.ENTITY; } } } | RDAPCLI { public static Type guessQueryType(String query) { try { if (query.matches("^\\d+$")) { return Type.AUTNUM; } if (query.matches("^[\\d\\.:/]+$")) { return Type.IP; } if (DomainName.of(query).getLevelSize() > 1) { return Type.DOMAIN; } return Type.ENTITY; } catch (IllegalArgumentException iae) { LOGGER.debug("Not a domain name, defaulting to entity", iae); return Type.ENTITY; } } private RDAPCLI(); } | RDAPCLI { public static Type guessQueryType(String query) { try { if (query.matches("^\\d+$")) { return Type.AUTNUM; } if (query.matches("^[\\d\\.:/]+$")) { return Type.IP; } if (DomainName.of(query).getLevelSize() > 1) { return Type.DOMAIN; } return Type.ENTITY; } catch (IllegalArgumentException iae) { LOGGER.debug("Not a domain name, defaulting to entity", iae); return Type.ENTITY; } } private RDAPCLI(); static void main(String[] args); static Type guessQueryType(String query); } | RDAPCLI { public static Type guessQueryType(String query) { try { if (query.matches("^\\d+$")) { return Type.AUTNUM; } if (query.matches("^[\\d\\.:/]+$")) { return Type.IP; } if (DomainName.of(query).getLevelSize() > 1) { return Type.DOMAIN; } return Type.ENTITY; } catch (IllegalArgumentException iae) { LOGGER.debug("Not a domain name, defaulting to entity", iae); return Type.ENTITY; } } private RDAPCLI(); static void main(String[] args); static Type guessQueryType(String query); } |
@Test public void testIsFQDN() { assertFalse(DomainName.of("www.example.com").isFQDN()); assertTrue(DomainName.of("www.example.com.").isFQDN()); } | public boolean isFQDN() { return labels.get(labels.size() - 1) instanceof Label.RootLabel; } | DomainName { public boolean isFQDN() { return labels.get(labels.size() - 1) instanceof Label.RootLabel; } } | DomainName { public boolean isFQDN() { return labels.get(labels.size() - 1) instanceof Label.RootLabel; } DomainName(List<Label> labels); } | DomainName { public boolean isFQDN() { return labels.get(labels.size() - 1) instanceof Label.RootLabel; } DomainName(List<Label> labels); static DomainName of(String domainName); DomainName toFQDN(); boolean isFQDN(); int getLevelSize(); List<Label> getLabels(); Label getTLDLabel(); String getStringValue(); Label getLevel(int level); DomainName toLDH(); DomainName toUnicode(); @Override boolean equals(Object o); @Override int hashCode(); } | DomainName { public boolean isFQDN() { return labels.get(labels.size() - 1) instanceof Label.RootLabel; } DomainName(List<Label> labels); static DomainName of(String domainName); DomainName toFQDN(); boolean isFQDN(); int getLevelSize(); List<Label> getLabels(); Label getTLDLabel(); String getStringValue(); Label getLevel(int level); DomainName toLDH(); DomainName toUnicode(); @Override boolean equals(Object o); @Override int hashCode(); } |
@Test public void testToFQDN() { DomainName dn = DomainName.of("www.example.com"); assertEquals(4, dn.toFQDN().getLabels().size()); assertEquals("www.example.com.", dn.toFQDN().getStringValue()); } | public DomainName toFQDN() { if (isFQDN()) { return this; } return new DomainName(new ImmutableList.Builder<Label>().addAll(labels).add(Label.RootLabel.getInstance()).build()); } | DomainName { public DomainName toFQDN() { if (isFQDN()) { return this; } return new DomainName(new ImmutableList.Builder<Label>().addAll(labels).add(Label.RootLabel.getInstance()).build()); } } | DomainName { public DomainName toFQDN() { if (isFQDN()) { return this; } return new DomainName(new ImmutableList.Builder<Label>().addAll(labels).add(Label.RootLabel.getInstance()).build()); } DomainName(List<Label> labels); } | DomainName { public DomainName toFQDN() { if (isFQDN()) { return this; } return new DomainName(new ImmutableList.Builder<Label>().addAll(labels).add(Label.RootLabel.getInstance()).build()); } DomainName(List<Label> labels); static DomainName of(String domainName); DomainName toFQDN(); boolean isFQDN(); int getLevelSize(); List<Label> getLabels(); Label getTLDLabel(); String getStringValue(); Label getLevel(int level); DomainName toLDH(); DomainName toUnicode(); @Override boolean equals(Object o); @Override int hashCode(); } | DomainName { public DomainName toFQDN() { if (isFQDN()) { return this; } return new DomainName(new ImmutableList.Builder<Label>().addAll(labels).add(Label.RootLabel.getInstance()).build()); } DomainName(List<Label> labels); static DomainName of(String domainName); DomainName toFQDN(); boolean isFQDN(); int getLevelSize(); List<Label> getLabels(); Label getTLDLabel(); String getStringValue(); Label getLevel(int level); DomainName toLDH(); DomainName toUnicode(); @Override boolean equals(Object o); @Override int hashCode(); } |
@Test public void shouldBePossibleToCreateUnvalidedPhoneNumber() throws URISyntaxException { Tel tel = Tel.unvalidatedTel("+29716"); assertNotNull(tel); assertEquals("tel:+29716", tel.getStringValue()); } | public static Tel unvalidatedTel(String telephoneNumber) throws URISyntaxException { return new Tel(new URI("tel:" + telephoneNumber)); } | Tel extends URIValue { public static Tel unvalidatedTel(String telephoneNumber) throws URISyntaxException { return new Tel(new URI("tel:" + telephoneNumber)); } } | Tel extends URIValue { public static Tel unvalidatedTel(String telephoneNumber) throws URISyntaxException { return new Tel(new URI("tel:" + telephoneNumber)); } private Tel(URI uri); Tel(TelephoneNumber telephoneNumber); Tel(String telephoneNumber); } | Tel extends URIValue { public static Tel unvalidatedTel(String telephoneNumber) throws URISyntaxException { return new Tel(new URI("tel:" + telephoneNumber)); } private Tel(URI uri); Tel(TelephoneNumber telephoneNumber); Tel(String telephoneNumber); static Tel unvalidatedTel(String telephoneNumber); } | Tel extends URIValue { public static Tel unvalidatedTel(String telephoneNumber) throws URISyntaxException { return new Tel(new URI("tel:" + telephoneNumber)); } private Tel(URI uri); Tel(TelephoneNumber telephoneNumber); Tel(String telephoneNumber); static Tel unvalidatedTel(String telephoneNumber); } |
@Test public void testLabelInstances() { Label label = Label.of("example"); assertTrue(label instanceof Label.ASCIILabel.LDHLabel.NonReservedLDHLabel); label = Label.of(""); assertTrue(label instanceof Label.RootLabel); label = Label.of("xn--bcher-kva"); assertTrue(label instanceof Label.ASCIILabel.LDHLabel.ReservedLDHLabel.ALabel); label = Label.of("xn--bcher-aaa"); assertTrue(label instanceof Label.ASCIILabel.LDHLabel.ReservedLDHLabel.FakeALabel); label = Label.of("_tcp"); assertTrue(label instanceof Label.ASCIILabel.NONLDHLabel); label = Label.of("-example"); assertTrue(label instanceof Label.ASCIILabel.NONLDHLabel); label = Label.of("example-"); assertTrue(label instanceof Label.ASCIILabel.NONLDHLabel); } | public static Label of(final String label) { if (StringUtils.isEmpty(label)) { return RootLabel.getInstance(); } if (!ASCIILabel.ASCII_SET.containsAll(label)) { IDNA.Info info = new IDNA.Info(); StringBuilder result = new StringBuilder(); IDNA.labelToUnicode(label, result, info); if (info.hasErrors()) { throw new LabelException.IDNParseException(info.getErrors()); } return new NonASCIILabel.ULabel(result.toString()); } if (!ASCIILabel.LDHLabel.LDH_SET.containsAll(label) || label.startsWith(HYPHEN) || label.endsWith(HYPHEN)) { return new ASCIILabel.NONLDHLabel(label); } if (!label.matches("^..--.*")) { return new ASCIILabel.LDHLabel.NonReservedLDHLabel(label); } if (label.startsWith("xn")) { Label aLabel = new ASCIILabel.LDHLabel.ReservedLDHLabel.ALabel(label); try { aLabel.toUnicode(); return aLabel; } catch (LabelException.IDNParseException e) { LOGGER.debug("Fake A-Label", e); return new ASCIILabel.LDHLabel.ReservedLDHLabel.FakeALabel(label, e.getErrors()); } } return new ASCIILabel.LDHLabel.ReservedLDHLabel(label); } | Label { public static Label of(final String label) { if (StringUtils.isEmpty(label)) { return RootLabel.getInstance(); } if (!ASCIILabel.ASCII_SET.containsAll(label)) { IDNA.Info info = new IDNA.Info(); StringBuilder result = new StringBuilder(); IDNA.labelToUnicode(label, result, info); if (info.hasErrors()) { throw new LabelException.IDNParseException(info.getErrors()); } return new NonASCIILabel.ULabel(result.toString()); } if (!ASCIILabel.LDHLabel.LDH_SET.containsAll(label) || label.startsWith(HYPHEN) || label.endsWith(HYPHEN)) { return new ASCIILabel.NONLDHLabel(label); } if (!label.matches("^..--.*")) { return new ASCIILabel.LDHLabel.NonReservedLDHLabel(label); } if (label.startsWith("xn")) { Label aLabel = new ASCIILabel.LDHLabel.ReservedLDHLabel.ALabel(label); try { aLabel.toUnicode(); return aLabel; } catch (LabelException.IDNParseException e) { LOGGER.debug("Fake A-Label", e); return new ASCIILabel.LDHLabel.ReservedLDHLabel.FakeALabel(label, e.getErrors()); } } return new ASCIILabel.LDHLabel.ReservedLDHLabel(label); } } | Label { public static Label of(final String label) { if (StringUtils.isEmpty(label)) { return RootLabel.getInstance(); } if (!ASCIILabel.ASCII_SET.containsAll(label)) { IDNA.Info info = new IDNA.Info(); StringBuilder result = new StringBuilder(); IDNA.labelToUnicode(label, result, info); if (info.hasErrors()) { throw new LabelException.IDNParseException(info.getErrors()); } return new NonASCIILabel.ULabel(result.toString()); } if (!ASCIILabel.LDHLabel.LDH_SET.containsAll(label) || label.startsWith(HYPHEN) || label.endsWith(HYPHEN)) { return new ASCIILabel.NONLDHLabel(label); } if (!label.matches("^..--.*")) { return new ASCIILabel.LDHLabel.NonReservedLDHLabel(label); } if (label.startsWith("xn")) { Label aLabel = new ASCIILabel.LDHLabel.ReservedLDHLabel.ALabel(label); try { aLabel.toUnicode(); return aLabel; } catch (LabelException.IDNParseException e) { LOGGER.debug("Fake A-Label", e); return new ASCIILabel.LDHLabel.ReservedLDHLabel.FakeALabel(label, e.getErrors()); } } return new ASCIILabel.LDHLabel.ReservedLDHLabel(label); } Label(String value); } | Label { public static Label of(final String label) { if (StringUtils.isEmpty(label)) { return RootLabel.getInstance(); } if (!ASCIILabel.ASCII_SET.containsAll(label)) { IDNA.Info info = new IDNA.Info(); StringBuilder result = new StringBuilder(); IDNA.labelToUnicode(label, result, info); if (info.hasErrors()) { throw new LabelException.IDNParseException(info.getErrors()); } return new NonASCIILabel.ULabel(result.toString()); } if (!ASCIILabel.LDHLabel.LDH_SET.containsAll(label) || label.startsWith(HYPHEN) || label.endsWith(HYPHEN)) { return new ASCIILabel.NONLDHLabel(label); } if (!label.matches("^..--.*")) { return new ASCIILabel.LDHLabel.NonReservedLDHLabel(label); } if (label.startsWith("xn")) { Label aLabel = new ASCIILabel.LDHLabel.ReservedLDHLabel.ALabel(label); try { aLabel.toUnicode(); return aLabel; } catch (LabelException.IDNParseException e) { LOGGER.debug("Fake A-Label", e); return new ASCIILabel.LDHLabel.ReservedLDHLabel.FakeALabel(label, e.getErrors()); } } return new ASCIILabel.LDHLabel.ReservedLDHLabel(label); } Label(String value); static Label of(final String label); String getStringValue(); Label toLDH(); Label toUnicode(); } | Label { public static Label of(final String label) { if (StringUtils.isEmpty(label)) { return RootLabel.getInstance(); } if (!ASCIILabel.ASCII_SET.containsAll(label)) { IDNA.Info info = new IDNA.Info(); StringBuilder result = new StringBuilder(); IDNA.labelToUnicode(label, result, info); if (info.hasErrors()) { throw new LabelException.IDNParseException(info.getErrors()); } return new NonASCIILabel.ULabel(result.toString()); } if (!ASCIILabel.LDHLabel.LDH_SET.containsAll(label) || label.startsWith(HYPHEN) || label.endsWith(HYPHEN)) { return new ASCIILabel.NONLDHLabel(label); } if (!label.matches("^..--.*")) { return new ASCIILabel.LDHLabel.NonReservedLDHLabel(label); } if (label.startsWith("xn")) { Label aLabel = new ASCIILabel.LDHLabel.ReservedLDHLabel.ALabel(label); try { aLabel.toUnicode(); return aLabel; } catch (LabelException.IDNParseException e) { LOGGER.debug("Fake A-Label", e); return new ASCIILabel.LDHLabel.ReservedLDHLabel.FakeALabel(label, e.getErrors()); } } return new ASCIILabel.LDHLabel.ReservedLDHLabel(label); } Label(String value); static Label of(final String label); String getStringValue(); Label toLDH(); Label toUnicode(); static final Logger LOGGER; static final int IDNA_OPTIONS; } |
@Test public void testToUnicode() { Label label = Label.of("xn--bcher-kva"); assertEquals("b\u00FCcher", label.toUnicode().getStringValue()); } | public Label toUnicode() { return this; } | Label { public Label toUnicode() { return this; } } | Label { public Label toUnicode() { return this; } Label(String value); } | Label { public Label toUnicode() { return this; } Label(String value); static Label of(final String label); String getStringValue(); Label toLDH(); Label toUnicode(); } | Label { public Label toUnicode() { return this; } Label(String value); static Label of(final String label); String getStringValue(); Label toLDH(); Label toUnicode(); static final Logger LOGGER; static final int IDNA_OPTIONS; } |
@Test public void testToLDH() { Label label = Label.of("b\u00FCcher"); assertEquals("xn--bcher-kva", label.toLDH().getStringValue()); label = Label.of("Bu\u0308cher"); assertEquals("xn--bcher-kva", label.toLDH().getStringValue()); assertEquals("b\u00FCcher", label.getStringValue()); } | public Label toLDH() { return this; } | Label { public Label toLDH() { return this; } } | Label { public Label toLDH() { return this; } Label(String value); } | Label { public Label toLDH() { return this; } Label(String value); static Label of(final String label); String getStringValue(); Label toLDH(); Label toUnicode(); } | Label { public Label toLDH() { return this; } Label(String value); static Label of(final String label); String getStringValue(); Label toLDH(); Label toUnicode(); static final Logger LOGGER; static final int IDNA_OPTIONS; } |
@Test public void testControlCharacters() { for (final String s : new UnicodeSet(0, 31)) { Assert.assertThrows(new Assert.Closure() { @Override public void execute() throws Throwable { Label.of(s); } }, LabelException.IDNParseException.class, "expects LabelException"); } } | public static Label of(final String label) { if (StringUtils.isEmpty(label)) { return RootLabel.getInstance(); } if (!ASCIILabel.ASCII_SET.containsAll(label)) { IDNA.Info info = new IDNA.Info(); StringBuilder result = new StringBuilder(); IDNA.labelToUnicode(label, result, info); if (info.hasErrors()) { throw new LabelException.IDNParseException(info.getErrors()); } return new NonASCIILabel.ULabel(result.toString()); } if (!ASCIILabel.LDHLabel.LDH_SET.containsAll(label) || label.startsWith(HYPHEN) || label.endsWith(HYPHEN)) { return new ASCIILabel.NONLDHLabel(label); } if (!label.matches("^..--.*")) { return new ASCIILabel.LDHLabel.NonReservedLDHLabel(label); } if (label.startsWith("xn")) { Label aLabel = new ASCIILabel.LDHLabel.ReservedLDHLabel.ALabel(label); try { aLabel.toUnicode(); return aLabel; } catch (LabelException.IDNParseException e) { LOGGER.debug("Fake A-Label", e); return new ASCIILabel.LDHLabel.ReservedLDHLabel.FakeALabel(label, e.getErrors()); } } return new ASCIILabel.LDHLabel.ReservedLDHLabel(label); } | Label { public static Label of(final String label) { if (StringUtils.isEmpty(label)) { return RootLabel.getInstance(); } if (!ASCIILabel.ASCII_SET.containsAll(label)) { IDNA.Info info = new IDNA.Info(); StringBuilder result = new StringBuilder(); IDNA.labelToUnicode(label, result, info); if (info.hasErrors()) { throw new LabelException.IDNParseException(info.getErrors()); } return new NonASCIILabel.ULabel(result.toString()); } if (!ASCIILabel.LDHLabel.LDH_SET.containsAll(label) || label.startsWith(HYPHEN) || label.endsWith(HYPHEN)) { return new ASCIILabel.NONLDHLabel(label); } if (!label.matches("^..--.*")) { return new ASCIILabel.LDHLabel.NonReservedLDHLabel(label); } if (label.startsWith("xn")) { Label aLabel = new ASCIILabel.LDHLabel.ReservedLDHLabel.ALabel(label); try { aLabel.toUnicode(); return aLabel; } catch (LabelException.IDNParseException e) { LOGGER.debug("Fake A-Label", e); return new ASCIILabel.LDHLabel.ReservedLDHLabel.FakeALabel(label, e.getErrors()); } } return new ASCIILabel.LDHLabel.ReservedLDHLabel(label); } } | Label { public static Label of(final String label) { if (StringUtils.isEmpty(label)) { return RootLabel.getInstance(); } if (!ASCIILabel.ASCII_SET.containsAll(label)) { IDNA.Info info = new IDNA.Info(); StringBuilder result = new StringBuilder(); IDNA.labelToUnicode(label, result, info); if (info.hasErrors()) { throw new LabelException.IDNParseException(info.getErrors()); } return new NonASCIILabel.ULabel(result.toString()); } if (!ASCIILabel.LDHLabel.LDH_SET.containsAll(label) || label.startsWith(HYPHEN) || label.endsWith(HYPHEN)) { return new ASCIILabel.NONLDHLabel(label); } if (!label.matches("^..--.*")) { return new ASCIILabel.LDHLabel.NonReservedLDHLabel(label); } if (label.startsWith("xn")) { Label aLabel = new ASCIILabel.LDHLabel.ReservedLDHLabel.ALabel(label); try { aLabel.toUnicode(); return aLabel; } catch (LabelException.IDNParseException e) { LOGGER.debug("Fake A-Label", e); return new ASCIILabel.LDHLabel.ReservedLDHLabel.FakeALabel(label, e.getErrors()); } } return new ASCIILabel.LDHLabel.ReservedLDHLabel(label); } Label(String value); } | Label { public static Label of(final String label) { if (StringUtils.isEmpty(label)) { return RootLabel.getInstance(); } if (!ASCIILabel.ASCII_SET.containsAll(label)) { IDNA.Info info = new IDNA.Info(); StringBuilder result = new StringBuilder(); IDNA.labelToUnicode(label, result, info); if (info.hasErrors()) { throw new LabelException.IDNParseException(info.getErrors()); } return new NonASCIILabel.ULabel(result.toString()); } if (!ASCIILabel.LDHLabel.LDH_SET.containsAll(label) || label.startsWith(HYPHEN) || label.endsWith(HYPHEN)) { return new ASCIILabel.NONLDHLabel(label); } if (!label.matches("^..--.*")) { return new ASCIILabel.LDHLabel.NonReservedLDHLabel(label); } if (label.startsWith("xn")) { Label aLabel = new ASCIILabel.LDHLabel.ReservedLDHLabel.ALabel(label); try { aLabel.toUnicode(); return aLabel; } catch (LabelException.IDNParseException e) { LOGGER.debug("Fake A-Label", e); return new ASCIILabel.LDHLabel.ReservedLDHLabel.FakeALabel(label, e.getErrors()); } } return new ASCIILabel.LDHLabel.ReservedLDHLabel(label); } Label(String value); static Label of(final String label); String getStringValue(); Label toLDH(); Label toUnicode(); } | Label { public static Label of(final String label) { if (StringUtils.isEmpty(label)) { return RootLabel.getInstance(); } if (!ASCIILabel.ASCII_SET.containsAll(label)) { IDNA.Info info = new IDNA.Info(); StringBuilder result = new StringBuilder(); IDNA.labelToUnicode(label, result, info); if (info.hasErrors()) { throw new LabelException.IDNParseException(info.getErrors()); } return new NonASCIILabel.ULabel(result.toString()); } if (!ASCIILabel.LDHLabel.LDH_SET.containsAll(label) || label.startsWith(HYPHEN) || label.endsWith(HYPHEN)) { return new ASCIILabel.NONLDHLabel(label); } if (!label.matches("^..--.*")) { return new ASCIILabel.LDHLabel.NonReservedLDHLabel(label); } if (label.startsWith("xn")) { Label aLabel = new ASCIILabel.LDHLabel.ReservedLDHLabel.ALabel(label); try { aLabel.toUnicode(); return aLabel; } catch (LabelException.IDNParseException e) { LOGGER.debug("Fake A-Label", e); return new ASCIILabel.LDHLabel.ReservedLDHLabel.FakeALabel(label, e.getErrors()); } } return new ASCIILabel.LDHLabel.ReservedLDHLabel(label); } Label(String value); static Label of(final String label); String getStringValue(); Label toLDH(); Label toUnicode(); static final Logger LOGGER; static final int IDNA_OPTIONS; } |
@Test public void testInvalidCountryCode() { assertThrows(new Closure() { @Override public void execute() throws Throwable { TelephoneNumber.of(1000, new BigInteger("1234567890")); } }, IllegalArgumentException.class, "Should throw IllegalArgumentException"); } | public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } | TelephoneNumber { public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } } | TelephoneNumber { public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } private TelephoneNumber(int countryCode, BigInteger nationalNumber); } | TelephoneNumber { public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } private TelephoneNumber(int countryCode, BigInteger nationalNumber); static String getRegion(int countryCode); static TelephoneNumber of(String number); static TelephoneNumber of(int countryCode, BigInteger nationalNumber); int getCountryCode(); BigInteger getNationalNumber(); String getRegion(); String getStringValue(); @Override String toString(); } | TelephoneNumber { public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } private TelephoneNumber(int countryCode, BigInteger nationalNumber); static String getRegion(int countryCode); static TelephoneNumber of(String number); static TelephoneNumber of(int countryCode, BigInteger nationalNumber); int getCountryCode(); BigInteger getNationalNumber(); String getRegion(); String getStringValue(); @Override String toString(); } |
@Test public void testTooLongTelephoneNumber() { assertThrows(new Closure() { @Override public void execute() throws Throwable { TelephoneNumber.of("+32 12345678901234"); } }, IllegalArgumentException.class, "Should throw IllegalArgumentException"); } | public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } | TelephoneNumber { public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } } | TelephoneNumber { public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } private TelephoneNumber(int countryCode, BigInteger nationalNumber); } | TelephoneNumber { public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } private TelephoneNumber(int countryCode, BigInteger nationalNumber); static String getRegion(int countryCode); static TelephoneNumber of(String number); static TelephoneNumber of(int countryCode, BigInteger nationalNumber); int getCountryCode(); BigInteger getNationalNumber(); String getRegion(); String getStringValue(); @Override String toString(); } | TelephoneNumber { public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } private TelephoneNumber(int countryCode, BigInteger nationalNumber); static String getRegion(int countryCode); static TelephoneNumber of(String number); static TelephoneNumber of(int countryCode, BigInteger nationalNumber); int getCountryCode(); BigInteger getNationalNumber(); String getRegion(); String getStringValue(); @Override String toString(); } |
@Test public void testInvalidCharacters() { assertThrows(new Closure() { @Override public void execute() throws Throwable { TelephoneNumber.of("+32 abcdefg"); } }, IllegalArgumentException.class, "Should throw IllegalArgumentException"); assertThrows(new Closure() { @Override public void execute() throws Throwable { TelephoneNumber.of("+32 %1234)56789"); } }, IllegalArgumentException.class, "Should throw IllegalArgumentException"); } | public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } | TelephoneNumber { public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } } | TelephoneNumber { public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } private TelephoneNumber(int countryCode, BigInteger nationalNumber); } | TelephoneNumber { public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } private TelephoneNumber(int countryCode, BigInteger nationalNumber); static String getRegion(int countryCode); static TelephoneNumber of(String number); static TelephoneNumber of(int countryCode, BigInteger nationalNumber); int getCountryCode(); BigInteger getNationalNumber(); String getRegion(); String getStringValue(); @Override String toString(); } | TelephoneNumber { public static TelephoneNumber of(String number) { String normalized = number.replaceAll("[\\(\\)\\.\\s-_]", ""); LOGGER.debug("Normalized telephone number: {}", normalized); if (!normalized.matches("^\\+?\\d+$")) { throw new IllegalArgumentException("bad number"); } String prefix = "", suffix = ""; if (normalized.startsWith("+")) { for (int i = 1; i <= 3; i++) { prefix = normalized.substring(1, i); suffix = normalized.substring(i); LOGGER.debug("prefix: {} suffix: {}", prefix, suffix); if (COUNTRY_CODES.containsKey(prefix)) { break; } } } else { prefix = "0"; suffix = normalized; } return new TelephoneNumber(Integer.valueOf(prefix), new BigInteger(suffix)); } private TelephoneNumber(int countryCode, BigInteger nationalNumber); static String getRegion(int countryCode); static TelephoneNumber of(String number); static TelephoneNumber of(int countryCode, BigInteger nationalNumber); int getCountryCode(); BigInteger getNationalNumber(); String getRegion(); String getStringValue(); @Override String toString(); } |
@Test public void testDoesItSmoke() { Assert.assertThrows(new Assert.Closure() { @Override public void execute() throws Throwable { CIDR.of("1.1.1.1/-1"); } }, IllegalArgumentException.class, "negative prefix size"); } | public static CIDR of(String cidr) { String[] parts = cidr.split("\\/"); if (parts.length == 1) { try { InetAddress address = InetAddress.getByName(parts[0]); int length = address instanceof Inet4Address ? 32 : 128; return new CIDR(address.getAddress(), length); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } } if (parts.length != 2) { throw new IllegalArgumentException("Invalid format"); } try { InetAddress address = InetAddress.getByName(parts[0]); return new CIDR(address.getAddress(),Integer.parseInt(parts[1])); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } } | CIDR { public static CIDR of(String cidr) { String[] parts = cidr.split("\\/"); if (parts.length == 1) { try { InetAddress address = InetAddress.getByName(parts[0]); int length = address instanceof Inet4Address ? 32 : 128; return new CIDR(address.getAddress(), length); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } } if (parts.length != 2) { throw new IllegalArgumentException("Invalid format"); } try { InetAddress address = InetAddress.getByName(parts[0]); return new CIDR(address.getAddress(),Integer.parseInt(parts[1])); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } } } | CIDR { public static CIDR of(String cidr) { String[] parts = cidr.split("\\/"); if (parts.length == 1) { try { InetAddress address = InetAddress.getByName(parts[0]); int length = address instanceof Inet4Address ? 32 : 128; return new CIDR(address.getAddress(), length); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } } if (parts.length != 2) { throw new IllegalArgumentException("Invalid format"); } try { InetAddress address = InetAddress.getByName(parts[0]); return new CIDR(address.getAddress(),Integer.parseInt(parts[1])); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } } CIDR(byte[] address, int size); } | CIDR { public static CIDR of(String cidr) { String[] parts = cidr.split("\\/"); if (parts.length == 1) { try { InetAddress address = InetAddress.getByName(parts[0]); int length = address instanceof Inet4Address ? 32 : 128; return new CIDR(address.getAddress(), length); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } } if (parts.length != 2) { throw new IllegalArgumentException("Invalid format"); } try { InetAddress address = InetAddress.getByName(parts[0]); return new CIDR(address.getAddress(),Integer.parseInt(parts[1])); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } } CIDR(byte[] address, int size); byte[] getAddress(); int getSize(); byte[] getMask(); boolean contains(InetAddress inet); static CIDR of(String cidr); } | CIDR { public static CIDR of(String cidr) { String[] parts = cidr.split("\\/"); if (parts.length == 1) { try { InetAddress address = InetAddress.getByName(parts[0]); int length = address instanceof Inet4Address ? 32 : 128; return new CIDR(address.getAddress(), length); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } } if (parts.length != 2) { throw new IllegalArgumentException("Invalid format"); } try { InetAddress address = InetAddress.getByName(parts[0]); return new CIDR(address.getAddress(),Integer.parseInt(parts[1])); } catch (UnknownHostException e) { throw new IllegalArgumentException(e); } } CIDR(byte[] address, int size); byte[] getAddress(); int getSize(); byte[] getMask(); boolean contains(InetAddress inet); static CIDR of(String cidr); } |
@Test public void translateExceptionIfPossible_should_translate_DuplicateItemNameException_into_DuplicateKeyException() { DuplicateItemNameException duplicateItemException = new DuplicateItemNameException("Duplicate Item"); DataAccessException dataAccessException = translator.translateExceptionIfPossible(duplicateItemException); assertThat(dataAccessException, is(instanceOf(DuplicateKeyException.class))); assertThat(dataAccessException, is(notNullValue())); assertThat(dataAccessException.getLocalizedMessage(), StringContains.containsString("Duplicate Item")); } | @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } |
@Test public void should_correctly_compare_alphanumerical_strings() throws Exception { AlphanumStringComparator comparator = new AlphanumStringComparator(); assertTrue(comparator.compare("10@foo", "2@foo") > 0); assertTrue(comparator.compare("2@foo", "10@foo") < 0); assertTrue(comparator.compare("10@foo", "10@foo") == 0); } | @Override public int compare(String s1, String s2) { int c = 0; Matcher m1 = prefixRexp.matcher(s1); Matcher m2 = prefixRexp.matcher(s2); if (m1.find() && m2.find()) { Integer i1 = Integer.valueOf(m1.group(1)); Integer i2 = Integer.valueOf(m2.group(1)); c = i1.compareTo(i2); } else { throw new IllegalArgumentException("Can not compare strings missing 'digit@' pattern"); } return c; } | AlphanumStringComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { int c = 0; Matcher m1 = prefixRexp.matcher(s1); Matcher m2 = prefixRexp.matcher(s2); if (m1.find() && m2.find()) { Integer i1 = Integer.valueOf(m1.group(1)); Integer i2 = Integer.valueOf(m2.group(1)); c = i1.compareTo(i2); } else { throw new IllegalArgumentException("Can not compare strings missing 'digit@' pattern"); } return c; } } | AlphanumStringComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { int c = 0; Matcher m1 = prefixRexp.matcher(s1); Matcher m2 = prefixRexp.matcher(s2); if (m1.find() && m2.find()) { Integer i1 = Integer.valueOf(m1.group(1)); Integer i2 = Integer.valueOf(m2.group(1)); c = i1.compareTo(i2); } else { throw new IllegalArgumentException("Can not compare strings missing 'digit@' pattern"); } return c; } } | AlphanumStringComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { int c = 0; Matcher m1 = prefixRexp.matcher(s1); Matcher m2 = prefixRexp.matcher(s2); if (m1.find() && m2.find()) { Integer i1 = Integer.valueOf(m1.group(1)); Integer i2 = Integer.valueOf(m2.group(1)); c = i1.compareTo(i2); } else { throw new IllegalArgumentException("Can not compare strings missing 'digit@' pattern"); } return c; } @Override int compare(String s1, String s2); } | AlphanumStringComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { int c = 0; Matcher m1 = prefixRexp.matcher(s1); Matcher m2 = prefixRexp.matcher(s2); if (m1.find() && m2.find()) { Integer i1 = Integer.valueOf(m1.group(1)); Integer i2 = Integer.valueOf(m2.group(1)); c = i1.compareTo(i2); } else { throw new IllegalArgumentException("Can not compare strings missing 'digit@' pattern"); } return c; } @Override int compare(String s1, String s2); } |
@Test public void splitToChunksOfSize_should_split_entries_exceeding_size() throws Exception { Map<String, List<String>> attributes = new LinkedHashMap<String, List<String>>(); for(int i = 0; i < SAMPLE_MAP_SIZE + 100; i++) { List<String> list = new ArrayList<String>(); list.add("Value: " + i); attributes.put("Key: " + i, list); } List<Map<String, List<String>>> chunks = MapUtils.splitToChunksOfSize(attributes, SAMPLE_MAP_SIZE); assertEquals(2, chunks.size()); Map<String, List<String>> firstChunk = chunks.get(0); assertEquals(SAMPLE_MAP_SIZE, firstChunk.size()); Map<String, List<String>> secondChunk = chunks.get(1); assertEquals(100, secondChunk.size()); assertTrue(secondChunk.containsKey("Key: " + 256)); assertTrue(secondChunk.containsKey("Key: " + 355)); } | public static List<Map<String, List<String>>> splitToChunksOfSize(Map<String, List<String>> rawMap, int chunkSize) { List<Map<String, List<String>>> mapChunks = new LinkedList<Map<String, List<String>>>(); Set<Map.Entry<String, List<String>>> rawEntries = rawMap.entrySet(); Map<String, List<String>> currentChunk = new LinkedHashMap<String, List<String>>(); int rawEntryIndex = 0; for(Map.Entry<String, List<String>> rawEntry : rawEntries) { if(rawEntryIndex % chunkSize == 0) { if(currentChunk.size() > 0) { mapChunks.add(currentChunk); } currentChunk = new LinkedHashMap<String, List<String>>(); } currentChunk.put(rawEntry.getKey(), rawEntry.getValue()); rawEntryIndex++; if(rawEntryIndex == rawMap.size()) { mapChunks.add(currentChunk); } } return mapChunks; } | MapUtils { public static List<Map<String, List<String>>> splitToChunksOfSize(Map<String, List<String>> rawMap, int chunkSize) { List<Map<String, List<String>>> mapChunks = new LinkedList<Map<String, List<String>>>(); Set<Map.Entry<String, List<String>>> rawEntries = rawMap.entrySet(); Map<String, List<String>> currentChunk = new LinkedHashMap<String, List<String>>(); int rawEntryIndex = 0; for(Map.Entry<String, List<String>> rawEntry : rawEntries) { if(rawEntryIndex % chunkSize == 0) { if(currentChunk.size() > 0) { mapChunks.add(currentChunk); } currentChunk = new LinkedHashMap<String, List<String>>(); } currentChunk.put(rawEntry.getKey(), rawEntry.getValue()); rawEntryIndex++; if(rawEntryIndex == rawMap.size()) { mapChunks.add(currentChunk); } } return mapChunks; } } | MapUtils { public static List<Map<String, List<String>>> splitToChunksOfSize(Map<String, List<String>> rawMap, int chunkSize) { List<Map<String, List<String>>> mapChunks = new LinkedList<Map<String, List<String>>>(); Set<Map.Entry<String, List<String>>> rawEntries = rawMap.entrySet(); Map<String, List<String>> currentChunk = new LinkedHashMap<String, List<String>>(); int rawEntryIndex = 0; for(Map.Entry<String, List<String>> rawEntry : rawEntries) { if(rawEntryIndex % chunkSize == 0) { if(currentChunk.size() > 0) { mapChunks.add(currentChunk); } currentChunk = new LinkedHashMap<String, List<String>>(); } currentChunk.put(rawEntry.getKey(), rawEntry.getValue()); rawEntryIndex++; if(rawEntryIndex == rawMap.size()) { mapChunks.add(currentChunk); } } return mapChunks; } private MapUtils(); } | MapUtils { public static List<Map<String, List<String>>> splitToChunksOfSize(Map<String, List<String>> rawMap, int chunkSize) { List<Map<String, List<String>>> mapChunks = new LinkedList<Map<String, List<String>>>(); Set<Map.Entry<String, List<String>>> rawEntries = rawMap.entrySet(); Map<String, List<String>> currentChunk = new LinkedHashMap<String, List<String>>(); int rawEntryIndex = 0; for(Map.Entry<String, List<String>> rawEntry : rawEntries) { if(rawEntryIndex % chunkSize == 0) { if(currentChunk.size() > 0) { mapChunks.add(currentChunk); } currentChunk = new LinkedHashMap<String, List<String>>(); } currentChunk.put(rawEntry.getKey(), rawEntry.getValue()); rawEntryIndex++; if(rawEntryIndex == rawMap.size()) { mapChunks.add(currentChunk); } } return mapChunks; } private MapUtils(); static List<Map<String, List<String>>> splitToChunksOfSize(Map<String, List<String>> rawMap, int chunkSize); } | MapUtils { public static List<Map<String, List<String>>> splitToChunksOfSize(Map<String, List<String>> rawMap, int chunkSize) { List<Map<String, List<String>>> mapChunks = new LinkedList<Map<String, List<String>>>(); Set<Map.Entry<String, List<String>>> rawEntries = rawMap.entrySet(); Map<String, List<String>> currentChunk = new LinkedHashMap<String, List<String>>(); int rawEntryIndex = 0; for(Map.Entry<String, List<String>> rawEntry : rawEntries) { if(rawEntryIndex % chunkSize == 0) { if(currentChunk.size() > 0) { mapChunks.add(currentChunk); } currentChunk = new LinkedHashMap<String, List<String>>(); } currentChunk.put(rawEntry.getKey(), rawEntry.getValue()); rawEntryIndex++; if(rawEntryIndex == rawMap.size()) { mapChunks.add(currentChunk); } } return mapChunks; } private MapUtils(); static List<Map<String, List<String>>> splitToChunksOfSize(Map<String, List<String>> rawMap, int chunkSize); } |
@Test public void should_create_corect_query_for_simple_property() { final String methodName = "findByItemName"; final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class); final String query = PartTreeConverter.toIndexedQuery(tree); final String expected = " itemName = ? "; assertEquals(expected, query); } | public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } private PartTreeConverter(); } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } private PartTreeConverter(); static String toIndexedQuery(final PartTree tree); } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } private PartTreeConverter(); static String toIndexedQuery(final PartTree tree); } |
@Test public void should_create_corect_query_for_between() { final String methodName = "readByAgeBetween"; final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class); final String query = PartTreeConverter.toIndexedQuery(tree); final String expected = " age BETWEEN ? and ? "; assertEquals(expected, query); } | public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } private PartTreeConverter(); } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } private PartTreeConverter(); static String toIndexedQuery(final PartTree tree); } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } private PartTreeConverter(); static String toIndexedQuery(final PartTree tree); } |
@Test public void should_create_corect_query_for_complex_operators() { final String methodName = "getByItemNameLikeOrAgeGreaterThanAndAgeLessThan"; final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class); final String query = PartTreeConverter.toIndexedQuery(tree); final String expected = " itemName LIKE ? OR age > ? AND age < ? "; assertEquals(expected, query); } | public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } private PartTreeConverter(); } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } private PartTreeConverter(); static String toIndexedQuery(final PartTree tree); } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } private PartTreeConverter(); static String toIndexedQuery(final PartTree tree); } |
@Test(expected = MappingException.class) public void shoud_fail_for_unsupported_operator() { final String methodName = "readByAgeEndsWith"; final PartTree tree = new PartTree(methodName, SimpleDbSampleEntity.class); PartTreeConverter.toIndexedQuery(tree); } | public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } private PartTreeConverter(); } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } private PartTreeConverter(); static String toIndexedQuery(final PartTree tree); } | PartTreeConverter { public static String toIndexedQuery(final PartTree tree) { final StringBuilder result = new StringBuilder(); final Iterator<OrPart> orIt = tree.iterator(); while(orIt.hasNext()) { final OrPart orPart = orIt.next(); final Iterator<Part> partIt = orPart.iterator(); while(partIt.hasNext()) { final Part part = partIt.next(); result.append(" " + part.getProperty().getSegment() + " "); result.append(convertOperator(part.getType())); if(partIt.hasNext()) { result.append(" AND "); } } if(orIt.hasNext()) { result.append(" OR "); } } return StringUtil.removeExtraSpaces(result.toString()); } private PartTreeConverter(); static String toIndexedQuery(final PartTree tree); } |
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test(expected = IllegalArgumentException.class) public void assertNotHavingNestedQueryParameters_should_fail_for_nested_attributes() { SimpleDbQueryMethod method = Mockito.mock(SimpleDbQueryMethod.class); Mockito.when(method.getDomainClazz()).thenReturn((Class) SampleEntity.class); SimpleDbRepositoryQuery repositoryQuery = new SimpleDbRepositoryQuery(method, null); repositoryQuery.assertNotHavingNestedQueryParameters("select sampleNestedAttribute from SampleEntity"); } | void assertNotHavingNestedQueryParameters(String query) { List<String> attributesFromQuery = QueryUtils.getQueryPartialFieldNames(query); final Class<?> domainClass = method.getDomainClazz(); for(String attribute : attributesFromQuery) { try { Field field = ReflectionUtils.getDeclaredFieldInHierarchy(domainClass, attribute); if(FieldTypeIdentifier.isOfType(field, FieldType.NESTED_ENTITY)) { throw new IllegalArgumentException("Invalid query parameter :" + attribute + " is nested object"); } } catch(NoSuchFieldException e) { } } } | SimpleDbRepositoryQuery implements RepositoryQuery { void assertNotHavingNestedQueryParameters(String query) { List<String> attributesFromQuery = QueryUtils.getQueryPartialFieldNames(query); final Class<?> domainClass = method.getDomainClazz(); for(String attribute : attributesFromQuery) { try { Field field = ReflectionUtils.getDeclaredFieldInHierarchy(domainClass, attribute); if(FieldTypeIdentifier.isOfType(field, FieldType.NESTED_ENTITY)) { throw new IllegalArgumentException("Invalid query parameter :" + attribute + " is nested object"); } } catch(NoSuchFieldException e) { } } } } | SimpleDbRepositoryQuery implements RepositoryQuery { void assertNotHavingNestedQueryParameters(String query) { List<String> attributesFromQuery = QueryUtils.getQueryPartialFieldNames(query); final Class<?> domainClass = method.getDomainClazz(); for(String attribute : attributesFromQuery) { try { Field field = ReflectionUtils.getDeclaredFieldInHierarchy(domainClass, attribute); if(FieldTypeIdentifier.isOfType(field, FieldType.NESTED_ENTITY)) { throw new IllegalArgumentException("Invalid query parameter :" + attribute + " is nested object"); } } catch(NoSuchFieldException e) { } } } SimpleDbRepositoryQuery(SimpleDbQueryMethod method, SimpleDbOperations simpledbOperations); } | SimpleDbRepositoryQuery implements RepositoryQuery { void assertNotHavingNestedQueryParameters(String query) { List<String> attributesFromQuery = QueryUtils.getQueryPartialFieldNames(query); final Class<?> domainClass = method.getDomainClazz(); for(String attribute : attributesFromQuery) { try { Field field = ReflectionUtils.getDeclaredFieldInHierarchy(domainClass, attribute); if(FieldTypeIdentifier.isOfType(field, FieldType.NESTED_ENTITY)) { throw new IllegalArgumentException("Invalid query parameter :" + attribute + " is nested object"); } } catch(NoSuchFieldException e) { } } } SimpleDbRepositoryQuery(SimpleDbQueryMethod method, SimpleDbOperations simpledbOperations); @Override Object execute(Object[] parameters); @Override QueryMethod getQueryMethod(); static RepositoryQuery fromQueryAnnotation(SimpleDbQueryMethod queryMethod,
SimpleDbOperations simpleDbOperations); } | SimpleDbRepositoryQuery implements RepositoryQuery { void assertNotHavingNestedQueryParameters(String query) { List<String> attributesFromQuery = QueryUtils.getQueryPartialFieldNames(query); final Class<?> domainClass = method.getDomainClazz(); for(String attribute : attributesFromQuery) { try { Field field = ReflectionUtils.getDeclaredFieldInHierarchy(domainClass, attribute); if(FieldTypeIdentifier.isOfType(field, FieldType.NESTED_ENTITY)) { throw new IllegalArgumentException("Invalid query parameter :" + attribute + " is nested object"); } } catch(NoSuchFieldException e) { } } } SimpleDbRepositoryQuery(SimpleDbQueryMethod method, SimpleDbOperations simpledbOperations); @Override Object execute(Object[] parameters); @Override QueryMethod getQueryMethod(); static RepositoryQuery fromQueryAnnotation(SimpleDbQueryMethod queryMethod,
SimpleDbOperations simpleDbOperations); } |
@Test(expected = IllegalArgumentException.class) public void executeSingleResultQuery_should_fail_if_multiple_results_are_retrieved() { SimpleDbOperations simpleDbOperations = Mockito.mock(SimpleDbOperations.class); List<SampleEntity> sampleMultipleResults = new ArrayList<SampleEntity>(); sampleMultipleResults.add(new SampleEntity()); sampleMultipleResults.add(new SampleEntity()); Mockito.when(simpleDbOperations.find(Mockito.same(SampleEntity.class), Mockito.anyString())).thenReturn( sampleMultipleResults); SimpleDbQueryRunner runner = new SimpleDbQueryRunner((SimpleDbOperations) simpleDbOperations, SampleEntity.class, null); runner.executeSingleResultQuery(); } | public Object executeSingleResultQuery() { List<?> returnListFromDb = executeQuery(); return getSingleResult(returnListFromDb); } | SimpleDbQueryRunner { public Object executeSingleResultQuery() { List<?> returnListFromDb = executeQuery(); return getSingleResult(returnListFromDb); } } | SimpleDbQueryRunner { public Object executeSingleResultQuery() { List<?> returnListFromDb = executeQuery(); return getSingleResult(returnListFromDb); } SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query); SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query,
Pageable pageable); } | SimpleDbQueryRunner { public Object executeSingleResultQuery() { List<?> returnListFromDb = executeQuery(); return getSingleResult(returnListFromDb); } SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query); SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query,
Pageable pageable); List<?> executeQuery(); Object executeSingleResultQuery(); long executeCount(); List<String> getRequestedQueryFieldNames(); String getSingleQueryFieldName(); Page<?> executePagedQuery(); } | SimpleDbQueryRunner { public Object executeSingleResultQuery() { List<?> returnListFromDb = executeQuery(); return getSingleResult(returnListFromDb); } SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query); SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query,
Pageable pageable); List<?> executeQuery(); Object executeSingleResultQuery(); long executeCount(); List<String> getRequestedQueryFieldNames(); String getSingleQueryFieldName(); Page<?> executePagedQuery(); } |
@Test public void getSingleResult_should_return_null_for_empty_list() { SimpleDbQueryRunner runner = new SimpleDbQueryRunner(null, SampleEntity.class, null); final Object result = runner.getSingleResult(new ArrayList<SampleEntity>()); assertNull(result); } | Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } | SimpleDbQueryRunner { Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } } | SimpleDbQueryRunner { Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query); SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query,
Pageable pageable); } | SimpleDbQueryRunner { Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query); SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query,
Pageable pageable); List<?> executeQuery(); Object executeSingleResultQuery(); long executeCount(); List<String> getRequestedQueryFieldNames(); String getSingleQueryFieldName(); Page<?> executePagedQuery(); } | SimpleDbQueryRunner { Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query); SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query,
Pageable pageable); List<?> executeQuery(); Object executeSingleResultQuery(); long executeCount(); List<String> getRequestedQueryFieldNames(); String getSingleQueryFieldName(); Page<?> executePagedQuery(); } |
@Test public void getSingleResult_should_return_single_value_from_list_with_one_element() { SimpleDbQueryRunner runner = new SimpleDbQueryRunner(null, SampleEntity.class, null); final ArrayList<SampleEntity> results = new ArrayList<SampleEntity>(); results.add(new SampleEntity()); final Object result = runner.getSingleResult(results); assertNotNull(result); } | Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } | SimpleDbQueryRunner { Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } } | SimpleDbQueryRunner { Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query); SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query,
Pageable pageable); } | SimpleDbQueryRunner { Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query); SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query,
Pageable pageable); List<?> executeQuery(); Object executeSingleResultQuery(); long executeCount(); List<String> getRequestedQueryFieldNames(); String getSingleQueryFieldName(); Page<?> executePagedQuery(); } | SimpleDbQueryRunner { Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query); SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query,
Pageable pageable); List<?> executeQuery(); Object executeSingleResultQuery(); long executeCount(); List<String> getRequestedQueryFieldNames(); String getSingleQueryFieldName(); Page<?> executePagedQuery(); } |
@Test public void translateExceptionIfPossible_should_translate_AttributeDoesNotExistException_into_EmptyResultDataAccessException() { AttributeDoesNotExistException attributeDoesNotExistException = new AttributeDoesNotExistException( "Attribute does not exist"); DataAccessException dataAccessException = translator .translateExceptionIfPossible(attributeDoesNotExistException); assertThat(dataAccessException, is(instanceOf(EmptyResultDataAccessException.class))); assertThat(dataAccessException, is(notNullValue())); assertThat(dataAccessException.getLocalizedMessage(), is("Attribute does not exist")); } | @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } |
@Test(expected = IllegalArgumentException.class) public void getSingleResult_should_fail_for_list_with_multiple_elements() { SimpleDbQueryRunner runner = new SimpleDbQueryRunner(null, SampleEntity.class, null); final ArrayList<SampleEntity> results = new ArrayList<SampleEntity>(); results.add(new SampleEntity()); results.add(new SampleEntity()); runner.getSingleResult(results); } | Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } | SimpleDbQueryRunner { Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } } | SimpleDbQueryRunner { Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query); SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query,
Pageable pageable); } | SimpleDbQueryRunner { Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query); SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query,
Pageable pageable); List<?> executeQuery(); Object executeSingleResultQuery(); long executeCount(); List<String> getRequestedQueryFieldNames(); String getSingleQueryFieldName(); Page<?> executePagedQuery(); } | SimpleDbQueryRunner { Object getSingleResult(List<?> returnListFromDb) { Assert.isTrue(returnListFromDb.size() <= 1, "Select statement should return only one entity from database, returned elements size=" + returnListFromDb.size() + ", for Query=" + query); return returnListFromDb.size() > 0 ? returnListFromDb.get(0) : null; } SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query); SimpleDbQueryRunner(SimpleDbOperations simpledbOperations, Class<?> domainClass, String query,
Pageable pageable); List<?> executeQuery(); Object executeSingleResultQuery(); long executeCount(); List<String> getRequestedQueryFieldNames(); String getSingleQueryFieldName(); Page<?> executePagedQuery(); } |
@Test public void filterNamedAttributesAsList_should_return_list_of_named_attributes() throws Exception { List<SampleEntity> entities = new ArrayList<SampleEntity>(); SampleEntity entity = new SampleEntity(); entity.setSampleAttribute(SAMPLE_INT_VALUE); entities.add(entity); List<Object> filteredAttributes = SimpleDbResultConverter.filterNamedAttributesAsList(entities, "sampleAttribute"); assertEquals(1, filteredAttributes.size()); Object firstElement = filteredAttributes.get(0); assertEquals(SAMPLE_INT_VALUE, firstElement); } | public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } | SimpleDbResultConverter { public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } } | SimpleDbResultConverter { public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter(); } | SimpleDbResultConverter { public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter(); static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName); static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName); static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames); } | SimpleDbResultConverter { public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter(); static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName); static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName); static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames); } |
@Test public void filterNamedAttributesAsList_should_work_for_list_attributes() throws Exception { List<SampleEntity> entities = new ArrayList<SampleEntity>(); SampleEntity entity = new SampleEntity(); entity.setSampleList(new ArrayList<Integer>()); entities.add(entity); List<Object> filteredAttributes = SimpleDbResultConverter.filterNamedAttributesAsList(entities, "sampleList"); assertEquals(1, filteredAttributes.size()); Object firstElement = filteredAttributes.get(0); assertTrue(firstElement instanceof List); } | public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } | SimpleDbResultConverter { public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } } | SimpleDbResultConverter { public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter(); } | SimpleDbResultConverter { public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter(); static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName); static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName); static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames); } | SimpleDbResultConverter { public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter(); static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName); static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName); static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames); } |
@Test(expected = MappingException.class) public void filterNamedAttributesAsList_should_not_return_list_of_named_attributes_for_wrong_att() throws Exception { List<SampleEntity> entities = new ArrayList<SampleEntity>(); SampleEntity entity = new SampleEntity(); entities.add(entity); SimpleDbResultConverter.filterNamedAttributesAsList(entities, "wrongAttribute"); } | public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } | SimpleDbResultConverter { public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } } | SimpleDbResultConverter { public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter(); } | SimpleDbResultConverter { public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter(); static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName); static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName); static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames); } | SimpleDbResultConverter { public static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName) { List<Object> ret = new ArrayList<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter(); static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName); static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName); static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames); } |
@Test public void filterNamedAttributesAsSet_should_return_Set_of_named_attributes() throws Exception { List<SampleEntity> entities = new ArrayList<SampleEntity>(); SampleEntity entity = new SampleEntity(); entity.setSampleAttribute(SAMPLE_INT_VALUE); entities.add(entity); Set<Object> filteredAttributes = SimpleDbResultConverter .filterNamedAttributesAsSet(entities, "sampleAttribute"); assertEquals(1, filteredAttributes.size()); Object firstElement = filteredAttributes.iterator().next(); assertEquals(SAMPLE_INT_VALUE, firstElement); } | public static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName) { Set<Object> ret = new LinkedHashSet<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } | SimpleDbResultConverter { public static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName) { Set<Object> ret = new LinkedHashSet<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } } | SimpleDbResultConverter { public static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName) { Set<Object> ret = new LinkedHashSet<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter(); } | SimpleDbResultConverter { public static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName) { Set<Object> ret = new LinkedHashSet<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter(); static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName); static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName); static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames); } | SimpleDbResultConverter { public static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName) { Set<Object> ret = new LinkedHashSet<Object>(); for(Object object : domainObjects) { ret.add(ReflectionUtils.callGetter(object, attributeName)); } return ret; } private SimpleDbResultConverter(); static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName); static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName); static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames); } |
@Test public void toListOfListOfObject_should_return_List_of_Lists_containing_requested_attributes() { List<SampleEntity> entities = new ArrayList<SampleEntity>(); SampleEntity entity = new SampleEntity(); entity.setSampleAttribute(SAMPLE_INT_VALUE); entity.setSampleList(new ArrayList<Integer>()); entities.add(entity); List<String> attributes = Arrays.asList("sampleAttribute", "sampleList"); List<List<Object>> filteredAttributes = SimpleDbResultConverter.toListOfListOfObject(entities, attributes); assertEquals(1, filteredAttributes.size()); List<Object> columns = filteredAttributes.get(0); assertEquals(2, columns.size()); assertEquals(SAMPLE_INT_VALUE, columns.get(0)); } | public static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames) { if(entityList.size() > 0) { List<List<Object>> rows = new ArrayList<List<Object>>(); for(Object entity : entityList) { List<Object> cols = new ArrayList<Object>(); for(String fieldName : requestedQueryFieldNames) { Object value = ReflectionUtils.callGetter(entity, fieldName); cols.add(value); } rows.add(cols); } return rows; } else { return Collections.emptyList(); } } | SimpleDbResultConverter { public static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames) { if(entityList.size() > 0) { List<List<Object>> rows = new ArrayList<List<Object>>(); for(Object entity : entityList) { List<Object> cols = new ArrayList<Object>(); for(String fieldName : requestedQueryFieldNames) { Object value = ReflectionUtils.callGetter(entity, fieldName); cols.add(value); } rows.add(cols); } return rows; } else { return Collections.emptyList(); } } } | SimpleDbResultConverter { public static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames) { if(entityList.size() > 0) { List<List<Object>> rows = new ArrayList<List<Object>>(); for(Object entity : entityList) { List<Object> cols = new ArrayList<Object>(); for(String fieldName : requestedQueryFieldNames) { Object value = ReflectionUtils.callGetter(entity, fieldName); cols.add(value); } rows.add(cols); } return rows; } else { return Collections.emptyList(); } } private SimpleDbResultConverter(); } | SimpleDbResultConverter { public static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames) { if(entityList.size() > 0) { List<List<Object>> rows = new ArrayList<List<Object>>(); for(Object entity : entityList) { List<Object> cols = new ArrayList<Object>(); for(String fieldName : requestedQueryFieldNames) { Object value = ReflectionUtils.callGetter(entity, fieldName); cols.add(value); } rows.add(cols); } return rows; } else { return Collections.emptyList(); } } private SimpleDbResultConverter(); static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName); static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName); static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames); } | SimpleDbResultConverter { public static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames) { if(entityList.size() > 0) { List<List<Object>> rows = new ArrayList<List<Object>>(); for(Object entity : entityList) { List<Object> cols = new ArrayList<Object>(); for(String fieldName : requestedQueryFieldNames) { Object value = ReflectionUtils.callGetter(entity, fieldName); cols.add(value); } rows.add(cols); } return rows; } else { return Collections.emptyList(); } } private SimpleDbResultConverter(); static List<Object> filterNamedAttributesAsList(List<?> domainObjects, String attributeName); static Set<Object> filterNamedAttributesAsSet(List<?> domainObjects, String attributeName); static List<List<Object>> toListOfListOfObject(List<?> entityList, List<String> requestedQueryFieldNames); } |
@Test public void detectResultType_should_return_COLLECTION_OF_DOMAIN_ENTITIES() throws Exception { SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectAll", SampleEntity.class); MultipleResultExecution multipleResultExecution = new MultipleResultExecution(null); assertEquals(MultipleResultExecution.MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES, multipleResultExecution.detectResultType(repositoryMethod)); } | MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } |
@Test public void detectResultType_for_selected_field_should_return_COLLECTION_OF_DOMAIN_ENTITIES() throws Exception { SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("partialSampleListSelect", SampleEntity.class); MultipleResultExecution multipleResultExecution = new MultipleResultExecution(null); assertEquals(MultipleResultExecution.MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES, multipleResultExecution.detectResultType(repositoryMethod)); } | MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } |
@Test public void detectResultType_should_return_LIST_OF_LIST_OF_OBJECT() throws Exception { SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectCoreFields", SampleEntity.class); MultipleResultExecution multipleResultExecution = new MultipleResultExecution(null); assertEquals(MultipleResultExecution.MultipleResultType.LIST_OF_LIST_OF_OBJECT, multipleResultExecution.detectResultType(repositoryMethod)); } | MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } |
@Test public void detectResultType_for_multiple_selected_attributes_should_return_LIST_OF_LIST_OF_OBJECT() throws Exception { SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectFields", SampleEntity.class); MultipleResultExecution multipleResultExecution = new MultipleResultExecution(null); assertEquals(MultipleResultExecution.MultipleResultType.LIST_OF_LIST_OF_OBJECT, multipleResultExecution.detectResultType(repositoryMethod)); } | MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } |
@Test public void translateExceptionIfPossible_should_translate_ResourceNotFoundException_into_DataRetrievalFailureException() { ResourceNotFoundException resourceNotFoundException = new ResourceNotFoundException("Resource Not Found"); DataAccessException dataAccessException = translator.translateExceptionIfPossible(resourceNotFoundException); assertThat(dataAccessException, is(instanceOf(DataRetrievalFailureException.class))); assertThat(dataAccessException, is(notNullValue())); assertThat(dataAccessException.getLocalizedMessage(), StringContains.containsString("Resource Not Found")); } | @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } |
@Test public void detectResultType_should_return_FIELD_OF_TYPE_COLLECTION() throws Exception { SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("sampleListSelect", SampleEntity.class); MultipleResultExecution multipleResultExecution = new MultipleResultExecution(null); assertEquals(MultipleResultExecution.MultipleResultType.FIELD_OF_TYPE_COLLECTION, multipleResultExecution.detectResultType(repositoryMethod)); } | MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } |
@Test public void detectResultType_should_return_LIST_OF_FIELDS() throws Exception { SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("sampleAllSampleListSelect", SampleEntity.class); MultipleResultExecution multipleResultExecution = new MultipleResultExecution(null); assertEquals(MultipleResultExecution.MultipleResultType.LIST_OF_FIELDS, multipleResultExecution.detectResultType(repositoryMethod)); } | MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } |
@Test public void detectResultType_should_return_SET_OF_FIELDS() throws Exception { SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("sampleAllSampleListSelectInSet", SampleEntity.class); MultipleResultExecution multipleResultExecution = new MultipleResultExecution(null); assertEquals(MultipleResultExecution.MultipleResultType.SET_OF_FIELDS, multipleResultExecution.detectResultType(repositoryMethod)); } | MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } |
@Test public void detectResultType_should_return_FIELD_OF_TYPE_COLLECTION_of_list_of_lists() throws Exception { SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("listOfListOfIntegerFieldSelect", SampleEntity.class); MultipleResultExecution multipleResultExecution = new MultipleResultExecution(null); assertEquals(MultipleResultExecution.MultipleResultType.FIELD_OF_TYPE_COLLECTION, multipleResultExecution.detectResultType(repositoryMethod)); } | MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } |
@Test(expected = IllegalArgumentException.class) public void detectResultType_should_return_error_for_inexisting_field() throws Exception { SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("sampleWrongField", SampleEntity.class); MultipleResultExecution multipleResultExecution = new MultipleResultExecution(null); multipleResultExecution.detectResultType(repositoryMethod); } | MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } | MultipleResultExecution extends AbstractSimpleDbQueryExecution { MultipleResultType detectResultType(SimpleDbQueryMethod method) { String query = method.getAnnotatedQuery(); if(method.returnsCollectionOfDomainClass()) { return MultipleResultType.COLLECTION_OF_DOMAIN_ENTITIES; } else if(QueryUtils.getQueryPartialFieldNames(query).size() > 1) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else { if(method.returnsListOfListOfObject()) { return MultipleResultType.LIST_OF_LIST_OF_OBJECT; } else if(method.returnsFieldOfTypeCollection()) { return MultipleResultType.FIELD_OF_TYPE_COLLECTION; } else if(List.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.LIST_OF_FIELDS; } else if(Set.class.isAssignableFrom(method.getReturnType())) { return MultipleResultType.SET_OF_FIELDS; } else { throw new IllegalArgumentException("Wrong return type for query: " + query); } } } MultipleResultExecution(SimpleDbOperations simpledbOperations); } |
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void doExecute_should_return_Page_type() throws Exception { final SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectAllIntoPage", SampleEntity.class); final PagedResultExecution execution = new PagedResultExecution(null); final SimpleDbQueryRunner queryRunner = Mockito.mock(SimpleDbQueryRunner.class); when(queryRunner.executePagedQuery()).thenReturn(new PageImpl(new ArrayList())); final Object result = execution.doExecute(repositoryMethod, queryRunner); assertTrue(Page.class.isAssignableFrom(result.getClass())); } | @Override protected Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner) { final Page<?> pagedResult = queryRunner.executePagedQuery(); if(queryMethod.isPageQuery()) { return pagedResult; } return pagedResult.getContent(); } | PagedResultExecution extends AbstractSimpleDbQueryExecution { @Override protected Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner) { final Page<?> pagedResult = queryRunner.executePagedQuery(); if(queryMethod.isPageQuery()) { return pagedResult; } return pagedResult.getContent(); } } | PagedResultExecution extends AbstractSimpleDbQueryExecution { @Override protected Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner) { final Page<?> pagedResult = queryRunner.executePagedQuery(); if(queryMethod.isPageQuery()) { return pagedResult; } return pagedResult.getContent(); } PagedResultExecution(SimpleDbOperations simpleDbOperations); } | PagedResultExecution extends AbstractSimpleDbQueryExecution { @Override protected Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner) { final Page<?> pagedResult = queryRunner.executePagedQuery(); if(queryMethod.isPageQuery()) { return pagedResult; } return pagedResult.getContent(); } PagedResultExecution(SimpleDbOperations simpleDbOperations); } | PagedResultExecution extends AbstractSimpleDbQueryExecution { @Override protected Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner) { final Page<?> pagedResult = queryRunner.executePagedQuery(); if(queryMethod.isPageQuery()) { return pagedResult; } return pagedResult.getContent(); } PagedResultExecution(SimpleDbOperations simpleDbOperations); } |
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void doExecute_should_return_List_type() throws Exception { final SimpleDbQueryMethod repositoryMethod = prepareQueryMethodToTest("selectAllIntoList", SampleEntity.class); final PagedResultExecution execution = new PagedResultExecution(null); final SimpleDbQueryRunner queryRunner = Mockito.mock(SimpleDbQueryRunner.class); when(queryRunner.executePagedQuery()).thenReturn(new PageImpl(new ArrayList())); final Object result = execution.doExecute(repositoryMethod, queryRunner); assertTrue(List.class.isAssignableFrom(result.getClass())); } | @Override protected Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner) { final Page<?> pagedResult = queryRunner.executePagedQuery(); if(queryMethod.isPageQuery()) { return pagedResult; } return pagedResult.getContent(); } | PagedResultExecution extends AbstractSimpleDbQueryExecution { @Override protected Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner) { final Page<?> pagedResult = queryRunner.executePagedQuery(); if(queryMethod.isPageQuery()) { return pagedResult; } return pagedResult.getContent(); } } | PagedResultExecution extends AbstractSimpleDbQueryExecution { @Override protected Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner) { final Page<?> pagedResult = queryRunner.executePagedQuery(); if(queryMethod.isPageQuery()) { return pagedResult; } return pagedResult.getContent(); } PagedResultExecution(SimpleDbOperations simpleDbOperations); } | PagedResultExecution extends AbstractSimpleDbQueryExecution { @Override protected Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner) { final Page<?> pagedResult = queryRunner.executePagedQuery(); if(queryMethod.isPageQuery()) { return pagedResult; } return pagedResult.getContent(); } PagedResultExecution(SimpleDbOperations simpleDbOperations); } | PagedResultExecution extends AbstractSimpleDbQueryExecution { @Override protected Object doExecute(SimpleDbQueryMethod queryMethod, SimpleDbQueryRunner queryRunner) { final Page<?> pagedResult = queryRunner.executePagedQuery(); if(queryMethod.isPageQuery()) { return pagedResult; } return pagedResult.getContent(); } PagedResultExecution(SimpleDbOperations simpleDbOperations); } |
@Test public void toSimpleDBAttributeValues_should_return_an_string_representation_of_concatenated_array_elements() throws ParseException { final int[] expectedIntArray = { 1, 2, 3, 4 }; final List<String> simpleDBValues = Arrays.asList("1", "2", "3", "4"); Object returnedPrimitiveCol = SimpleDBAttributeConverter.decodeToPrimitiveArray(simpleDBValues, int.class); int arrayLength = Array.getLength(returnedPrimitiveCol); for(int idx = 0; idx < arrayLength; idx++) { assertEquals(expectedIntArray[idx], Array.get(returnedPrimitiveCol, idx)); } } | public static Object decodeToPrimitiveArray(List<String> fromSimpleDbAttValues, Class<?> retType) throws ParseException { Object primitiveCollection = Array.newInstance(retType, fromSimpleDbAttValues.size()); int idx = 0; for(Iterator<String> iterator = fromSimpleDbAttValues.iterator(); iterator.hasNext(); idx++) { Array.set(primitiveCollection, idx, decodeToFieldOfType(iterator.next(), retType)); } return primitiveCollection; } | SimpleDBAttributeConverter { public static Object decodeToPrimitiveArray(List<String> fromSimpleDbAttValues, Class<?> retType) throws ParseException { Object primitiveCollection = Array.newInstance(retType, fromSimpleDbAttValues.size()); int idx = 0; for(Iterator<String> iterator = fromSimpleDbAttValues.iterator(); iterator.hasNext(); idx++) { Array.set(primitiveCollection, idx, decodeToFieldOfType(iterator.next(), retType)); } return primitiveCollection; } } | SimpleDBAttributeConverter { public static Object decodeToPrimitiveArray(List<String> fromSimpleDbAttValues, Class<?> retType) throws ParseException { Object primitiveCollection = Array.newInstance(retType, fromSimpleDbAttValues.size()); int idx = 0; for(Iterator<String> iterator = fromSimpleDbAttValues.iterator(); iterator.hasNext(); idx++) { Array.set(primitiveCollection, idx, decodeToFieldOfType(iterator.next(), retType)); } return primitiveCollection; } private SimpleDBAttributeConverter(); } | SimpleDBAttributeConverter { public static Object decodeToPrimitiveArray(List<String> fromSimpleDbAttValues, Class<?> retType) throws ParseException { Object primitiveCollection = Array.newInstance(retType, fromSimpleDbAttValues.size()); int idx = 0; for(Iterator<String> iterator = fromSimpleDbAttValues.iterator(); iterator.hasNext(); idx++) { Array.set(primitiveCollection, idx, decodeToFieldOfType(iterator.next(), retType)); } return primitiveCollection; } private SimpleDBAttributeConverter(); static String encode(Object ob); static List<String> encodeArray(final Object arrayValues); static Object decodeToFieldOfType(String value, Class<?> retType); static Object decodeToPrimitiveArray(List<String> fromSimpleDbAttValues, Class<?> retType); } | SimpleDBAttributeConverter { public static Object decodeToPrimitiveArray(List<String> fromSimpleDbAttValues, Class<?> retType) throws ParseException { Object primitiveCollection = Array.newInstance(retType, fromSimpleDbAttValues.size()); int idx = 0; for(Iterator<String> iterator = fromSimpleDbAttValues.iterator(); iterator.hasNext(); idx++) { Array.set(primitiveCollection, idx, decodeToFieldOfType(iterator.next(), retType)); } return primitiveCollection; } private SimpleDBAttributeConverter(); static String encode(Object ob); static List<String> encodeArray(final Object arrayValues); static Object decodeToFieldOfType(String value, Class<?> retType); static Object decodeToPrimitiveArray(List<String> fromSimpleDbAttValues, Class<?> retType); } |
@Test public void splitAttributeValuesWithExceedingLengths_should_detect_long_attributes() throws Exception { Map<String, String> rawAttributes = new LinkedHashMap<String, String>(); rawAttributes.put(SAMPLE_ATT_NAME, STRING_OF_MAX_SIMPLE_DB_LENGTH + "c"); Map<String, List<String>> splitAttributes = SimpleDbAttributeValueSplitter .splitAttributeValuesWithExceedingLengths(rawAttributes); assertEquals("count(keys) == 1", 1, splitAttributes.keySet().size()); Iterator<List<String>> iterator = splitAttributes.values().iterator(); List<String> next = null; if (iterator.hasNext()) { next = iterator.next(); } assertNotNull(next); assertEquals("count(values) == 2", 2, next.size()); } | public static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes) { Map<String, List<String>> splitAttributes = new LinkedHashMap<String, List<String>>(); Set<Map.Entry<String, String>> rawEntries = rawAttributes.entrySet(); for(Map.Entry<String, String> rawEntry : rawEntries) { splitAttributes.put(rawEntry.getKey(), new ArrayList<String>()); if(rawEntry.getValue().length() > MAX_ATTR_VALUE_LEN) { splitAttributes.get(rawEntry.getKey()).addAll(splitExceedingValue(rawEntry.getValue())); } else { splitAttributes.get(rawEntry.getKey()).add(rawEntry.getValue()); } } return splitAttributes; } | SimpleDbAttributeValueSplitter { public static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes) { Map<String, List<String>> splitAttributes = new LinkedHashMap<String, List<String>>(); Set<Map.Entry<String, String>> rawEntries = rawAttributes.entrySet(); for(Map.Entry<String, String> rawEntry : rawEntries) { splitAttributes.put(rawEntry.getKey(), new ArrayList<String>()); if(rawEntry.getValue().length() > MAX_ATTR_VALUE_LEN) { splitAttributes.get(rawEntry.getKey()).addAll(splitExceedingValue(rawEntry.getValue())); } else { splitAttributes.get(rawEntry.getKey()).add(rawEntry.getValue()); } } return splitAttributes; } } | SimpleDbAttributeValueSplitter { public static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes) { Map<String, List<String>> splitAttributes = new LinkedHashMap<String, List<String>>(); Set<Map.Entry<String, String>> rawEntries = rawAttributes.entrySet(); for(Map.Entry<String, String> rawEntry : rawEntries) { splitAttributes.put(rawEntry.getKey(), new ArrayList<String>()); if(rawEntry.getValue().length() > MAX_ATTR_VALUE_LEN) { splitAttributes.get(rawEntry.getKey()).addAll(splitExceedingValue(rawEntry.getValue())); } else { splitAttributes.get(rawEntry.getKey()).add(rawEntry.getValue()); } } return splitAttributes; } private SimpleDbAttributeValueSplitter(); } | SimpleDbAttributeValueSplitter { public static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes) { Map<String, List<String>> splitAttributes = new LinkedHashMap<String, List<String>>(); Set<Map.Entry<String, String>> rawEntries = rawAttributes.entrySet(); for(Map.Entry<String, String> rawEntry : rawEntries) { splitAttributes.put(rawEntry.getKey(), new ArrayList<String>()); if(rawEntry.getValue().length() > MAX_ATTR_VALUE_LEN) { splitAttributes.get(rawEntry.getKey()).addAll(splitExceedingValue(rawEntry.getValue())); } else { splitAttributes.get(rawEntry.getKey()).add(rawEntry.getValue()); } } return splitAttributes; } private SimpleDbAttributeValueSplitter(); static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes); static Map<String, String> combineAttributeValuesWithExceedingLengths(Map<String, List<String>> multiValueAttributes); } | SimpleDbAttributeValueSplitter { public static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes) { Map<String, List<String>> splitAttributes = new LinkedHashMap<String, List<String>>(); Set<Map.Entry<String, String>> rawEntries = rawAttributes.entrySet(); for(Map.Entry<String, String> rawEntry : rawEntries) { splitAttributes.put(rawEntry.getKey(), new ArrayList<String>()); if(rawEntry.getValue().length() > MAX_ATTR_VALUE_LEN) { splitAttributes.get(rawEntry.getKey()).addAll(splitExceedingValue(rawEntry.getValue())); } else { splitAttributes.get(rawEntry.getKey()).add(rawEntry.getValue()); } } return splitAttributes; } private SimpleDbAttributeValueSplitter(); static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes); static Map<String, String> combineAttributeValuesWithExceedingLengths(Map<String, List<String>> multiValueAttributes); static final int MAX_ATTR_VALUE_LEN; } |
@Test public void splitAttributeValuesWithExceedingLengths_should_not_split_short_attributes() throws Exception { Map<String, String> rawAttributes = new LinkedHashMap<String, String>(); rawAttributes.put(SAMPLE_ATT_NAME, "shortValue"); Map<String, List<String>> splitAttributes = SimpleDbAttributeValueSplitter .splitAttributeValuesWithExceedingLengths(rawAttributes); assertEquals(1, splitAttributes.keySet().size()); List<String> firstSplitAttribute = splitAttributes.values().iterator().next(); assertEquals("shortValue", firstSplitAttribute.get(0)); } | public static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes) { Map<String, List<String>> splitAttributes = new LinkedHashMap<String, List<String>>(); Set<Map.Entry<String, String>> rawEntries = rawAttributes.entrySet(); for(Map.Entry<String, String> rawEntry : rawEntries) { splitAttributes.put(rawEntry.getKey(), new ArrayList<String>()); if(rawEntry.getValue().length() > MAX_ATTR_VALUE_LEN) { splitAttributes.get(rawEntry.getKey()).addAll(splitExceedingValue(rawEntry.getValue())); } else { splitAttributes.get(rawEntry.getKey()).add(rawEntry.getValue()); } } return splitAttributes; } | SimpleDbAttributeValueSplitter { public static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes) { Map<String, List<String>> splitAttributes = new LinkedHashMap<String, List<String>>(); Set<Map.Entry<String, String>> rawEntries = rawAttributes.entrySet(); for(Map.Entry<String, String> rawEntry : rawEntries) { splitAttributes.put(rawEntry.getKey(), new ArrayList<String>()); if(rawEntry.getValue().length() > MAX_ATTR_VALUE_LEN) { splitAttributes.get(rawEntry.getKey()).addAll(splitExceedingValue(rawEntry.getValue())); } else { splitAttributes.get(rawEntry.getKey()).add(rawEntry.getValue()); } } return splitAttributes; } } | SimpleDbAttributeValueSplitter { public static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes) { Map<String, List<String>> splitAttributes = new LinkedHashMap<String, List<String>>(); Set<Map.Entry<String, String>> rawEntries = rawAttributes.entrySet(); for(Map.Entry<String, String> rawEntry : rawEntries) { splitAttributes.put(rawEntry.getKey(), new ArrayList<String>()); if(rawEntry.getValue().length() > MAX_ATTR_VALUE_LEN) { splitAttributes.get(rawEntry.getKey()).addAll(splitExceedingValue(rawEntry.getValue())); } else { splitAttributes.get(rawEntry.getKey()).add(rawEntry.getValue()); } } return splitAttributes; } private SimpleDbAttributeValueSplitter(); } | SimpleDbAttributeValueSplitter { public static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes) { Map<String, List<String>> splitAttributes = new LinkedHashMap<String, List<String>>(); Set<Map.Entry<String, String>> rawEntries = rawAttributes.entrySet(); for(Map.Entry<String, String> rawEntry : rawEntries) { splitAttributes.put(rawEntry.getKey(), new ArrayList<String>()); if(rawEntry.getValue().length() > MAX_ATTR_VALUE_LEN) { splitAttributes.get(rawEntry.getKey()).addAll(splitExceedingValue(rawEntry.getValue())); } else { splitAttributes.get(rawEntry.getKey()).add(rawEntry.getValue()); } } return splitAttributes; } private SimpleDbAttributeValueSplitter(); static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes); static Map<String, String> combineAttributeValuesWithExceedingLengths(Map<String, List<String>> multiValueAttributes); } | SimpleDbAttributeValueSplitter { public static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes) { Map<String, List<String>> splitAttributes = new LinkedHashMap<String, List<String>>(); Set<Map.Entry<String, String>> rawEntries = rawAttributes.entrySet(); for(Map.Entry<String, String> rawEntry : rawEntries) { splitAttributes.put(rawEntry.getKey(), new ArrayList<String>()); if(rawEntry.getValue().length() > MAX_ATTR_VALUE_LEN) { splitAttributes.get(rawEntry.getKey()).addAll(splitExceedingValue(rawEntry.getValue())); } else { splitAttributes.get(rawEntry.getKey()).add(rawEntry.getValue()); } } return splitAttributes; } private SimpleDbAttributeValueSplitter(); static Map<String, List<String>> splitAttributeValuesWithExceedingLengths(Map<String, String> rawAttributes); static Map<String, String> combineAttributeValuesWithExceedingLengths(Map<String, List<String>> multiValueAttributes); static final int MAX_ATTR_VALUE_LEN; } |
@Test public void translateExceptionIfPossible_should_translate_InvalidParameterValueException_into_InvalidDataAccessResourceUsageException() { InvalidParameterValueException invalidParameterValueException = new InvalidParameterValueException( "Invalid Parameter"); DataAccessException dataAccessException = translator .translateExceptionIfPossible(invalidParameterValueException); assertThat(dataAccessException, is(instanceOf(InvalidDataAccessResourceUsageException.class))); assertThat(invalidParameterValueException, is(notNullValue())); assertThat(invalidParameterValueException.getLocalizedMessage(), is("Invalid Parameter")); } | @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } |
@Test public void should_create_correct_queries_if_no_other_clauses_are_specified() throws Exception { QueryBuilder builder = new QueryBuilder(SimpleDbSampleEntity.entityInformation()); String returnedQuery = builder.toString(); assertEquals("select * from `simpleDbSampleEntity`", returnedQuery); } | @Override public String toString() { String result = query.toString(); LOGGER.debug("Created query: {}", result); return result; } | QueryBuilder { @Override public String toString() { String result = query.toString(); LOGGER.debug("Created query: {}", result); return result; } } | QueryBuilder { @Override public String toString() { String result = query.toString(); LOGGER.debug("Created query: {}", result); return result; } QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation); QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation, boolean shouldCount); QueryBuilder(String customQuery); QueryBuilder(String customQuery, boolean shouldCount); } | QueryBuilder { @Override public String toString() { String result = query.toString(); LOGGER.debug("Created query: {}", result); return result; } QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation); QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation, boolean shouldCount); QueryBuilder(String customQuery); QueryBuilder(String customQuery, boolean shouldCount); QueryBuilder withLimit(final int limit); QueryBuilder withIds(Iterable<?> iterable); QueryBuilder with(Sort sort); QueryBuilder with(Pageable pageable); @Override String toString(); } | QueryBuilder { @Override public String toString() { String result = query.toString(); LOGGER.debug("Created query: {}", result); return result; } QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation); QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation, boolean shouldCount); QueryBuilder(String customQuery); QueryBuilder(String customQuery, boolean shouldCount); QueryBuilder withLimit(final int limit); QueryBuilder withIds(Iterable<?> iterable); QueryBuilder with(Sort sort); QueryBuilder with(Pageable pageable); @Override String toString(); } |
@Test public void should_include_count_clause_if_requested() throws Exception { QueryBuilder builder = new QueryBuilder(SimpleDbSampleEntity.entityInformation(), true); String returnedQuery = builder.toString(); assertThat(returnedQuery, containsString("select count(*) from")); } | @Override public String toString() { String result = query.toString(); LOGGER.debug("Created query: {}", result); return result; } | QueryBuilder { @Override public String toString() { String result = query.toString(); LOGGER.debug("Created query: {}", result); return result; } } | QueryBuilder { @Override public String toString() { String result = query.toString(); LOGGER.debug("Created query: {}", result); return result; } QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation); QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation, boolean shouldCount); QueryBuilder(String customQuery); QueryBuilder(String customQuery, boolean shouldCount); } | QueryBuilder { @Override public String toString() { String result = query.toString(); LOGGER.debug("Created query: {}", result); return result; } QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation); QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation, boolean shouldCount); QueryBuilder(String customQuery); QueryBuilder(String customQuery, boolean shouldCount); QueryBuilder withLimit(final int limit); QueryBuilder withIds(Iterable<?> iterable); QueryBuilder with(Sort sort); QueryBuilder with(Pageable pageable); @Override String toString(); } | QueryBuilder { @Override public String toString() { String result = query.toString(); LOGGER.debug("Created query: {}", result); return result; } QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation); QueryBuilder(SimpleDbEntityInformation<?, ?> entityInformation, boolean shouldCount); QueryBuilder(String customQuery); QueryBuilder(String customQuery, boolean shouldCount); QueryBuilder withLimit(final int limit); QueryBuilder withIds(Iterable<?> iterable); QueryBuilder with(Sort sort); QueryBuilder with(Pageable pageable); @Override String toString(); } |
@Test public void test_getSerializedPrimitiveAttributes() throws ParseException { final SampleEntity entity = new SampleEntity(); entity.setIntField(11); entity.setLongField(123); entity.setShortField((short) -12); entity.setFloatField(-0.01f); entity.setDoubleField(1.2d); entity.setByteField((byte) 1); entity.setBooleanField(Boolean.TRUE); entity.setStringField("string"); entity.setDoubleWrapper(Double.valueOf("2323.32d")); EntityWrapper<SampleEntity, String> sdbEntity = new EntityWrapper<SampleEntity, String>( EntityInformationSupport.readEntityInformation(SampleEntity.class), entity); assertNotNull(sdbEntity); final Map<String, String> attributes = sdbEntity.serialize(); assertNotNull(attributes); String intValues = attributes.get("intField"); assertNotNull(intValues); assertEquals(entity.getIntField(), ((Integer) SimpleDBAttributeConverter.decodeToFieldOfType(intValues, Integer.class)).intValue()); String longValues = attributes.get("longField"); assertEquals(entity.getLongField(), ((Long) SimpleDBAttributeConverter.decodeToFieldOfType(longValues, Long.class)).longValue()); String shortValues = attributes.get("shortField"); assertEquals(entity.getShortField(), ((Short) SimpleDBAttributeConverter.decodeToFieldOfType(shortValues, Short.class)).shortValue()); String floatValues = attributes.get("floatField"); assertTrue(entity.getFloatField() == ((Float) SimpleDBAttributeConverter.decodeToFieldOfType(floatValues, Float.class)).floatValue()); String doubleValues = attributes.get("doubleField"); assertTrue(entity.getDoubleField() == ((Double) SimpleDBAttributeConverter.decodeToFieldOfType(doubleValues, Double.class)).doubleValue()); String byteValues = attributes.get("byteField"); assertTrue(entity.getByteField() == ((Byte) SimpleDBAttributeConverter.decodeToFieldOfType(byteValues, Byte.class)).byteValue()); String booleanValues = attributes.get("booleanField"); assertTrue(entity.getBooleanField() == ((Boolean) SimpleDBAttributeConverter.decodeToFieldOfType(booleanValues, Boolean.class)).booleanValue()); } | public Map<String, String> serialize() { return serialize(""); } | EntityWrapper { public Map<String, String> serialize() { return serialize(""); } } | EntityWrapper { public Map<String, String> serialize() { return serialize(""); } EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item, boolean isNested); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, boolean isNested); } | EntityWrapper { public Map<String, String> serialize() { return serialize(""); } EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item, boolean isNested); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, boolean isNested); String getDomain(); String getItemName(); Map<String, String> getAttributes(); T getItem(); void generateIdIfNotSet(); void setId(String itemName); Map<String, String> serialize(); Object deserialize(final Map<String, String> attributes); Map<String, List<String>> toMultiValueAttributes(); } | EntityWrapper { public Map<String, String> serialize() { return serialize(""); } EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item, boolean isNested); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, boolean isNested); String getDomain(); String getItemName(); Map<String, String> getAttributes(); T getItem(); void generateIdIfNotSet(); void setId(String itemName); Map<String, String> serialize(); Object deserialize(final Map<String, String> attributes); Map<String, List<String>> toMultiValueAttributes(); } |
@Test public void should_generate_attribute_keys_for_nested_domain_fields() { final AClass aDomain = new AClass(); { aDomain.nestedB = new BClass(); { aDomain.nestedB.floatField = 21f; aDomain.nestedB.nestedNestedC = new CClass(); { aDomain.nestedB.nestedNestedC.doubleField = 14d; } } } EntityWrapper<AClass, String> sdbEntity = new EntityWrapper<AClass, String>( EntityInformationSupport.readEntityInformation(AClass.class), aDomain); final Map<String, String> attributes = sdbEntity.serialize(); assertNotNull(attributes); assertEquals(3, attributes.size()); final Set<String> keySet = attributes.keySet(); assertTrue(keySet.contains("intField")); assertTrue(keySet.contains("nestedB.floatField")); assertTrue(keySet.contains("nestedB.nestedNestedC.doubleField")); } | public Map<String, String> serialize() { return serialize(""); } | EntityWrapper { public Map<String, String> serialize() { return serialize(""); } } | EntityWrapper { public Map<String, String> serialize() { return serialize(""); } EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item, boolean isNested); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, boolean isNested); } | EntityWrapper { public Map<String, String> serialize() { return serialize(""); } EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item, boolean isNested); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, boolean isNested); String getDomain(); String getItemName(); Map<String, String> getAttributes(); T getItem(); void generateIdIfNotSet(); void setId(String itemName); Map<String, String> serialize(); Object deserialize(final Map<String, String> attributes); Map<String, List<String>> toMultiValueAttributes(); } | EntityWrapper { public Map<String, String> serialize() { return serialize(""); } EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, T item, boolean isNested); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation); EntityWrapper(SimpleDbEntityInformation<T, ?> entityInformation, boolean isNested); String getDomain(); String getItemName(); Map<String, String> getAttributes(); T getItem(); void generateIdIfNotSet(); void setId(String itemName); Map<String, String> serialize(); Object deserialize(final Map<String, String> attributes); Map<String, List<String>> toMultiValueAttributes(); } |
@Test public void populateDomainItem_should_convert_item_name() { Item sampleItem = new Item(SAMPLE_ITEM_NAME, new ArrayList<Attribute>()); SimpleDbEntityInformation<SimpleDbSampleEntity, String> entityInformation = SimpleDbSampleEntity .entityInformation(); domainItemBuilder = new DomainItemBuilder<SimpleDbSampleEntity>(); SimpleDbSampleEntity returnedDomainEntity = domainItemBuilder.populateDomainItem(entityInformation, sampleItem); assertEquals(SAMPLE_ITEM_NAME, returnedDomainEntity.getItemName()); } | public T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item) { return buildDomainItem(entityInformation, item); } | DomainItemBuilder { public T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item) { return buildDomainItem(entityInformation, item); } } | DomainItemBuilder { public T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item) { return buildDomainItem(entityInformation, item); } } | DomainItemBuilder { public T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item) { return buildDomainItem(entityInformation, item); } List<T> populateDomainItems(SimpleDbEntityInformation<T, ?> entityInformation, SelectResult selectResult); T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item); } | DomainItemBuilder { public T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item) { return buildDomainItem(entityInformation, item); } List<T> populateDomainItems(SimpleDbEntityInformation<T, ?> entityInformation, SelectResult selectResult); T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item); } |
@Test public void populateDomainItem_should_convert_attributes() { List<Attribute> attributeList = new ArrayList<Attribute>(); attributeList.add(new Attribute("booleanField", "" + SAMPLE_BOOLEAN_ATT_VALUE)); Item sampleItem = new Item(SAMPLE_ITEM_NAME, attributeList); SimpleDbEntityInformation<SimpleDbSampleEntity, String> entityInformation = SimpleDbSampleEntity .entityInformation(); domainItemBuilder = new DomainItemBuilder<SimpleDbSampleEntity>(); SimpleDbSampleEntity returnedDomainEntity = domainItemBuilder.populateDomainItem(entityInformation, sampleItem); assertTrue(returnedDomainEntity.getBooleanField() == SAMPLE_BOOLEAN_ATT_VALUE); } | public T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item) { return buildDomainItem(entityInformation, item); } | DomainItemBuilder { public T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item) { return buildDomainItem(entityInformation, item); } } | DomainItemBuilder { public T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item) { return buildDomainItem(entityInformation, item); } } | DomainItemBuilder { public T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item) { return buildDomainItem(entityInformation, item); } List<T> populateDomainItems(SimpleDbEntityInformation<T, ?> entityInformation, SelectResult selectResult); T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item); } | DomainItemBuilder { public T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item) { return buildDomainItem(entityInformation, item); } List<T> populateDomainItems(SimpleDbEntityInformation<T, ?> entityInformation, SelectResult selectResult); T populateDomainItem(SimpleDbEntityInformation<T, ?> entityInformation, Item item); } |
@Test public void translateExceptionIfPossible_should_translate_NoSuchDomainException_into_EmptyResultDataAccessException() { NoSuchDomainException noSuchDomainException = new NoSuchDomainException("No such domain"); DataAccessException dataAccessException = translator.translateExceptionIfPossible(noSuchDomainException); assertThat(dataAccessException, is(instanceOf(EmptyResultDataAccessException.class))); assertThat(dataAccessException, is(notNullValue())); assertThat(dataAccessException.getLocalizedMessage(), is("No such domain")); } | @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } |
@Test public void translateExceptionIfPossible_should_translate_NumberDomainsExceededException_into_DataIntegrityViolationException() { NumberDomainsExceededException numberDomainsExceededException = new NumberDomainsExceededException( "Invalid domain number"); DataAccessException dataAccessException = translator .translateExceptionIfPossible(numberDomainsExceededException); assertThat(dataAccessException, is(instanceOf(DataIntegrityViolationException.class))); assertThat(dataAccessException, is(notNullValue())); assertThat(dataAccessException.getLocalizedMessage(), StringContains.containsString("Invalid domain number")); } | @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } |
@Test public void translateExceptionIfPossible_should_translate_InvalidNextTokenException_into_InvalidDataAccessApiUsageException() { InvalidNextTokenException invalidNextTokenException = new InvalidNextTokenException("Invalid Token"); DataAccessException dataAccessException = translator.translateExceptionIfPossible(invalidNextTokenException); assertThat(dataAccessException, is(instanceOf(InvalidDataAccessApiUsageException.class))); assertThat(dataAccessException, is(notNullValue())); assertThat(dataAccessException.getLocalizedMessage(), StringContains.containsString("Invalid Token")); } | @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } |
@Test public void translateExceptionIfPossible_should_translate_AmazonServiceException_into_DataAccessResourceFailureException() { AmazonServiceException amazonServiceException = new AmazonServiceException("Amazon internal exception"); DataAccessException dataAccessException = translator.translateExceptionIfPossible(amazonServiceException); assertThat(dataAccessException, is(instanceOf(DataAccessResourceFailureException.class))); assertThat(dataAccessException, is(notNullValue())); assertThat(dataAccessException.getLocalizedMessage(), StringContains.containsString("Amazon internal exception")); } | @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } |
@Test public void translateExceptionIfPossible_should_translate_AmazonClientException_into_UncategorizedSpringDaoException() { AmazonClientException amazonClientException = new AmazonClientException("Amazon internal client exception"); DataAccessException dataAccessException = translator.translateExceptionIfPossible(amazonClientException); assertThat(dataAccessException, is(instanceOf(UncategorizedSpringDaoException.class))); assertThat(dataAccessException, is(notNullValue())); assertThat(dataAccessException.getLocalizedMessage(), StringContains.containsString("Amazon internal client exception")); } | @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } |
@Test public void translateExceptionIfPossible_should_not_interpret_non_translated_exception_like_mapping_exceptions() { MappingException mappingException = new MappingException("Invalid Query"); DataAccessException dataAccessException = translator.translateExceptionIfPossible(mappingException); assertThat(dataAccessException, is(nullValue())); } | @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } | SimpleDbExceptionTranslator implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException e) { final String errorMessage = e.getLocalizedMessage(); if(e instanceof DuplicateItemNameException) { return new DuplicateKeyException(errorMessage, e); } if(e instanceof AttributeDoesNotExistException) { return new EmptyResultDataAccessException(errorMessage, -1); } if(e instanceof ResourceNotFoundException) { return new DataRetrievalFailureException(errorMessage, e); } if(e instanceof InvalidParameterValueException) { return new InvalidDataAccessResourceUsageException(errorMessage, e); } if(e instanceof NoSuchDomainException) { return new EmptyResultDataAccessException(errorMessage, -1); } if((e instanceof NumberDomainAttributesExceededException) || (e instanceof NumberDomainsExceededException)) { return new DataIntegrityViolationException(errorMessage, e); } if((e instanceof InvalidNextTokenException) || (e instanceof TooManyRequestedAttributesException) || (e instanceof MissingParameterException) ) { return new InvalidDataAccessApiUsageException(errorMessage, e); } if(e instanceof AmazonServiceException) { return new DataAccessResourceFailureException(errorMessage, e); } if(e instanceof AmazonClientException) { return new UncategorizedSpringDaoException(errorMessage, e); } return null; } private SimpleDbExceptionTranslator(); static synchronized SimpleDbExceptionTranslator getTranslatorInstance(); RuntimeException translateAmazonClientException(AmazonClientException e); @Override DataAccessException translateExceptionIfPossible(RuntimeException e); } |
@Test public void objectToStringMapNull() { MediaLibraryStatistics statistics = null; Map<String, String> stringStringMap = Util.objectToStringMap(statistics); assertNull(stringStringMap); } | public static Map<String, String> objectToStringMap(Object object) { TypeReference<HashMap<String, String>> typeReference = new TypeReference<HashMap<String, String>>() {}; return objectMapper.convertValue(object, typeReference); } | Util { public static Map<String, String> objectToStringMap(Object object) { TypeReference<HashMap<String, String>> typeReference = new TypeReference<HashMap<String, String>>() {}; return objectMapper.convertValue(object, typeReference); } } | Util { public static Map<String, String> objectToStringMap(Object object) { TypeReference<HashMap<String, String>> typeReference = new TypeReference<HashMap<String, String>>() {}; return objectMapper.convertValue(object, typeReference); } private Util(); } | Util { public static Map<String, String> objectToStringMap(Object object) { TypeReference<HashMap<String, String>> typeReference = new TypeReference<HashMap<String, String>>() {}; return objectMapper.convertValue(object, typeReference); } private Util(); static String getDefaultMusicFolder(); static String getDefaultPodcastFolder(); static String getDefaultPlaylistFolder(); static boolean isWindows(); static void setContentLength(HttpServletResponse response, long length); static List<T> subList(List<T> list, long offset, long max); static List<Integer> toIntegerList(int[] values); static int[] toIntArray(List<Integer> values); static String debugObject(Object object); static String getURLForRequest(HttpServletRequest request); static String getAnonymizedURLForRequest(HttpServletRequest request); static boolean isInstanceOfClassName(Object o, String className); static Map<String, String> objectToStringMap(Object object); static T stringMapToObject(Class<T> clazz, Map<String, String> data); static T stringMapToValidObject(Class<T> clazz, Map<String, String> data); } | Util { public static Map<String, String> objectToStringMap(Object object) { TypeReference<HashMap<String, String>> typeReference = new TypeReference<HashMap<String, String>>() {}; return objectMapper.convertValue(object, typeReference); } private Util(); static String getDefaultMusicFolder(); static String getDefaultPodcastFolder(); static String getDefaultPlaylistFolder(); static boolean isWindows(); static void setContentLength(HttpServletResponse response, long length); static List<T> subList(List<T> list, long offset, long max); static List<Integer> toIntegerList(int[] values); static int[] toIntArray(List<Integer> values); static String debugObject(Object object); static String getURLForRequest(HttpServletRequest request); static String getAnonymizedURLForRequest(HttpServletRequest request); static boolean isInstanceOfClassName(Object o, String className); static Map<String, String> objectToStringMap(Object object); static T stringMapToObject(Class<T> clazz, Map<String, String> data); static T stringMapToValidObject(Class<T> clazz, Map<String, String> data); } |
@Test public void testRedirectLoop() { List<InternetRadioSource> radioSources = internetRadioService.getInternetRadioSources(radioMoveLoop); Assert.assertEquals(0, radioSources.size()); } | public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); void clearInternetRadioSourceCache(); void clearInternetRadioSourceCache(Integer internetRadioId); List<InternetRadioSource> getInternetRadioSources(InternetRadio radio); } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); void clearInternetRadioSourceCache(); void clearInternetRadioSourceCache(Integer internetRadioId); List<InternetRadioSource> getInternetRadioSources(InternetRadio radio); } |
@Test public void objectToStringMap() { Date date = new Date(1568350960725L); MediaLibraryStatistics statistics = new MediaLibraryStatistics(date); statistics.incrementAlbums(5); statistics.incrementSongs(4); statistics.incrementArtists(910823); statistics.incrementTotalDurationInSeconds(30); statistics.incrementTotalLengthInBytes(2930491082L); Map<String, String> stringStringMap = Util.objectToStringMap(statistics); assertEquals("5", stringStringMap.get("albumCount")); assertEquals("4", stringStringMap.get("songCount")); assertEquals("910823", stringStringMap.get("artistCount")); assertEquals("30", stringStringMap.get("totalDurationInSeconds")); assertEquals("2930491082", stringStringMap.get("totalLengthInBytes")); assertEquals("1568350960725", stringStringMap.get("scanDate")); } | public static Map<String, String> objectToStringMap(Object object) { TypeReference<HashMap<String, String>> typeReference = new TypeReference<HashMap<String, String>>() {}; return objectMapper.convertValue(object, typeReference); } | Util { public static Map<String, String> objectToStringMap(Object object) { TypeReference<HashMap<String, String>> typeReference = new TypeReference<HashMap<String, String>>() {}; return objectMapper.convertValue(object, typeReference); } } | Util { public static Map<String, String> objectToStringMap(Object object) { TypeReference<HashMap<String, String>> typeReference = new TypeReference<HashMap<String, String>>() {}; return objectMapper.convertValue(object, typeReference); } private Util(); } | Util { public static Map<String, String> objectToStringMap(Object object) { TypeReference<HashMap<String, String>> typeReference = new TypeReference<HashMap<String, String>>() {}; return objectMapper.convertValue(object, typeReference); } private Util(); static String getDefaultMusicFolder(); static String getDefaultPodcastFolder(); static String getDefaultPlaylistFolder(); static boolean isWindows(); static void setContentLength(HttpServletResponse response, long length); static List<T> subList(List<T> list, long offset, long max); static List<Integer> toIntegerList(int[] values); static int[] toIntArray(List<Integer> values); static String debugObject(Object object); static String getURLForRequest(HttpServletRequest request); static String getAnonymizedURLForRequest(HttpServletRequest request); static boolean isInstanceOfClassName(Object o, String className); static Map<String, String> objectToStringMap(Object object); static T stringMapToObject(Class<T> clazz, Map<String, String> data); static T stringMapToValidObject(Class<T> clazz, Map<String, String> data); } | Util { public static Map<String, String> objectToStringMap(Object object) { TypeReference<HashMap<String, String>> typeReference = new TypeReference<HashMap<String, String>>() {}; return objectMapper.convertValue(object, typeReference); } private Util(); static String getDefaultMusicFolder(); static String getDefaultPodcastFolder(); static String getDefaultPlaylistFolder(); static boolean isWindows(); static void setContentLength(HttpServletResponse response, long length); static List<T> subList(List<T> list, long offset, long max); static List<Integer> toIntegerList(int[] values); static int[] toIntArray(List<Integer> values); static String debugObject(Object object); static String getURLForRequest(HttpServletRequest request); static String getAnonymizedURLForRequest(HttpServletRequest request); static boolean isInstanceOfClassName(Object o, String className); static Map<String, String> objectToStringMap(Object object); static T stringMapToObject(Class<T> clazz, Map<String, String> data); static T stringMapToValidObject(Class<T> clazz, Map<String, String> data); } |
@Test public void stringMapToObject() { Map<String, String> stringStringMap = new HashMap<>(); stringStringMap.put("albumCount", "5"); stringStringMap.put("songCount", "4"); stringStringMap.put("artistCount", "910823"); stringStringMap.put("totalDurationInSeconds", "30"); stringStringMap.put("totalLengthInBytes", "2930491082"); stringStringMap.put("scanDate", "1568350960725"); MediaLibraryStatistics statistics = Util.stringMapToObject(MediaLibraryStatistics.class, stringStringMap); assertEquals(new Integer(5), statistics.getAlbumCount()); assertEquals(new Integer(4), statistics.getSongCount()); assertEquals(new Integer(910823), statistics.getArtistCount()); assertEquals(new Long(30L), statistics.getTotalDurationInSeconds()); assertEquals(new Long(2930491082L), statistics.getTotalLengthInBytes()); assertEquals(new Date(1568350960725L), statistics.getScanDate()); } | public static <T> T stringMapToObject(Class<T> clazz, Map<String, String> data) { return objectMapper.convertValue(data, clazz); } | Util { public static <T> T stringMapToObject(Class<T> clazz, Map<String, String> data) { return objectMapper.convertValue(data, clazz); } } | Util { public static <T> T stringMapToObject(Class<T> clazz, Map<String, String> data) { return objectMapper.convertValue(data, clazz); } private Util(); } | Util { public static <T> T stringMapToObject(Class<T> clazz, Map<String, String> data) { return objectMapper.convertValue(data, clazz); } private Util(); static String getDefaultMusicFolder(); static String getDefaultPodcastFolder(); static String getDefaultPlaylistFolder(); static boolean isWindows(); static void setContentLength(HttpServletResponse response, long length); static List<T> subList(List<T> list, long offset, long max); static List<Integer> toIntegerList(int[] values); static int[] toIntArray(List<Integer> values); static String debugObject(Object object); static String getURLForRequest(HttpServletRequest request); static String getAnonymizedURLForRequest(HttpServletRequest request); static boolean isInstanceOfClassName(Object o, String className); static Map<String, String> objectToStringMap(Object object); static T stringMapToObject(Class<T> clazz, Map<String, String> data); static T stringMapToValidObject(Class<T> clazz, Map<String, String> data); } | Util { public static <T> T stringMapToObject(Class<T> clazz, Map<String, String> data) { return objectMapper.convertValue(data, clazz); } private Util(); static String getDefaultMusicFolder(); static String getDefaultPodcastFolder(); static String getDefaultPlaylistFolder(); static boolean isWindows(); static void setContentLength(HttpServletResponse response, long length); static List<T> subList(List<T> list, long offset, long max); static List<Integer> toIntegerList(int[] values); static int[] toIntArray(List<Integer> values); static String debugObject(Object object); static String getURLForRequest(HttpServletRequest request); static String getAnonymizedURLForRequest(HttpServletRequest request); static boolean isInstanceOfClassName(Object o, String className); static Map<String, String> objectToStringMap(Object object); static T stringMapToObject(Class<T> clazz, Map<String, String> data); static T stringMapToValidObject(Class<T> clazz, Map<String, String> data); } |
@Test public void stringMapToObjectWithExtraneousData() { Map<String, String> stringStringMap = new HashMap<>(); stringStringMap.put("albumCount", "5"); stringStringMap.put("songCount", "4"); stringStringMap.put("artistCount", "910823"); stringStringMap.put("totalDurationInSeconds", "30"); stringStringMap.put("totalLengthInBytes", "2930491082"); stringStringMap.put("scanDate", "1568350960725"); stringStringMap.put("extraneousData", "nothingHereToLookAt"); MediaLibraryStatistics statistics = Util.stringMapToObject(MediaLibraryStatistics.class, stringStringMap); assertEquals(new Integer(5), statistics.getAlbumCount()); assertEquals(new Integer(4), statistics.getSongCount()); assertEquals(new Integer(910823), statistics.getArtistCount()); assertEquals(new Long(30L), statistics.getTotalDurationInSeconds()); assertEquals(new Long(2930491082L), statistics.getTotalLengthInBytes()); assertEquals(new Date(1568350960725L), statistics.getScanDate()); } | public static <T> T stringMapToObject(Class<T> clazz, Map<String, String> data) { return objectMapper.convertValue(data, clazz); } | Util { public static <T> T stringMapToObject(Class<T> clazz, Map<String, String> data) { return objectMapper.convertValue(data, clazz); } } | Util { public static <T> T stringMapToObject(Class<T> clazz, Map<String, String> data) { return objectMapper.convertValue(data, clazz); } private Util(); } | Util { public static <T> T stringMapToObject(Class<T> clazz, Map<String, String> data) { return objectMapper.convertValue(data, clazz); } private Util(); static String getDefaultMusicFolder(); static String getDefaultPodcastFolder(); static String getDefaultPlaylistFolder(); static boolean isWindows(); static void setContentLength(HttpServletResponse response, long length); static List<T> subList(List<T> list, long offset, long max); static List<Integer> toIntegerList(int[] values); static int[] toIntArray(List<Integer> values); static String debugObject(Object object); static String getURLForRequest(HttpServletRequest request); static String getAnonymizedURLForRequest(HttpServletRequest request); static boolean isInstanceOfClassName(Object o, String className); static Map<String, String> objectToStringMap(Object object); static T stringMapToObject(Class<T> clazz, Map<String, String> data); static T stringMapToValidObject(Class<T> clazz, Map<String, String> data); } | Util { public static <T> T stringMapToObject(Class<T> clazz, Map<String, String> data) { return objectMapper.convertValue(data, clazz); } private Util(); static String getDefaultMusicFolder(); static String getDefaultPodcastFolder(); static String getDefaultPlaylistFolder(); static boolean isWindows(); static void setContentLength(HttpServletResponse response, long length); static List<T> subList(List<T> list, long offset, long max); static List<Integer> toIntegerList(int[] values); static int[] toIntArray(List<Integer> values); static String debugObject(Object object); static String getURLForRequest(HttpServletRequest request); static String getAnonymizedURLForRequest(HttpServletRequest request); static boolean isInstanceOfClassName(Object o, String className); static Map<String, String> objectToStringMap(Object object); static T stringMapToObject(Class<T> clazz, Map<String, String> data); static T stringMapToValidObject(Class<T> clazz, Map<String, String> data); } |
@Test(expected = IllegalArgumentException.class) public void stringMapToValidObjectWithNoData() { Map<String, String> stringStringMap = new HashMap<>(); MediaLibraryStatistics statistics = Util.stringMapToValidObject(MediaLibraryStatistics.class, stringStringMap); } | public static <T> T stringMapToValidObject(Class<T> clazz, Map<String, String> data) { T object = stringMapToObject(clazz, data); Set<ConstraintViolation<T>> validate = validator.validate(object); if (validate.isEmpty()) { return object; } else { throw new IllegalArgumentException("Created object was not valid"); } } | Util { public static <T> T stringMapToValidObject(Class<T> clazz, Map<String, String> data) { T object = stringMapToObject(clazz, data); Set<ConstraintViolation<T>> validate = validator.validate(object); if (validate.isEmpty()) { return object; } else { throw new IllegalArgumentException("Created object was not valid"); } } } | Util { public static <T> T stringMapToValidObject(Class<T> clazz, Map<String, String> data) { T object = stringMapToObject(clazz, data); Set<ConstraintViolation<T>> validate = validator.validate(object); if (validate.isEmpty()) { return object; } else { throw new IllegalArgumentException("Created object was not valid"); } } private Util(); } | Util { public static <T> T stringMapToValidObject(Class<T> clazz, Map<String, String> data) { T object = stringMapToObject(clazz, data); Set<ConstraintViolation<T>> validate = validator.validate(object); if (validate.isEmpty()) { return object; } else { throw new IllegalArgumentException("Created object was not valid"); } } private Util(); static String getDefaultMusicFolder(); static String getDefaultPodcastFolder(); static String getDefaultPlaylistFolder(); static boolean isWindows(); static void setContentLength(HttpServletResponse response, long length); static List<T> subList(List<T> list, long offset, long max); static List<Integer> toIntegerList(int[] values); static int[] toIntArray(List<Integer> values); static String debugObject(Object object); static String getURLForRequest(HttpServletRequest request); static String getAnonymizedURLForRequest(HttpServletRequest request); static boolean isInstanceOfClassName(Object o, String className); static Map<String, String> objectToStringMap(Object object); static T stringMapToObject(Class<T> clazz, Map<String, String> data); static T stringMapToValidObject(Class<T> clazz, Map<String, String> data); } | Util { public static <T> T stringMapToValidObject(Class<T> clazz, Map<String, String> data) { T object = stringMapToObject(clazz, data); Set<ConstraintViolation<T>> validate = validator.validate(object); if (validate.isEmpty()) { return object; } else { throw new IllegalArgumentException("Created object was not valid"); } } private Util(); static String getDefaultMusicFolder(); static String getDefaultPodcastFolder(); static String getDefaultPlaylistFolder(); static boolean isWindows(); static void setContentLength(HttpServletResponse response, long length); static List<T> subList(List<T> list, long offset, long max); static List<Integer> toIntegerList(int[] values); static int[] toIntArray(List<Integer> values); static String debugObject(Object object); static String getURLForRequest(HttpServletRequest request); static String getAnonymizedURLForRequest(HttpServletRequest request); static boolean isInstanceOfClassName(Object o, String className); static Map<String, String> objectToStringMap(Object object); static T stringMapToObject(Class<T> clazz, Map<String, String> data); static T stringMapToValidObject(Class<T> clazz, Map<String, String> data); } |
@Test public void addJWTToken() { UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(uriString); String actualUri = service.addJWTToken(builder).build().toUriString(); String jwtToken = UriComponentsBuilder.fromUriString(actualUri).build().getQueryParams().getFirst( JWTSecurityService.JWT_PARAM_NAME); DecodedJWT verify = verifier.verify(jwtToken); Claim claim = verify.getClaim(JWTSecurityService.CLAIM_PATH); assertEquals(expectedClaimString, claim.asString()); } | public String addJWTToken(String uri) { return addJWTToken(UriComponentsBuilder.fromUriString(uri)).build().toString(); } | JWTSecurityService { public String addJWTToken(String uri) { return addJWTToken(UriComponentsBuilder.fromUriString(uri)).build().toString(); } } | JWTSecurityService { public String addJWTToken(String uri) { return addJWTToken(UriComponentsBuilder.fromUriString(uri)).build().toString(); } @Autowired JWTSecurityService(SettingsService settingsService); } | JWTSecurityService { public String addJWTToken(String uri) { return addJWTToken(UriComponentsBuilder.fromUriString(uri)).build().toString(); } @Autowired JWTSecurityService(SettingsService settingsService); static String generateKey(); static Algorithm getAlgorithm(String jwtKey); String addJWTToken(String uri); UriComponentsBuilder addJWTToken(UriComponentsBuilder builder); UriComponentsBuilder addJWTToken(UriComponentsBuilder builder, Date expires); static DecodedJWT verify(String jwtKey, String token); DecodedJWT verify(String credentials); } | JWTSecurityService { public String addJWTToken(String uri) { return addJWTToken(UriComponentsBuilder.fromUriString(uri)).build().toString(); } @Autowired JWTSecurityService(SettingsService settingsService); static String generateKey(); static Algorithm getAlgorithm(String jwtKey); String addJWTToken(String uri); UriComponentsBuilder addJWTToken(UriComponentsBuilder builder); UriComponentsBuilder addJWTToken(UriComponentsBuilder builder, Date expires); static DecodedJWT verify(String jwtKey, String token); DecodedJWT verify(String credentials); static final String JWT_PARAM_NAME; static final String CLAIM_PATH; static final int DEFAULT_DAYS_VALID_FOR; } |
@Test public void testParseSimplePlaylist() { List<InternetRadioSource> radioSources = internetRadioService.getInternetRadioSources(radio1); Assert.assertEquals(2, radioSources.size()); Assert.assertEquals(TEST_STREAM_URL_1, radioSources.get(0).getStreamUrl()); Assert.assertEquals(TEST_STREAM_URL_2, radioSources.get(1).getStreamUrl()); } | public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); void clearInternetRadioSourceCache(); void clearInternetRadioSourceCache(Integer internetRadioId); List<InternetRadioSource> getInternetRadioSources(InternetRadio radio); } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); void clearInternetRadioSourceCache(); void clearInternetRadioSourceCache(Integer internetRadioId); List<InternetRadioSource> getInternetRadioSources(InternetRadio radio); } |
@Test public void testRedirects() { List<InternetRadioSource> radioSources = internetRadioService.getInternetRadioSources(radioMove); Assert.assertEquals(2, radioSources.size()); Assert.assertEquals(TEST_STREAM_URL_3, radioSources.get(0).getStreamUrl()); Assert.assertEquals(TEST_STREAM_URL_4, radioSources.get(1).getStreamUrl()); } | public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); void clearInternetRadioSourceCache(); void clearInternetRadioSourceCache(Integer internetRadioId); List<InternetRadioSource> getInternetRadioSources(InternetRadio radio); } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); void clearInternetRadioSourceCache(); void clearInternetRadioSourceCache(Integer internetRadioId); List<InternetRadioSource> getInternetRadioSources(InternetRadio radio); } |
@Test public void testLargeInput() { List<InternetRadioSource> radioSources = internetRadioService.getInternetRadioSources(radioLarge); Assert.assertEquals(250, radioSources.size()); } | public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); void clearInternetRadioSourceCache(); void clearInternetRadioSourceCache(Integer internetRadioId); List<InternetRadioSource> getInternetRadioSources(InternetRadio radio); } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); void clearInternetRadioSourceCache(); void clearInternetRadioSourceCache(Integer internetRadioId); List<InternetRadioSource> getInternetRadioSources(InternetRadio radio); } |
@Test public void testLargeInputURL() { List<InternetRadioSource> radioSources = internetRadioService.getInternetRadioSources(radioLarge2); Assert.assertEquals(1, radioSources.size()); } | public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); void clearInternetRadioSourceCache(); void clearInternetRadioSourceCache(Integer internetRadioId); List<InternetRadioSource> getInternetRadioSources(InternetRadio radio); } | InternetRadioService { public List<InternetRadioSource> getInternetRadioSources(InternetRadio radio) { List<InternetRadioSource> sources; if (cachedSources.containsKey(radio.getId())) { LOG.debug("Got cached sources for internet radio {}!", radio.getStreamUrl()); sources = cachedSources.get(radio.getId()); } else { LOG.debug("Retrieving sources for internet radio {}...", radio.getStreamUrl()); try { sources = retrieveInternetRadioSources(radio); if (sources.isEmpty()) { LOG.warn("No entries found for internet radio {}.", radio.getStreamUrl()); } else { LOG.info("Retrieved playlist for internet radio {}, got {} sources.", radio.getStreamUrl(), sources.size()); } } catch (Exception e) { LOG.error("Failed to retrieve sources for internet radio {}.", radio.getStreamUrl(), e); sources = new ArrayList<>(); } cachedSources.put(radio.getId(), sources); } return sources; } InternetRadioService(); void clearInternetRadioSourceCache(); void clearInternetRadioSourceCache(Integer internetRadioId); List<InternetRadioSource> getInternetRadioSources(InternetRadio radio); } |
@Test public void listCsars() throws Exception { ResultActions resultActions = mvc.perform( get(LIST_CSARS_URL).accept(ACCEPTED_MIME_TYPE) ).andDo(print()).andExpect(status().is2xxSuccessful()); resultActions.andExpect(jsonPath("$.links[0].rel").value("self")); resultActions.andExpect(jsonPath("$.links[0].href").value(LIST_CSARS_SELF_URL)); resultActions.andExpect(jsonPath("$.content").exists()); resultActions.andExpect(jsonPath("$.content").isArray()); resultActions.andExpect(jsonPath("$.content[2]").doesNotExist()); resultActions.andReturn(); } | @ApiOperation( value = "List all CSARs stored on the server", notes = "Returns a Hypermedia Resource containing all CSARs" + " that have been uploaded to the server and did not get removed", response = CsarResources.class, produces = "application/hal+json" ) @RequestMapping( path = "", method = RequestMethod.GET, produces = "application/hal+json" ) public ResponseEntity<Resources<CsarResponse>> listCSARs() { Link selfLink = linkTo(methodOn(CsarController.class).listCSARs()).withSelfRel(); List<CsarResponse> responses = new ArrayList<>(); for (Csar csar : csarService.getCsars()) { responses.add(new CsarResponse(csar.getIdentifier(), csar.getLifecyclePhases())); } Resources<CsarResponse> csarResources = new HiddenResources<>(responses, selfLink); return ResponseEntity.ok().body(csarResources); } | CsarController { @ApiOperation( value = "List all CSARs stored on the server", notes = "Returns a Hypermedia Resource containing all CSARs" + " that have been uploaded to the server and did not get removed", response = CsarResources.class, produces = "application/hal+json" ) @RequestMapping( path = "", method = RequestMethod.GET, produces = "application/hal+json" ) public ResponseEntity<Resources<CsarResponse>> listCSARs() { Link selfLink = linkTo(methodOn(CsarController.class).listCSARs()).withSelfRel(); List<CsarResponse> responses = new ArrayList<>(); for (Csar csar : csarService.getCsars()) { responses.add(new CsarResponse(csar.getIdentifier(), csar.getLifecyclePhases())); } Resources<CsarResponse> csarResources = new HiddenResources<>(responses, selfLink); return ResponseEntity.ok().body(csarResources); } } | CsarController { @ApiOperation( value = "List all CSARs stored on the server", notes = "Returns a Hypermedia Resource containing all CSARs" + " that have been uploaded to the server and did not get removed", response = CsarResources.class, produces = "application/hal+json" ) @RequestMapping( path = "", method = RequestMethod.GET, produces = "application/hal+json" ) public ResponseEntity<Resources<CsarResponse>> listCSARs() { Link selfLink = linkTo(methodOn(CsarController.class).listCSARs()).withSelfRel(); List<CsarResponse> responses = new ArrayList<>(); for (Csar csar : csarService.getCsars()) { responses.add(new CsarResponse(csar.getIdentifier(), csar.getLifecyclePhases())); } Resources<CsarResponse> csarResources = new HiddenResources<>(responses, selfLink); return ResponseEntity.ok().body(csarResources); } @Autowired CsarController(CsarService csarService); } | CsarController { @ApiOperation( value = "List all CSARs stored on the server", notes = "Returns a Hypermedia Resource containing all CSARs" + " that have been uploaded to the server and did not get removed", response = CsarResources.class, produces = "application/hal+json" ) @RequestMapping( path = "", method = RequestMethod.GET, produces = "application/hal+json" ) public ResponseEntity<Resources<CsarResponse>> listCSARs() { Link selfLink = linkTo(methodOn(CsarController.class).listCSARs()).withSelfRel(); List<CsarResponse> responses = new ArrayList<>(); for (Csar csar : csarService.getCsars()) { responses.add(new CsarResponse(csar.getIdentifier(), csar.getLifecyclePhases())); } Resources<CsarResponse> csarResources = new HiddenResources<>(responses, selfLink); return ResponseEntity.ok().body(csarResources); } @Autowired CsarController(CsarService csarService); @ApiOperation( value = "List all CSARs stored on the server", notes = "Returns a Hypermedia Resource containing all CSARs" + " that have been uploaded to the server and did not get removed", response = CsarResources.class, produces = "application/hal+json" ) @RequestMapping( path = "", method = RequestMethod.GET, produces = "application/hal+json" ) ResponseEntity<Resources<CsarResponse>> listCSARs(); @ApiOperation( value = "Returns details for a specific name (identifier)", notes = "Returns the element with the given name, Object contents are " + "equal to a regular /csars request (if you just look at the desired entry)" ) @ApiResponses({ @ApiResponse( code = 200, message = "The Csar was found and the contents are found in the body", response = CsarResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given name (identifier)", response = RestErrorResponse.class ) }) @RequestMapping( path = "/{name}", method = RequestMethod.GET, produces = "application/hal+json" ) ResponseEntity<CsarResponse> getCSARInfo(
@ApiParam(value = "The unique identifier for the CSAR", required = true, example = "test")
@PathVariable(name = "name") String name
); @ApiOperation( value = "Creates a new CSAR", notes = "This operation creates a new CSAR if the name (identifier) is not used already. " + "The uploaded file has to be a valid CSAR archive. " + "Once the file was uploaded the server will synchronously " + "(the client has to wait for the response) unzip the archive and parse it. " + "Upload gets performed using Multipart Form upload.", code = 201 ) @ApiResponses({ @ApiResponse( code = 201, message = "The upload of the csar was successful", response = Void.class ), @ApiResponse( code = 406, message = "CSAR upload rejected - given ID already in use", response = Void.class ), @ApiResponse( code = 500, message = "The server encountered a unexpected problem", response = Void.class ) }) @RequestMapping( path = "/{name}", method = {RequestMethod.PUT, RequestMethod.POST}, produces = "application/hal+json" ) ResponseEntity<Void> uploadCSAR(
@ApiParam(value = "The unique identifier for the CSAR", required = true)
@PathVariable(name = "name") String name,
@ApiParam(value = "The CSAR Archive (Compressed as ZIP)", required = true)
@RequestParam(name = "file", required = true) MultipartFile file
// HttpServletRequest request
); @ApiOperation( value = "Deletes a Existing CSAR", notes = "Deletes the Resulting CSAR and its transformations (if none of them is running). " + "If a transformation is running (in the state TRANSFORMING) the CSAR cannot be deleted" ) @ApiResponses({ @ApiResponse( code = 200, message = "The deletion of the CSAR was successful", response = Void.class ), @ApiResponse( code = 400, message = "The deletion of the CSAR failed, because there is one or more transformations still running.", response = RestErrorResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given name (identifier)", response = RestErrorResponse.class ) }) @RequestMapping( path = "/{name}/delete", method = {RequestMethod.DELETE}, produces = "application/hal+json" ) ResponseEntity<Void> deleteCsar(
@ApiParam(value = "The unique identifier for the CSAR", required = true, example = "my-csar-name")
@PathVariable("name") String name
); @RequestMapping( path = "/{name}/logs", method = RequestMethod.GET, produces = "application/hal+json" ) @ApiOperation( value = "Get the logs of a csar", tags = {"csars"}, notes = "Returns the logs for a csar, starting at a specific position. from the given start index all " + "following log lines get returned. If the start index is larger than the current last log index the operation " + "will return a empty list." ) @ApiResponses({ @ApiResponse( code = 200, message = "The operation was executed successfully", response = LogResponse.class ), @ApiResponse( code = 400, message = "The given start value is less than zero", response = RestErrorResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given identifier", response = RestErrorResponse.class ) }) ResponseEntity<LogResponse> getLogs(
@ApiParam(value = "The unique identifier for the CSAR", required = true, example = "test")
@PathVariable(name = "name") String csarId,
@ApiParam(value = "The index of the first log entry you want (0 returns the whole log)", required = true, example = "0")
@RequestParam(name = "start", required = false, defaultValue = "0") Long start
); } | CsarController { @ApiOperation( value = "List all CSARs stored on the server", notes = "Returns a Hypermedia Resource containing all CSARs" + " that have been uploaded to the server and did not get removed", response = CsarResources.class, produces = "application/hal+json" ) @RequestMapping( path = "", method = RequestMethod.GET, produces = "application/hal+json" ) public ResponseEntity<Resources<CsarResponse>> listCSARs() { Link selfLink = linkTo(methodOn(CsarController.class).listCSARs()).withSelfRel(); List<CsarResponse> responses = new ArrayList<>(); for (Csar csar : csarService.getCsars()) { responses.add(new CsarResponse(csar.getIdentifier(), csar.getLifecyclePhases())); } Resources<CsarResponse> csarResources = new HiddenResources<>(responses, selfLink); return ResponseEntity.ok().body(csarResources); } @Autowired CsarController(CsarService csarService); @ApiOperation( value = "List all CSARs stored on the server", notes = "Returns a Hypermedia Resource containing all CSARs" + " that have been uploaded to the server and did not get removed", response = CsarResources.class, produces = "application/hal+json" ) @RequestMapping( path = "", method = RequestMethod.GET, produces = "application/hal+json" ) ResponseEntity<Resources<CsarResponse>> listCSARs(); @ApiOperation( value = "Returns details for a specific name (identifier)", notes = "Returns the element with the given name, Object contents are " + "equal to a regular /csars request (if you just look at the desired entry)" ) @ApiResponses({ @ApiResponse( code = 200, message = "The Csar was found and the contents are found in the body", response = CsarResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given name (identifier)", response = RestErrorResponse.class ) }) @RequestMapping( path = "/{name}", method = RequestMethod.GET, produces = "application/hal+json" ) ResponseEntity<CsarResponse> getCSARInfo(
@ApiParam(value = "The unique identifier for the CSAR", required = true, example = "test")
@PathVariable(name = "name") String name
); @ApiOperation( value = "Creates a new CSAR", notes = "This operation creates a new CSAR if the name (identifier) is not used already. " + "The uploaded file has to be a valid CSAR archive. " + "Once the file was uploaded the server will synchronously " + "(the client has to wait for the response) unzip the archive and parse it. " + "Upload gets performed using Multipart Form upload.", code = 201 ) @ApiResponses({ @ApiResponse( code = 201, message = "The upload of the csar was successful", response = Void.class ), @ApiResponse( code = 406, message = "CSAR upload rejected - given ID already in use", response = Void.class ), @ApiResponse( code = 500, message = "The server encountered a unexpected problem", response = Void.class ) }) @RequestMapping( path = "/{name}", method = {RequestMethod.PUT, RequestMethod.POST}, produces = "application/hal+json" ) ResponseEntity<Void> uploadCSAR(
@ApiParam(value = "The unique identifier for the CSAR", required = true)
@PathVariable(name = "name") String name,
@ApiParam(value = "The CSAR Archive (Compressed as ZIP)", required = true)
@RequestParam(name = "file", required = true) MultipartFile file
// HttpServletRequest request
); @ApiOperation( value = "Deletes a Existing CSAR", notes = "Deletes the Resulting CSAR and its transformations (if none of them is running). " + "If a transformation is running (in the state TRANSFORMING) the CSAR cannot be deleted" ) @ApiResponses({ @ApiResponse( code = 200, message = "The deletion of the CSAR was successful", response = Void.class ), @ApiResponse( code = 400, message = "The deletion of the CSAR failed, because there is one or more transformations still running.", response = RestErrorResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given name (identifier)", response = RestErrorResponse.class ) }) @RequestMapping( path = "/{name}/delete", method = {RequestMethod.DELETE}, produces = "application/hal+json" ) ResponseEntity<Void> deleteCsar(
@ApiParam(value = "The unique identifier for the CSAR", required = true, example = "my-csar-name")
@PathVariable("name") String name
); @RequestMapping( path = "/{name}/logs", method = RequestMethod.GET, produces = "application/hal+json" ) @ApiOperation( value = "Get the logs of a csar", tags = {"csars"}, notes = "Returns the logs for a csar, starting at a specific position. from the given start index all " + "following log lines get returned. If the start index is larger than the current last log index the operation " + "will return a empty list." ) @ApiResponses({ @ApiResponse( code = 200, message = "The operation was executed successfully", response = LogResponse.class ), @ApiResponse( code = 400, message = "The given start value is less than zero", response = RestErrorResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given identifier", response = RestErrorResponse.class ) }) ResponseEntity<LogResponse> getLogs(
@ApiParam(value = "The unique identifier for the CSAR", required = true, example = "test")
@PathVariable(name = "name") String csarId,
@ApiParam(value = "The index of the first log entry you want (0 returns the whole log)", required = true, example = "0")
@RequestParam(name = "start", required = false, defaultValue = "0") Long start
); } |
@Test public void testBuilderWithMarkdownString() { logger.info("Initilaizing Readme Builder"); ReadmeBuilder builder = new ReadmeBuilder("# Hello World", "Hello"); logger.info("Rendering"); String result = builder.toString(); logger.info("Rendered: {}", result); assertTrue(result.contains("<h1>Hello World</h1>")); assertTrue(result.contains("<title>Hello</title>")); } | @Override public String toString() { Parser markdownParser = Parser.builder().build(); Node markdownDocument = markdownParser.parse(this.markdownText); HtmlRenderer renderer = HtmlRenderer.builder().build(); return TEMPLATE.replace(README_TEMPLATE_TITLE_KEY, this.pageTitle) .replace(README_TEMPLATE_BODY_KEY, renderer.render(markdownDocument)); } | ReadmeBuilder { @Override public String toString() { Parser markdownParser = Parser.builder().build(); Node markdownDocument = markdownParser.parse(this.markdownText); HtmlRenderer renderer = HtmlRenderer.builder().build(); return TEMPLATE.replace(README_TEMPLATE_TITLE_KEY, this.pageTitle) .replace(README_TEMPLATE_BODY_KEY, renderer.render(markdownDocument)); } } | ReadmeBuilder { @Override public String toString() { Parser markdownParser = Parser.builder().build(); Node markdownDocument = markdownParser.parse(this.markdownText); HtmlRenderer renderer = HtmlRenderer.builder().build(); return TEMPLATE.replace(README_TEMPLATE_TITLE_KEY, this.pageTitle) .replace(README_TEMPLATE_BODY_KEY, renderer.render(markdownDocument)); } ReadmeBuilder(String markdownText, String pageTitle); } | ReadmeBuilder { @Override public String toString() { Parser markdownParser = Parser.builder().build(); Node markdownDocument = markdownParser.parse(this.markdownText); HtmlRenderer renderer = HtmlRenderer.builder().build(); return TEMPLATE.replace(README_TEMPLATE_TITLE_KEY, this.pageTitle) .replace(README_TEMPLATE_BODY_KEY, renderer.render(markdownDocument)); } ReadmeBuilder(String markdownText, String pageTitle); static ReadmeBuilder fromMarkdownResource(String title, String path, TransformationContext context); @Override String toString(); } | ReadmeBuilder { @Override public String toString() { Parser markdownParser = Parser.builder().build(); Node markdownDocument = markdownParser.parse(this.markdownText); HtmlRenderer renderer = HtmlRenderer.builder().build(); return TEMPLATE.replace(README_TEMPLATE_TITLE_KEY, this.pageTitle) .replace(README_TEMPLATE_BODY_KEY, renderer.render(markdownDocument)); } ReadmeBuilder(String markdownText, String pageTitle); static ReadmeBuilder fromMarkdownResource(String title, String path, TransformationContext context); @Override String toString(); } |
@Test(expected = ValidationFailureException.class) public void modelCheckTest() throws Exception { EffectiveModel singleComputeModel = new EffectiveModelFactory().create(TestCsars.VALID_SINGLE_COMPUTE_WINDOWS_TEMPLATE, logMock()); TransformationContext context = setUpMockTransformationContext(singleComputeModel); KubernetesLifecycle lifecycle = plugin.getInstance(context); plugin.transform(lifecycle); } | @Override public KubernetesLifecycle getInstance(TransformationContext context) throws Exception { return new KubernetesLifecycle(context, mapper); } | KubernetesPlugin extends ToscanaPlugin<KubernetesLifecycle> { @Override public KubernetesLifecycle getInstance(TransformationContext context) throws Exception { return new KubernetesLifecycle(context, mapper); } } | KubernetesPlugin extends ToscanaPlugin<KubernetesLifecycle> { @Override public KubernetesLifecycle getInstance(TransformationContext context) throws Exception { return new KubernetesLifecycle(context, mapper); } @Autowired KubernetesPlugin(BaseImageMapper mapper); } | KubernetesPlugin extends ToscanaPlugin<KubernetesLifecycle> { @Override public KubernetesLifecycle getInstance(TransformationContext context) throws Exception { return new KubernetesLifecycle(context, mapper); } @Autowired KubernetesPlugin(BaseImageMapper mapper); @Override KubernetesLifecycle getInstance(TransformationContext context); } | KubernetesPlugin extends ToscanaPlugin<KubernetesLifecycle> { @Override public KubernetesLifecycle getInstance(TransformationContext context) throws Exception { return new KubernetesLifecycle(context, mapper); } @Autowired KubernetesPlugin(BaseImageMapper mapper); @Override KubernetesLifecycle getInstance(TransformationContext context); static final String DOCKER_PUSH_TO_REGISTRY_PROPERTY_KEY; static final String DOCKER_REGISTRY_URL_PROPERTY_KEY; static final String DOCKER_REGISTRY_USERNAME_PROPERTY_KEY; static final String DOCKER_REGISTRY_PASSWORD_PROPERTY_KEY; static final String DOCKER_REGISTRY_REPOSITORY_PROPERTY_KEY; } |
@Test public void validate() { Optional<String> result = SudoUtils.getSudoInstallCommand(input); if (expected == null) { assertTrue(!result.isPresent()); return; } String r = result.get(); assertEquals(r, expected); } | public static Optional<String> getSudoInstallCommand(String baseImage) { String imageName = baseImage.split(":")[0]; return Optional.ofNullable(IMAGE_MAP.get(imageName)); } | SudoUtils { public static Optional<String> getSudoInstallCommand(String baseImage) { String imageName = baseImage.split(":")[0]; return Optional.ofNullable(IMAGE_MAP.get(imageName)); } } | SudoUtils { public static Optional<String> getSudoInstallCommand(String baseImage) { String imageName = baseImage.split(":")[0]; return Optional.ofNullable(IMAGE_MAP.get(imageName)); } } | SudoUtils { public static Optional<String> getSudoInstallCommand(String baseImage) { String imageName = baseImage.split(":")[0]; return Optional.ofNullable(IMAGE_MAP.get(imageName)); } static Optional<String> getSudoInstallCommand(String baseImage); } | SudoUtils { public static Optional<String> getSudoInstallCommand(String baseImage) { String imageName = baseImage.split(":")[0]; return Optional.ofNullable(IMAGE_MAP.get(imageName)); } static Optional<String> getSudoInstallCommand(String baseImage); } |
@Test public void testReplicationControllerCreation() { ResourceFileCreator resourceFileCreator = new ResourceFileCreator(Pod.getPods(TestNodeStacks.getLampNodeStacks(logMock()))); HashMap<String, String> result = null; try { result = resourceFileCreator.getResourceYaml(); } catch (JsonProcessingException e) { e.printStackTrace(); fail(); } String service = result.get(appServiceName); String deployment = result.get(appDeploymentName); Yaml yaml = new Yaml(); deploymentTest((Map) yaml.load(deployment)); } | public HashMap<String, String> getResourceYaml() throws JsonProcessingException { HashMap<String, String> result = new HashMap<>(); for (IKubernetesResource<?> resource : resources) { result.put(resource.getName(), resource.toYaml()); } return result; } | ResourceFileCreator { public HashMap<String, String> getResourceYaml() throws JsonProcessingException { HashMap<String, String> result = new HashMap<>(); for (IKubernetesResource<?> resource : resources) { result.put(resource.getName(), resource.toYaml()); } return result; } } | ResourceFileCreator { public HashMap<String, String> getResourceYaml() throws JsonProcessingException { HashMap<String, String> result = new HashMap<>(); for (IKubernetesResource<?> resource : resources) { result.put(resource.getName(), resource.toYaml()); } return result; } ResourceFileCreator(Collection<Pod> pods); } | ResourceFileCreator { public HashMap<String, String> getResourceYaml() throws JsonProcessingException { HashMap<String, String> result = new HashMap<>(); for (IKubernetesResource<?> resource : resources) { result.put(resource.getName(), resource.toYaml()); } return result; } ResourceFileCreator(Collection<Pod> pods); HashMap<String, String> getResourceYaml(); } | ResourceFileCreator { public HashMap<String, String> getResourceYaml() throws JsonProcessingException { HashMap<String, String> result = new HashMap<>(); for (IKubernetesResource<?> resource : resources) { result.put(resource.getName(), resource.toYaml()); } return result; } ResourceFileCreator(Collection<Pod> pods); HashMap<String, String> getResourceYaml(); } |
@Test public void testNoneSet() { assertFalse(anythingSet(new OsCapability(entity))); } | public static boolean anythingSet(OsCapability capability) { Optional[] optionals = { capability.getDistribution(), capability.getArchitecture(), capability.getType(), capability.getVersion() }; return Arrays.stream(optionals).anyMatch(Optional::isPresent); } | MapperUtils { public static boolean anythingSet(OsCapability capability) { Optional[] optionals = { capability.getDistribution(), capability.getArchitecture(), capability.getType(), capability.getVersion() }; return Arrays.stream(optionals).anyMatch(Optional::isPresent); } } | MapperUtils { public static boolean anythingSet(OsCapability capability) { Optional[] optionals = { capability.getDistribution(), capability.getArchitecture(), capability.getType(), capability.getVersion() }; return Arrays.stream(optionals).anyMatch(Optional::isPresent); } } | MapperUtils { public static boolean anythingSet(OsCapability capability) { Optional[] optionals = { capability.getDistribution(), capability.getArchitecture(), capability.getType(), capability.getVersion() }; return Arrays.stream(optionals).anyMatch(Optional::isPresent); } static boolean anythingSet(OsCapability capability); } | MapperUtils { public static boolean anythingSet(OsCapability capability) { Optional[] optionals = { capability.getDistribution(), capability.getArchitecture(), capability.getType(), capability.getVersion() }; return Arrays.stream(optionals).anyMatch(Optional::isPresent); } static boolean anythingSet(OsCapability capability); static final Comparator<DockerImageTag> TAG_COMPARATOR_MINOR_VERSION; } |
@Test public void testOneSet() { assertTrue(anythingSet(new OsCapability(entity).setType(Type.LINUX))); } | public static boolean anythingSet(OsCapability capability) { Optional[] optionals = { capability.getDistribution(), capability.getArchitecture(), capability.getType(), capability.getVersion() }; return Arrays.stream(optionals).anyMatch(Optional::isPresent); } | MapperUtils { public static boolean anythingSet(OsCapability capability) { Optional[] optionals = { capability.getDistribution(), capability.getArchitecture(), capability.getType(), capability.getVersion() }; return Arrays.stream(optionals).anyMatch(Optional::isPresent); } } | MapperUtils { public static boolean anythingSet(OsCapability capability) { Optional[] optionals = { capability.getDistribution(), capability.getArchitecture(), capability.getType(), capability.getVersion() }; return Arrays.stream(optionals).anyMatch(Optional::isPresent); } } | MapperUtils { public static boolean anythingSet(OsCapability capability) { Optional[] optionals = { capability.getDistribution(), capability.getArchitecture(), capability.getType(), capability.getVersion() }; return Arrays.stream(optionals).anyMatch(Optional::isPresent); } static boolean anythingSet(OsCapability capability); } | MapperUtils { public static boolean anythingSet(OsCapability capability) { Optional[] optionals = { capability.getDistribution(), capability.getArchitecture(), capability.getType(), capability.getVersion() }; return Arrays.stream(optionals).anyMatch(Optional::isPresent); } static boolean anythingSet(OsCapability capability); static final Comparator<DockerImageTag> TAG_COMPARATOR_MINOR_VERSION; } |
@Test public void testMapOsCapabilityToImageId() throws ParseException { try { String imageId = capabilityMapper.mapOsCapabilityToImageId(osCapability); Assert.assertThat(imageId, CoreMatchers.containsString("ami-")); } catch (SdkClientException se) { logger.info("Probably no internet connection / credentials, omitting test"); } } | public String mapOsCapabilityToImageId(OsCapability osCapability) throws SdkClientException, ParseException, IllegalArgumentException { AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withRegion(awsRegion) .build(); DescribeImagesRequest describeImagesRequest = new DescribeImagesRequest() .withFilters( new Filter("virtualization-type").withValues("hvm"), new Filter("root-device-type").withValues("ebs")) .withOwners("099720109477"); if (osCapability.getType().isPresent() && osCapability.getType().get().equals(OsCapability.Type.WINDOWS)) { describeImagesRequest.withFilters(new Filter("platform").withValues("windows")); } if (osCapability.getDistribution().isPresent()) { if (osCapability.getDistribution().get().equals(OsCapability.Distribution.UBUNTU)) { describeImagesRequest.withFilters(new Filter("name").withValues("*ubuntu/images/*")); } else { describeImagesRequest.withFilters(new Filter("name").withValues("*" + osCapability.getDistribution() .toString() + "*")); } } if (osCapability.getVersion().isPresent()) { describeImagesRequest.withFilters(new Filter("name").withValues("*" + osCapability.getVersion().get() + "*")); } if (osCapability.getArchitecture().isPresent()) { if (osCapability.getArchitecture().get().equals(OsCapability.Architecture.x86_64)) { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_64)); } else if (osCapability.getArchitecture().get().equals(OsCapability.Architecture.x86_32)) { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_32)); } else { throw new UnsupportedOperationException("This architecture is not supported " + osCapability .getArchitecture()); } } else { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_64)); } try { DescribeImagesResult describeImagesResult = ec2.describeImages(describeImagesRequest); String imageId = processResult(describeImagesResult); logger.debug("ImageId is: '{}'", imageId); return imageId; } catch (SdkClientException se) { logger.error("Cannot connect to AWS to request image Ids"); throw se; } catch (ParseException pe) { logger.error("Error parsing date format of image creation dates"); throw pe; } catch (IllegalArgumentException ie) { logger.error("With the filters created from the OsCapability there are no valid images received"); throw ie; } } | CapabilityMapper { public String mapOsCapabilityToImageId(OsCapability osCapability) throws SdkClientException, ParseException, IllegalArgumentException { AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withRegion(awsRegion) .build(); DescribeImagesRequest describeImagesRequest = new DescribeImagesRequest() .withFilters( new Filter("virtualization-type").withValues("hvm"), new Filter("root-device-type").withValues("ebs")) .withOwners("099720109477"); if (osCapability.getType().isPresent() && osCapability.getType().get().equals(OsCapability.Type.WINDOWS)) { describeImagesRequest.withFilters(new Filter("platform").withValues("windows")); } if (osCapability.getDistribution().isPresent()) { if (osCapability.getDistribution().get().equals(OsCapability.Distribution.UBUNTU)) { describeImagesRequest.withFilters(new Filter("name").withValues("*ubuntu/images/*")); } else { describeImagesRequest.withFilters(new Filter("name").withValues("*" + osCapability.getDistribution() .toString() + "*")); } } if (osCapability.getVersion().isPresent()) { describeImagesRequest.withFilters(new Filter("name").withValues("*" + osCapability.getVersion().get() + "*")); } if (osCapability.getArchitecture().isPresent()) { if (osCapability.getArchitecture().get().equals(OsCapability.Architecture.x86_64)) { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_64)); } else if (osCapability.getArchitecture().get().equals(OsCapability.Architecture.x86_32)) { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_32)); } else { throw new UnsupportedOperationException("This architecture is not supported " + osCapability .getArchitecture()); } } else { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_64)); } try { DescribeImagesResult describeImagesResult = ec2.describeImages(describeImagesRequest); String imageId = processResult(describeImagesResult); logger.debug("ImageId is: '{}'", imageId); return imageId; } catch (SdkClientException se) { logger.error("Cannot connect to AWS to request image Ids"); throw se; } catch (ParseException pe) { logger.error("Error parsing date format of image creation dates"); throw pe; } catch (IllegalArgumentException ie) { logger.error("With the filters created from the OsCapability there are no valid images received"); throw ie; } } } | CapabilityMapper { public String mapOsCapabilityToImageId(OsCapability osCapability) throws SdkClientException, ParseException, IllegalArgumentException { AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withRegion(awsRegion) .build(); DescribeImagesRequest describeImagesRequest = new DescribeImagesRequest() .withFilters( new Filter("virtualization-type").withValues("hvm"), new Filter("root-device-type").withValues("ebs")) .withOwners("099720109477"); if (osCapability.getType().isPresent() && osCapability.getType().get().equals(OsCapability.Type.WINDOWS)) { describeImagesRequest.withFilters(new Filter("platform").withValues("windows")); } if (osCapability.getDistribution().isPresent()) { if (osCapability.getDistribution().get().equals(OsCapability.Distribution.UBUNTU)) { describeImagesRequest.withFilters(new Filter("name").withValues("*ubuntu/images/*")); } else { describeImagesRequest.withFilters(new Filter("name").withValues("*" + osCapability.getDistribution() .toString() + "*")); } } if (osCapability.getVersion().isPresent()) { describeImagesRequest.withFilters(new Filter("name").withValues("*" + osCapability.getVersion().get() + "*")); } if (osCapability.getArchitecture().isPresent()) { if (osCapability.getArchitecture().get().equals(OsCapability.Architecture.x86_64)) { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_64)); } else if (osCapability.getArchitecture().get().equals(OsCapability.Architecture.x86_32)) { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_32)); } else { throw new UnsupportedOperationException("This architecture is not supported " + osCapability .getArchitecture()); } } else { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_64)); } try { DescribeImagesResult describeImagesResult = ec2.describeImages(describeImagesRequest); String imageId = processResult(describeImagesResult); logger.debug("ImageId is: '{}'", imageId); return imageId; } catch (SdkClientException se) { logger.error("Cannot connect to AWS to request image Ids"); throw se; } catch (ParseException pe) { logger.error("Error parsing date format of image creation dates"); throw pe; } catch (IllegalArgumentException ie) { logger.error("With the filters created from the OsCapability there are no valid images received"); throw ie; } } CapabilityMapper(String awsRegion, AWSCredentials awsCredentials, Logger logger); } | CapabilityMapper { public String mapOsCapabilityToImageId(OsCapability osCapability) throws SdkClientException, ParseException, IllegalArgumentException { AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withRegion(awsRegion) .build(); DescribeImagesRequest describeImagesRequest = new DescribeImagesRequest() .withFilters( new Filter("virtualization-type").withValues("hvm"), new Filter("root-device-type").withValues("ebs")) .withOwners("099720109477"); if (osCapability.getType().isPresent() && osCapability.getType().get().equals(OsCapability.Type.WINDOWS)) { describeImagesRequest.withFilters(new Filter("platform").withValues("windows")); } if (osCapability.getDistribution().isPresent()) { if (osCapability.getDistribution().get().equals(OsCapability.Distribution.UBUNTU)) { describeImagesRequest.withFilters(new Filter("name").withValues("*ubuntu/images/*")); } else { describeImagesRequest.withFilters(new Filter("name").withValues("*" + osCapability.getDistribution() .toString() + "*")); } } if (osCapability.getVersion().isPresent()) { describeImagesRequest.withFilters(new Filter("name").withValues("*" + osCapability.getVersion().get() + "*")); } if (osCapability.getArchitecture().isPresent()) { if (osCapability.getArchitecture().get().equals(OsCapability.Architecture.x86_64)) { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_64)); } else if (osCapability.getArchitecture().get().equals(OsCapability.Architecture.x86_32)) { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_32)); } else { throw new UnsupportedOperationException("This architecture is not supported " + osCapability .getArchitecture()); } } else { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_64)); } try { DescribeImagesResult describeImagesResult = ec2.describeImages(describeImagesRequest); String imageId = processResult(describeImagesResult); logger.debug("ImageId is: '{}'", imageId); return imageId; } catch (SdkClientException se) { logger.error("Cannot connect to AWS to request image Ids"); throw se; } catch (ParseException pe) { logger.error("Error parsing date format of image creation dates"); throw pe; } catch (IllegalArgumentException ie) { logger.error("With the filters created from the OsCapability there are no valid images received"); throw ie; } } CapabilityMapper(String awsRegion, AWSCredentials awsCredentials, Logger logger); String mapOsCapabilityToImageId(OsCapability osCapability); String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction); Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability); void mapDiskSize(ComputeCapability computeCapability, CloudFormationModule cfnModule, String nodeName); } | CapabilityMapper { public String mapOsCapabilityToImageId(OsCapability osCapability) throws SdkClientException, ParseException, IllegalArgumentException { AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .withRegion(awsRegion) .build(); DescribeImagesRequest describeImagesRequest = new DescribeImagesRequest() .withFilters( new Filter("virtualization-type").withValues("hvm"), new Filter("root-device-type").withValues("ebs")) .withOwners("099720109477"); if (osCapability.getType().isPresent() && osCapability.getType().get().equals(OsCapability.Type.WINDOWS)) { describeImagesRequest.withFilters(new Filter("platform").withValues("windows")); } if (osCapability.getDistribution().isPresent()) { if (osCapability.getDistribution().get().equals(OsCapability.Distribution.UBUNTU)) { describeImagesRequest.withFilters(new Filter("name").withValues("*ubuntu/images/*")); } else { describeImagesRequest.withFilters(new Filter("name").withValues("*" + osCapability.getDistribution() .toString() + "*")); } } if (osCapability.getVersion().isPresent()) { describeImagesRequest.withFilters(new Filter("name").withValues("*" + osCapability.getVersion().get() + "*")); } if (osCapability.getArchitecture().isPresent()) { if (osCapability.getArchitecture().get().equals(OsCapability.Architecture.x86_64)) { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_64)); } else if (osCapability.getArchitecture().get().equals(OsCapability.Architecture.x86_32)) { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_32)); } else { throw new UnsupportedOperationException("This architecture is not supported " + osCapability .getArchitecture()); } } else { describeImagesRequest.withFilters(new Filter("architecture").withValues(ARCH_x86_64)); } try { DescribeImagesResult describeImagesResult = ec2.describeImages(describeImagesRequest); String imageId = processResult(describeImagesResult); logger.debug("ImageId is: '{}'", imageId); return imageId; } catch (SdkClientException se) { logger.error("Cannot connect to AWS to request image Ids"); throw se; } catch (ParseException pe) { logger.error("Error parsing date format of image creation dates"); throw pe; } catch (IllegalArgumentException ie) { logger.error("With the filters created from the OsCapability there are no valid images received"); throw ie; } } CapabilityMapper(String awsRegion, AWSCredentials awsCredentials, Logger logger); String mapOsCapabilityToImageId(OsCapability osCapability); String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction); Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability); void mapDiskSize(ComputeCapability computeCapability, CloudFormationModule cfnModule, String nodeName); static final String EC2_DISTINCTION; static final String RDS_DISTINCTION; } |
@Test public void testMapComputeCapabilityToInstanceTypeEC2() { String instanceType = capabilityMapper.mapComputeCapabilityToInstanceType(containerCapability, EC2_DISTINCTION); Assert.assertEquals(instanceType, expectedEC2); } | public String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction) throws IllegalArgumentException { Integer numCpus = computeCapability.getNumCpus().orElse(0); Integer memSize = computeCapability.getMemSizeInMb().orElse(0); final ImmutableList<InstanceType> instanceTypes; if (EC2_DISTINCTION.equals(distinction)) { instanceTypes = EC2_INSTANCE_TYPES; } else if (RDS_DISTINCTION.equals(distinction)) { instanceTypes = RDS_INSTANCE_CLASSES; } else { throw new IllegalArgumentException("Distinction not supported: " + distinction); } List<Integer> allNumCpus = instanceTypes.stream() .map(InstanceType::getNumCpus) .sorted() .collect(Collectors.toList()); List<Integer> allMemSizes = instanceTypes.stream() .map(InstanceType::getMemSize) .sorted() .collect(Collectors.toList()); try { logger.debug("Check numCpus: '{}'", numCpus); numCpus = checkValue(numCpus, allNumCpus); logger.debug("Check memSize: '{}'", memSize); memSize = checkValue(memSize, allMemSizes); } catch (IllegalArgumentException ie) { logger.error("Values numCpus: '{}' and/or memSize: are too big. No InstanceType found", numCpus, memSize); throw ie; } String instanceType = findCombination(numCpus, memSize, instanceTypes, allNumCpus, allMemSizes); logger.debug("InstanceType is: '{}'", instanceType); return instanceType; } | CapabilityMapper { public String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction) throws IllegalArgumentException { Integer numCpus = computeCapability.getNumCpus().orElse(0); Integer memSize = computeCapability.getMemSizeInMb().orElse(0); final ImmutableList<InstanceType> instanceTypes; if (EC2_DISTINCTION.equals(distinction)) { instanceTypes = EC2_INSTANCE_TYPES; } else if (RDS_DISTINCTION.equals(distinction)) { instanceTypes = RDS_INSTANCE_CLASSES; } else { throw new IllegalArgumentException("Distinction not supported: " + distinction); } List<Integer> allNumCpus = instanceTypes.stream() .map(InstanceType::getNumCpus) .sorted() .collect(Collectors.toList()); List<Integer> allMemSizes = instanceTypes.stream() .map(InstanceType::getMemSize) .sorted() .collect(Collectors.toList()); try { logger.debug("Check numCpus: '{}'", numCpus); numCpus = checkValue(numCpus, allNumCpus); logger.debug("Check memSize: '{}'", memSize); memSize = checkValue(memSize, allMemSizes); } catch (IllegalArgumentException ie) { logger.error("Values numCpus: '{}' and/or memSize: are too big. No InstanceType found", numCpus, memSize); throw ie; } String instanceType = findCombination(numCpus, memSize, instanceTypes, allNumCpus, allMemSizes); logger.debug("InstanceType is: '{}'", instanceType); return instanceType; } } | CapabilityMapper { public String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction) throws IllegalArgumentException { Integer numCpus = computeCapability.getNumCpus().orElse(0); Integer memSize = computeCapability.getMemSizeInMb().orElse(0); final ImmutableList<InstanceType> instanceTypes; if (EC2_DISTINCTION.equals(distinction)) { instanceTypes = EC2_INSTANCE_TYPES; } else if (RDS_DISTINCTION.equals(distinction)) { instanceTypes = RDS_INSTANCE_CLASSES; } else { throw new IllegalArgumentException("Distinction not supported: " + distinction); } List<Integer> allNumCpus = instanceTypes.stream() .map(InstanceType::getNumCpus) .sorted() .collect(Collectors.toList()); List<Integer> allMemSizes = instanceTypes.stream() .map(InstanceType::getMemSize) .sorted() .collect(Collectors.toList()); try { logger.debug("Check numCpus: '{}'", numCpus); numCpus = checkValue(numCpus, allNumCpus); logger.debug("Check memSize: '{}'", memSize); memSize = checkValue(memSize, allMemSizes); } catch (IllegalArgumentException ie) { logger.error("Values numCpus: '{}' and/or memSize: are too big. No InstanceType found", numCpus, memSize); throw ie; } String instanceType = findCombination(numCpus, memSize, instanceTypes, allNumCpus, allMemSizes); logger.debug("InstanceType is: '{}'", instanceType); return instanceType; } CapabilityMapper(String awsRegion, AWSCredentials awsCredentials, Logger logger); } | CapabilityMapper { public String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction) throws IllegalArgumentException { Integer numCpus = computeCapability.getNumCpus().orElse(0); Integer memSize = computeCapability.getMemSizeInMb().orElse(0); final ImmutableList<InstanceType> instanceTypes; if (EC2_DISTINCTION.equals(distinction)) { instanceTypes = EC2_INSTANCE_TYPES; } else if (RDS_DISTINCTION.equals(distinction)) { instanceTypes = RDS_INSTANCE_CLASSES; } else { throw new IllegalArgumentException("Distinction not supported: " + distinction); } List<Integer> allNumCpus = instanceTypes.stream() .map(InstanceType::getNumCpus) .sorted() .collect(Collectors.toList()); List<Integer> allMemSizes = instanceTypes.stream() .map(InstanceType::getMemSize) .sorted() .collect(Collectors.toList()); try { logger.debug("Check numCpus: '{}'", numCpus); numCpus = checkValue(numCpus, allNumCpus); logger.debug("Check memSize: '{}'", memSize); memSize = checkValue(memSize, allMemSizes); } catch (IllegalArgumentException ie) { logger.error("Values numCpus: '{}' and/or memSize: are too big. No InstanceType found", numCpus, memSize); throw ie; } String instanceType = findCombination(numCpus, memSize, instanceTypes, allNumCpus, allMemSizes); logger.debug("InstanceType is: '{}'", instanceType); return instanceType; } CapabilityMapper(String awsRegion, AWSCredentials awsCredentials, Logger logger); String mapOsCapabilityToImageId(OsCapability osCapability); String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction); Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability); void mapDiskSize(ComputeCapability computeCapability, CloudFormationModule cfnModule, String nodeName); } | CapabilityMapper { public String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction) throws IllegalArgumentException { Integer numCpus = computeCapability.getNumCpus().orElse(0); Integer memSize = computeCapability.getMemSizeInMb().orElse(0); final ImmutableList<InstanceType> instanceTypes; if (EC2_DISTINCTION.equals(distinction)) { instanceTypes = EC2_INSTANCE_TYPES; } else if (RDS_DISTINCTION.equals(distinction)) { instanceTypes = RDS_INSTANCE_CLASSES; } else { throw new IllegalArgumentException("Distinction not supported: " + distinction); } List<Integer> allNumCpus = instanceTypes.stream() .map(InstanceType::getNumCpus) .sorted() .collect(Collectors.toList()); List<Integer> allMemSizes = instanceTypes.stream() .map(InstanceType::getMemSize) .sorted() .collect(Collectors.toList()); try { logger.debug("Check numCpus: '{}'", numCpus); numCpus = checkValue(numCpus, allNumCpus); logger.debug("Check memSize: '{}'", memSize); memSize = checkValue(memSize, allMemSizes); } catch (IllegalArgumentException ie) { logger.error("Values numCpus: '{}' and/or memSize: are too big. No InstanceType found", numCpus, memSize); throw ie; } String instanceType = findCombination(numCpus, memSize, instanceTypes, allNumCpus, allMemSizes); logger.debug("InstanceType is: '{}'", instanceType); return instanceType; } CapabilityMapper(String awsRegion, AWSCredentials awsCredentials, Logger logger); String mapOsCapabilityToImageId(OsCapability osCapability); String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction); Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability); void mapDiskSize(ComputeCapability computeCapability, CloudFormationModule cfnModule, String nodeName); static final String EC2_DISTINCTION; static final String RDS_DISTINCTION; } |
@Test public void testMapComputeCapabilityToInstanceTypeRDS() { String instanceType = capabilityMapper.mapComputeCapabilityToInstanceType(containerCapability, RDS_DISTINCTION); Assert.assertEquals(instanceType, expectedRDS); } | public String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction) throws IllegalArgumentException { Integer numCpus = computeCapability.getNumCpus().orElse(0); Integer memSize = computeCapability.getMemSizeInMb().orElse(0); final ImmutableList<InstanceType> instanceTypes; if (EC2_DISTINCTION.equals(distinction)) { instanceTypes = EC2_INSTANCE_TYPES; } else if (RDS_DISTINCTION.equals(distinction)) { instanceTypes = RDS_INSTANCE_CLASSES; } else { throw new IllegalArgumentException("Distinction not supported: " + distinction); } List<Integer> allNumCpus = instanceTypes.stream() .map(InstanceType::getNumCpus) .sorted() .collect(Collectors.toList()); List<Integer> allMemSizes = instanceTypes.stream() .map(InstanceType::getMemSize) .sorted() .collect(Collectors.toList()); try { logger.debug("Check numCpus: '{}'", numCpus); numCpus = checkValue(numCpus, allNumCpus); logger.debug("Check memSize: '{}'", memSize); memSize = checkValue(memSize, allMemSizes); } catch (IllegalArgumentException ie) { logger.error("Values numCpus: '{}' and/or memSize: are too big. No InstanceType found", numCpus, memSize); throw ie; } String instanceType = findCombination(numCpus, memSize, instanceTypes, allNumCpus, allMemSizes); logger.debug("InstanceType is: '{}'", instanceType); return instanceType; } | CapabilityMapper { public String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction) throws IllegalArgumentException { Integer numCpus = computeCapability.getNumCpus().orElse(0); Integer memSize = computeCapability.getMemSizeInMb().orElse(0); final ImmutableList<InstanceType> instanceTypes; if (EC2_DISTINCTION.equals(distinction)) { instanceTypes = EC2_INSTANCE_TYPES; } else if (RDS_DISTINCTION.equals(distinction)) { instanceTypes = RDS_INSTANCE_CLASSES; } else { throw new IllegalArgumentException("Distinction not supported: " + distinction); } List<Integer> allNumCpus = instanceTypes.stream() .map(InstanceType::getNumCpus) .sorted() .collect(Collectors.toList()); List<Integer> allMemSizes = instanceTypes.stream() .map(InstanceType::getMemSize) .sorted() .collect(Collectors.toList()); try { logger.debug("Check numCpus: '{}'", numCpus); numCpus = checkValue(numCpus, allNumCpus); logger.debug("Check memSize: '{}'", memSize); memSize = checkValue(memSize, allMemSizes); } catch (IllegalArgumentException ie) { logger.error("Values numCpus: '{}' and/or memSize: are too big. No InstanceType found", numCpus, memSize); throw ie; } String instanceType = findCombination(numCpus, memSize, instanceTypes, allNumCpus, allMemSizes); logger.debug("InstanceType is: '{}'", instanceType); return instanceType; } } | CapabilityMapper { public String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction) throws IllegalArgumentException { Integer numCpus = computeCapability.getNumCpus().orElse(0); Integer memSize = computeCapability.getMemSizeInMb().orElse(0); final ImmutableList<InstanceType> instanceTypes; if (EC2_DISTINCTION.equals(distinction)) { instanceTypes = EC2_INSTANCE_TYPES; } else if (RDS_DISTINCTION.equals(distinction)) { instanceTypes = RDS_INSTANCE_CLASSES; } else { throw new IllegalArgumentException("Distinction not supported: " + distinction); } List<Integer> allNumCpus = instanceTypes.stream() .map(InstanceType::getNumCpus) .sorted() .collect(Collectors.toList()); List<Integer> allMemSizes = instanceTypes.stream() .map(InstanceType::getMemSize) .sorted() .collect(Collectors.toList()); try { logger.debug("Check numCpus: '{}'", numCpus); numCpus = checkValue(numCpus, allNumCpus); logger.debug("Check memSize: '{}'", memSize); memSize = checkValue(memSize, allMemSizes); } catch (IllegalArgumentException ie) { logger.error("Values numCpus: '{}' and/or memSize: are too big. No InstanceType found", numCpus, memSize); throw ie; } String instanceType = findCombination(numCpus, memSize, instanceTypes, allNumCpus, allMemSizes); logger.debug("InstanceType is: '{}'", instanceType); return instanceType; } CapabilityMapper(String awsRegion, AWSCredentials awsCredentials, Logger logger); } | CapabilityMapper { public String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction) throws IllegalArgumentException { Integer numCpus = computeCapability.getNumCpus().orElse(0); Integer memSize = computeCapability.getMemSizeInMb().orElse(0); final ImmutableList<InstanceType> instanceTypes; if (EC2_DISTINCTION.equals(distinction)) { instanceTypes = EC2_INSTANCE_TYPES; } else if (RDS_DISTINCTION.equals(distinction)) { instanceTypes = RDS_INSTANCE_CLASSES; } else { throw new IllegalArgumentException("Distinction not supported: " + distinction); } List<Integer> allNumCpus = instanceTypes.stream() .map(InstanceType::getNumCpus) .sorted() .collect(Collectors.toList()); List<Integer> allMemSizes = instanceTypes.stream() .map(InstanceType::getMemSize) .sorted() .collect(Collectors.toList()); try { logger.debug("Check numCpus: '{}'", numCpus); numCpus = checkValue(numCpus, allNumCpus); logger.debug("Check memSize: '{}'", memSize); memSize = checkValue(memSize, allMemSizes); } catch (IllegalArgumentException ie) { logger.error("Values numCpus: '{}' and/or memSize: are too big. No InstanceType found", numCpus, memSize); throw ie; } String instanceType = findCombination(numCpus, memSize, instanceTypes, allNumCpus, allMemSizes); logger.debug("InstanceType is: '{}'", instanceType); return instanceType; } CapabilityMapper(String awsRegion, AWSCredentials awsCredentials, Logger logger); String mapOsCapabilityToImageId(OsCapability osCapability); String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction); Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability); void mapDiskSize(ComputeCapability computeCapability, CloudFormationModule cfnModule, String nodeName); } | CapabilityMapper { public String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction) throws IllegalArgumentException { Integer numCpus = computeCapability.getNumCpus().orElse(0); Integer memSize = computeCapability.getMemSizeInMb().orElse(0); final ImmutableList<InstanceType> instanceTypes; if (EC2_DISTINCTION.equals(distinction)) { instanceTypes = EC2_INSTANCE_TYPES; } else if (RDS_DISTINCTION.equals(distinction)) { instanceTypes = RDS_INSTANCE_CLASSES; } else { throw new IllegalArgumentException("Distinction not supported: " + distinction); } List<Integer> allNumCpus = instanceTypes.stream() .map(InstanceType::getNumCpus) .sorted() .collect(Collectors.toList()); List<Integer> allMemSizes = instanceTypes.stream() .map(InstanceType::getMemSize) .sorted() .collect(Collectors.toList()); try { logger.debug("Check numCpus: '{}'", numCpus); numCpus = checkValue(numCpus, allNumCpus); logger.debug("Check memSize: '{}'", memSize); memSize = checkValue(memSize, allMemSizes); } catch (IllegalArgumentException ie) { logger.error("Values numCpus: '{}' and/or memSize: are too big. No InstanceType found", numCpus, memSize); throw ie; } String instanceType = findCombination(numCpus, memSize, instanceTypes, allNumCpus, allMemSizes); logger.debug("InstanceType is: '{}'", instanceType); return instanceType; } CapabilityMapper(String awsRegion, AWSCredentials awsCredentials, Logger logger); String mapOsCapabilityToImageId(OsCapability osCapability); String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction); Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability); void mapDiskSize(ComputeCapability computeCapability, CloudFormationModule cfnModule, String nodeName); static final String EC2_DISTINCTION; static final String RDS_DISTINCTION; } |
@Test public void testMapComputeCapabilityToRDSAllocatedStorage() { int newDiskSize = capabilityMapper.mapComputeCapabilityToRDSAllocatedStorage(containerCapability); Assert.assertEquals(newDiskSize, expectedDiskSize); } | public Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability) { final Integer minSize = 20; final Integer maxSize = 6144; Integer diskSize = computeCapability.getDiskSizeInMb().orElse(minSize * 1000); diskSize = diskSize / 1000; if (diskSize > maxSize) { logger.debug("Disk size: '{}'", maxSize); return maxSize; } if (diskSize < minSize) { logger.debug("Disk size: '{}'", minSize); return minSize; } logger.debug("Disk size: '{}'", diskSize); return diskSize; } | CapabilityMapper { public Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability) { final Integer minSize = 20; final Integer maxSize = 6144; Integer diskSize = computeCapability.getDiskSizeInMb().orElse(minSize * 1000); diskSize = diskSize / 1000; if (diskSize > maxSize) { logger.debug("Disk size: '{}'", maxSize); return maxSize; } if (diskSize < minSize) { logger.debug("Disk size: '{}'", minSize); return minSize; } logger.debug("Disk size: '{}'", diskSize); return diskSize; } } | CapabilityMapper { public Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability) { final Integer minSize = 20; final Integer maxSize = 6144; Integer diskSize = computeCapability.getDiskSizeInMb().orElse(minSize * 1000); diskSize = diskSize / 1000; if (diskSize > maxSize) { logger.debug("Disk size: '{}'", maxSize); return maxSize; } if (diskSize < minSize) { logger.debug("Disk size: '{}'", minSize); return minSize; } logger.debug("Disk size: '{}'", diskSize); return diskSize; } CapabilityMapper(String awsRegion, AWSCredentials awsCredentials, Logger logger); } | CapabilityMapper { public Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability) { final Integer minSize = 20; final Integer maxSize = 6144; Integer diskSize = computeCapability.getDiskSizeInMb().orElse(minSize * 1000); diskSize = diskSize / 1000; if (diskSize > maxSize) { logger.debug("Disk size: '{}'", maxSize); return maxSize; } if (diskSize < minSize) { logger.debug("Disk size: '{}'", minSize); return minSize; } logger.debug("Disk size: '{}'", diskSize); return diskSize; } CapabilityMapper(String awsRegion, AWSCredentials awsCredentials, Logger logger); String mapOsCapabilityToImageId(OsCapability osCapability); String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction); Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability); void mapDiskSize(ComputeCapability computeCapability, CloudFormationModule cfnModule, String nodeName); } | CapabilityMapper { public Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability) { final Integer minSize = 20; final Integer maxSize = 6144; Integer diskSize = computeCapability.getDiskSizeInMb().orElse(minSize * 1000); diskSize = diskSize / 1000; if (diskSize > maxSize) { logger.debug("Disk size: '{}'", maxSize); return maxSize; } if (diskSize < minSize) { logger.debug("Disk size: '{}'", minSize); return minSize; } logger.debug("Disk size: '{}'", diskSize); return diskSize; } CapabilityMapper(String awsRegion, AWSCredentials awsCredentials, Logger logger); String mapOsCapabilityToImageId(OsCapability osCapability); String mapComputeCapabilityToInstanceType(ComputeCapability computeCapability, String distinction); Integer mapComputeCapabilityToRDSAllocatedStorage(ComputeCapability computeCapability); void mapDiskSize(ComputeCapability computeCapability, CloudFormationModule cfnModule, String nodeName); static final String EC2_DISTINCTION; static final String RDS_DISTINCTION; } |
@Test public void testDelete() throws Exception { final boolean[] executed = new boolean[]{false}; doAnswer(iom -> executed[0] = true).when(service).deleteCsar(any(Csar.class)); mvc.perform( delete(DELETE_VALID_CSAR_URL).accept(ACCEPTED_MIME_TYPE) ).andDo(print()) .andExpect(status().is(200)) .andExpect(content().bytes(new byte[0])); assertTrue("csarService.delete() did not get called!", executed[0]); } | @ApiOperation( value = "Deletes a Existing CSAR", notes = "Deletes the Resulting CSAR and its transformations (if none of them is running). " + "If a transformation is running (in the state TRANSFORMING) the CSAR cannot be deleted" ) @ApiResponses({ @ApiResponse( code = 200, message = "The deletion of the CSAR was successful", response = Void.class ), @ApiResponse( code = 400, message = "The deletion of the CSAR failed, because there is one or more transformations still running.", response = RestErrorResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given name (identifier)", response = RestErrorResponse.class ) }) @RequestMapping( path = "/{name}/delete", method = {RequestMethod.DELETE}, produces = "application/hal+json" ) public ResponseEntity<Void> deleteCsar( @ApiParam(value = "The unique identifier for the CSAR", required = true, example = "my-csar-name") @PathVariable("name") String name ) { Csar csar = getCsarForName(name); csar.getTransformations().forEach((k, v) -> { if (v.getState() == TransformationState.TRANSFORMING) { throw new ActiveTransformationsException( String.format( "Transformation %s/%s is still running. Cannot delete csar while a transformation is running!", name, k ) ); } }); csarService.deleteCsar(csar); return ResponseEntity.ok().build(); } | CsarController { @ApiOperation( value = "Deletes a Existing CSAR", notes = "Deletes the Resulting CSAR and its transformations (if none of them is running). " + "If a transformation is running (in the state TRANSFORMING) the CSAR cannot be deleted" ) @ApiResponses({ @ApiResponse( code = 200, message = "The deletion of the CSAR was successful", response = Void.class ), @ApiResponse( code = 400, message = "The deletion of the CSAR failed, because there is one or more transformations still running.", response = RestErrorResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given name (identifier)", response = RestErrorResponse.class ) }) @RequestMapping( path = "/{name}/delete", method = {RequestMethod.DELETE}, produces = "application/hal+json" ) public ResponseEntity<Void> deleteCsar( @ApiParam(value = "The unique identifier for the CSAR", required = true, example = "my-csar-name") @PathVariable("name") String name ) { Csar csar = getCsarForName(name); csar.getTransformations().forEach((k, v) -> { if (v.getState() == TransformationState.TRANSFORMING) { throw new ActiveTransformationsException( String.format( "Transformation %s/%s is still running. Cannot delete csar while a transformation is running!", name, k ) ); } }); csarService.deleteCsar(csar); return ResponseEntity.ok().build(); } } | CsarController { @ApiOperation( value = "Deletes a Existing CSAR", notes = "Deletes the Resulting CSAR and its transformations (if none of them is running). " + "If a transformation is running (in the state TRANSFORMING) the CSAR cannot be deleted" ) @ApiResponses({ @ApiResponse( code = 200, message = "The deletion of the CSAR was successful", response = Void.class ), @ApiResponse( code = 400, message = "The deletion of the CSAR failed, because there is one or more transformations still running.", response = RestErrorResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given name (identifier)", response = RestErrorResponse.class ) }) @RequestMapping( path = "/{name}/delete", method = {RequestMethod.DELETE}, produces = "application/hal+json" ) public ResponseEntity<Void> deleteCsar( @ApiParam(value = "The unique identifier for the CSAR", required = true, example = "my-csar-name") @PathVariable("name") String name ) { Csar csar = getCsarForName(name); csar.getTransformations().forEach((k, v) -> { if (v.getState() == TransformationState.TRANSFORMING) { throw new ActiveTransformationsException( String.format( "Transformation %s/%s is still running. Cannot delete csar while a transformation is running!", name, k ) ); } }); csarService.deleteCsar(csar); return ResponseEntity.ok().build(); } @Autowired CsarController(CsarService csarService); } | CsarController { @ApiOperation( value = "Deletes a Existing CSAR", notes = "Deletes the Resulting CSAR and its transformations (if none of them is running). " + "If a transformation is running (in the state TRANSFORMING) the CSAR cannot be deleted" ) @ApiResponses({ @ApiResponse( code = 200, message = "The deletion of the CSAR was successful", response = Void.class ), @ApiResponse( code = 400, message = "The deletion of the CSAR failed, because there is one or more transformations still running.", response = RestErrorResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given name (identifier)", response = RestErrorResponse.class ) }) @RequestMapping( path = "/{name}/delete", method = {RequestMethod.DELETE}, produces = "application/hal+json" ) public ResponseEntity<Void> deleteCsar( @ApiParam(value = "The unique identifier for the CSAR", required = true, example = "my-csar-name") @PathVariable("name") String name ) { Csar csar = getCsarForName(name); csar.getTransformations().forEach((k, v) -> { if (v.getState() == TransformationState.TRANSFORMING) { throw new ActiveTransformationsException( String.format( "Transformation %s/%s is still running. Cannot delete csar while a transformation is running!", name, k ) ); } }); csarService.deleteCsar(csar); return ResponseEntity.ok().build(); } @Autowired CsarController(CsarService csarService); @ApiOperation( value = "List all CSARs stored on the server", notes = "Returns a Hypermedia Resource containing all CSARs" + " that have been uploaded to the server and did not get removed", response = CsarResources.class, produces = "application/hal+json" ) @RequestMapping( path = "", method = RequestMethod.GET, produces = "application/hal+json" ) ResponseEntity<Resources<CsarResponse>> listCSARs(); @ApiOperation( value = "Returns details for a specific name (identifier)", notes = "Returns the element with the given name, Object contents are " + "equal to a regular /csars request (if you just look at the desired entry)" ) @ApiResponses({ @ApiResponse( code = 200, message = "The Csar was found and the contents are found in the body", response = CsarResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given name (identifier)", response = RestErrorResponse.class ) }) @RequestMapping( path = "/{name}", method = RequestMethod.GET, produces = "application/hal+json" ) ResponseEntity<CsarResponse> getCSARInfo(
@ApiParam(value = "The unique identifier for the CSAR", required = true, example = "test")
@PathVariable(name = "name") String name
); @ApiOperation( value = "Creates a new CSAR", notes = "This operation creates a new CSAR if the name (identifier) is not used already. " + "The uploaded file has to be a valid CSAR archive. " + "Once the file was uploaded the server will synchronously " + "(the client has to wait for the response) unzip the archive and parse it. " + "Upload gets performed using Multipart Form upload.", code = 201 ) @ApiResponses({ @ApiResponse( code = 201, message = "The upload of the csar was successful", response = Void.class ), @ApiResponse( code = 406, message = "CSAR upload rejected - given ID already in use", response = Void.class ), @ApiResponse( code = 500, message = "The server encountered a unexpected problem", response = Void.class ) }) @RequestMapping( path = "/{name}", method = {RequestMethod.PUT, RequestMethod.POST}, produces = "application/hal+json" ) ResponseEntity<Void> uploadCSAR(
@ApiParam(value = "The unique identifier for the CSAR", required = true)
@PathVariable(name = "name") String name,
@ApiParam(value = "The CSAR Archive (Compressed as ZIP)", required = true)
@RequestParam(name = "file", required = true) MultipartFile file
// HttpServletRequest request
); @ApiOperation( value = "Deletes a Existing CSAR", notes = "Deletes the Resulting CSAR and its transformations (if none of them is running). " + "If a transformation is running (in the state TRANSFORMING) the CSAR cannot be deleted" ) @ApiResponses({ @ApiResponse( code = 200, message = "The deletion of the CSAR was successful", response = Void.class ), @ApiResponse( code = 400, message = "The deletion of the CSAR failed, because there is one or more transformations still running.", response = RestErrorResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given name (identifier)", response = RestErrorResponse.class ) }) @RequestMapping( path = "/{name}/delete", method = {RequestMethod.DELETE}, produces = "application/hal+json" ) ResponseEntity<Void> deleteCsar(
@ApiParam(value = "The unique identifier for the CSAR", required = true, example = "my-csar-name")
@PathVariable("name") String name
); @RequestMapping( path = "/{name}/logs", method = RequestMethod.GET, produces = "application/hal+json" ) @ApiOperation( value = "Get the logs of a csar", tags = {"csars"}, notes = "Returns the logs for a csar, starting at a specific position. from the given start index all " + "following log lines get returned. If the start index is larger than the current last log index the operation " + "will return a empty list." ) @ApiResponses({ @ApiResponse( code = 200, message = "The operation was executed successfully", response = LogResponse.class ), @ApiResponse( code = 400, message = "The given start value is less than zero", response = RestErrorResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given identifier", response = RestErrorResponse.class ) }) ResponseEntity<LogResponse> getLogs(
@ApiParam(value = "The unique identifier for the CSAR", required = true, example = "test")
@PathVariable(name = "name") String csarId,
@ApiParam(value = "The index of the first log entry you want (0 returns the whole log)", required = true, example = "0")
@RequestParam(name = "start", required = false, defaultValue = "0") Long start
); } | CsarController { @ApiOperation( value = "Deletes a Existing CSAR", notes = "Deletes the Resulting CSAR and its transformations (if none of them is running). " + "If a transformation is running (in the state TRANSFORMING) the CSAR cannot be deleted" ) @ApiResponses({ @ApiResponse( code = 200, message = "The deletion of the CSAR was successful", response = Void.class ), @ApiResponse( code = 400, message = "The deletion of the CSAR failed, because there is one or more transformations still running.", response = RestErrorResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given name (identifier)", response = RestErrorResponse.class ) }) @RequestMapping( path = "/{name}/delete", method = {RequestMethod.DELETE}, produces = "application/hal+json" ) public ResponseEntity<Void> deleteCsar( @ApiParam(value = "The unique identifier for the CSAR", required = true, example = "my-csar-name") @PathVariable("name") String name ) { Csar csar = getCsarForName(name); csar.getTransformations().forEach((k, v) -> { if (v.getState() == TransformationState.TRANSFORMING) { throw new ActiveTransformationsException( String.format( "Transformation %s/%s is still running. Cannot delete csar while a transformation is running!", name, k ) ); } }); csarService.deleteCsar(csar); return ResponseEntity.ok().build(); } @Autowired CsarController(CsarService csarService); @ApiOperation( value = "List all CSARs stored on the server", notes = "Returns a Hypermedia Resource containing all CSARs" + " that have been uploaded to the server and did not get removed", response = CsarResources.class, produces = "application/hal+json" ) @RequestMapping( path = "", method = RequestMethod.GET, produces = "application/hal+json" ) ResponseEntity<Resources<CsarResponse>> listCSARs(); @ApiOperation( value = "Returns details for a specific name (identifier)", notes = "Returns the element with the given name, Object contents are " + "equal to a regular /csars request (if you just look at the desired entry)" ) @ApiResponses({ @ApiResponse( code = 200, message = "The Csar was found and the contents are found in the body", response = CsarResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given name (identifier)", response = RestErrorResponse.class ) }) @RequestMapping( path = "/{name}", method = RequestMethod.GET, produces = "application/hal+json" ) ResponseEntity<CsarResponse> getCSARInfo(
@ApiParam(value = "The unique identifier for the CSAR", required = true, example = "test")
@PathVariable(name = "name") String name
); @ApiOperation( value = "Creates a new CSAR", notes = "This operation creates a new CSAR if the name (identifier) is not used already. " + "The uploaded file has to be a valid CSAR archive. " + "Once the file was uploaded the server will synchronously " + "(the client has to wait for the response) unzip the archive and parse it. " + "Upload gets performed using Multipart Form upload.", code = 201 ) @ApiResponses({ @ApiResponse( code = 201, message = "The upload of the csar was successful", response = Void.class ), @ApiResponse( code = 406, message = "CSAR upload rejected - given ID already in use", response = Void.class ), @ApiResponse( code = 500, message = "The server encountered a unexpected problem", response = Void.class ) }) @RequestMapping( path = "/{name}", method = {RequestMethod.PUT, RequestMethod.POST}, produces = "application/hal+json" ) ResponseEntity<Void> uploadCSAR(
@ApiParam(value = "The unique identifier for the CSAR", required = true)
@PathVariable(name = "name") String name,
@ApiParam(value = "The CSAR Archive (Compressed as ZIP)", required = true)
@RequestParam(name = "file", required = true) MultipartFile file
// HttpServletRequest request
); @ApiOperation( value = "Deletes a Existing CSAR", notes = "Deletes the Resulting CSAR and its transformations (if none of them is running). " + "If a transformation is running (in the state TRANSFORMING) the CSAR cannot be deleted" ) @ApiResponses({ @ApiResponse( code = 200, message = "The deletion of the CSAR was successful", response = Void.class ), @ApiResponse( code = 400, message = "The deletion of the CSAR failed, because there is one or more transformations still running.", response = RestErrorResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given name (identifier)", response = RestErrorResponse.class ) }) @RequestMapping( path = "/{name}/delete", method = {RequestMethod.DELETE}, produces = "application/hal+json" ) ResponseEntity<Void> deleteCsar(
@ApiParam(value = "The unique identifier for the CSAR", required = true, example = "my-csar-name")
@PathVariable("name") String name
); @RequestMapping( path = "/{name}/logs", method = RequestMethod.GET, produces = "application/hal+json" ) @ApiOperation( value = "Get the logs of a csar", tags = {"csars"}, notes = "Returns the logs for a csar, starting at a specific position. from the given start index all " + "following log lines get returned. If the start index is larger than the current last log index the operation " + "will return a empty list." ) @ApiResponses({ @ApiResponse( code = 200, message = "The operation was executed successfully", response = LogResponse.class ), @ApiResponse( code = 400, message = "The given start value is less than zero", response = RestErrorResponse.class ), @ApiResponse( code = 404, message = "There is no CSAR for the given identifier", response = RestErrorResponse.class ) }) ResponseEntity<LogResponse> getLogs(
@ApiParam(value = "The unique identifier for the CSAR", required = true, example = "test")
@PathVariable(name = "name") String csarId,
@ApiParam(value = "The index of the first log entry you want (0 returns the whole log)", required = true, example = "0")
@RequestParam(name = "start", required = false, defaultValue = "0") Long start
); } |
@Test public void testWriteScripts() throws Exception { cfnModule.addFileUpload(new FileUpload(FILENAME_TEST_FILE, FROM_CSAR)); fileCreator.writeScripts(); File deployScript = new File(targetDir, SCRIPTS_DIR_PATH + FILENAME_DEPLOY + BASH_FILE_ENDING); File fileUploadScript = new File(targetDir, SCRIPTS_DIR_PATH + FILENAME_UPLOAD + BASH_FILE_ENDING); File createStackScript = new File(targetDir, SCRIPTS_DIR_PATH + FILENAME_CREATE_STACK + BASH_FILE_ENDING); assertTrue(deployScript.exists()); assertTrue(fileUploadScript.exists()); String expectedDeployContent = SHEBANG + "\n" + SOURCE_UTIL_ALL + "\n" + SUBCOMMAND_EXIT + "\n" + "check \"aws\"\n" + "source file-upload.sh\n" + "source create-stack.sh\n"; String expectedFileUploadContent = SHEBANG + "\n" + SOURCE_UTIL_ALL + "\n" + SUBCOMMAND_EXIT + "\n" + "createBucket " + cfnModule.getBucketName() + " " + cfnModule.getAWSRegion() + "\n" + "uploadFile " + cfnModule.getBucketName() + " \"" + FILENAME_TEST_FILE + "\" \"" + FILEPATH_TARGET_TEST_FILE_LOCAL + "\"" + "\n"; String expectedCreateStackContent = SHEBANG + "\n" + SOURCE_UTIL_ALL + "\n" + SUBCOMMAND_EXIT + "\n" + CLI_COMMAND_CREATESTACK + CLI_PARAM_STACKNAME + cfnModule.getStackName() + " " + CLI_PARAM_TEMPLATEFILE + "../" + TEMPLATE_YAML + " " + CLI_PARAM_CAPABILITIES + " " + CAPABILITY_IAM + "\n"; String actualDeployContent = FileUtils.readFileToString(deployScript, StandardCharsets.UTF_8); String actualFileUploadContent = FileUtils.readFileToString(fileUploadScript, StandardCharsets.UTF_8); String actualCreateStackContent = FileUtils.readFileToString(createStackScript, StandardCharsets.UTF_8); assertEquals(expectedDeployContent, actualDeployContent); assertEquals(expectedFileUploadContent, actualFileUploadContent); assertEquals(expectedCreateStackContent, actualCreateStackContent); } | public void writeScripts() throws IOException { writeFileUploadScript(); writeStackCreationScript(); writeDeployScript(); writeCleanUpScript(); } | CloudFormationFileCreator { public void writeScripts() throws IOException { writeFileUploadScript(); writeStackCreationScript(); writeDeployScript(); writeCleanUpScript(); } } | CloudFormationFileCreator { public void writeScripts() throws IOException { writeFileUploadScript(); writeStackCreationScript(); writeDeployScript(); writeCleanUpScript(); } CloudFormationFileCreator(TransformationContext context, CloudFormationModule cfnModule); } | CloudFormationFileCreator { public void writeScripts() throws IOException { writeFileUploadScript(); writeStackCreationScript(); writeDeployScript(); writeCleanUpScript(); } CloudFormationFileCreator(TransformationContext context, CloudFormationModule cfnModule); void copyFiles(); void writeScripts(); void copyUtilScripts(); void copyUtilDependencies(); void writeReadme(TransformationContext context); } | CloudFormationFileCreator { public void writeScripts() throws IOException { writeFileUploadScript(); writeStackCreationScript(); writeDeployScript(); writeCleanUpScript(); } CloudFormationFileCreator(TransformationContext context, CloudFormationModule cfnModule); void copyFiles(); void writeScripts(); void copyUtilScripts(); void copyUtilDependencies(); void writeReadme(TransformationContext context); static final String CLI_COMMAND_CREATESTACK; static final String CLI_COMMAND_DELETESTACK; static final String CLI_COMMAND_DELETEBUCKET; static final String COMMAND_ECHO; static final String STRING_DELETESTACK; static final String CLI_PARAM_STACKNAME; static final String CLI_PARAM_TEMPLATEFILE; static final String CLI_PARAM_PARAMOVERRIDES; static final String CLI_PARAM_CAPABILITIES; static final String CLI_PARAM_BUCKET; static final String CLI_PARAM_FORCE; static final String CAPABILITY_IAM; static final String FILENAME_DEPLOY; static final String FILENAME_UPLOAD; static final String FILENAME_CREATE_STACK; static final String FILENAME_CLEANUP; static final String TEMPLATE_YAML; static final String CHANGE_TO_PARENT_DIRECTORY; static final String RELATIVE_DIRECTORY_PREFIX; static final String FILEPATH_CLOUDFORMATION; static final String FILEPATH_SCRIPTS_UTIL; static final String FILEPATH_FILES_UTIL; } |
@Test public void copyUtilScripts() throws Exception { fileCreator.copyUtilScripts(); File createBucketUtilScript = new File(targetDir, UTIL_DIR_PATH + FILENAME_CREATE_BUCKET + BASH_FILE_ENDING); File uploadFileUtilScript = new File(targetDir, UTIL_DIR_PATH + FILENAME_UPLOAD_FILE + BASH_FILE_ENDING); assertTrue(createBucketUtilScript.exists()); assertTrue(uploadFileUtilScript.exists()); } | public void copyUtilScripts() throws IOException { List<String> utilScripts = IOUtils.readLines( getClass().getResourceAsStream(FILEPATH_SCRIPTS_UTIL + "scripts-list"), Charsets.UTF_8 ); logger.debug("Copying util scripts to the target artifact."); copyUtilFile(utilScripts, FILEPATH_SCRIPTS_UTIL, UTIL_DIR_PATH); } | CloudFormationFileCreator { public void copyUtilScripts() throws IOException { List<String> utilScripts = IOUtils.readLines( getClass().getResourceAsStream(FILEPATH_SCRIPTS_UTIL + "scripts-list"), Charsets.UTF_8 ); logger.debug("Copying util scripts to the target artifact."); copyUtilFile(utilScripts, FILEPATH_SCRIPTS_UTIL, UTIL_DIR_PATH); } } | CloudFormationFileCreator { public void copyUtilScripts() throws IOException { List<String> utilScripts = IOUtils.readLines( getClass().getResourceAsStream(FILEPATH_SCRIPTS_UTIL + "scripts-list"), Charsets.UTF_8 ); logger.debug("Copying util scripts to the target artifact."); copyUtilFile(utilScripts, FILEPATH_SCRIPTS_UTIL, UTIL_DIR_PATH); } CloudFormationFileCreator(TransformationContext context, CloudFormationModule cfnModule); } | CloudFormationFileCreator { public void copyUtilScripts() throws IOException { List<String> utilScripts = IOUtils.readLines( getClass().getResourceAsStream(FILEPATH_SCRIPTS_UTIL + "scripts-list"), Charsets.UTF_8 ); logger.debug("Copying util scripts to the target artifact."); copyUtilFile(utilScripts, FILEPATH_SCRIPTS_UTIL, UTIL_DIR_PATH); } CloudFormationFileCreator(TransformationContext context, CloudFormationModule cfnModule); void copyFiles(); void writeScripts(); void copyUtilScripts(); void copyUtilDependencies(); void writeReadme(TransformationContext context); } | CloudFormationFileCreator { public void copyUtilScripts() throws IOException { List<String> utilScripts = IOUtils.readLines( getClass().getResourceAsStream(FILEPATH_SCRIPTS_UTIL + "scripts-list"), Charsets.UTF_8 ); logger.debug("Copying util scripts to the target artifact."); copyUtilFile(utilScripts, FILEPATH_SCRIPTS_UTIL, UTIL_DIR_PATH); } CloudFormationFileCreator(TransformationContext context, CloudFormationModule cfnModule); void copyFiles(); void writeScripts(); void copyUtilScripts(); void copyUtilDependencies(); void writeReadme(TransformationContext context); static final String CLI_COMMAND_CREATESTACK; static final String CLI_COMMAND_DELETESTACK; static final String CLI_COMMAND_DELETEBUCKET; static final String COMMAND_ECHO; static final String STRING_DELETESTACK; static final String CLI_PARAM_STACKNAME; static final String CLI_PARAM_TEMPLATEFILE; static final String CLI_PARAM_PARAMOVERRIDES; static final String CLI_PARAM_CAPABILITIES; static final String CLI_PARAM_BUCKET; static final String CLI_PARAM_FORCE; static final String CAPABILITY_IAM; static final String FILENAME_DEPLOY; static final String FILENAME_UPLOAD; static final String FILENAME_CREATE_STACK; static final String FILENAME_CLEANUP; static final String TEMPLATE_YAML; static final String CHANGE_TO_PARENT_DIRECTORY; static final String RELATIVE_DIRECTORY_PREFIX; static final String FILEPATH_CLOUDFORMATION; static final String FILEPATH_SCRIPTS_UTIL; static final String FILEPATH_FILES_UTIL; } |
@Test public void copyFiles() { cfnModule.addFileUpload(new FileUpload(FILENAME_TEST_FILE, FROM_CSAR)); fileCreator.copyFiles(); assertTrue(FILEPATH_TARGET_TEST_FILE.exists()); } | public void copyFiles() { List<String> fileUploadList = getFilePaths(getFileUploadByType(cfnModule.getFileUploadList(), FROM_CSAR)); logger.debug("Checking if files need to be copied."); if (!fileUploadList.isEmpty()) { logger.debug("Files to be copied found. Attempting to copy files to the target artifact."); fileUploadList.forEach((filePath) -> { String targetPath = FILEPATH_TARGET + filePath; try { cfnModule.getFileAccess().copy(filePath, targetPath); } catch (IOException e) { throw new TransformationFailureException("Copying of files to the target artifact failed.", e); } }); } else { logger.debug("No files to be copied found. Skipping copying of files."); } } | CloudFormationFileCreator { public void copyFiles() { List<String> fileUploadList = getFilePaths(getFileUploadByType(cfnModule.getFileUploadList(), FROM_CSAR)); logger.debug("Checking if files need to be copied."); if (!fileUploadList.isEmpty()) { logger.debug("Files to be copied found. Attempting to copy files to the target artifact."); fileUploadList.forEach((filePath) -> { String targetPath = FILEPATH_TARGET + filePath; try { cfnModule.getFileAccess().copy(filePath, targetPath); } catch (IOException e) { throw new TransformationFailureException("Copying of files to the target artifact failed.", e); } }); } else { logger.debug("No files to be copied found. Skipping copying of files."); } } } | CloudFormationFileCreator { public void copyFiles() { List<String> fileUploadList = getFilePaths(getFileUploadByType(cfnModule.getFileUploadList(), FROM_CSAR)); logger.debug("Checking if files need to be copied."); if (!fileUploadList.isEmpty()) { logger.debug("Files to be copied found. Attempting to copy files to the target artifact."); fileUploadList.forEach((filePath) -> { String targetPath = FILEPATH_TARGET + filePath; try { cfnModule.getFileAccess().copy(filePath, targetPath); } catch (IOException e) { throw new TransformationFailureException("Copying of files to the target artifact failed.", e); } }); } else { logger.debug("No files to be copied found. Skipping copying of files."); } } CloudFormationFileCreator(TransformationContext context, CloudFormationModule cfnModule); } | CloudFormationFileCreator { public void copyFiles() { List<String> fileUploadList = getFilePaths(getFileUploadByType(cfnModule.getFileUploadList(), FROM_CSAR)); logger.debug("Checking if files need to be copied."); if (!fileUploadList.isEmpty()) { logger.debug("Files to be copied found. Attempting to copy files to the target artifact."); fileUploadList.forEach((filePath) -> { String targetPath = FILEPATH_TARGET + filePath; try { cfnModule.getFileAccess().copy(filePath, targetPath); } catch (IOException e) { throw new TransformationFailureException("Copying of files to the target artifact failed.", e); } }); } else { logger.debug("No files to be copied found. Skipping copying of files."); } } CloudFormationFileCreator(TransformationContext context, CloudFormationModule cfnModule); void copyFiles(); void writeScripts(); void copyUtilScripts(); void copyUtilDependencies(); void writeReadme(TransformationContext context); } | CloudFormationFileCreator { public void copyFiles() { List<String> fileUploadList = getFilePaths(getFileUploadByType(cfnModule.getFileUploadList(), FROM_CSAR)); logger.debug("Checking if files need to be copied."); if (!fileUploadList.isEmpty()) { logger.debug("Files to be copied found. Attempting to copy files to the target artifact."); fileUploadList.forEach((filePath) -> { String targetPath = FILEPATH_TARGET + filePath; try { cfnModule.getFileAccess().copy(filePath, targetPath); } catch (IOException e) { throw new TransformationFailureException("Copying of files to the target artifact failed.", e); } }); } else { logger.debug("No files to be copied found. Skipping copying of files."); } } CloudFormationFileCreator(TransformationContext context, CloudFormationModule cfnModule); void copyFiles(); void writeScripts(); void copyUtilScripts(); void copyUtilDependencies(); void writeReadme(TransformationContext context); static final String CLI_COMMAND_CREATESTACK; static final String CLI_COMMAND_DELETESTACK; static final String CLI_COMMAND_DELETEBUCKET; static final String COMMAND_ECHO; static final String STRING_DELETESTACK; static final String CLI_PARAM_STACKNAME; static final String CLI_PARAM_TEMPLATEFILE; static final String CLI_PARAM_PARAMOVERRIDES; static final String CLI_PARAM_CAPABILITIES; static final String CLI_PARAM_BUCKET; static final String CLI_PARAM_FORCE; static final String CAPABILITY_IAM; static final String FILENAME_DEPLOY; static final String FILENAME_UPLOAD; static final String FILENAME_CREATE_STACK; static final String FILENAME_CLEANUP; static final String TEMPLATE_YAML; static final String CHANGE_TO_PARENT_DIRECTORY; static final String RELATIVE_DIRECTORY_PREFIX; static final String FILEPATH_CLOUDFORMATION; static final String FILEPATH_SCRIPTS_UTIL; static final String FILEPATH_FILES_UTIL; } |
@Test public void appendTest() throws IOException { String string = UUID.randomUUID().toString(); bashScript.append(string); File expectedGeneratedScript = new File(targetScriptFolder, fileName + ".sh"); List<String> result = IOUtils.readLines(new FileInputStream(expectedGeneratedScript)); assertEquals(string, result.get(result.size() - 1)); } | public void append(String string) throws IOException { logger.debug("Appending {} to {}.sh", string, name); access.access(scriptPath).appendln(string).close(); } | BashScript { public void append(String string) throws IOException { logger.debug("Appending {} to {}.sh", string, name); access.access(scriptPath).appendln(string).close(); } } | BashScript { public void append(String string) throws IOException { logger.debug("Appending {} to {}.sh", string, name); access.access(scriptPath).appendln(string).close(); } BashScript(PluginFileAccess access, String name); } | BashScript { public void append(String string) throws IOException { logger.debug("Appending {} to {}.sh", string, name); access.access(scriptPath).appendln(string).close(); } BashScript(PluginFileAccess access, String name); void append(String string); void checkEnvironment(String command); String getScriptPath(); } | BashScript { public void append(String string) throws IOException { logger.debug("Appending {} to {}.sh", string, name); access.access(scriptPath).appendln(string).close(); } BashScript(PluginFileAccess access, String name); void append(String string); void checkEnvironment(String command); String getScriptPath(); static final String SHEBANG; static final String SOURCE_UTIL_ALL; static final String SUBCOMMAND_EXIT; } |
@Test public void unzipFile() throws IOException { ZipInputStream is = new ZipInputStream(new FileInputStream(TestCsars.VALID_LAMP_INPUT)); boolean result = ZipUtility.unzip(is, tmpdir.toString()); assertTrue(result); } | public static boolean unzip(ZipInputStream zipIn, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { return false; } while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { extractFile(zipIn, filePath); } else { logger.trace("Creating directory: {}", filePath); File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); return true; } | ZipUtility { public static boolean unzip(ZipInputStream zipIn, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { return false; } while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { extractFile(zipIn, filePath); } else { logger.trace("Creating directory: {}", filePath); File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); return true; } } | ZipUtility { public static boolean unzip(ZipInputStream zipIn, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { return false; } while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { extractFile(zipIn, filePath); } else { logger.trace("Creating directory: {}", filePath); File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); return true; } } | ZipUtility { public static boolean unzip(ZipInputStream zipIn, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { return false; } while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { extractFile(zipIn, filePath); } else { logger.trace("Creating directory: {}", filePath); File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); return true; } static boolean unzip(ZipInputStream zipIn, String destDirectory); static void compressDirectory(File directory, OutputStream output); } | ZipUtility { public static boolean unzip(ZipInputStream zipIn, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipEntry entry = zipIn.getNextEntry(); if (entry == null) { return false; } while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { extractFile(zipIn, filePath); } else { logger.trace("Creating directory: {}", filePath); File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } zipIn.close(); return true; } static boolean unzip(ZipInputStream zipIn, String destDirectory); static void compressDirectory(File directory, OutputStream output); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.