method2testcases
stringlengths
118
6.63k
### Question: CassandraDataSetService implements DataSetService { @Override public DataSet createDataSet(String providerId, String dataSetId, String description) throws ProviderNotExistsException, DataSetAlreadyExistsException { Date now = new Date(); if (uis.getProvider(providerId) == null) { throw new ProviderNotExistsException(); } DataSet ds = dataSetDAO.getDataSet(providerId, dataSetId); if (ds != null) { throw new DataSetAlreadyExistsException("Data set with provided name already exists"); } return dataSetDAO .createDataSet(providerId, dataSetId, description, now); } @Override ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit); @Override void addAssignment(String providerId, String dataSetId, String recordId, String schema, String version); @Override void removeAssignment(String providerId, String dataSetId, String recordId, String schema, String versionId); @Override DataSet createDataSet(String providerId, String dataSetId, String description); @Override DataSet updateDataSet(String providerId, String dataSetId, String description); @Override ResultSlice<DataSet> getDataSets(String providerId, String thresholdDatasetId, int limit); @Override ResultSlice<CloudTagsResponse> getDataSetsRevisions(String providerId, String dataSetId, String revisionProviderId, String revisionName, Date revisionTimestamp, String representationName, String startFrom, int limit); @Override void addDataSetsRevisions(String providerId, String dataSetId, Revision revision, String representationName, String cloudId); @Override ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationPublished(String dataSetId, String providerId, String representationName, Date dateFrom, String startFrom, int numberOfElementsPerPage); @Override void updateAllRevisionDatasetsEntries(String globalId, String schema, String version, Revision revision); @Override void deleteDataSet(String providerId, String dataSetId); @Override Set<String> getAllDataSetRepresentationsNames(String providerId, String dataSetId); @Override void updateProviderDatasetRepresentation(String globalId, String schema, String version, Revision revision); @Override String getLatestVersionForGivenRevision(String dataSetId, String providerId, String cloudId, String representationName, String revisionName, String revisionProviderId); @Override void addLatestRevisionForGivenVersionInDataset(DataSet dataSet, Representation representation, Revision revision); @Override ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(String dataSetId, String providerId, String revisionName, String revisionProvider, String representationName, String startFrom, Boolean isDeleted, int numberOfElementsPerPage); @Override void deleteRevision(String cloudId, String representationName, String version, String revisionName, String revisionProviderId, Date revisionTimestamp); }### Answer: @Test public void shouldCreateDataSet() throws Exception { makeUISProviderSuccess(); String dsName = "ds"; String description = "description of data set"; DataSet ds = cassandraDataSetService.createDataSet(PROVIDER_ID, dsName, description); assertThat(ds.getId(), is(dsName)); assertThat(ds.getDescription(), is(description)); assertThat(ds.getProviderId(), is(PROVIDER_ID)); } @Test(expected = ProviderNotExistsException.class) public void shouldThrowExceptionWhenCreatingDatasetForNotExistingProvider() throws Exception { makeUISProviderFailure(); cassandraDataSetService.createDataSet("not-existing-provider", "ds", "description"); } @Test(expected = DataSetAlreadyExistsException.class) public void shouldNotCreateTwoDatasetsWithSameNameForProvider() throws Exception { String dsName = "ds"; makeUISProviderSuccess(); cassandraDataSetService .createDataSet(PROVIDER_ID, dsName, "description"); cassandraDataSetService.createDataSet(PROVIDER_ID, dsName, "description of another"); }
### Question: CassandraDataSetService implements DataSetService { @Override public void deleteDataSet(String providerId, String dataSetId) throws DataSetNotExistsException { checkIfDatasetExists(dataSetId, providerId); String nextToken = null; int maxSize = 10000; List<Properties> representations = dataSetDAO.listDataSet(providerId, dataSetId, null, maxSize); for (Properties representation : representations) { removeAssignment(providerId, dataSetId, representation.getProperty("cloudId"), representation.getProperty("schema"), representation.getProperty("versionId")); } while (representations.size() == maxSize + 1) { nextToken = representations.get(maxSize).getProperty("nextSlice"); representations = dataSetDAO.listDataSet(providerId, dataSetId, nextToken, maxSize); for (Properties representation : representations) { removeAssignment(providerId, dataSetId, representation.getProperty("cloudId"), representation.getProperty("schema"), representation.getProperty("versionId")); } } dataSetDAO.deleteDataSet(providerId, dataSetId); } @Override ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit); @Override void addAssignment(String providerId, String dataSetId, String recordId, String schema, String version); @Override void removeAssignment(String providerId, String dataSetId, String recordId, String schema, String versionId); @Override DataSet createDataSet(String providerId, String dataSetId, String description); @Override DataSet updateDataSet(String providerId, String dataSetId, String description); @Override ResultSlice<DataSet> getDataSets(String providerId, String thresholdDatasetId, int limit); @Override ResultSlice<CloudTagsResponse> getDataSetsRevisions(String providerId, String dataSetId, String revisionProviderId, String revisionName, Date revisionTimestamp, String representationName, String startFrom, int limit); @Override void addDataSetsRevisions(String providerId, String dataSetId, Revision revision, String representationName, String cloudId); @Override ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationPublished(String dataSetId, String providerId, String representationName, Date dateFrom, String startFrom, int numberOfElementsPerPage); @Override void updateAllRevisionDatasetsEntries(String globalId, String schema, String version, Revision revision); @Override void deleteDataSet(String providerId, String dataSetId); @Override Set<String> getAllDataSetRepresentationsNames(String providerId, String dataSetId); @Override void updateProviderDatasetRepresentation(String globalId, String schema, String version, Revision revision); @Override String getLatestVersionForGivenRevision(String dataSetId, String providerId, String cloudId, String representationName, String revisionName, String revisionProviderId); @Override void addLatestRevisionForGivenVersionInDataset(DataSet dataSet, Representation representation, Revision revision); @Override ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(String dataSetId, String providerId, String revisionName, String revisionProvider, String representationName, String startFrom, Boolean isDeleted, int numberOfElementsPerPage); @Override void deleteRevision(String cloudId, String representationName, String version, String revisionName, String revisionProviderId, Date revisionTimestamp); }### Answer: @Test(expected = DataSetNotExistsException.class) public void shouldThrowExceptionWhenDeletingNotExistingDataSet() throws Exception { cassandraDataSetService.deleteDataSet("xxx", "xxx"); }
### Question: CassandraDataSetService implements DataSetService { @Override public ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationPublished(String dataSetId, String providerId, String representationName, Date dateFrom, String startFrom, int numberOfElementsPerPage) throws ProviderNotExistsException, DataSetNotExistsException { validateRequest(dataSetId, providerId); List<Properties> list = dataSetDAO.getDataSetCloudIdsByRepresentationPublished(providerId, dataSetId, representationName, dateFrom, startFrom, numberOfElementsPerPage); String nextToken = null; if (list.size() == numberOfElementsPerPage + 1) { nextToken = list.get(numberOfElementsPerPage).getProperty("nextSlice"); list.remove(numberOfElementsPerPage); } return new ResultSlice<>(nextToken, prepareResponseList(list)); } @Override ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit); @Override void addAssignment(String providerId, String dataSetId, String recordId, String schema, String version); @Override void removeAssignment(String providerId, String dataSetId, String recordId, String schema, String versionId); @Override DataSet createDataSet(String providerId, String dataSetId, String description); @Override DataSet updateDataSet(String providerId, String dataSetId, String description); @Override ResultSlice<DataSet> getDataSets(String providerId, String thresholdDatasetId, int limit); @Override ResultSlice<CloudTagsResponse> getDataSetsRevisions(String providerId, String dataSetId, String revisionProviderId, String revisionName, Date revisionTimestamp, String representationName, String startFrom, int limit); @Override void addDataSetsRevisions(String providerId, String dataSetId, Revision revision, String representationName, String cloudId); @Override ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationPublished(String dataSetId, String providerId, String representationName, Date dateFrom, String startFrom, int numberOfElementsPerPage); @Override void updateAllRevisionDatasetsEntries(String globalId, String schema, String version, Revision revision); @Override void deleteDataSet(String providerId, String dataSetId); @Override Set<String> getAllDataSetRepresentationsNames(String providerId, String dataSetId); @Override void updateProviderDatasetRepresentation(String globalId, String schema, String version, Revision revision); @Override String getLatestVersionForGivenRevision(String dataSetId, String providerId, String cloudId, String representationName, String revisionName, String revisionProviderId); @Override void addLatestRevisionForGivenVersionInDataset(DataSet dataSet, Representation representation, Revision revision); @Override ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(String dataSetId, String providerId, String revisionName, String revisionProvider, String representationName, String startFrom, Boolean isDeleted, int numberOfElementsPerPage); @Override void deleteRevision(String cloudId, String representationName, String version, String revisionName, String revisionProviderId, Date revisionTimestamp); }### Answer: @Test(expected = DataSetNotExistsException.class) public void shouldThrowExceptionWhenRequestingCloudIdsForNonExistingDataSet() throws Exception { makeUISProviderExistsSuccess(); cassandraDataSetService.getDataSetCloudIdsByRepresentationPublished("non-existent-ds", "provider", "representation", new Date(), null, 1); } @Test(expected = ProviderNotExistsException.class) public void shouldThrowExceptionWhenRequestingCloudIdsForNonExistingProvider() throws Exception { makeUISProviderExistsFailure(); cassandraDataSetService.getDataSetCloudIdsByRepresentationPublished("ds", "non-existent-provider", "representation", new Date(), null, 1); }
### Question: CassandraDataSetService implements DataSetService { @Override public void deleteRevision(String cloudId, String representationName, String version, String revisionName, String revisionProviderId, Date revisionTimestamp) throws RepresentationNotExistsException { checkIfRepresentationExists(representationName, version, cloudId); Revision revision = new Revision(revisionName, revisionProviderId); revision.setCreationTimeStamp(revisionTimestamp); Collection<CompoundDataSetId> compoundDataSetIds = dataSetDAO.getDataSetAssignmentsByRepresentationVersion(cloudId, representationName, version); for (CompoundDataSetId compoundDataSetId : compoundDataSetIds) { dataSetDAO.removeDataSetsRevision(compoundDataSetId.getDataSetProviderId(), compoundDataSetId.getDataSetId(), revision, representationName, cloudId); dataSetDAO.deleteProviderDatasetRepresentationInfo(compoundDataSetId.getDataSetId(), compoundDataSetId.getDataSetProviderId(), cloudId, representationName, revisionTimestamp); } recordDAO.deleteRepresentationRevision(cloudId, representationName, version, revisionProviderId, revisionName, revisionTimestamp); recordDAO.removeRevisionFromRepresentationVersion(cloudId, representationName, version,revision); } @Override ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit); @Override void addAssignment(String providerId, String dataSetId, String recordId, String schema, String version); @Override void removeAssignment(String providerId, String dataSetId, String recordId, String schema, String versionId); @Override DataSet createDataSet(String providerId, String dataSetId, String description); @Override DataSet updateDataSet(String providerId, String dataSetId, String description); @Override ResultSlice<DataSet> getDataSets(String providerId, String thresholdDatasetId, int limit); @Override ResultSlice<CloudTagsResponse> getDataSetsRevisions(String providerId, String dataSetId, String revisionProviderId, String revisionName, Date revisionTimestamp, String representationName, String startFrom, int limit); @Override void addDataSetsRevisions(String providerId, String dataSetId, Revision revision, String representationName, String cloudId); @Override ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationPublished(String dataSetId, String providerId, String representationName, Date dateFrom, String startFrom, int numberOfElementsPerPage); @Override void updateAllRevisionDatasetsEntries(String globalId, String schema, String version, Revision revision); @Override void deleteDataSet(String providerId, String dataSetId); @Override Set<String> getAllDataSetRepresentationsNames(String providerId, String dataSetId); @Override void updateProviderDatasetRepresentation(String globalId, String schema, String version, Revision revision); @Override String getLatestVersionForGivenRevision(String dataSetId, String providerId, String cloudId, String representationName, String revisionName, String revisionProviderId); @Override void addLatestRevisionForGivenVersionInDataset(DataSet dataSet, Representation representation, Revision revision); @Override ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(String dataSetId, String providerId, String revisionName, String revisionProvider, String representationName, String startFrom, Boolean isDeleted, int numberOfElementsPerPage); @Override void deleteRevision(String cloudId, String representationName, String version, String revisionName, String revisionProviderId, Date revisionTimestamp); }### Answer: @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsException() throws Exception { makeUISProviderSuccess(); makeUISSuccess(); makeDatasetExists(); Date date = new Date(); String cloudId = "2EEN23VWNXOW7LGLM6SKTDOZUBUOTKEWZ3IULSYEWEMERHISS6XA"; cassandraDataSetService.deleteRevision(cloudId, REPRESENTATION, "3d6381c0-a3cf-11e9-960f-fa163e8d4ae3", REVISION, PROVIDER_ID, date); }
### Question: DynamicContentDAO { public void deleteContent(String fileName, Storage stored) throws FileNotExistsException { getContentDAO(stored).deleteContent(fileName); } @Autowired DynamicContentDAO(Map<Storage,ContentDAO> contentDAOs); void copyContent(String sourceObjectId, String trgObjectId, Storage stored); void deleteContent(String fileName, Storage stored); void getContent(String fileName, long start, long end, OutputStream os, Storage stored); PutResult putContent(String fileName, InputStream data, Storage stored); }### Answer: @Test(expected = ContentDaoNotFoundException.class) public void shouldThrowExceptionOnNonExistingDAO() throws FileNotExistsException { final DynamicContentDAO instance = new DynamicContentDAO(prepareDAOMap( mock(SwiftContentDAO.class) )); instance.deleteContent("exampleFileName",Storage.DATA_BASE); } @Test public void shouldProperlySelectDataBaseDeleteContent() throws FileNotExistsException { SwiftContentDAO daoMock = mock(SwiftContentDAO.class); final DynamicContentDAO instance = new DynamicContentDAO(prepareDAOMap(daoMock)); instance.deleteContent("exampleFileName",Storage.OBJECT_STORAGE); verify(daoMock).deleteContent(anyString()); }
### Question: CassandraRecordService implements RecordService { @Override public Representation createRepresentation(String cloudId, String representationName, String providerId) throws ProviderNotExistsException, RecordNotExistsException { Date now = new Date(); DataProvider dataProvider; if ((dataProvider = uis.getProvider(providerId)) == null) { throw new ProviderNotExistsException(String.format("Provider %s does not exist.", providerId)); } if (uis.existsCloudId(cloudId)) { Representation rep = recordDAO.createRepresentation(cloudId, representationName, providerId, now); return rep; } else { throw new RecordNotExistsException(cloudId); } } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart, long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); }### Answer: @Test(expected = RecordNotExistsException.class) public void shouldThrowExpWhileCreatingRepresentationIfNoRecordInUis() throws Exception { makeUISThrowRecordNotExist(); mockUISProvider1Success(); cassandraRecordService.createRepresentation("globalId", "dc", PROVIDER_1_ID); } @Test(expected = SystemException.class) public void shouldThrowSystemExpWhileCreatingRepresentationIfUisFails() throws Exception { mockUISProvider1Success(); makeUISThrowSystemException(); cassandraRecordService.createRepresentation("globalId", "dc", PROVIDER_1_ID); } @Test(expected = ProviderNotExistsException.class) public void shouldNotCreateRepresentationForNotExistingProvider() throws Exception { makeUISFailure(); makeUISProviderFailure(); cassandraRecordService.createRepresentation("globalId", "dc", "not-existing"); }
### Question: CassandraRecordService implements RecordService { @Override public Record getRecord(String cloudId) throws RecordNotExistsException { Record record = null; if (uis.existsCloudId(cloudId)) { record = recordDAO.getRecord(cloudId); if (record.getRepresentations().isEmpty()) { throw new RecordNotExistsException(cloudId); } } else { throw new RecordNotExistsException(cloudId); } return record; } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart, long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); }### Answer: @Test(expected = RecordNotExistsException.class) public void shouldThrowExpWhileGettingRecordIfNoRecordInUis() throws Exception { makeUISThrowRecordNotExist(); cassandraRecordService.getRecord("globalId"); } @Test(expected = SystemException.class) public void shouldThrowSystemExpWhileGettingRecordIfUisFails() throws Exception { makeUISThrowSystemException(); cassandraRecordService.getRecord("globalId"); }
### Question: CassandraRecordService implements RecordService { @Override public void deleteRecord(String cloudId) throws RecordNotExistsException, RepresentationNotExistsException { if (uis.existsCloudId(cloudId)) { List<Representation> allRecordRepresentationsInAllVersions = recordDAO.listRepresentationVersions(cloudId); if (allRecordRepresentationsInAllVersions.isEmpty()) { throw new RepresentationNotExistsException(String.format( "No representation found for given cloudId %s", cloudId)); } sortByProviderId(allRecordRepresentationsInAllVersions); String dPId = null; for (Representation repVersion : allRecordRepresentationsInAllVersions) { removeFilesFromRepresentationVersion(cloudId, repVersion); removeRepresentationAssignmentFromDataSets(cloudId, repVersion); deleteRepresentationRevision(cloudId, repVersion); recordDAO.deleteRepresentation(cloudId, repVersion.getRepresentationName(), repVersion.getVersion()); } } else { throw new RecordNotExistsException(cloudId); } } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart, long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); }### Answer: @Test(expected = RecordNotExistsException.class) public void shouldThrowExpWhileDeletingRecordIfNoRecordInUis() throws Exception { makeUISThrowRecordNotExist(); cassandraRecordService.deleteRecord("globalId"); } @Test(expected = SystemException.class) public void shouldThrowSystemExpWhileDeletingRecordIfUisFails() throws Exception { makeUISThrowSystemException(); cassandraRecordService.deleteRecord("globalId"); } @Test(expected = RepresentationNotExistsException.class) public void shouldThrowExcWhenDeletingRecordHasNoRepresentations() throws Exception { makeUISSuccess(); mockUISProvider1Success(); cassandraRecordService.deleteRecord("globalId"); }
### Question: CassandraRecordService implements RecordService { @Override public Representation getRepresentation(String globalId, String schema) throws RepresentationNotExistsException { Representation rep = recordDAO.getLatestPersistentRepresentation(globalId, schema); if (rep == null) { throw new RepresentationNotExistsException(); } else { return rep; } } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart, long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); }### Answer: @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotFoundExpWhenNoSuchRepresentation() throws Exception { makeUISSuccess(); cassandraRecordService.getRepresentation("globalId", "not_existing_schema"); }
### Question: CustomFileNameMigrator extends SwiftMigrator { @Override public String nameConversion(final String s) { return s.contains("|") ? s.replace("|", "_") : null; } @Override String nameConversion(final String s); }### Answer: @Test public void shouldRetrunNullString() { final String fileName = ""; final String output = migrator.nameConversion(fileName); assertEquals(null, output); } @Test public void shouldConvertFileProperly() { final String fileName = "test2|test1|tes2"; final String output = migrator.nameConversion(fileName); assertEquals("test2_test1_tes2", output); } @Test public void shouldConvertFileProperly2() { final String fileName = "test2_test1|tes2"; final String output = migrator.nameConversion(fileName); assertEquals("test2_test1_tes2", output); }
### Question: CassandraRecordService implements RecordService { @Override public void deleteRepresentation(String globalId, String schema) throws RepresentationNotExistsException { List<Representation> listRepresentations = recordDAO.listRepresentationVersions(globalId, schema); sortByProviderId(listRepresentations); String dPId = null; for (Representation rep : listRepresentations) { removeFilesFromRepresentationVersion(globalId, rep); removeRepresentationAssignmentFromDataSets(globalId, rep); deleteRepresentationRevision(globalId, rep); } recordDAO.deleteRepresentation(globalId, schema); } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart, long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); }### Answer: @Test public void shouldDeletePersistentRepresentation() throws Exception { makeUISSuccess(); mockUISProvider1Success(); Representation r = insertDummyPersistentRepresentation("globalId", "dc", PROVIDER_1_ID); cassandraRecordService.deleteRepresentation(r.getCloudId(), r.getRepresentationName(), r.getVersion()); }
### Question: CassandraRecordService implements RecordService { @Override public boolean putContent(String globalId, String schema, String version, File file, InputStream content) throws CannotModifyPersistentRepresentationException, RepresentationNotExistsException { DateTime now = new DateTime(); Representation representation = getRepresentation(globalId, schema, version); if (representation.isPersistent()) { throw new CannotModifyPersistentRepresentationException(); } boolean isCreate = true; for (File f : representation.getFiles()) { if (f.getFileName().equals(file.getFileName())) { isCreate = false; break; } } String keyForFile = FileUtils.generateKeyForFile(globalId, schema, version, file.getFileName()); PutResult result; try { result = contentDAO.putContent(keyForFile, content, file.getFileStorage()); } catch (IOException ex) { throw new SystemException(ex); } file.setMd5(result.getMd5()); DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); file.setDate(fmt.print(now)); file.setContentLength(result.getContentLength()); recordDAO.addOrReplaceFileInRepresentation(globalId, schema, version, file); for (Revision revision : representation.getRevisions()) { recordDAO.addOrReplaceFileInRepresentationRevision(globalId, schema, version, revision.getRevisionProviderId(), revision.getRevisionName(), revision.getCreationTimeStamp(), file); } return isCreate; } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart, long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); }### Answer: @Test(expected = CannotModifyPersistentRepresentationException.class) public void shouldNotAddFileToPersistentRepresentation() throws Exception { makeUISSuccess(); mockUISProvider1Success(); Representation r = insertDummyPersistentRepresentation("globalId", "dc", PROVIDER_1_ID); byte[] dummyContent = {1, 2, 3}; File f = new File("content.xml", "application/xml", null, null, 0, null, OBJECT_STORAGE); cassandraRecordService.putContent(r.getCloudId(), r.getRepresentationName(), r.getVersion(), f, new ByteArrayInputStream(dummyContent)); }
### Question: CassandraRecordService implements RecordService { @Override public void deleteContent(String globalId, String schema, String version, String fileName) throws FileNotExistsException, CannotModifyPersistentRepresentationException, RepresentationNotExistsException { Representation representation = getRepresentation(globalId, schema, version); if (representation.isPersistent()) { throw new CannotModifyPersistentRepresentationException(); } recordDAO.removeFileFromRepresentation(globalId, schema, version, fileName); recordDAO.removeFileFromRepresentationRevisionsTable(representation, fileName); File file = findFileInRepresentation(representation, fileName); contentDAO.deleteContent(FileUtils.generateKeyForFile(globalId, schema, version, fileName), file.getFileStorage()); } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart, long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); }### Answer: @Test(expected = CannotModifyPersistentRepresentationException.class) public void shouldNotRemoveFileFromPersistentRepresentation() throws Exception { makeUISSuccess(); mockUISProvider1Success(); Representation r = insertDummyPersistentRepresentation("globalId", "dc", PROVIDER_1_ID); File f = r.getFiles().get(0); cassandraRecordService.deleteContent(r.getCloudId(), r.getRepresentationName(), r.getVersion(), f.getFileName()); }
### Question: CassandraRecordService implements RecordService { @Override public void addRevision(String globalId, String schema, String version, Revision revision) throws RevisionIsNotValidException { recordDAO.addOrReplaceRevisionInRepresentation(globalId, schema, version, revision); } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart, long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); }### Answer: @Test public void addRevision() throws Exception { makeUISSuccess(); mockUISProvider1Success(); Representation r = cassandraRecordService.createRepresentation( "globalId", "edm", PROVIDER_1_ID); Revision revision = new Revision(REVISION_NAME, REVISION_PROVIDER); cassandraRecordService.addRevision(r.getCloudId(), r.getRepresentationName(), r.getVersion(), revision); r = cassandraRecordService.getRepresentation(r.getCloudId(), r.getRepresentationName(), r.getVersion()); assertNotNull(r.getRevisions()); assertFalse(r.getRevisions().isEmpty()); assertEquals(r.getRevisions().size(), 1); }
### Question: CassandraRecordService implements RecordService { @Override public Revision getRevision(String globalId, String schema, String version, String revisionKey) throws RevisionNotExistsException, RepresentationNotExistsException { Representation rep = getRepresentation(globalId, schema, version); for (Revision revision : rep.getRevisions()) { if (revision != null) { if (RevisionUtils.getRevisionKey(revision).equals(revisionKey)) { return revision; } } } throw new RevisionNotExistsException(); } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart, long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); }### Answer: @Test public void getRevision() throws Exception { makeUISSuccess(); mockUISProvider1Success(); Representation r = cassandraRecordService.createRepresentation( "globalId", "edm", PROVIDER_1_ID); Revision revision = new Revision(REVISION_NAME, REVISION_PROVIDER, new Date(), true, false, true); cassandraRecordService.addRevision(r.getCloudId(), r.getRepresentationName(), r.getVersion(), revision); String revisionKey = RevisionUtils.getRevisionKey(revision); Revision storedRevision = cassandraRecordService.getRevision(r.getCloudId(), r.getRepresentationName(), r.getVersion(), revisionKey); assertNotNull(storedRevision); assertThat(storedRevision, is(revision)); } @Test(expected = RepresentationNotExistsException.class) public void getRevisionFromNonExistedRepresentation() throws Exception { makeUISSuccess(); mockUISProvider1Success(); String revisionKey = RevisionUtils.getRevisionKey(REVISION_PROVIDER, REVISION_NAME, new Date().getTime()); cassandraRecordService.getRevision("globalId", "not_existing_schema", "5573dbf0-5979-11e6-9061-1c6f653f9042", revisionKey); }
### Question: InMemoryDataSetService implements DataSetService { @Override public ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit) throws DataSetNotExistsException { int treshold = 0; if (thresholdParam != null) { treshold = parseInteger(thresholdParam); } List<Representation> listOfAllStubs = dataSetDAO.listDataSet(providerId, dataSetId); if (listOfAllStubs.size() != 0 && treshold >= listOfAllStubs.size()) { throw new IllegalArgumentException("Illegal threshold param value: '" + thresholdParam + "'."); } int newOffset = -1; List<Representation> listOfStubs = listOfAllStubs; if (limit > 0) { listOfStubs = listOfAllStubs.subList(treshold, Math.min(treshold + limit, listOfAllStubs.size())); if (listOfAllStubs.size() > treshold + limit) { newOffset = treshold + limit; } } List<Representation> toReturn = new ArrayList<>(listOfStubs.size()); for (Representation stub : listOfStubs) { Representation realContent; try { realContent = recordDAO.getRepresentation(stub.getCloudId(), stub.getRepresentationName(), stub.getVersion()); } catch (RepresentationNotExistsException e) { continue; } toReturn.add(realContent); } return newOffset == -1 ? new ResultSlice<>(null, toReturn) : new ResultSlice<>(Integer.toString(newOffset), toReturn); } InMemoryDataSetService(InMemoryDataSetDAO dataSetDAO, InMemoryRecordDAO recordDAO, UISClientHandler dataProviderDao); InMemoryDataSetService(); @Override ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit); @Override void addAssignment(String providerId, String dataSetId, String recordId, String schema, String version); @Override void removeAssignment(String providerId, String dataSetId, String recordId, String schema); @Override DataSet createDataSet(String providerId, String dataSetId, String description); @Override ResultSlice<DataSet> getDataSets(String providerId, String thresholdDatasetId, int limit); @Override void deleteDataSet(String providerId, String dataSetId); @Override DataSet updateDataSet(String providerId, String dataSetId, String description); }### Answer: @Test @Parameters(method = "listDatasetParams") public void shouldListDataSet(String threshold, int limit, String nextSlice, int fromIndex, int toIndex) throws Exception { ResultSlice<Representation> actual = dataSetService.listDataSet(providerId, dataSetId, threshold, limit); assertThat("Next slice should be equal '" + nextSlice + "' but was '" + actual.getNextSlice() + "'", actual.getNextSlice(), equalTo(nextSlice)); assertThat("Lists of representations are not equal", actual.getResults(), equalTo(representations.subList(fromIndex, toIndex))); } @Test public void shouldListEmptyDataSet() throws Exception { when(datasetDao.listDataSet(providerId, dataSetId)).thenReturn(new ArrayList<Representation>()); InMemoryRecordDAO recordDao = new InMemoryRecordListDAO(new ArrayList<Representation>()); dataSetService = new InMemoryDataSetService(datasetDao, recordDao, uisHandler); ResultSlice<Representation> actual = dataSetService.listDataSet(providerId, dataSetId, null, 100); assertThat("Next slice should be null, but was '" + actual.getNextSlice() + "'", actual.getNextSlice(), nullValue()); assertTrue("List of representations should be empty, but was: " + actual.getResults(), actual.getResults() .isEmpty()); }
### Question: InMemoryRecordService implements RecordService { public ResultSlice<Representation> search(RepresentationSearchParams searchParams, String thresholdParam, int limit) { int threshold = 0; if (thresholdParam != null) { threshold = parseInteger(thresholdParam); } String providerId = searchParams.getDataProvider(); String schema = searchParams.getSchema(); String dataSetId = searchParams.getDataSetId(); List<Representation> allRecords; if (providerId != null && dataSetId != null) { List<Representation> toReturn = new ArrayList<>(); try { List<Representation> representationStubs = dataSetDAO.listDataSet(providerId, dataSetId); for (Representation stub : representationStubs) { if (schema == null || schema.equals(stub.getRepresentationName())) { Representation realContent; try { realContent = recordDAO.getRepresentation(stub.getCloudId(), stub.getRepresentationName(), stub.getVersion()); toReturn.add(realContent); } catch (RepresentationNotExistsException ex) { } } } } catch (DataSetNotExistsException ex) { allRecords = Collections.emptyList(); } allRecords = toReturn; } else { allRecords = recordDAO.findRepresentations(providerId, schema); } if (allRecords.size() != 0 && threshold >= allRecords.size()) { throw new IllegalArgumentException("Illegal threshold param value: '" + thresholdParam + "'."); } return prepareResultSlice(limit, threshold, allRecords); } InMemoryRecordService(); InMemoryRecordService(InMemoryRecordDAO recordDAO, InMemoryContentDAO contentDAO, InMemoryDataSetDAO dataSetDAO, UISClientHandler uisHandler); @Override Record getRecord(String globalId); @Override void deleteRecord(String globalId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String globalId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override void getContent(String globalId, String schema, String version, String fileName, long rangeStart, long rangeEnd, OutputStream os); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); ResultSlice<Representation> search(RepresentationSearchParams searchParams, String thresholdParam, int limit); @Override File getFile(String globalId, String schema, String version, String fileName); }### Answer: @Test @Parameters(method = "searchRepresentatonsParams") public void shouldSearchRepresentations(String threshold, int limit, int fromIndex, int toIndex, String nextSlice) { List<Representation> representations = createRepresentations(5, PROVIDER_ID, SCHEMA); when(recordDAO.findRepresentations(PROVIDER_ID, SCHEMA)).thenReturn(representations); InMemoryRecordService recordService = new InMemoryRecordService(recordDAO, null, null, null); RepresentationSearchParams searchParams = RepresentationSearchParams.builder().setDataProvider(PROVIDER_ID) .setSchema(SCHEMA).build(); ResultSlice<Representation> actual = recordService.search(searchParams, threshold, limit); assertEquals("List of representations are not equal. ", representations.subList(fromIndex, toIndex), actual.getResults()); assertEquals("Next slice ", actual.getNextSlice(), nextSlice); }
### Question: DataSetServiceClient extends MCSClient { public List<DataSet> getDataSetsForProvider(String providerId) throws MCSException { List<DataSet> resultList = new ArrayList<>(); ResultSlice resultSlice; String startFrom = null; do { resultSlice = getDataSetsForProviderChunk(providerId, startFrom); if (resultSlice == null || resultSlice.getResults() == null) { throw new DriverException("Getting DataSet: result chunk obtained but is empty."); } resultList.addAll(resultSlice.getResults()); startFrom = resultSlice.getNextSlice(); } while (resultSlice.getNextSlice() != null); return resultList; } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password, final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk( String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet( String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet( String providerId, String dataSetId, String cloudId, String representationName, String version, String key, String value); void unassignRepresentationFromDataSet( String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk( String providerId, String dataSetId, String representationName, String revisionName, String revisionProviderId, String revisionTimestamp, String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions( String providerId, String dataSetId, String representationName, String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId, String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk( String dataSetId, String providerId, String revisionProvider, String revisionName, String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision( String dataSetId, String providerId, String revisionProvider, String revisionName, String representationName, Boolean isDeleted); String getLatelyTaggedRecords( String dataSetId, String providerId, String cloudId, String representationName, String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); }### Answer: @Betamax(tape = "dataSets_shouldReturnAllDataSets") @Test public void shouldReturnAllDataSets() throws MCSException { String providerId = "Provider002"; int resultSize = 200; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); List<DataSet> result = instance.getDataSetsForProvider(providerId); assertNotNull(result); assertEquals(result.size(), resultSize); } @Betamax(tape = "dataSets_shouldNotThrowProviderNotExistsForDataSetsAll") @Test public void shouldNotThrowProviderNotExistsForDataSetsAll() throws MCSException { String providerId = "notFoundProviderId"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); List<DataSet> result = instance.getDataSetsForProvider(providerId); assertNotNull(result); assertEquals(result.size(), 0); }
### Question: AuthenticationResource { @PostMapping(value = "/create-user", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasRole('ROLE_ADMIN')") public ResponseEntity<String> createCloudUser( @RequestParam(AASParamConstants.P_USER_NAME) String username, @RequestParam(AASParamConstants.P_PASS_TOKEN) String password) throws DatabaseConnectionException, UserExistsException, InvalidUsernameException, InvalidPasswordException { authenticationService.createUser(new User(username, password)); return ResponseEntity.ok("Cloud user was created!"); } @PostMapping(value = "/create-user", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasRole('ROLE_ADMIN')") ResponseEntity<String> createCloudUser( @RequestParam(AASParamConstants.P_USER_NAME) String username, @RequestParam(AASParamConstants.P_PASS_TOKEN) String password); @PostMapping(value = "/delete-user", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasRole('ROLE_ADMIN')") ResponseEntity<String> deleteCloudUser( @RequestParam(AASParamConstants.P_USER_NAME) String username); @PostMapping(value = "/update-user", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasRole('ROLE_ADMIN')") ResponseEntity<String> updateCloudUser( @RequestParam(AASParamConstants.P_USER_NAME) String username, @RequestParam(AASParamConstants.P_PASS_TOKEN) String password); }### Answer: @Test public void testCreateCloudUser() throws Exception { Mockito.doReturn(new User(username, password)).when(authenticationService).getUser(username); mockMvc.perform(post("/create-user") .param(AASParamConstants.P_USER_NAME, username) .param(AASParamConstants.P_PASS_TOKEN, password)) .andExpect(status().isOk()); }
### Question: MCSExceptionProvider { public static MCSException generateException(ErrorInfo errorInfo) { if (errorInfo == null) { throw new DriverException("Null errorInfo passed to generating exception."); } McsErrorCode errorCode; try { errorCode = McsErrorCode.valueOf(errorInfo.getErrorCode()); } catch (IllegalArgumentException e) { throw new DriverException("Unknown errorCode returned from service.", e); } String details = errorInfo.getDetails(); switch (errorCode) { case ACCESS_DENIED_OR_OBJECT_DOES_NOT_EXIST_EXCEPTION: return new AccessDeniedOrObjectDoesNotExistException(details); case CANNOT_MODIFY_PERSISTENT_REPRESENTATION: return new CannotModifyPersistentRepresentationException(details); case DATASET_ALREADY_EXISTS: return new DataSetAlreadyExistsException(details); case DATASET_NOT_EXISTS: return new DataSetNotExistsException(details); case FILE_ALREADY_EXISTS: return new FileAlreadyExistsException(details); case FILE_NOT_EXISTS: return new FileNotExistsException(details); case PROVIDER_NOT_EXISTS: return new ProviderNotExistsException(details); case RECORD_NOT_EXISTS: return new RecordNotExistsException(details); case REPRESENTATION_NOT_EXISTS: return new RepresentationNotExistsException(details); case VERSION_NOT_EXISTS: return new VersionNotExistsException(details); case FILE_CONTENT_HASH_MISMATCH: return new FileContentHashMismatchException(details); case REPRESENTATION_ALREADY_IN_SET: return new RepresentationAlreadyInSet(details); case CANNOT_PERSIST_EMPTY_REPRESENTATION: return new CannotPersistEmptyRepresentationException(details); case WRONG_CONTENT_RANGE: return new WrongContentRangeException(details); case OTHER: throw new DriverException(details); default: return new MCSException(details); } } private MCSExceptionProvider(); static MCSException generateException(ErrorInfo errorInfo); }### Answer: @Test(expected = DriverException.class) public void shouldThrowDriverExceptionWhenNullErrorInfoPassed() { ErrorInfo errorInfo = null; MCSExceptionProvider.generateException(errorInfo); } @Test(expected = DriverException.class) public void shouldThrowDriverExceptionWhenUnknownErrorInfoCodePassed() { ErrorInfo errorInfo = new ErrorInfo("THIS_IS_REALLY_WRONG_CODE", null); MCSExceptionProvider.generateException(errorInfo); } @Test @Parameters(method = "statusCodes") public void shouldReturnCorrectException(Throwable ex, String errorCode) { ErrorInfo errorInfo = new ErrorInfo(errorCode, "details"); MCSException exception = MCSExceptionProvider.generateException(errorInfo); Assert.assertEquals(ex.getClass(), exception.getClass()); assertThat(exception.getMessage(), is(errorInfo.getDetails())); } @Test public void shouldReturnRecordNotExistsException() { ErrorInfo errorInfo = new ErrorInfo(McsErrorCode.RECORD_NOT_EXISTS.toString(), "details"); MCSException exception = MCSExceptionProvider.generateException(errorInfo); assertTrue(exception instanceof RecordNotExistsException); assertThat(exception.getMessage(), is("There is no record with provided global id: " + errorInfo.getDetails())); } @Test(expected = DriverException.class) public void shouldThrowDriverException() { ErrorInfo errorInfo = new ErrorInfo(McsErrorCode.OTHER.toString(), "details"); MCSExceptionProvider.generateException(errorInfo); }
### Question: CassandraAuthenticationService implements UserDetailsService, AuthenticationService { @Override public User getUser(String userName) throws DatabaseConnectionException, UserDoesNotExistException { return userDao.getUser(userName); } CassandraAuthenticationService(); CassandraAuthenticationService(CassandraUserDAO userDao); @Override UserDetails loadUserByUsername(final String userName); @Override User getUser(String userName); @Override void createUser(final User user); @Override void updateUser(final User user); @Override void deleteUser(final String userName); }### Answer: @Test(expected = UserDoesNotExistException.class) public void testUserDoesNotExist() throws Exception { service.getUser("test2"); }
### Question: CassandraAuthenticationService implements UserDetailsService, AuthenticationService { @Override public void deleteUser(final String userName) throws DatabaseConnectionException, UserDoesNotExistException { userDao.deleteUser(userName); } CassandraAuthenticationService(); CassandraAuthenticationService(CassandraUserDAO userDao); @Override UserDetails loadUserByUsername(final String userName); @Override User getUser(String userName); @Override void createUser(final User user); @Override void updateUser(final User user); @Override void deleteUser(final String userName); }### Answer: @Test(expected = UserDoesNotExistException.class) public void testDeleteUser() throws Exception { dao.createUser(new SpringUser("test3", "test3")); service.deleteUser("test3"); service.getUser("test3"); } @Test(expected = UserDoesNotExistException.class) public void testDeleteUserException() throws Exception { service.deleteUser("test4"); }
### Question: RemoverImpl implements Remover { @Override public void removeNotifications(long taskId) { int retries = DEFAULT_RETRIES; while (true) { try { subTaskInfoDAO.removeNotifications(taskId); break; } catch (Exception e) { if (retries-- > 0) { LOGGER.warn("Error while removing the logs. Retries left: " + retries); waitForTheNextCall(); } else { LOGGER.error("Error while removing the logs."); throw e; } } } } RemoverImpl(String hosts, int port, String keyspaceName, String userName, String password); RemoverImpl(CassandraSubTaskInfoDAO subTaskInfoDAO, CassandraTaskErrorsDAO taskErrorDAO, CassandraNodeStatisticsDAO cassandraNodeStatisticsDAO); @Override void removeNotifications(long taskId); @Override void removeErrorReports(long taskId); @Override void removeStatistics(long taskId); }### Answer: @Test public void shouldSuccessfullyRemoveNotifications() { doNothing().when(subTaskInfoDAO).removeNotifications(eq(TASK_ID)); removerImpl.removeNotifications(TASK_ID); verify(subTaskInfoDAO, times(1)).removeNotifications((eq(TASK_ID))); } @Test(expected = Exception.class) public void shouldRetry5TimesBeforeFailing() { doThrow(Exception.class).when(subTaskInfoDAO).removeNotifications(eq(TASK_ID)); removerImpl.removeNotifications(TASK_ID); verify(subTaskInfoDAO, times(6)).removeNotifications((eq(TASK_ID))); }
### Question: CassandraAclService implements AclService { @Override public Acl readAclById(ObjectIdentity object) throws NotFoundException { return readAclById(object, null); } CassandraAclService(AclRepository aclRepository, AclCache aclCache, PermissionGrantingStrategy grantingStrategy, AclAuthorizationStrategy aclAuthorizationStrategy, PermissionFactory permissionFactory); @Override List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity); @Override Acl readAclById(ObjectIdentity object); @Override Acl readAclById(ObjectIdentity object, List<Sid> sids); @Override Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects); @Override Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids); }### Answer: @Test(expected = NotFoundException.class) public void testCreateAndRetrieve() throws Exception { TestingAuthenticationToken auth = new TestingAuthenticationToken(creator, creator); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity obj = new ObjectIdentityImpl(testKey, testValue); MutableAcl acl = mutableAclService.createAcl(obj); acl.insertAce(0, BasePermission.READ, new PrincipalSid(creator), true); acl.insertAce(1, BasePermission.WRITE, new PrincipalSid(creator), true); acl.insertAce(2, BasePermission.DELETE, new PrincipalSid(creator), true); acl.insertAce(3, BasePermission.ADMINISTRATION, new PrincipalSid(creator), true); mutableAclService.updateAcl(acl); Acl readAcl = mutableAclService.readAclById(obj); Assert.assertTrue(acl.getEntries().size() == readAcl.getEntries().size()); mutableAclService.readAclById(new ObjectIdentityImpl(testKey, creator)); }
### Question: RecordServiceClient extends MCSClient { public Record getRecord(String cloudId) throws MCSException { WebTarget target = client .target(baseUrl) .path(RECORDS_RESOURCE) .resolveTemplate(CLOUD_ID, cloudId); Builder request = target.request(); Response response = null; try { response = request.get(); if (response.getStatus() == Response.Status.OK.getStatusCode()) { return response.readEntity(Record.class); } ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } finally { closeResponse(response); } } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password, final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId, String representationName, String providerId, InputStream data, String fileName, String mediaType); URI createRepresentation(String cloudId, String representationName, String providerId, InputStream data, String fileName, String mediaType, String key, String value); URI createRepresentation(String cloudId, String representationName, String providerId, InputStream data, String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName, String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version, String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version, String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version, String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision( String cloudId, String representationName, String revisionName, String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision( String cloudId, String representationName, String revisionName, String revisionProviderId, String revisionTimestamp, String key, String value); void close(); }### Answer: @Betamax(tape = "records_shouldRetrieveRecord") @Test public void shouldRetrieveRecord() throws MCSException { RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); Record record = instance.getRecord(CLOUD_ID); assertNotNull(record); assertEquals(CLOUD_ID, record.getCloudId()); } @Betamax(tape = "records_shouldThrowRecordNotExistsForGetRecord") @Test(expected = RecordNotExistsException.class) public void shouldThrowRecordNotExistsForGetRecord() throws MCSException { String cloudId = "noSuchRecord"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.getRecord(cloudId); }
### Question: RecordServiceClient extends MCSClient { public void deleteRecord(String cloudId) throws MCSException { WebTarget target = client .target(baseUrl) .path(RECORDS_RESOURCE) .resolveTemplate(CLOUD_ID, cloudId); Builder request = target.request(); handleDeleteRequest(request); } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password, final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId, String representationName, String providerId, InputStream data, String fileName, String mediaType); URI createRepresentation(String cloudId, String representationName, String providerId, InputStream data, String fileName, String mediaType, String key, String value); URI createRepresentation(String cloudId, String representationName, String providerId, InputStream data, String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName, String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version, String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version, String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version, String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision( String cloudId, String representationName, String revisionName, String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision( String cloudId, String representationName, String revisionName, String revisionProviderId, String revisionTimestamp, String key, String value); void close(); }### Answer: @Betamax(tape = "records_shouldThrowRecordNotExistsForDeleteRecord") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRecordNotExistsForDeleteRecord() throws MCSException { String cloudId = "noSuchRecord"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.deleteRecord(cloudId); }
### Question: CassandraAclRepository implements AclRepository { @Override public Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup) { assertAclObjectIdentityList(objectIdsToLookup); if (LOG.isDebugEnabled()) { LOG.debug("BEGIN findAcls: objectIdentities: " + objectIdsToLookup); } List<String> ids = new ArrayList<>(objectIdsToLookup.size()); for (AclObjectIdentity entry : objectIdsToLookup) { ids.add(entry.getRowId()); } ResultSet resultSet = session.execute(QueryBuilder.select().all().from(keyspace, AOI_TABLE) .where(QueryBuilder.in("id", ids.toArray())).setConsistencyLevel(ConsistencyLevel.QUORUM)); Map<AclObjectIdentity, Set<AclEntry>> resultMap = new HashMap<>(); for (Row row : resultSet.all()) { resultMap.put(convertToAclObjectIdentity(row, true), new TreeSet<>(new Comparator<AclEntry>() { @Override public int compare(AclEntry o1, AclEntry o2) { return Integer.compare(o1.getOrder(), o2.getOrder()); } })); } resultSet = session.execute(QueryBuilder.select().all().from(keyspace, ACL_TABLE) .where(QueryBuilder.in("id", ids.toArray())).setConsistencyLevel(ConsistencyLevel.QUORUM)); for (Row row : resultSet.all()) { String aoiId = row.getString("id"); AclEntry aclEntry = new AclEntry(); aclEntry.setAuditFailure(row.getBool("isAuditFailure")); aclEntry.setAuditSuccess(row.getBool("isAuditSuccess")); aclEntry.setGranting(row.getBool("isGranting")); aclEntry.setMask(row.getInt("mask")); aclEntry.setOrder(row.getInt("aclOrder")); aclEntry.setSid(row.getString("sid")); aclEntry.setSidPrincipal(row.getBool("isSidPrincipal")); aclEntry.setId(aoiId + ":" + aclEntry.getSid() + ":" + aclEntry.getOrder()); for (Entry<AclObjectIdentity, Set<AclEntry>> entry : resultMap.entrySet()) { if (entry.getKey().getRowId().equals(aoiId)) { entry.getValue().add(aclEntry); break; } } } if (LOG.isDebugEnabled()) { LOG.debug("END findAcls: objectIdentities: " + resultMap.keySet() + ", aclEntries: " + resultMap.values()); } return resultMap; } CassandraAclRepository(CassandraConnectionProvider provider, boolean initSchema); CassandraAclRepository(Session session, String keyspace); CassandraAclRepository(Session session, String keyspace, boolean initSchema); @Override Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup); @Override AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId); @Override List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId); @Override void deleteAcls(List<AclObjectIdentity> objectIdsToDelete); @Override void saveAcl(AclObjectIdentity aoi); @Override void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries); void createAoisTable(); void createChilrenTable(); void createAclsTable(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testFindAclListEmpty() { service.findAcls(new ArrayList<AclObjectIdentity>()); } @Test(expected = IllegalArgumentException.class) public void testFindNullAclList() { service.findAcls(null); }
### Question: CassandraAclRepository implements AclRepository { @Override public AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId) { assertAclObjectIdentity(objectId); if (LOG.isDebugEnabled()) { LOG.debug("BEGIN findAclObjectIdentity: objectIdentity: " + objectId); } Row row = session .execute(QueryBuilder.select().all().from(keyspace, AOI_TABLE) .where(QueryBuilder.eq("id", objectId.getRowId())).setConsistencyLevel(ConsistencyLevel.QUORUM)) .one(); AclObjectIdentity objectIdentity = convertToAclObjectIdentity(row, true); if (LOG.isDebugEnabled()) { LOG.debug("END findAclObjectIdentity: objectIdentity: " + objectIdentity); } return objectIdentity; } CassandraAclRepository(CassandraConnectionProvider provider, boolean initSchema); CassandraAclRepository(Session session, String keyspace); CassandraAclRepository(Session session, String keyspace, boolean initSchema); @Override Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup); @Override AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId); @Override List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId); @Override void deleteAcls(List<AclObjectIdentity> objectIdsToDelete); @Override void saveAcl(AclObjectIdentity aoi); @Override void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries); void createAoisTable(); void createChilrenTable(); void createAclsTable(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testFindNullAcl() { service.findAclObjectIdentity(null); } @Test public void testFindAclNotExisting() { AclObjectIdentity newAoi = new AclObjectIdentity(); newAoi.setId("invalid"); newAoi.setObjectClass(aoi_class); newAoi.setOwnerId(sid1); service.findAclObjectIdentity(newAoi); } @Test(expected = IllegalArgumentException.class) public void testFindAclWithNullValues() { AclObjectIdentity newAoi = new AclObjectIdentity(); service.findAclObjectIdentity(newAoi); }
### Question: RecordServiceClient extends MCSClient { public void revokePermissionsToVersion(String cloudId, String representationName, String version, String userName, Permission permission) throws MCSException { WebTarget target = client .target(baseUrl) .path(REPRESENTATION_PERMISSION) .resolveTemplate(CLOUD_ID, cloudId) .resolveTemplate(REPRESENTATION_NAME, representationName) .resolveTemplate(VERSION, version) .resolveTemplate(PERMISSION, permission.getValue()) .resolveTemplate(USER_NAME, userName); Builder request = target.request(); handleDeleteRequest(request); } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password, final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId, String representationName, String providerId, InputStream data, String fileName, String mediaType); URI createRepresentation(String cloudId, String representationName, String providerId, InputStream data, String fileName, String mediaType, String key, String value); URI createRepresentation(String cloudId, String representationName, String providerId, InputStream data, String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName, String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version, String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version, String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version, String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision( String cloudId, String representationName, String revisionName, String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision( String cloudId, String representationName, String revisionName, String revisionProviderId, String revisionTimestamp, String key, String value); void close(); }### Answer: @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) @Betamax(tape = "records_shouldThrowAccessDeniedOrObjectDoesNotExistExceptionWhileTryingToRevokePermissions") public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionWhileTryingToRevokePermissions() throws MCSException, IOException { RecordServiceClient client = new RecordServiceClient("http: client.revokePermissionsToVersion(CLOUD_ID, REPRESENTATION_NAME, VERSION, "user", Permission.READ); }
### Question: CassandraDataProviderService implements DataProviderService { @Override public DataProvider getProvider(String providerId) throws ProviderDoesNotExistException { LOGGER.info("getProvider() providerId='{}'", providerId); DataProvider dp = dataProviderDao.getProvider(providerId); if (dp == null) { LOGGER.warn("ProviderDoesNotExistException providerId='{}''", providerId); throw new ProviderDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getErrorInfo(providerId))); } else { return dp; } } CassandraDataProviderService(CassandraDataProviderDAO dataProviderDao); @Override ResultSlice<DataProvider> getProviders(String thresholdProviderId, int limit); @Override DataProvider getProvider(String providerId); @Override DataProvider createProvider(String providerId, DataProviderProperties properties); @Override DataProvider updateProvider(String providerId, DataProviderProperties properties); @Override DataProvider updateProvider(DataProvider dataProvider); @Override void deleteProvider(String providerId); }### Answer: @Test(expected = ProviderDoesNotExistException.class) public void shouldFailWhenFetchingNonExistingProvider() throws ProviderDoesNotExistException { cassandraDataProviderService.getProvider("provident"); }
### Question: CassandraDataProviderService implements DataProviderService { @Override public ResultSlice<DataProvider> getProviders(String thresholdProviderId, int limit) { LOGGER.info("getProviders() thresholdProviderId='{}', limit='{}'", thresholdProviderId, limit); String nextProvider = null; List<DataProvider> providers = dataProviderDao.getProviders(thresholdProviderId, limit + 1); final int providerSize = providers.size(); if (providerSize == limit + 1) { nextProvider = providers.get(limit).getId(); providers.remove(limit); } LOGGER.info("getProviders() returning providers={} and nextProvider={} for thresholdProviderId='{}', limit='{}'", providerSize, nextProvider, thresholdProviderId, limit); return new ResultSlice<DataProvider>(nextProvider, providers); } CassandraDataProviderService(CassandraDataProviderDAO dataProviderDao); @Override ResultSlice<DataProvider> getProviders(String thresholdProviderId, int limit); @Override DataProvider getProvider(String providerId); @Override DataProvider createProvider(String providerId, DataProviderProperties properties); @Override DataProvider updateProvider(String providerId, DataProviderProperties properties); @Override DataProvider updateProvider(DataProvider dataProvider); @Override void deleteProvider(String providerId); }### Answer: @Test public void shouldReturnEmptyArrayWhenNoProviderAdded() { assertTrue("Expecting no providers", cassandraDataProviderService.getProviders(null, 1).getResults().isEmpty()); }
### Question: CassandraDataProviderService implements DataProviderService { @Override public void deleteProvider(String providerId) throws ProviderDoesNotExistException { LOGGER.info("Deleting provider {}", providerId); DataProvider dp = dataProviderDao.getProvider(providerId); if (dp == null) { LOGGER.warn("ProviderDoesNotExistException providerId='{}'", providerId); throw new ProviderDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getErrorInfo(providerId))); } dataProviderDao.deleteProvider(providerId); } CassandraDataProviderService(CassandraDataProviderDAO dataProviderDao); @Override ResultSlice<DataProvider> getProviders(String thresholdProviderId, int limit); @Override DataProvider getProvider(String providerId); @Override DataProvider createProvider(String providerId, DataProviderProperties properties); @Override DataProvider updateProvider(String providerId, DataProviderProperties properties); @Override DataProvider updateProvider(DataProvider dataProvider); @Override void deleteProvider(String providerId); }### Answer: @Test(expected = ProviderDoesNotExistException.class) public void shouldThrowExceptionWhenDeletingNonExistingProvider() throws ProviderDoesNotExistException { cassandraDataProviderService.deleteProvider("not existing provident"); }
### Question: CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public CloudId getCloudId(String providerId, String recordId) throws DatabaseConnectionException, RecordDoesNotExistException { LOGGER.info("getCloudId() providerId='{}', recordId='{}'", providerId, recordId); List<CloudId> cloudIds = localIdDao.searchById(providerId, recordId); if (cloudIds.isEmpty()) { throw new RecordDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.RECORD_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.RECORD_DOES_NOT_EXIST.getErrorInfo(providerId, recordId))); } final CloudId cloudId = cloudIds.get(0); LOGGER.info("getCloudId() returning cloudId='{}'", cloudId); return cloudId; } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao, CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); }### Answer: @Test(expected = RecordDoesNotExistException.class) public void testRecordDoesNotExist() throws Exception { service.getCloudId("test2", "test2"); }
### Question: CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public List<CloudId> getLocalIdsByCloudId(String cloudId) throws DatabaseConnectionException, CloudIdDoesNotExistException { LOGGER.info("getLocalIdsByCloudId() cloudId='{}'", cloudId); List<CloudId> cloudIds = cloudIdDao.searchById(cloudId); if (cloudIds.isEmpty()) { LOGGER.warn("CloudIdDoesNotExistException for cloudId={}", cloudId); throw new CloudIdDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.CLOUDID_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.CLOUDID_DOES_NOT_EXIST.getErrorInfo(cloudId))); } List<CloudId> localIds = new ArrayList<>(); for (CloudId cId : cloudIds) { if (localIdDao.searchById(cId.getLocalId().getProviderId(), cId.getLocalId().getRecordId()).size() > 0) { localIds.add(cId); } } return localIds; } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao, CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); }### Answer: @Test(expected = CloudIdDoesNotExistException.class) public void testGetLocalIdsByCloudId() throws Exception { List<CloudId> gid = service.getLocalIdsByCloudId(IdGenerator .encodeWithSha256AndBase32("/test11/test11")); CloudId gId = service.createCloudId("test11", "test11"); gid = service.getLocalIdsByCloudId(gId.getId()); assertEquals(gid.size(), 1); }
### Question: CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit) throws DatabaseConnectionException, ProviderDoesNotExistException { LOGGER.info("getCloudIdsByProvider() providerId='{}', startRecordId='{}', end='{}'", providerId, startRecordId, limit); if (dataProviderDao.getProvider(providerId) == null) { LOGGER.warn("ProviderDoesNotExistException for providerId='{}', startRecordId='{}', end='{}'", providerId, startRecordId, limit); throw new ProviderDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getErrorInfo(providerId))); } if (startRecordId == null) { return localIdDao.searchById(providerId); } else { return localIdDao.searchByIdWithPagination(startRecordId, limit, providerId); } } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao, CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); }### Answer: @Test public void testGetCloudIdsByProvider() throws Exception { String providerId = "providerId"; dataProviderDao.createDataProvider(providerId, new DataProviderProperties()); service.createCloudId(providerId, "test3"); service.createCloudId(providerId, "test2"); List<CloudId> cIds = service .getCloudIdsByProvider(providerId, null, 10000); assertThat(cIds.size(), is(2)); }
### Question: CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public CloudId createIdMapping(String cloudId, String providerId, String recordId) throws DatabaseConnectionException, CloudIdDoesNotExistException, IdHasBeenMappedException, ProviderDoesNotExistException, CloudIdAlreadyExistException { LOGGER.info("createIdMapping() creating mapping for cloudId='{}', providerId='{}', recordId='{}'", cloudId, providerId, recordId); if (dataProviderDao.getProvider(providerId) == null) { LOGGER.warn("ProviderDoesNotExistException for cloudId='{}', providerId='{}', recordId='{}'", cloudId, providerId, recordId); throw new ProviderDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getErrorInfo(providerId))); } List<CloudId> cloudIds = cloudIdDao.searchById(cloudId); if (cloudIds.isEmpty()) { LOGGER.warn("CloudIdDoesNotExistException for cloudId='{}', providerId='{}', recordId='{}'", cloudId, providerId, recordId); throw new CloudIdDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.CLOUDID_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.CLOUDID_DOES_NOT_EXIST.getErrorInfo(cloudId))); } List<CloudId> localIds = localIdDao.searchById(providerId, recordId); if (!localIds.isEmpty()) { LOGGER.warn("IdHasBeenMappedException for cloudId='{}', providerId='{}', recordId='{}'", cloudId, providerId, recordId); throw new IdHasBeenMappedException(new IdentifierErrorInfo( IdentifierErrorTemplate.ID_HAS_BEEN_MAPPED.getHttpCode(), IdentifierErrorTemplate.ID_HAS_BEEN_MAPPED.getErrorInfo(providerId, recordId, cloudId))); } localIdDao.insert(providerId, recordId, cloudId); cloudIdDao.insert(false, cloudId, providerId, recordId); CloudId newCloudId = new CloudId(); newCloudId.setId(cloudId); LocalId lid = new LocalId(); lid.setProviderId(providerId); lid.setRecordId(recordId); newCloudId.setLocalId(lid); LOGGER.info("createIdMapping() new mapping created! new cloudId='{}' for already " + "existing cloudId='{}', providerId='{}', recordId='{}'", newCloudId, cloudId, providerId, recordId); return newCloudId; } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao, CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); }### Answer: @Test(expected = IdHasBeenMappedException.class) public void testCreateIdMapping() throws Exception { dataProviderDao.createDataProvider("test12", new DataProviderProperties()); CloudId gid = service.createCloudId("test12", "test12"); service.createIdMapping(gid.getId(), "test12", "test13"); service.createIdMapping(gid.getId(), "test12", "test13"); }
### Question: CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public void removeIdMapping(String providerId, String recordId) throws DatabaseConnectionException, ProviderDoesNotExistException { LOGGER.info("removeIdMapping() removing Id mapping for providerId='{}', recordId='{}' ...", providerId, recordId); if (dataProviderDao.getProvider(providerId) == null) { LOGGER.warn("ProviderDoesNotExistException for providerId='{}', recordId='{}'", providerId, recordId); throw new ProviderDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getErrorInfo(providerId))); } localIdDao.delete(providerId, recordId); LOGGER.info("Id mapping removed for providerId='{}', recordId='{}'", providerId, recordId); } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao, CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); }### Answer: @Test(expected = RecordDoesNotExistException.class) public void testRemoveIdMapping() throws Exception { dataProviderDao.createDataProvider("test16", new DataProviderProperties()); service.createCloudId("test16", "test16"); service.removeIdMapping("test16", "test16"); service.getCloudId("test16", "test16"); }
### Question: CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public List<CloudId> deleteCloudId(String cloudId) throws DatabaseConnectionException, CloudIdDoesNotExistException { LOGGER.info("deleteCloudId() deleting cloudId='{}' ...", cloudId); if (cloudIdDao.searchById(cloudId).isEmpty()) { LOGGER.warn("CloudIdDoesNotExistException for cloudId='{}'", cloudId); throw new CloudIdDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.CLOUDID_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.CLOUDID_DOES_NOT_EXIST.getErrorInfo(cloudId))); } List<CloudId> localIds = cloudIdDao.searchAll(cloudId); for (CloudId cId : localIds) { localIdDao.delete(cId.getLocalId().getProviderId(), cId.getLocalId().getRecordId()); cloudIdDao.delete(cloudId, cId.getLocalId().getProviderId(), cId.getLocalId().getRecordId()); } LOGGER.info("CloudId deleted for cloudId='{}'", cloudId); return localIds; } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao, CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); }### Answer: @Test(expected = RecordDoesNotExistException.class) public void testDeleteCloudId() throws Exception { dataProviderDao.createDataProvider("test21", new DataProviderProperties()); CloudId cId = service.createCloudId("test21", "test21"); service.deleteCloudId(cId.getId()); service.getCloudId(cId.getLocalId().getProviderId(), cId.getLocalId() .getRecordId()); } @Test(expected = CloudIdDoesNotExistException.class) public void testDeleteCloudIdException() throws Exception { service.deleteCloudId("test"); }
### Question: CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public CloudId createCloudId(String... recordInfo) throws DatabaseConnectionException, RecordExistsException, ProviderDoesNotExistException, CloudIdAlreadyExistException { LOGGER.info("createCloudId() creating cloudId"); String providerId = recordInfo[0]; LOGGER.info("createCloudId() creating cloudId providerId={}", providerId); if (dataProviderDao.getProvider(providerId) == null) { LOGGER.warn("ProviderDoesNotExistException for providerId={}", providerId); throw new ProviderDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getErrorInfo(providerId))); } String recordId = recordInfo.length > 1 ? recordInfo[1] : IdGenerator.timeEncode(providerId); LOGGER.info("createCloudId() creating cloudId providerId='{}', recordId='{}'", providerId, recordId); if (!localIdDao.searchById(providerId, recordId).isEmpty()) { LOGGER.warn("RecordExistsException for providerId={}, recordId={}", providerId, recordId); throw new RecordExistsException(new IdentifierErrorInfo( IdentifierErrorTemplate.RECORD_EXISTS.getHttpCode(), IdentifierErrorTemplate.RECORD_EXISTS.getErrorInfo(providerId, recordId))); } String id = IdGenerator.encodeWithSha256AndBase32("/" + providerId + "/" + recordId); List<CloudId> cloudIds = cloudIdDao.insert(false, id, providerId, recordId); localIdDao.insert(providerId, recordId, id); CloudId cloudId = new CloudId(); cloudId.setId(cloudIds.get(0).getId()); LocalId lId = new LocalId(); lId.setProviderId(providerId); lId.setRecordId(recordId); cloudId.setLocalId(lId); return cloudId; } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao, CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); }### Answer: @Test @Ignore public void createCloudIdCollisonTest() throws DatabaseConnectionException, RecordExistsException, ProviderDoesNotExistException, RecordDatasetEmptyException, CloudIdDoesNotExistException, CloudIdAlreadyExistException { final Map<String, String> map = new HashMap<String, String>(); dataProviderDao.createDataProvider("testprovider", new DataProviderProperties()); for (BigInteger bigCounter = BigInteger.ONE; bigCounter .compareTo(new BigInteger("5000000")) < 0; bigCounter = bigCounter .add(BigInteger.ONE)) { final String counterString = bigCounter.toString(32); final String encodedId = service.createCloudId("testprovider") .getId(); if (map.containsKey(encodedId)) { throw new RuntimeException("bigCounter: " + bigCounter + " | counterString: " + counterString + " | encodedId:" + encodedId + " == collision with ==> " + map.get(encodedId)); } else { map.put(encodedId, "bigCounter: " + bigCounter + " | counterString: " + counterString + " | encodedId:" + encodedId); } } }
### Question: CassandraCloudIdDAO { public List<CloudId> insert(boolean insertOnlyIfNoExist, String... args) throws DatabaseConnectionException, CloudIdAlreadyExistException { ResultSet rs = null; try { if (insertOnlyIfNoExist) { rs = dbService.getSession().execute(insertIfNoExistsStatement.bind(args[0], args[1], args[2])); Row row = rs.one(); if (!row.getBool("[applied]")) { throw new CloudIdAlreadyExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.CLOUDID_ALREADY_EXIST.getHttpCode(), IdentifierErrorTemplate.CLOUDID_ALREADY_EXIST.getErrorInfo(args[0]))); } } else { dbService.getSession().execute(insertStatement.bind(args[0], args[1], args[2])); } } catch (NoHostAvailableException e) { throw new DatabaseConnectionException(new IdentifierErrorInfo( IdentifierErrorTemplate.DATABASE_CONNECTION_ERROR.getHttpCode(), IdentifierErrorTemplate.DATABASE_CONNECTION_ERROR.getErrorInfo(hostList, port, e.getMessage()))); } CloudId cId = new CloudId(); LocalId lId = new LocalId(); lId.setProviderId(args[1]); lId.setRecordId(args[2]); cId.setLocalId(lId); cId.setId(args[0]); List<CloudId> cIds = new ArrayList<>(); cIds.add(cId); return cIds; } CassandraCloudIdDAO(CassandraConnectionProvider dbService); List<CloudId> searchById(String... args); List<CloudId> searchAll(String args); List<CloudId> insert(boolean insertOnlyIfNoExist, String... args); void delete(String... args); String getHostList(); String getKeyspace(); String getPort(); }### Answer: @Test(expected = CloudIdAlreadyExistException.class) public void insert_tryInsertTheSameContentTwice_ThrowsCloudIdAlreadyExistException() throws Exception { final String providerId = "providerId"; final String recordId = "recordId"; final String id = "id"; service.insert(true, id, providerId, recordId); service.insert(true, id, providerId, recordId); }
### Question: StaticUrlProvider implements UrlProvider { public String getBaseUrl() { return baseUrl; } StaticUrlProvider(final String serviceUrl); String getBaseUrl(); }### Answer: @Test @Parameters({"uis/,uis","uis,uis","uis public void shouldGetUrlWithoutSlashAtTheEnd(String inputSuffix, String expectedSuffix) { StaticUrlProvider provider = new StaticUrlProvider(URL_PREFIX + inputSuffix); String result = provider.getBaseUrl(); assertThat(result,is(URL_PREFIX + expectedSuffix)); }
### Question: DateAdapter extends XmlAdapter<String, Date> { @Override public Date unmarshal(String stringDate) throws ParseException { if (stringDate == null || stringDate.isEmpty()) { return null; } try { Date date = GregorianCalendar.getInstance().getTime(); if(date == null){ throw new ParseException("Cannot parse the date. The accepted date format is "+FORMAT, 0); } return date; } catch (ParseException e) { throw new ParseException(e.getMessage() + ". The accepted date format is "+FORMAT, e.getErrorOffset()); } } @Override String marshal(Date date); @Override Date unmarshal(String stringDate); }### Answer: @Test public void shouldSerializeTheDateSuccessfully() throws ParseException { Date date = dateAdapter.unmarshal(DATE_STRING); assertEquals(cal.getTime(), date); } @Test(expected = ParseException.class) public void shouldThrowParsingException() throws ParseException { String unParsedDateString = "2017-11-23"; dateAdapter.unmarshal(unParsedDateString); } @Test public void shouldCreateNullDateInCaseEmptyOrNull() throws ParseException { assertNull(dateAdapter.unmarshal(null)); assertNull(dateAdapter.unmarshal("")); }
### Question: DateAdapter extends XmlAdapter<String, Date> { @Override public String marshal(Date date) { if (date == null) { throw new RuntimeException("The revision creation Date shouldn't be null"); } return FORMATTER.format(date); } @Override String marshal(Date date); @Override Date unmarshal(String stringDate); }### Answer: @Test public void shouldDeSerializeTheDateSuccessfully() { assertEquals(dateAdapter.marshal(cal.getTime()), DATE_STRING); } @Test(expected = RuntimeException.class) public void shouldThrowRunTimeException() { dateAdapter.marshal(null); }
### Question: CassandraAclRepository implements AclRepository { @Override public List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId) { assertAclObjectIdentity(objectId); if (LOG.isDebugEnabled()) { LOG.debug("BEGIN findAclObjectIdentityChildren: objectIdentity: " + objectId); } ResultSet resultSet = session.execute(QueryBuilder.select().all().from(keyspace, CHILDREN_TABLE) .where(QueryBuilder.eq("id", objectId.getRowId())).setConsistencyLevel(ConsistencyLevel.QUORUM)); List<AclObjectIdentity> result = new ArrayList<>(); for (Row row : resultSet.all()) { result.add(convertToAclObjectIdentity(row, false)); } if (LOG.isDebugEnabled()) { LOG.debug("END findAclObjectIdentityChildren: children: " + result); } return result; } CassandraAclRepository(CassandraConnectionProvider provider, boolean initSchema); CassandraAclRepository(Session session, String keyspace); CassandraAclRepository(Session session, String keyspace, boolean initSchema); @Override Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup); @Override AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId); @Override List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId); @Override void deleteAcls(List<AclObjectIdentity> objectIdsToDelete); @Override void saveAcl(AclObjectIdentity aoi); @Override void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries); void createAoisTable(); void createChilrenTable(); void createAclsTable(); }### Answer: @Test public void testFindAclChildrenForNotExistingAcl() { AclObjectIdentity newAoi = new AclObjectIdentity(); newAoi.setId("invalid"); newAoi.setObjectClass(aoi_class); newAoi.setOwnerId(sid1); List<AclObjectIdentity> children = service .findAclObjectIdentityChildren(newAoi); assertTrue(children.isEmpty()); } @Test(expected = IllegalArgumentException.class) public void testFindNullAclChildren() { service.findAclObjectIdentityChildren(null); } @Test(expected = IllegalArgumentException.class) public void testFindAclChildrenWithNullValues() { AclObjectIdentity newAoi = new AclObjectIdentity(); service.findAclObjectIdentityChildren(newAoi); }
### Question: CassandraAclRepository implements AclRepository { @Override public void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries) throws AclNotFoundException { assertAclObjectIdentity(aoi); if (LOG.isDebugEnabled()) { LOG.debug("BEGIN updateAcl: aclObjectIdentity: " + aoi + ", entries: " + entries); } AclObjectIdentity persistedAoi = findAclObjectIdentity(aoi); if (persistedAoi == null) { throw new AclNotFoundException("Object identity '" + aoi + "' does not exist"); } Batch batch = QueryBuilder.batch(); batch.add(QueryBuilder.insertInto(keyspace, AOI_TABLE).values(AOI_KEYS, new Object[] { aoi.getRowId(), aoi.getId(), aoi.getObjectClass(), aoi.isEntriesInheriting(), aoi.getOwnerId(), aoi.isOwnerPrincipal(), aoi.getParentObjectId(), aoi.getParentObjectClass() })); batch.add(QueryBuilder.delete().all().from(keyspace, ACL_TABLE).where(QueryBuilder.eq("id", aoi.getRowId()))); boolean parentChanged = false; if (!(persistedAoi.getParentRowId() == null ? aoi.getParentRowId() == null : persistedAoi.getParentRowId().equals(aoi.getParentRowId()))) { parentChanged = true; if (persistedAoi.getParentRowId() != null) { batch.add(QueryBuilder.delete().all().from(keyspace, CHILDREN_TABLE) .where(QueryBuilder.eq("id", persistedAoi.getParentRowId())) .and(QueryBuilder.eq("childId", aoi.getRowId()))).setConsistencyLevel(ConsistencyLevel.QUORUM); } } session.execute(batch); batch = QueryBuilder.batch(); boolean executeBatch = false; if (entries != null && !entries.isEmpty()) { for (AclEntry entry : entries) { batch.add(QueryBuilder.insertInto(keyspace, ACL_TABLE).values(ACL_KEYS, new Object[] { aoi.getRowId(), entry.getOrder(), entry.getSid(), entry.getMask(), entry.isSidPrincipal(), entry.isGranting(), entry.isAuditSuccess(), entry.isAuditFailure() })); } executeBatch = true; } if (parentChanged) { if (aoi.getParentRowId() != null) { batch.add(QueryBuilder.insertInto(keyspace, CHILDREN_TABLE).values(CHILD_KEYS, new Object[] { aoi.getParentRowId(), aoi.getRowId(), aoi.getId(), aoi.getObjectClass() })) .setConsistencyLevel(ConsistencyLevel.QUORUM); } executeBatch = true; } if (executeBatch) { session.execute(batch); } if (LOG.isDebugEnabled()) { LOG.debug("END updateAcl"); } } CassandraAclRepository(CassandraConnectionProvider provider, boolean initSchema); CassandraAclRepository(Session session, String keyspace); CassandraAclRepository(Session session, String keyspace, boolean initSchema); @Override Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup); @Override AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId); @Override List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId); @Override void deleteAcls(List<AclObjectIdentity> objectIdsToDelete); @Override void saveAcl(AclObjectIdentity aoi); @Override void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries); void createAoisTable(); void createChilrenTable(); void createAclsTable(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testUpdateNullAcl() { service.updateAcl(null, null); } @Test(expected = AclNotFoundException.class) public void testUpdateAclNotExisting() { AclObjectIdentity newAoi = new AclObjectIdentity(); newAoi.setId("invalid"); newAoi.setObjectClass(aoi_class); newAoi.setOwnerId(sid1); service.updateAcl(newAoi, new ArrayList<AclEntry>()); }
### Question: CassandraAclRepository implements AclRepository { @Override public void saveAcl(AclObjectIdentity aoi) throws AclAlreadyExistsException { assertAclObjectIdentity(aoi); if (LOG.isDebugEnabled()) { LOG.debug("BEGIN saveAcl: aclObjectIdentity: " + aoi); } if (findAclObjectIdentity(aoi) != null) { throw new AclAlreadyExistsException("Object identity '" + aoi + "' already exists"); } Batch batch = QueryBuilder.batch(); batch.add(QueryBuilder.insertInto(keyspace, AOI_TABLE).values(AOI_KEYS, new Object[] { aoi.getRowId(), aoi.getId(), aoi.getObjectClass(), aoi.isEntriesInheriting(), aoi.getOwnerId(), aoi.isOwnerPrincipal(), aoi.getParentObjectId(), aoi.getParentObjectClass() })) .setConsistencyLevel(ConsistencyLevel.QUORUM); if (aoi.getParentRowId() != null) { batch.add(QueryBuilder.insertInto(keyspace, CHILDREN_TABLE).values(CHILD_KEYS, new Object[] { aoi.getParentRowId(), aoi.getRowId(), aoi.getId(), aoi.getObjectClass() })) .setConsistencyLevel(ConsistencyLevel.QUORUM); } session.execute(batch); if (LOG.isDebugEnabled()) { LOG.debug("END saveAcl"); } } CassandraAclRepository(CassandraConnectionProvider provider, boolean initSchema); CassandraAclRepository(Session session, String keyspace); CassandraAclRepository(Session session, String keyspace, boolean initSchema); @Override Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup); @Override AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId); @Override List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId); @Override void deleteAcls(List<AclObjectIdentity> objectIdsToDelete); @Override void saveAcl(AclObjectIdentity aoi); @Override void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries); void createAoisTable(); void createChilrenTable(); void createAclsTable(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testSaveNullAcl() { service.saveAcl(null); } @Test(expected = AclAlreadyExistsException.class) public void testSaveAclAlreadyExisting() { AclObjectIdentity newAoi = createDefaultTestAOI(); service.saveAcl(newAoi); service.saveAcl(newAoi); } @Test(expected = IllegalArgumentException.class) public void testSaveAclWithNullValues() { AclObjectIdentity newAoi = new AclObjectIdentity(); service.saveAcl(newAoi); }
### Question: CassandraAclRepository implements AclRepository { @Override public void deleteAcls(List<AclObjectIdentity> objectIdsToDelete) { assertAclObjectIdentityList(objectIdsToDelete); if (LOG.isDebugEnabled()) { LOG.debug("BEGIN deleteAcls: objectIdsToDelete: " + objectIdsToDelete); } List<String> ids = new ArrayList<>(objectIdsToDelete.size()); for (AclObjectIdentity entry : objectIdsToDelete) { ids.add(entry.getRowId()); } Batch batch = QueryBuilder.batch(); batch.add(QueryBuilder.delete().all().from(keyspace, AOI_TABLE).where(QueryBuilder.in("id", ids.toArray()))); batch.add(QueryBuilder.delete().all().from(keyspace, CHILDREN_TABLE) .where(QueryBuilder.in("id", ids.toArray()))).setConsistencyLevel(ConsistencyLevel.QUORUM); session.execute(batch); if (LOG.isDebugEnabled()) { LOG.debug("END deleteAcls"); } } CassandraAclRepository(CassandraConnectionProvider provider, boolean initSchema); CassandraAclRepository(Session session, String keyspace); CassandraAclRepository(Session session, String keyspace, boolean initSchema); @Override Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup); @Override AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId); @Override List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId); @Override void deleteAcls(List<AclObjectIdentity> objectIdsToDelete); @Override void saveAcl(AclObjectIdentity aoi); @Override void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries); void createAoisTable(); void createChilrenTable(); void createAclsTable(); }### Answer: @Test(expected = IllegalArgumentException.class) public void testDeleteNullAcl() { service.deleteAcls(null); } @Test public void testDeleteAclNotExisting() { AclObjectIdentity newAoi = new AclObjectIdentity(); newAoi.setId("invalid"); newAoi.setObjectClass(aoi_class); newAoi.setOwnerId(sid1); service.deleteAcls(Arrays.asList(new AclObjectIdentity[] { newAoi })); } @Test(expected = IllegalArgumentException.class) public void testDeleteEmptyAclList() { service.deleteAcls(new ArrayList<AclObjectIdentity>()); } @Test(expected = IllegalArgumentException.class) public void testDeleteAclWithNullValues() { AclObjectIdentity newAoi = new AclObjectIdentity(); service.deleteAcls(Arrays.asList(new AclObjectIdentity[] { newAoi })); }
### Question: BucketsHandler { public Bucket getCurrentBucket(String bucketsTableName, String objectId) { String query = "SELECT object_id, bucket_id, rows_count FROM " + bucketsTableName + " WHERE object_id = '" + objectId + "';"; ResultSet rs = session.execute(query); List<Row> rows = rs.all(); Row row = rows.isEmpty() ? null : rows.get(rows.size() - 1); if (row != null) { return new Bucket( row.getString(OBJECT_ID_COLUMN_NAME), row.getUUID(BUCKET_ID_COLUMN_NAME).toString(), row.getLong(ROWS_COUNT_COLUMN_NAME)); } return null; } BucketsHandler(Session session); Bucket getCurrentBucket(String bucketsTableName, String objectId); void increaseBucketCount(String bucketsTableName, Bucket bucket); void decreaseBucketCount(String bucketsTableName, Bucket bucket); List<Bucket> getAllBuckets(String bucketsTableName, String objectId); Bucket getBucket(String bucketsTableName, Bucket bucket); Bucket getNextBucket(String bucketsTableName, String objectId); Bucket getNextBucket(String bucketsTableName, String objectId, Bucket bucket); void removeBucket(String bucketsTableName, Bucket bucket); static final String OBJECT_ID_COLUMN_NAME; static final String BUCKET_ID_COLUMN_NAME; static final String ROWS_COUNT_COLUMN_NAME; }### Answer: @Test public void currentBucketShouldBeNull() { Bucket bucket = bucketsHandler.getCurrentBucket(BUCKETS_TABLE_NAME, "sampleObject"); Assert.assertNull(bucket); }
### Question: RemoverImpl implements Remover { @Override public void removeErrorReports(long taskId) { int retries = DEFAULT_RETRIES; while (true) { try { taskErrorDAO.removeErrors(taskId); break; } catch (Exception e) { if (retries-- > 0) { LOGGER.warn("Error while removing the error reports. Retries left: " + retries); waitForTheNextCall(); } else { LOGGER.error("Error while removing the error reports."); throw e; } } } } RemoverImpl(String hosts, int port, String keyspaceName, String userName, String password); RemoverImpl(CassandraSubTaskInfoDAO subTaskInfoDAO, CassandraTaskErrorsDAO taskErrorDAO, CassandraNodeStatisticsDAO cassandraNodeStatisticsDAO); @Override void removeNotifications(long taskId); @Override void removeErrorReports(long taskId); @Override void removeStatistics(long taskId); }### Answer: @Test public void shouldSuccessfullyRemoveErrors() { doNothing().when(taskErrorDAO).removeErrors(eq(TASK_ID)); removerImpl.removeErrorReports(TASK_ID); verify(taskErrorDAO, times(1)).removeErrors((eq(TASK_ID))); } @Test(expected = Exception.class) public void shouldRetry5TimesBeforeFailingWhileRemovingErrorReports() { doThrow(Exception.class).when(taskErrorDAO).removeErrors(eq(TASK_ID)); removerImpl.removeErrorReports(TASK_ID); verify(taskErrorDAO, times(6)).removeErrors((eq(TASK_ID))); }
### Question: BucketsHandler { public void increaseBucketCount(String bucketsTableName, Bucket bucket) { String query = "UPDATE " + bucketsTableName + " SET rows_count = rows_count + 1 WHERE object_id = '" + bucket.getObjectId() + "' AND bucket_id = " + UUID.fromString(bucket.getBucketId()) + ";"; session.execute(query); } BucketsHandler(Session session); Bucket getCurrentBucket(String bucketsTableName, String objectId); void increaseBucketCount(String bucketsTableName, Bucket bucket); void decreaseBucketCount(String bucketsTableName, Bucket bucket); List<Bucket> getAllBuckets(String bucketsTableName, String objectId); Bucket getBucket(String bucketsTableName, Bucket bucket); Bucket getNextBucket(String bucketsTableName, String objectId); Bucket getNextBucket(String bucketsTableName, String objectId, Bucket bucket); void removeBucket(String bucketsTableName, Bucket bucket); static final String OBJECT_ID_COLUMN_NAME; static final String BUCKET_ID_COLUMN_NAME; static final String ROWS_COUNT_COLUMN_NAME; }### Answer: @Test public void shouldCreateNewBucket() { Bucket bucket = new Bucket("sampleObjectId", new com.eaio.uuid.UUID().toString(), 0); bucketsHandler.increaseBucketCount(BUCKETS_TABLE_NAME, bucket); assertResults(bucket, 1); } @Test public void shouldUpdateCounterForExistingBucket() { Bucket bucket = new Bucket("sampleObjectId", new com.eaio.uuid.UUID().toString(), 0); bucketsHandler.increaseBucketCount(BUCKETS_TABLE_NAME, bucket); bucketsHandler.increaseBucketCount(BUCKETS_TABLE_NAME, bucket); assertResults(bucket, 2); }
### Question: StatisticsBolt extends AbstractDpsBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { try { if (!statsAlreadyCalculated(stormTaskTuple)) { LOGGER.info("Calculating file statistics for {}", stormTaskTuple); countStatistics(stormTaskTuple); markRecordStatsAsCalculated(stormTaskTuple); } else { LOGGER.info("File stats will NOT be calculated because if was already done in the previous attempt"); } stormTaskTuple.setFileData((byte[]) null); outputCollector.emit(anchorTuple, stormTaskTuple.toStormTuple()); } catch (Exception e) { emitErrorNotification(anchorTuple, stormTaskTuple.getTaskId(), stormTaskTuple.getFileUrl(), e.getMessage(), "Statistics for the given file could not be prepared.", StormTaskTupleHelper.getRecordProcessingStartTime(stormTaskTuple)); } outputCollector.ack(anchorTuple); } StatisticsBolt(String hosts, int port, String keyspaceName, String userName, String password); @Override void prepare(); @Override void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple); static final Logger LOGGER; }### Answer: @Test public void testCountStatisticsSuccessfully() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] fileData = Files.readAllBytes(Paths.get("src/test/resources/example1.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, fileData, new HashMap<String, String>(), new Revision()); List<NodeStatistics> generated = new RecordStatisticsGenerator(new String(fileData)).getStatistics(); statisticsBolt.execute(anchorTuple, tuple); assertSuccess(1); assertDataStoring(generated); } @Test public void testAggregatedCountStatisticsSuccessfully() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); Tuple anchorTuple2 = mock(TupleImpl.class); byte[] fileData = Files.readAllBytes(Paths.get("src/test/resources/example1.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, fileData, new HashMap<String, String>(), new Revision()); List<NodeStatistics> generated = new RecordStatisticsGenerator(new String(fileData)).getStatistics(); byte[] fileData2 = Files.readAllBytes(Paths.get("src/test/resources/example2.xml")); StormTaskTuple tuple2 = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, fileData2, new HashMap<String, String>(), new Revision()); List<NodeStatistics> generated2 = new RecordStatisticsGenerator(new String(fileData2)).getStatistics(); statisticsBolt.execute(anchorTuple, tuple); statisticsBolt.execute(anchorTuple2, tuple2); assertSuccess(2); assertDataStoring(generated, generated2); } @Test public void testCountStatisticsFailed() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] fileData = Files.readAllBytes(Paths.get("src/test/resources/example1.xml")); fileData[0] = 'X'; StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, fileData, new HashMap<String, String>(), new Revision()); statisticsBolt.execute(anchorTuple, tuple); assertFailure(); }
### Question: ValidationBolt extends AbstractDpsBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { try { reorderFileContent(stormTaskTuple); validateFileAndEmit(anchorTuple, stormTaskTuple); } catch (Exception e) { LOGGER.error("Validation Bolt error: {}", e.getMessage()); emitErrorNotification(anchorTuple, stormTaskTuple.getTaskId(), stormTaskTuple.getFileUrl(), e.getMessage(), "Error while validation. The full error :" + ExceptionUtils.getStackTrace(e), StormTaskTupleHelper.getRecordProcessingStartTime(stormTaskTuple)); } outputCollector.ack(anchorTuple); } ValidationBolt(Properties properties); @Override void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple); @Override void prepare(); static final Logger LOGGER; }### Answer: @Test public void validateEdmInternalFile() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] FILE_DATA = Files.readAllBytes(Paths.get("src/test/resources/Item_35834473_test.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, FILE_DATA, prepareStormTaskTupleParameters("edm-internal", null), new Revision()); validationBolt.execute(anchorTuple, tuple); assertSuccessfulValidation(); } @Test public void validateEdmInternalFileWithProvidedRootLocation() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] FILE_DATA = Files.readAllBytes(Paths.get("src/test/resources/Item_35834473_test.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, FILE_DATA, prepareStormTaskTupleParameters("edm-internal", "EDM-INTERNAL.xsd"), new Revision()); validationBolt.execute(anchorTuple, tuple); assertSuccessfulValidation(); } @Test public void validateEdmExternalFile() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] FILE_DATA = Files.readAllBytes(Paths.get("src/test/resources/Item_35834473.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, FILE_DATA, prepareStormTaskTupleParameters("edm-external", null), new Revision()); validationBolt.execute(anchorTuple, tuple); assertSuccessfulValidation(); } @Test public void validateEdmExternalOutOfOrderFile() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] FILE_DATA = Files.readAllBytes(Paths.get("src/test/resources/edmExternalWithOutOfOrderElements.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, FILE_DATA, prepareStormTaskTupleParameters("edm-external", null), new Revision()); validationBolt.execute(anchorTuple, tuple); assertSuccessfulValidation(); } @Test public void sendErrorNotificationWhenTheValidationFails() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] FILE_DATA = Files.readAllBytes(Paths.get("src/test/resources/Item_35834473_test.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, FILE_DATA, prepareStormTaskTupleParameters("edm-external", null), new Revision()); validationBolt.execute(anchorTuple, tuple); assertFailedValidation(); }
### Question: RecordStatisticsGenerator { public List<NodeStatistics> getStatistics() throws SAXException, IOException, ParserConfigurationException { Document doc = getParsedDocument(); doc.getDocumentElement().normalize(); Node root = doc.getDocumentElement(); addRootToNodeList(root); prepareNodeStatistics(root); return new ArrayList<>(nodeStatistics.values()); } RecordStatisticsGenerator(String fileContent); List<NodeStatistics> getStatistics(); }### Answer: @Test public void nodeContentsSizeShouldBeSmallerThanMaximumSize() throws Exception { String fileContent = readFile("src/test/resources/BigContent.xml"); RecordStatisticsGenerator xmlParser = new RecordStatisticsGenerator(fileContent); List<NodeStatistics> nodeModelList = xmlParser.getStatistics(); for (NodeStatistics nodeModel : nodeModelList) { assertTrue(nodeModel.getValue().length() <= MAX_SIZE); } }
### Question: RemoverImpl implements Remover { @Override public void removeStatistics(long taskId) { int retries = DEFAULT_RETRIES; while (true) { try { cassandraNodeStatisticsDAO.removeStatistics(taskId); break; } catch (Exception e) { if (retries-- > 0) { LOGGER.warn("Error while removing the validation statistics. Retries left: " + retries); waitForTheNextCall(); } else { LOGGER.error("rror while removing the validation statistics."); throw e; } } } } RemoverImpl(String hosts, int port, String keyspaceName, String userName, String password); RemoverImpl(CassandraSubTaskInfoDAO subTaskInfoDAO, CassandraTaskErrorsDAO taskErrorDAO, CassandraNodeStatisticsDAO cassandraNodeStatisticsDAO); @Override void removeNotifications(long taskId); @Override void removeErrorReports(long taskId); @Override void removeStatistics(long taskId); }### Answer: @Test public void shouldSuccessfullyRemoveStatistics() { doNothing().when(cassandraNodeStatisticsDAO).removeStatistics(eq(TASK_ID)); removerImpl.removeStatistics(TASK_ID); verify(cassandraNodeStatisticsDAO, times(1)).removeStatistics((eq(TASK_ID))); } @Test(expected = Exception.class) public void shouldRetry5TimesBeforeFailingWhileRemovingStatistics() { doThrow(Exception.class).when(cassandraNodeStatisticsDAO).removeStatistics(eq(TASK_ID)); removerImpl.removeStatistics(TASK_ID); verify(cassandraNodeStatisticsDAO, times(6)).removeStatistics((eq(TASK_ID))); }
### Question: HttpKafkaSpout extends CustomKafkaSpout { @Override public void deactivate() { LOGGER.info("Deactivate method was executed"); deactivateWaitingTasks(); deactivateCurrentTask(); LOGGER.info("Deactivate method was finished"); } HttpKafkaSpout(KafkaSpoutConfig spoutConf); HttpKafkaSpout(KafkaSpoutConfig spoutConf, String hosts, int port, String keyspaceName, String userName, String password); @Override void open(Map conf, TopologyContext context, SpoutOutputCollector collector); @Override void nextTuple(); @Override void declareOutputFields(OutputFieldsDeclarer declarer); @Override void deactivate(); }### Answer: @Test public void deactivateShouldClearTheTaskQueue() throws Exception { final int taskCount = 10; for (int i = 0; i < taskCount; i++) { httpKafkaSpout.taskDownloader.taskQueue.put(new DpsTask()); } assertTrue(!httpKafkaSpout.taskDownloader.taskQueue.isEmpty()); httpKafkaSpout.deactivate(); assertTrue(httpKafkaSpout.taskDownloader.taskQueue.isEmpty()); verify(cassandraTaskInfoDAO, atLeast(taskCount)).setTaskDropped(anyLong(), anyString()); }
### Question: ZipUnpackingService implements FileUnpackingService { public void unpackFile(final String compressedFilePath, final String destinationFolder) throws CompressionExtensionNotRecognizedException, IOException { final List<String> zipFiles = new ArrayList<>(); ZipUtil.unpack(new File(compressedFilePath), new File(destinationFolder), new NameMapper() { public String map(String name) { if (CompressionFileExtension.contains(FilenameUtils.getExtension(name))) { String compressedFilePath = destinationFolder + name; zipFiles.add(compressedFilePath); } return name; } }); for (String nestedCompressedFile : zipFiles) { String extension = FilenameUtils.getExtension(nestedCompressedFile); UnpackingServiceFactory.createUnpackingService(extension).unpackFile(nestedCompressedFile, FilenameUtils.removeExtension(nestedCompressedFile) + File.separator); } } void unpackFile(final String compressedFilePath, final String destinationFolder); }### Answer: @Test public void shouldUnpackTheZipFilesRecursively() throws CompressionExtensionNotRecognizedException, IOException { zipUnpackingService.unpackFile(DESTINATION_DIR + FILE_NAME + ZIP_EXTENSION, DESTINATION_DIR); Collection files = getXMLFiles(DESTINATION_DIR + DEFAULT_DESTINATION_NAME); assertNotNull(files); assertEquals(XML_FILES_COUNT,files.size()); } @Test public void shouldUnpackTheZipFilesWithNestedFoldersRecursively() throws CompressionExtensionNotRecognizedException, IOException { zipUnpackingService.unpackFile(DESTINATION_DIR + FILE_NAME2 + ZIP_EXTENSION, DESTINATION_DIR); Collection files = getXMLFiles(DESTINATION_DIR + DEFAULT_DESTINATION_NAME); assertNotNull(files); assertEquals(XML_FILES_COUNT,files.size()); } @Test public void shouldUnpackTheZipFilesWithNestedMixedCompressedFiles() throws CompressionExtensionNotRecognizedException, IOException { zipUnpackingService.unpackFile(DESTINATION_DIR + FILE_NAME3 + ZIP_EXTENSION, DESTINATION_DIR); Collection files = getXMLFiles(DESTINATION_DIR + DEFAULT_DESTINATION_NAME); assertNotNull(files); assertEquals(XML_FILES_COUNT,files.size()); }
### Question: GzUnpackingService implements FileUnpackingService { public void unpackFile(final String zipFile, final String destinationFolder) throws CompressionExtensionNotRecognizedException, IOException { String[] extensions = CompressionFileExtension.getExtensionValues(); unpackFile(zipFile, destinationFolder, extensions); } void unpackFile(final String zipFile, final String destinationFolder); static final String TAR; }### Answer: @Test public void shouldUnpackTheTarGzFilesRecursively() throws CompressionExtensionNotRecognizedException, IOException { gzUnpackingService.unpackFile(DESTINATION_DIR + FILE_NAME + ".tar.gz", DESTINATION_DIR); Collection files = getXMLFiles(DESTINATION_DIR + FILE_NAME); assertNotNull(files); assertEquals(XML_FILES_COUNT,files.size()); } @Test public void shouldUnpackTheTarGzFilesRecursivelyWithCompressedXMLFiles() throws CompressionExtensionNotRecognizedException, IOException { gzUnpackingService.unpackFile(DESTINATION_DIR + FILE_NAME2 + ".tar.gz", DESTINATION_DIR); Collection files = getXMLFiles(DESTINATION_DIR + FILE_NAME2); assertNotNull(files); assertEquals(XML_FILES_COUNT,files.size()); } @Test public void shouldUnpackTheTGZFilesRecursivelyWithCompressedXMLFiles() throws CompressionExtensionNotRecognizedException, IOException { gzUnpackingService.unpackFile(DESTINATION_DIR + FILE_NAME2 + ".tgz", DESTINATION_DIR); Collection files = getXMLFiles(DESTINATION_DIR + FILE_NAME2); assertNotNull(files); assertEquals(XML_FILES_COUNT,files.size()); } @Test public void shouldUnpackTheTarGzFilesRecursivelyWithMixedNestedCompressedFiles() throws CompressionExtensionNotRecognizedException, IOException { gzUnpackingService.unpackFile(DESTINATION_DIR + FILE_NAME3 + ".tar.gz", DESTINATION_DIR); Collection files = getXMLFiles(DESTINATION_DIR + FILE_NAME3); assertNotNull(files); assertEquals(XML_FILES_COUNT,files.size()); }
### Question: UnpackingServiceFactory { public static FileUnpackingService createUnpackingService(String compressingExtension) throws CompressionExtensionNotRecognizedException { if (compressingExtension.equals(CompressionFileExtension.ZIP.getExtension())) return ZIP_UNPACKING_SERVICE; else if (compressingExtension.equals(CompressionFileExtension.GZIP.getExtension()) || compressingExtension.equals(CompressionFileExtension.TGZIP.getExtension())) return GZ_UNPACKING_SERVICE; else throw new CompressionExtensionNotRecognizedException("This compression extension is not recognized " + compressingExtension); } static FileUnpackingService createUnpackingService(String compressingExtension); }### Answer: @Test public void shouldReturnZipService() throws CompressionExtensionNotRecognizedException { FileUnpackingService fileUnpackingService = UnpackingServiceFactory.createUnpackingService(ZIP_EXTENSION); assertTrue(fileUnpackingService instanceof ZipUnpackingService); } @Test public void shouldReturnGZipService() throws CompressionExtensionNotRecognizedException { FileUnpackingService fileUnpackingService = UnpackingServiceFactory.createUnpackingService(GZIP_EXTENSION); assertTrue(fileUnpackingService instanceof GzUnpackingService); } @Test public void shouldReturnGZipServiceFotTGZExtension() throws CompressionExtensionNotRecognizedException { FileUnpackingService fileUnpackingService = UnpackingServiceFactory.createUnpackingService(TGZIP_EXTENSION); assertTrue(fileUnpackingService instanceof GzUnpackingService); } @Test(expected = CompressionExtensionNotRecognizedException.class) public void shouldThrowExceptionIfTheExTensionWasNotRecognized() throws CompressionExtensionNotRecognizedException { UnpackingServiceFactory.createUnpackingService(UNDEFINED_COMPRESSION_EXTENSION); }
### Question: XsltBolt extends AbstractDpsBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { StringWriter writer = null; try { final String fileUrl = stormTaskTuple.getFileUrl(); final String xsltUrl = stormTaskTuple.getParameter(PluginParameterKeys.XSLT_URL); LOGGER.info("Processing file: {} with xslt schema:{}", fileUrl, xsltUrl); final XsltTransformer xsltTransformer = prepareXsltTransformer(stormTaskTuple); writer = xsltTransformer .transform(stormTaskTuple.getFileData(), prepareEuropeanaGeneratedIdsMap(stormTaskTuple)); LOGGER.info("XsltBolt: transformation success for: {}", fileUrl); stormTaskTuple.setFileData(writer.toString().getBytes(StandardCharsets.UTF_8)); final UrlParser urlParser = new UrlParser(fileUrl); if (urlParser.isUrlToRepresentationVersionFile()) { stormTaskTuple .addParameter(PluginParameterKeys.CLOUD_ID, urlParser.getPart(UrlPart.RECORDS)); stormTaskTuple.addParameter(PluginParameterKeys.REPRESENTATION_NAME, urlParser.getPart(UrlPart.REPRESENTATIONS)); stormTaskTuple.addParameter(PluginParameterKeys.REPRESENTATION_VERSION, urlParser.getPart(UrlPart.VERSIONS)); } clearParametersStormTuple(stormTaskTuple); outputCollector.emit(anchorTuple, stormTaskTuple.toStormTuple()); outputCollector.ack(anchorTuple); } catch (Exception e) { LOGGER.error("XsltBolt error:{}", e.getMessage()); emitErrorNotification(anchorTuple, stormTaskTuple.getTaskId(), "", e.getMessage(), ExceptionUtils.getStackTrace(e), StormTaskTupleHelper.getRecordProcessingStartTime(stormTaskTuple)); outputCollector.ack(anchorTuple); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { LOGGER.error("Error: during closing the writer {}", e.getMessage()); } } } } @Override void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple); @Override void prepare(); }### Answer: @Test public void executeBolt() throws IOException { Tuple anchorTuple = mock(TupleImpl.class); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, readMockContentOfURL(sampleXmlFileName), prepareStormTaskTupleParameters(sampleXsltFileName), new Revision()); xsltBolt.execute(anchorTuple, tuple); when(outputCollector.emit(anyList())).thenReturn(null); verify(outputCollector, times(1)).emit(Mockito.any(Tuple.class), captor.capture()); assertThat(captor.getAllValues().size(), is(1)); List<Values> allValues = captor.getAllValues(); assertEmittedTuple(allValues, 4); } @Test public void executeBoltWithInjection() throws IOException { Tuple anchorTuple = mock(TupleImpl.class); HashMap<String, String> parameters = prepareStormTaskTupleParameters(injectNodeXsltFileName); parameters.put(PluginParameterKeys.METIS_DATASET_ID, EXAMPLE_METIS_DATASET_ID); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, readMockContentOfURL(injectXmlFileName), parameters, new Revision()); xsltBolt.execute(anchorTuple, tuple); when(outputCollector.emit(anyList())).thenReturn(null); verify(outputCollector, times(1)).emit(Mockito.any(Tuple.class), captor.capture()); assertThat(captor.getAllValues().size(), is(1)); List<Values> allValues = captor.getAllValues(); assertEmittedTuple(allValues, 4); String transformed = new String((byte[]) allValues.get(0).get(3)); assertNotNull(transformed); assertTrue(transformed.contains(EXAMPLE_METIS_DATASET_ID)); }
### Question: KafkaBridge { public void importTopic(String topicToImport) throws Exception { List<String> topics = availableTopics; if (StringUtils.isNotEmpty(topicToImport)) { List<String> topics_subset = new ArrayList<>(); for(String topic : topics) { if (Pattern.compile(topicToImport).matcher(topic).matches()) { topics_subset.add(topic); } } topics = topics_subset; } if (CollectionUtils.isNotEmpty(topics)) { for(String topic : topics) { createOrUpdateTopic(topic); } } } KafkaBridge(Configuration atlasConf, AtlasClientV2 atlasClientV2); static void main(String[] args); void importTopic(String topicToImport); }### Answer: @Test public void testImportTopic() throws Exception { List<String> topics = setupTopic(zkClient, TEST_TOPIC_NAME); AtlasEntity.AtlasEntityWithExtInfo atlasEntityWithExtInfo = new AtlasEntity.AtlasEntityWithExtInfo( getTopicEntityWithGuid("0dd466a4-3838-4537-8969-6abb8b9e9185")); KafkaBridge kafkaBridge = mock(KafkaBridge.class); when(kafkaBridge.createEntityInAtlas(atlasEntityWithExtInfo)).thenReturn(atlasEntityWithExtInfo); try { kafkaBridge.importTopic(TEST_TOPIC_NAME); } catch (Exception e) { Assert.fail("KafkaBridge import failed ", e); } }
### Question: AtlasMapType extends AtlasType { @Override public boolean isValidValue(Object obj) { if (obj != null) { if (obj instanceof Map) { Map<Object, Objects> map = (Map<Object, Objects>) obj; for (Map.Entry e : map.entrySet()) { if (!keyType.isValidValue(e.getKey()) || !valueType.isValidValue(e.getValue())) { return false; } } } else { return false; } } return true; } AtlasMapType(AtlasType keyType, AtlasType valueType); AtlasMapType(String keyTypeName, String valueTypeName, AtlasTypeRegistry typeRegistry); String getKeyTypeName(); String getValueTypeName(); AtlasType getKeyType(); AtlasType getValueType(); void setKeyType(AtlasType keyType); @Override Map<Object, Object> createDefaultValue(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Map<Object, Object> getNormalizedValue(Object obj); @Override Map<Object, Object> getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); }### Answer: @Test public void testMapTypeIsValidValue() { for (Object value : validValues) { assertTrue(intIntMapType.isValidValue(value), "value=" + value); } for (Object value : invalidValues) { assertFalse(intIntMapType.isValidValue(value), "value=" + value); } }
### Question: UserProfileService { public AtlasUserProfile saveUserProfile(AtlasUserProfile profile) throws AtlasBaseException { return dataAccess.save(profile); } @Inject UserProfileService(DataAccess dataAccess); AtlasUserProfile saveUserProfile(AtlasUserProfile profile); AtlasUserProfile getUserProfile(String userName); AtlasUserSavedSearch addSavedSearch(AtlasUserSavedSearch savedSearch); AtlasUserSavedSearch updateSavedSearch(AtlasUserSavedSearch savedSearch); List<AtlasUserSavedSearch> getSavedSearches(String userName); AtlasUserSavedSearch getSavedSearch(String userName, String searchName); AtlasUserSavedSearch getSavedSearch(String guid); void deleteUserProfile(String userName); void deleteSavedSearch(String guid); void deleteSearchBySearchName(String userName, String searchName); }### Answer: @Test(dependsOnMethods = "filterInternalType") public void createsNewProfile() throws AtlasBaseException { for (int i = 0; i < NUM_USERS; i++) { AtlasUserProfile expected = getAtlasUserProfile(i); AtlasUserProfile actual = userProfileService.saveUserProfile(expected); assertNotNull(actual); assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getFullName(), actual.getFullName()); assertNotNull(actual.getGuid()); } }
### Question: UserProfileService { public AtlasUserSavedSearch addSavedSearch(AtlasUserSavedSearch savedSearch) throws AtlasBaseException { String userName = savedSearch.getOwnerName(); AtlasUserProfile userProfile = null; try { userProfile = getUserProfile(userName); } catch (AtlasBaseException excp) { } if (userProfile == null) { userProfile = new AtlasUserProfile(userName); } checkIfQueryAlreadyExists(savedSearch, userProfile); userProfile.getSavedSearches().add(savedSearch); userProfile = dataAccess.save(userProfile); for (AtlasUserSavedSearch s : userProfile.getSavedSearches()) { if(s.getName().equals(savedSearch.getName())) { return s; } } return savedSearch; } @Inject UserProfileService(DataAccess dataAccess); AtlasUserProfile saveUserProfile(AtlasUserProfile profile); AtlasUserProfile getUserProfile(String userName); AtlasUserSavedSearch addSavedSearch(AtlasUserSavedSearch savedSearch); AtlasUserSavedSearch updateSavedSearch(AtlasUserSavedSearch savedSearch); List<AtlasUserSavedSearch> getSavedSearches(String userName); AtlasUserSavedSearch getSavedSearch(String userName, String searchName); AtlasUserSavedSearch getSavedSearch(String guid); void deleteUserProfile(String userName); void deleteSavedSearch(String guid); void deleteSearchBySearchName(String userName, String searchName); }### Answer: @Test(dependsOnMethods = "saveSearchesForUser", expectedExceptions = AtlasBaseException.class) public void attemptToAddExistingSearch() throws AtlasBaseException { String userName = getIndexBasedUserName(0); SearchParameters expectedSearchParameter = getActualSearchParameters(); for (int j = 0; j < NUM_SEARCHES; j++) { String queryName = getIndexBasedQueryName(j); AtlasUserSavedSearch expected = getDefaultSavedSearch(userName, queryName, expectedSearchParameter); AtlasUserSavedSearch actual = userProfileService.addSavedSearch(expected); assertNotNull(actual); assertNotNull(actual.getGuid()); assertEquals(actual.getOwnerName(), expected.getOwnerName()); assertEquals(actual.getName(), expected.getName()); assertEquals(actual.getSearchType(), expected.getSearchType()); assertEquals(actual.getSearchParameters(), expected.getSearchParameters()); } }
### Question: UserProfileService { public List<AtlasUserSavedSearch> getSavedSearches(String userName) throws AtlasBaseException { AtlasUserProfile profile = null; try { profile = getUserProfile(userName); } catch (AtlasBaseException excp) { } return (profile != null) ? profile.getSavedSearches() : null; } @Inject UserProfileService(DataAccess dataAccess); AtlasUserProfile saveUserProfile(AtlasUserProfile profile); AtlasUserProfile getUserProfile(String userName); AtlasUserSavedSearch addSavedSearch(AtlasUserSavedSearch savedSearch); AtlasUserSavedSearch updateSavedSearch(AtlasUserSavedSearch savedSearch); List<AtlasUserSavedSearch> getSavedSearches(String userName); AtlasUserSavedSearch getSavedSearch(String userName, String searchName); AtlasUserSavedSearch getSavedSearch(String guid); void deleteUserProfile(String userName); void deleteSavedSearch(String guid); void deleteSearchBySearchName(String userName, String searchName); }### Answer: @Test(dependsOnMethods = "attemptToAddExistingSearch") public void verifySavedSearchesForUser() throws AtlasBaseException { String userName = getIndexBasedUserName(0); List<AtlasUserSavedSearch> searches = userProfileService.getSavedSearches(userName); List<String> names = getIndexBasedQueryNamesList(); for (int i = 0; i < names.size(); i++) { assertTrue(names.contains(searches.get(i).getName()), searches.get(i).getName() + " failed!"); } } @Test(dependsOnMethods = "verifySavedSearchesForUser") public void verifyQueryConversionFromJSON() throws AtlasBaseException { List<AtlasUserSavedSearch> list = userProfileService.getSavedSearches("first-0"); for (int i = 0; i < NUM_SEARCHES; i++) { SearchParameters sp = list.get(i).getSearchParameters(); String json = AtlasType.toJson(sp); assertEquals(AtlasType.toJson(getActualSearchParameters()).replace("\n", "").replace(" ", ""), json); } }
### Question: AtlasMapType extends AtlasType { @Override public Map<Object, Object> getNormalizedValue(Object obj) { if (obj == null) { return null; } if (obj instanceof String) { obj = AtlasType.fromJson(obj.toString(), Map.class); } if (obj instanceof Map) { Map<Object, Object> ret = new HashMap<>(); Map<Object, Objects> map = (Map<Object, Objects>) obj; for (Map.Entry e : map.entrySet()) { Object normalizedKey = keyType.getNormalizedValue(e.getKey()); if (normalizedKey != null) { Object value = e.getValue(); if (value != null) { Object normalizedValue = valueType.getNormalizedValue(e.getValue()); if (normalizedValue != null) { ret.put(normalizedKey, normalizedValue); } else { return null; } } else { ret.put(normalizedKey, value); } } else { return null; } } return ret; } return null; } AtlasMapType(AtlasType keyType, AtlasType valueType); AtlasMapType(String keyTypeName, String valueTypeName, AtlasTypeRegistry typeRegistry); String getKeyTypeName(); String getValueTypeName(); AtlasType getKeyType(); AtlasType getValueType(); void setKeyType(AtlasType keyType); @Override Map<Object, Object> createDefaultValue(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Map<Object, Object> getNormalizedValue(Object obj); @Override Map<Object, Object> getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); }### Answer: @Test public void testMapTypeGetNormalizedValue() { assertNull(intIntMapType.getNormalizedValue(null), "value=" + null); for (Object value : validValues) { if (value == null) { continue; } Map<Object, Object> normalizedValue = intIntMapType.getNormalizedValue(value); assertNotNull(normalizedValue, "value=" + value); } for (Object value : invalidValues) { assertNull(intIntMapType.getNormalizedValue(value), "value=" + value); } }
### Question: AtlasMapType extends AtlasType { @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof Map) { Map<Object, Objects> map = (Map<Object, Objects>) obj; for (Map.Entry e : map.entrySet()) { Object key = e.getKey(); if (!keyType.isValidValue(key)) { ret = false; messages.add(objName + "." + key + ": invalid key for type " + getTypeName()); } else { Object value = e.getValue(); ret = valueType.validateValue(value, objName + "." + key, messages) && ret; } } } else { ret = false; messages.add(objName + "=" + obj + ": invalid value for type " + getTypeName()); } } return ret; } AtlasMapType(AtlasType keyType, AtlasType valueType); AtlasMapType(String keyTypeName, String valueTypeName, AtlasTypeRegistry typeRegistry); String getKeyTypeName(); String getValueTypeName(); AtlasType getKeyType(); AtlasType getValueType(); void setKeyType(AtlasType keyType); @Override Map<Object, Object> createDefaultValue(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Map<Object, Object> getNormalizedValue(Object obj); @Override Map<Object, Object> getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); }### Answer: @Test public void testMapTypeValidateValue() { List<String> messages = new ArrayList<>(); for (Object value : validValues) { assertTrue(intIntMapType.validateValue(value, "testObj", messages)); assertEquals(messages.size(), 0, "value=" + value); } for (Object value : invalidValues) { assertFalse(intIntMapType.validateValue(value, "testObj", messages)); assertTrue(messages.size() > 0, "value=" + value); messages.clear(); } }
### Question: AtlasArrayType extends AtlasType { @Override public Collection<?> createDefaultValue() { Collection<Object> ret = new ArrayList<>(); ret.add(elementType.createDefaultValue()); if (minCount != COUNT_NOT_SET) { for (int i = 1; i < minCount; i++) { ret.add(elementType.createDefaultValue()); } } return ret; } AtlasArrayType(AtlasType elementType); AtlasArrayType(AtlasType elementType, int minCount, int maxCount, Cardinality cardinality); AtlasArrayType(String elementTypeName, AtlasTypeRegistry typeRegistry); AtlasArrayType(String elementTypeName, int minCount, int maxCount, Cardinality cardinality, AtlasTypeRegistry typeRegistry); String getElementTypeName(); void setMinCount(int minCount); int getMinCount(); void setMaxCount(int maxCount); int getMaxCount(); void setCardinality(Cardinality cardinality); Cardinality getCardinality(); AtlasType getElementType(); @Override Collection<?> createDefaultValue(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Collection<?> getNormalizedValue(Object obj); @Override Collection<?> getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); }### Answer: @Test public void testArrayTypeDefaultValue() { Collection defValue = intArrayType.createDefaultValue(); assertEquals(defValue.size(), 1); }
### Question: AtlasClassificationDefStoreV2 extends AtlasAbstractDefStoreV2<AtlasClassificationDef> { @Override public boolean isValidName(String typeName) { Matcher m = TRAIT_NAME_PATTERN.matcher(typeName); return m.matches(); } AtlasClassificationDefStoreV2(AtlasTypeDefGraphStoreV2 typeDefStore, AtlasTypeRegistry typeRegistry); @Override AtlasVertex preCreate(AtlasClassificationDef classificationDef); @Override AtlasClassificationDef create(AtlasClassificationDef classificationDef, AtlasVertex preCreateResult); @Override List<AtlasClassificationDef> getAll(); @Override AtlasClassificationDef getByName(String name); @Override AtlasClassificationDef getByGuid(String guid); @Override AtlasClassificationDef update(AtlasClassificationDef classifiDef); @Override AtlasClassificationDef updateByName(String name, AtlasClassificationDef classificationDef); @Override AtlasClassificationDef updateByGuid(String guid, AtlasClassificationDef classificationDef); @Override AtlasVertex preDeleteByName(String name); @Override AtlasVertex preDeleteByGuid(String guid); @Override boolean isValidName(String typeName); }### Answer: @Test(dataProvider = "traitRegexString") public void testIsValidName(String data, boolean expected) { assertEquals(classificationDefStore.isValidName(data), expected); }
### Question: AtlasRelationshipDefStoreV2 extends AtlasAbstractDefStoreV2<AtlasRelationshipDef> { @Override public AtlasRelationshipDef create(AtlasRelationshipDef relationshipDef, AtlasVertex preCreateResult) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasRelationshipDefStoreV1.create({}, {})", relationshipDef, preCreateResult); } verifyTypeReadAccess(relationshipDef.getEndDef1().getType()); verifyTypeReadAccess(relationshipDef.getEndDef2().getType()); AtlasAuthorizationUtils.verifyAccess(new AtlasTypeAccessRequest(AtlasPrivilege.TYPE_CREATE, relationshipDef), "create relationship-def ", relationshipDef.getName()); AtlasVertex vertex = (preCreateResult == null) ? preCreate(relationshipDef) : preCreateResult; AtlasRelationshipDef ret = toRelationshipDef(vertex); if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasRelationshipDefStoreV1.create({}, {}): {}", relationshipDef, preCreateResult, ret); } return ret; } @Inject AtlasRelationshipDefStoreV2(AtlasTypeDefGraphStoreV2 typeDefStore, AtlasTypeRegistry typeRegistry); @Override AtlasVertex preCreate(AtlasRelationshipDef relationshipDef); @Override AtlasRelationshipDef create(AtlasRelationshipDef relationshipDef, AtlasVertex preCreateResult); @Override List<AtlasRelationshipDef> getAll(); @Override AtlasRelationshipDef getByName(String name); @Override AtlasRelationshipDef getByGuid(String guid); @Override AtlasRelationshipDef update(AtlasRelationshipDef relationshipDef); @Override AtlasRelationshipDef updateByName(String name, AtlasRelationshipDef relationshipDef); @Override AtlasRelationshipDef updateByGuid(String guid, AtlasRelationshipDef relationshipDef); @Override AtlasVertex preDeleteByName(String name); @Override AtlasVertex preDeleteByGuid(String guid); static void preUpdateCheck(AtlasRelationshipDef newRelationshipDef, AtlasRelationshipDef existingRelationshipDef); static void setVertexPropertiesFromRelationshipDef(AtlasRelationshipDef relationshipDef, AtlasVertex vertex); }### Answer: @Test(dataProvider = "invalidAttributeNameWithReservedKeywords") public void testCreateTypeWithReservedKeywords(AtlasRelationshipDef atlasRelationshipDef) throws AtlasException { try { ApplicationProperties.get().setProperty(AtlasAbstractDefStoreV2.ALLOW_RESERVED_KEYWORDS, false); relationshipDefStore.create(atlasRelationshipDef, null); } catch (AtlasBaseException e) { Assert.assertEquals(e.getAtlasErrorCode(), AtlasErrorCode.ATTRIBUTE_NAME_INVALID); } }
### Question: AtlasRelationshipDefStoreV2 extends AtlasAbstractDefStoreV2<AtlasRelationshipDef> { private void preUpdateCheck(AtlasRelationshipDef newRelationshipDef, AtlasRelationshipType relationshipType, AtlasVertex vertex) throws AtlasBaseException { AtlasRelationshipDef existingRelationshipDef = toRelationshipDef(vertex); preUpdateCheck(newRelationshipDef, existingRelationshipDef); AtlasStructDefStoreV2.updateVertexPreUpdate(newRelationshipDef, relationshipType, vertex, typeDefStore); setVertexPropertiesFromRelationshipDef(newRelationshipDef, vertex); } @Inject AtlasRelationshipDefStoreV2(AtlasTypeDefGraphStoreV2 typeDefStore, AtlasTypeRegistry typeRegistry); @Override AtlasVertex preCreate(AtlasRelationshipDef relationshipDef); @Override AtlasRelationshipDef create(AtlasRelationshipDef relationshipDef, AtlasVertex preCreateResult); @Override List<AtlasRelationshipDef> getAll(); @Override AtlasRelationshipDef getByName(String name); @Override AtlasRelationshipDef getByGuid(String guid); @Override AtlasRelationshipDef update(AtlasRelationshipDef relationshipDef); @Override AtlasRelationshipDef updateByName(String name, AtlasRelationshipDef relationshipDef); @Override AtlasRelationshipDef updateByGuid(String guid, AtlasRelationshipDef relationshipDef); @Override AtlasVertex preDeleteByName(String name); @Override AtlasVertex preDeleteByGuid(String guid); static void preUpdateCheck(AtlasRelationshipDef newRelationshipDef, AtlasRelationshipDef existingRelationshipDef); static void setVertexPropertiesFromRelationshipDef(AtlasRelationshipDef relationshipDef, AtlasVertex vertex); }### Answer: @Test(dataProvider = "updateValidProperties") public void testupdateVertexPreUpdatepropagateTags(AtlasRelationshipDef existingRelationshipDef,AtlasRelationshipDef newRelationshipDef) throws AtlasBaseException { AtlasRelationshipDefStoreV2.preUpdateCheck(existingRelationshipDef, newRelationshipDef); } @Test(dataProvider = "updateRename") public void testupdateVertexPreUpdateRename(AtlasRelationshipDef existingRelationshipDef,AtlasRelationshipDef newRelationshipDef) { try { AtlasRelationshipDefStoreV2.preUpdateCheck(existingRelationshipDef, newRelationshipDef); fail("expected error"); } catch (AtlasBaseException e) { if (!e.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_INVALID_NAME_UPDATE)){ fail("unexpected AtlasErrorCode "+e.getAtlasErrorCode()); } } } @Test(dataProvider = "updateRelCat") public void testupdateVertexPreUpdateRelcat(AtlasRelationshipDef existingRelationshipDef,AtlasRelationshipDef newRelationshipDef) { try { AtlasRelationshipDefStoreV2.preUpdateCheck(existingRelationshipDef, newRelationshipDef); fail("expected error"); } catch (AtlasBaseException e) { if (!e.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_INVALID_CATEGORY_UPDATE)){ fail("unexpected AtlasErrorCode "+e.getAtlasErrorCode()); } } } @Test(dataProvider = "updateEnd1") public void testupdateVertexPreUpdateEnd1(AtlasRelationshipDef existingRelationshipDef,AtlasRelationshipDef newRelationshipDef) { try { AtlasRelationshipDefStoreV2.preUpdateCheck(existingRelationshipDef, newRelationshipDef); fail("expected error"); } catch (AtlasBaseException e) { if (!e.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_INVALID_END1_UPDATE)){ fail("unexpected AtlasErrorCode "+e.getAtlasErrorCode()); } } } @Test(dataProvider = "updateEnd2") public void testupdateVertexPreUpdateEnd2(AtlasRelationshipDef existingRelationshipDef,AtlasRelationshipDef newRelationshipDef) { try { AtlasRelationshipDefStoreV2.preUpdateCheck(existingRelationshipDef, newRelationshipDef); fail("expected error"); } catch (AtlasBaseException e) { if (!e.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_INVALID_END2_UPDATE)){ fail("unexpected AtlasErrorCode "+e.getAtlasErrorCode()); } } }
### Question: AtlasEntityDefStoreV2 extends AtlasAbstractDefStoreV2<AtlasEntityDef> { @Override public AtlasEntityDef create(AtlasEntityDef entityDef, AtlasVertex preCreateResult) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasEntityDefStoreV1.create({}, {})", entityDef, preCreateResult); } verifyAttributeTypeReadAccess(entityDef.getAttributeDefs()); AtlasAuthorizationUtils.verifyAccess(new AtlasTypeAccessRequest(AtlasPrivilege.TYPE_CREATE, entityDef), "create entity-def ", entityDef.getName()); AtlasVertex vertex = (preCreateResult == null) ? preCreate(entityDef) : preCreateResult; updateVertexAddReferences(entityDef, vertex); AtlasEntityDef ret = toEntityDef(vertex); if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasEntityDefStoreV1.create({}, {}): {}", entityDef, preCreateResult, ret); } return ret; } @Inject AtlasEntityDefStoreV2(AtlasTypeDefGraphStoreV2 typeDefStore, AtlasTypeRegistry typeRegistry); @Override AtlasVertex preCreate(AtlasEntityDef entityDef); @Override AtlasEntityDef create(AtlasEntityDef entityDef, AtlasVertex preCreateResult); @Override List<AtlasEntityDef> getAll(); @Override AtlasEntityDef getByName(String name); @Override AtlasEntityDef getByGuid(String guid); @Override AtlasEntityDef update(AtlasEntityDef entityDef); @Override AtlasEntityDef updateByName(String name, AtlasEntityDef entityDef); @Override AtlasEntityDef updateByGuid(String guid, AtlasEntityDef entityDef); @Override AtlasVertex preDeleteByName(String name); @Override AtlasVertex preDeleteByGuid(String guid); }### Answer: @Test(dataProvider = "invalidAttributeNameWithReservedKeywords") public void testCreateTypeWithReservedKeywords(AtlasEntityDef atlasEntityDef) throws AtlasException { try { ApplicationProperties.get().setProperty(AtlasAbstractDefStoreV2.ALLOW_RESERVED_KEYWORDS, false); entityDefStore.create(atlasEntityDef, null); } catch (AtlasBaseException e) { Assert.assertEquals(e.getAtlasErrorCode(), AtlasErrorCode.ATTRIBUTE_NAME_INVALID); } }
### Question: AtlasArrayType extends AtlasType { @Override public boolean isValidValue(Object obj) { if (obj != null) { if (obj instanceof List || obj instanceof Set) { Collection objList = (Collection) obj; if (!isValidElementCount(objList.size())) { return false; } for (Object element : objList) { if (!elementType.isValidValue(element)) { return false; } } } else if (obj.getClass().isArray()) { int arrayLen = Array.getLength(obj); if (!isValidElementCount(arrayLen)) { return false; } for (int i = 0; i < arrayLen; i++) { if (!elementType.isValidValue(Array.get(obj, i))) { return false; } } } else { return false; } } return true; } AtlasArrayType(AtlasType elementType); AtlasArrayType(AtlasType elementType, int minCount, int maxCount, Cardinality cardinality); AtlasArrayType(String elementTypeName, AtlasTypeRegistry typeRegistry); AtlasArrayType(String elementTypeName, int minCount, int maxCount, Cardinality cardinality, AtlasTypeRegistry typeRegistry); String getElementTypeName(); void setMinCount(int minCount); int getMinCount(); void setMaxCount(int maxCount); int getMaxCount(); void setCardinality(Cardinality cardinality); Cardinality getCardinality(); AtlasType getElementType(); @Override Collection<?> createDefaultValue(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Collection<?> getNormalizedValue(Object obj); @Override Collection<?> getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); }### Answer: @Test public void testArrayTypeIsValidValue() { for (Object value : validValues) { assertTrue(intArrayType.isValidValue(value), "value=" + value); } for (Object value : invalidValues) { assertFalse(intArrayType.isValidValue(value), "value=" + value); } }
### Question: AtlasArrayType extends AtlasType { @Override public Collection<?> getNormalizedValue(Object obj) { Collection<Object> ret = null; if (obj instanceof String) { obj = AtlasType.fromJson(obj.toString(), List.class); } if (obj instanceof List || obj instanceof Set) { Collection collObj = (Collection) obj; if (isValidElementCount(collObj.size())) { ret = new ArrayList<>(collObj.size()); for (Object element : collObj) { if (element != null) { Object normalizedValue = elementType.getNormalizedValue(element); if (normalizedValue != null) { ret.add(normalizedValue); } else { ret = null; break; } } else { ret.add(element); } } } } else if (obj != null && obj.getClass().isArray()) { int arrayLen = Array.getLength(obj); if (isValidElementCount(arrayLen)) { ret = new ArrayList<>(arrayLen); for (int i = 0; i < arrayLen; i++) { Object element = Array.get(obj, i); if (element != null) { Object normalizedValue = elementType.getNormalizedValue(element); if (normalizedValue != null) { ret.add(normalizedValue); } else { ret = null; break; } } else { ret.add(element); } } } } return ret; } AtlasArrayType(AtlasType elementType); AtlasArrayType(AtlasType elementType, int minCount, int maxCount, Cardinality cardinality); AtlasArrayType(String elementTypeName, AtlasTypeRegistry typeRegistry); AtlasArrayType(String elementTypeName, int minCount, int maxCount, Cardinality cardinality, AtlasTypeRegistry typeRegistry); String getElementTypeName(); void setMinCount(int minCount); int getMinCount(); void setMaxCount(int maxCount); int getMaxCount(); void setCardinality(Cardinality cardinality); Cardinality getCardinality(); AtlasType getElementType(); @Override Collection<?> createDefaultValue(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Collection<?> getNormalizedValue(Object obj); @Override Collection<?> getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); }### Answer: @Test public void testArrayTypeGetNormalizedValue() { assertNull(intArrayType.getNormalizedValue(null), "value=" + null); for (Object value : validValues) { if (value == null) { continue; } Collection normalizedValue = intArrayType.getNormalizedValue(value); assertNotNull(normalizedValue, "value=" + value); } for (Object value : invalidValues) { assertNull(intArrayType.getNormalizedValue(value), "value=" + value); } }
### Question: AtlasTypeDefGraphStore implements AtlasTypeDefStore { @Override public AtlasEntityDef getEntityDefByName(String name) throws AtlasBaseException { AtlasEntityDef ret = typeRegistry.getEntityDefByName(name); if (ret == null) { ret = StringUtils.equals(name, ALL_ENTITY_TYPES) ? AtlasEntityType.getEntityRoot().getEntityDef() : null; if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_NOT_FOUND, name); } return ret; } AtlasAuthorizationUtils.verifyAccess(new AtlasTypeAccessRequest(AtlasPrivilege.TYPE_READ, ret), "read type ", name); return ret; } protected AtlasTypeDefGraphStore(AtlasTypeRegistry typeRegistry, Set<TypeDefChangeListener> typeDefChangeListeners); AtlasTypeRegistry getTypeRegistry(); @Override void init(); @Override AtlasEnumDef getEnumDefByName(String name); @Override AtlasEnumDef getEnumDefByGuid(String guid); @Override @GraphTransaction AtlasEnumDef updateEnumDefByName(String name, AtlasEnumDef enumDef); @Override @GraphTransaction AtlasEnumDef updateEnumDefByGuid(String guid, AtlasEnumDef enumDef); @Override AtlasStructDef getStructDefByName(String name); @Override AtlasStructDef getStructDefByGuid(String guid); @Override AtlasRelationshipDef getRelationshipDefByName(String name); @Override AtlasRelationshipDef getRelationshipDefByGuid(String guid); @Override AtlasBusinessMetadataDef getBusinessMetadataDefByName(String name); @Override AtlasBusinessMetadataDef getBusinessMetadataDefByGuid(String guid); @Override @GraphTransaction AtlasStructDef updateStructDefByName(String name, AtlasStructDef structDef); @Override @GraphTransaction AtlasStructDef updateStructDefByGuid(String guid, AtlasStructDef structDef); @Override AtlasClassificationDef getClassificationDefByName(String name); @Override AtlasClassificationDef getClassificationDefByGuid(String guid); @Override @GraphTransaction AtlasClassificationDef updateClassificationDefByName(String name, AtlasClassificationDef classificationDef); @Override @GraphTransaction AtlasClassificationDef updateClassificationDefByGuid(String guid, AtlasClassificationDef classificationDef); @Override AtlasEntityDef getEntityDefByName(String name); @Override AtlasEntityDef getEntityDefByGuid(String guid); @Override @GraphTransaction AtlasEntityDef updateEntityDefByName(String name, AtlasEntityDef entityDef); @Override @GraphTransaction AtlasEntityDef updateEntityDefByGuid(String guid, AtlasEntityDef entityDef); @Override @GraphTransaction AtlasRelationshipDef updateRelationshipDefByName(String name, AtlasRelationshipDef relationshipDef); @Override @GraphTransaction AtlasRelationshipDef updateRelationshipDefByGuid(String guid, AtlasRelationshipDef relationshipDef); @Override @GraphTransaction AtlasTypesDef createTypesDef(AtlasTypesDef typesDef); @Override @GraphTransaction AtlasTypesDef createUpdateTypesDef(AtlasTypesDef typesDef); @Override @GraphTransaction AtlasTypesDef createUpdateTypesDef(AtlasTypesDef typesToCreate, AtlasTypesDef typesToUpdate); @Override @GraphTransaction AtlasTypesDef updateTypesDef(AtlasTypesDef typesDef); @Override @GraphTransaction void deleteTypesDef(AtlasTypesDef typesDef); @Override @GraphTransaction void deleteTypeByName(String typeName); @Override AtlasTypesDef searchTypesDef(SearchFilter searchFilter); @Override AtlasBaseTypeDef getByName(String name); @Override AtlasBaseTypeDef getByGuid(String guid); @Override void notifyLoadCompletion(); }### Answer: @Test public void testGetOnAllEntityTypes() throws AtlasBaseException { AtlasEntityDef entityDefByName = typeDefStore.getEntityDefByName("_ALL_ENTITY_TYPES"); assertNotNull(entityDefByName); assertEquals(entityDefByName, AtlasEntityType.getEntityRoot().getEntityDef()); }
### Question: AtlasTypeDefGraphStore implements AtlasTypeDefStore { @Override public AtlasClassificationDef getClassificationDefByName(String name) throws AtlasBaseException { AtlasClassificationDef ret = typeRegistry.getClassificationDefByName(name); if (ret == null) { ret = StringUtils.equalsIgnoreCase(name, ALL_CLASSIFICATION_TYPES) ? AtlasClassificationType.getClassificationRoot().getClassificationDef() : null; if (ret == null) { throw new AtlasBaseException(AtlasErrorCode.TYPE_NAME_NOT_FOUND, name); } return ret; } AtlasAuthorizationUtils.verifyAccess(new AtlasTypeAccessRequest(AtlasPrivilege.TYPE_READ, ret), "read type ", name); return ret; } protected AtlasTypeDefGraphStore(AtlasTypeRegistry typeRegistry, Set<TypeDefChangeListener> typeDefChangeListeners); AtlasTypeRegistry getTypeRegistry(); @Override void init(); @Override AtlasEnumDef getEnumDefByName(String name); @Override AtlasEnumDef getEnumDefByGuid(String guid); @Override @GraphTransaction AtlasEnumDef updateEnumDefByName(String name, AtlasEnumDef enumDef); @Override @GraphTransaction AtlasEnumDef updateEnumDefByGuid(String guid, AtlasEnumDef enumDef); @Override AtlasStructDef getStructDefByName(String name); @Override AtlasStructDef getStructDefByGuid(String guid); @Override AtlasRelationshipDef getRelationshipDefByName(String name); @Override AtlasRelationshipDef getRelationshipDefByGuid(String guid); @Override AtlasBusinessMetadataDef getBusinessMetadataDefByName(String name); @Override AtlasBusinessMetadataDef getBusinessMetadataDefByGuid(String guid); @Override @GraphTransaction AtlasStructDef updateStructDefByName(String name, AtlasStructDef structDef); @Override @GraphTransaction AtlasStructDef updateStructDefByGuid(String guid, AtlasStructDef structDef); @Override AtlasClassificationDef getClassificationDefByName(String name); @Override AtlasClassificationDef getClassificationDefByGuid(String guid); @Override @GraphTransaction AtlasClassificationDef updateClassificationDefByName(String name, AtlasClassificationDef classificationDef); @Override @GraphTransaction AtlasClassificationDef updateClassificationDefByGuid(String guid, AtlasClassificationDef classificationDef); @Override AtlasEntityDef getEntityDefByName(String name); @Override AtlasEntityDef getEntityDefByGuid(String guid); @Override @GraphTransaction AtlasEntityDef updateEntityDefByName(String name, AtlasEntityDef entityDef); @Override @GraphTransaction AtlasEntityDef updateEntityDefByGuid(String guid, AtlasEntityDef entityDef); @Override @GraphTransaction AtlasRelationshipDef updateRelationshipDefByName(String name, AtlasRelationshipDef relationshipDef); @Override @GraphTransaction AtlasRelationshipDef updateRelationshipDefByGuid(String guid, AtlasRelationshipDef relationshipDef); @Override @GraphTransaction AtlasTypesDef createTypesDef(AtlasTypesDef typesDef); @Override @GraphTransaction AtlasTypesDef createUpdateTypesDef(AtlasTypesDef typesDef); @Override @GraphTransaction AtlasTypesDef createUpdateTypesDef(AtlasTypesDef typesToCreate, AtlasTypesDef typesToUpdate); @Override @GraphTransaction AtlasTypesDef updateTypesDef(AtlasTypesDef typesDef); @Override @GraphTransaction void deleteTypesDef(AtlasTypesDef typesDef); @Override @GraphTransaction void deleteTypeByName(String typeName); @Override AtlasTypesDef searchTypesDef(SearchFilter searchFilter); @Override AtlasBaseTypeDef getByName(String name); @Override AtlasBaseTypeDef getByGuid(String guid); @Override void notifyLoadCompletion(); }### Answer: @Test public void testGetOnAllClassificationTypes() throws AtlasBaseException { AtlasClassificationDef classificationTypeDef = typeDefStore.getClassificationDefByName("_ALL_CLASSIFICATION_TYPES"); assertNotNull(classificationTypeDef); assertEquals(classificationTypeDef, AtlasClassificationType.getClassificationRoot().getClassificationDef()); }
### Question: HdfsPathEntityCreator { public AtlasEntity.AtlasEntityWithExtInfo getCreateEntity(AtlasObjectId item) throws AtlasBaseException { if(item.getUniqueAttributes() == null || !item.getUniqueAttributes().containsKey(HDFS_PATH_ATTRIBUTE_NAME_PATH)) { return null; } return getCreateEntity((String) item.getUniqueAttributes().get(HDFS_PATH_ATTRIBUTE_NAME_PATH)); } @Inject HdfsPathEntityCreator(AtlasTypeRegistry typeRegistry, AtlasEntityStoreV2 entityStore); AtlasEntity.AtlasEntityWithExtInfo getCreateEntity(AtlasObjectId item); AtlasEntity.AtlasEntityWithExtInfo getCreateEntity(String path); AtlasEntity.AtlasEntityWithExtInfo getCreateEntity(String path, String clusterName); static String getQualifiedName(String path, String clusterName); static final String HDFS_PATH_TYPE; static final String HDFS_PATH_ATTRIBUTE_NAME_NAME; static final String HDFS_PATH_ATTRIBUTE_NAME_CLUSTER_NAME; static final String HDFS_PATH_ATTRIBUTE_NAME_PATH; static final String HDFS_PATH_ATTRIBUTE_QUALIFIED_NAME; }### Answer: @Test(dependsOnMethods = "verifyCreate") public void verifyGet() throws AtlasBaseException { AtlasEntity.AtlasEntityWithExtInfo entityWithExtInfo = hdfsPathEntityCreator.getCreateEntity(expectedPath, expectedClusterName); assertNotNull(entityWithExtInfo); }
### Question: ExportService { public AtlasExportResult run(ZipSink exportSink, AtlasExportRequest request, String userName, String hostName, String requestingIP) throws AtlasBaseException { long startTime = System.currentTimeMillis(); AtlasExportResult result = new AtlasExportResult(request, userName, requestingIP, hostName, startTime, getCurrentChangeMarker()); ExportContext context = new ExportContext(result, exportSink); exportTypeProcessor = new ExportTypeProcessor(typeRegistry); try { LOG.info("==> export(user={}, from={})", userName, requestingIP); AtlasExportResult.OperationStatus[] statuses = processItems(request, context); processTypesDef(context); long endTime = System.currentTimeMillis(); updateSinkWithOperationMetrics(userName, context, statuses, startTime, endTime); } catch(Exception ex) { LOG.error("Operation failed: ", ex); } finally { entitiesExtractor.close(); LOG.info("<== export(user={}, from={}): status {}: changeMarker: {}", userName, requestingIP, context.result.getOperationStatus(), context.result.getChangeMarker()); context.clear(); result.clear(); } return context.result; } @Inject ExportService(final AtlasTypeRegistry typeRegistry, AtlasGraph graph, AuditsWriter auditsWriter, HdfsPathEntityCreator hdfsPathEntityCreator); AtlasExportResult run(ZipSink exportSink, AtlasExportRequest request, String userName, String hostName, String requestingIP); void processEntity(AtlasEntityWithExtInfo entityWithExtInfo, ExportContext context); }### Answer: @Test public void exportType() throws AtlasBaseException { String requestingIP = "1.0.0.0"; String hostName = "root"; AtlasExportRequest request = getRequestForFullFetch(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipSink zipSink = new ZipSink(baos); AtlasExportResult result = exportService.run(zipSink, request, "admin", hostName, requestingIP); assertNotNull(exportService); assertEquals(result.getHostName(), hostName); assertEquals(result.getClientIpAddress(), requestingIP); assertEquals(request, result.getRequest()); assertNotNull(result.getSourceClusterName()); } @Test(expectedExceptions = AtlasBaseException.class) public void requestingEntityNotFound_NoData() throws AtlasBaseException, IOException { String requestingIP = "1.0.0.0"; String hostName = "root"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipSink zipSink = new ZipSink(baos); AtlasExportResult result = exportService.run( zipSink, getRequestForFullFetch(), "admin", hostName, requestingIP); Assert.assertNull(result.getData()); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); new ZipSource(bais); }
### Question: ExportService { @VisibleForTesting AtlasExportResult.OperationStatus getOverallOperationStatus(AtlasExportResult.OperationStatus... statuses) { AtlasExportResult.OperationStatus overall = (statuses.length == 0) ? AtlasExportResult.OperationStatus.FAIL : statuses[0]; for (AtlasExportResult.OperationStatus s : statuses) { if (overall != s) { overall = AtlasExportResult.OperationStatus.PARTIAL_SUCCESS; } } return overall; } @Inject ExportService(final AtlasTypeRegistry typeRegistry, AtlasGraph graph, AuditsWriter auditsWriter, HdfsPathEntityCreator hdfsPathEntityCreator); AtlasExportResult run(ZipSink exportSink, AtlasExportRequest request, String userName, String hostName, String requestingIP); void processEntity(AtlasEntityWithExtInfo entityWithExtInfo, ExportContext context); }### Answer: @Test public void verifyOverallStatus() { assertEquals(AtlasExportResult.OperationStatus.FAIL, exportService.getOverallOperationStatus()); assertEquals(AtlasExportResult.OperationStatus.SUCCESS, exportService.getOverallOperationStatus(AtlasExportResult.OperationStatus.SUCCESS)); assertEquals(AtlasExportResult.OperationStatus.SUCCESS, exportService.getOverallOperationStatus( AtlasExportResult.OperationStatus.SUCCESS, AtlasExportResult.OperationStatus.SUCCESS, AtlasExportResult.OperationStatus.SUCCESS)); assertEquals(AtlasExportResult.OperationStatus.PARTIAL_SUCCESS, exportService.getOverallOperationStatus( AtlasExportResult.OperationStatus.FAIL, AtlasExportResult.OperationStatus.PARTIAL_SUCCESS, AtlasExportResult.OperationStatus.SUCCESS)); assertEquals(AtlasExportResult.OperationStatus.PARTIAL_SUCCESS, exportService.getOverallOperationStatus( AtlasExportResult.OperationStatus.FAIL, AtlasExportResult.OperationStatus.FAIL, AtlasExportResult.OperationStatus.PARTIAL_SUCCESS)); assertEquals(AtlasExportResult.OperationStatus.FAIL, exportService.getOverallOperationStatus( AtlasExportResult.OperationStatus.FAIL, AtlasExportResult.OperationStatus.FAIL, AtlasExportResult.OperationStatus.FAIL)); }
### Question: ExportImportAuditService { public ExportImportAuditEntry get(ExportImportAuditEntry entry) throws AtlasBaseException { if(entry.getGuid() == null) { throw new AtlasBaseException("entity does not have GUID set. load cannot proceed."); } return dataAccess.load(entry); } @Inject ExportImportAuditService(DataAccess dataAccess, AtlasDiscoveryService discoveryService); @GraphTransaction void save(ExportImportAuditEntry entry); ExportImportAuditEntry get(ExportImportAuditEntry entry); List<ExportImportAuditEntry> get(String userName, String operation, String cluster, String startTime, String endTime, int limit, int offset); void add(String userName, String sourceCluster, String targetCluster, String operation, String result, long startTime, long endTime, boolean hasData); }### Answer: @Test public void numberOfSavedEntries_Retrieved() throws AtlasBaseException, InterruptedException { final String source1 = "server1"; final String target1 = "cly"; int MAX_ENTRIES = 5; for (int i = 0; i < MAX_ENTRIES; i++) { saveAndGet(source1, ExportImportAuditEntry.OPERATION_EXPORT, target1); } pauseForIndexCreation(); List<ExportImportAuditEntry> results = auditService.get("", ExportImportAuditEntry.OPERATION_EXPORT, "", "", "", 10, 0); assertTrue(results.size() > 0); }
### Question: AtlasArrayType extends AtlasType { @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof List || obj instanceof Set) { Collection objList = (Collection) obj; if (!isValidElementCount(objList.size())) { ret = false; messages.add(objName + ": incorrect number of values. found=" + objList.size() + "; expected: minCount=" + minCount + ", maxCount=" + maxCount); } int idx = 0; for (Object element : objList) { ret = elementType.validateValue(element, objName + "[" + idx + "]", messages) && ret; idx++; } } else if (obj.getClass().isArray()) { int arrayLen = Array.getLength(obj); if (!isValidElementCount(arrayLen)) { ret = false; messages.add(objName + ": incorrect number of values. found=" + arrayLen + "; expected: minCount=" + minCount + ", maxCount=" + maxCount); } for (int i = 0; i < arrayLen; i++) { ret = elementType.validateValue(Array.get(obj, i), objName + "[" + i + "]", messages) && ret; } } else { ret = false; messages.add(objName + "=" + obj + ": invalid value for type " + getTypeName()); } } return ret; } AtlasArrayType(AtlasType elementType); AtlasArrayType(AtlasType elementType, int minCount, int maxCount, Cardinality cardinality); AtlasArrayType(String elementTypeName, AtlasTypeRegistry typeRegistry); AtlasArrayType(String elementTypeName, int minCount, int maxCount, Cardinality cardinality, AtlasTypeRegistry typeRegistry); String getElementTypeName(); void setMinCount(int minCount); int getMinCount(); void setMaxCount(int maxCount); int getMaxCount(); void setCardinality(Cardinality cardinality); Cardinality getCardinality(); AtlasType getElementType(); @Override Collection<?> createDefaultValue(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Collection<?> getNormalizedValue(Object obj); @Override Collection<?> getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); }### Answer: @Test public void testArrayTypeValidateValue() { List<String> messages = new ArrayList<>(); for (Object value : validValues) { assertTrue(intArrayType.validateValue(value, "testObj", messages)); assertEquals(messages.size(), 0, "value=" + value); } for (Object value : invalidValues) { assertFalse(intArrayType.validateValue(value, "testObj", messages)); assertTrue(messages.size() > 0, "value=" + value); messages.clear(); } }
### Question: ZipSource implements EntityImportStream { @Override public List<String> getCreationOrder() { return this.creationOrder; } ZipSource(InputStream inputStream); ZipSource(InputStream inputStream, ImportTransforms importTransform); @Override ImportTransforms getImportTransform(); @Override void setImportTransform(ImportTransforms importTransform); @Override List<BaseEntityHandler> getEntityHandlers(); @Override void setEntityHandlers(List<BaseEntityHandler> entityHandlers); @Override AtlasTypesDef getTypesDef(); @Override AtlasExportResult getExportResult(); @Override List<String> getCreationOrder(); AtlasEntityWithExtInfo getEntityWithExtInfo(String guid); @Override void close(); @Override boolean hasNext(); @Override AtlasEntity next(); @Override AtlasEntityWithExtInfo getNextEntityWithExtInfo(); @Override void reset(); @Override AtlasEntity getByGuid(String guid); int size(); @Override void onImportComplete(String guid); @Override void setPosition(int index); @Override void setPositionUsingEntityGuid(String guid); @Override int getPosition(); }### Answer: @Test(expectedExceptions = AtlasBaseException.class) public void improperInit_ReturnsNullCreationOrder() throws IOException, AtlasBaseException { byte bytes[] = new byte[10]; ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ZipSource zs = new ZipSource(bais); List<String> s = zs.getCreationOrder(); Assert.assertNull(s); }
### Question: ImportTransforms { public AtlasEntity.AtlasEntityWithExtInfo apply(AtlasEntity.AtlasEntityWithExtInfo entityWithExtInfo) throws AtlasBaseException { if (entityWithExtInfo == null) { return entityWithExtInfo; } apply(entityWithExtInfo.getEntity()); if(MapUtils.isNotEmpty(entityWithExtInfo.getReferredEntities())) { for (AtlasEntity e : entityWithExtInfo.getReferredEntities().values()) { apply(e); } } return entityWithExtInfo; } private ImportTransforms(); private ImportTransforms(String jsonString); static ImportTransforms fromJson(String jsonString); Map<String, Map<String, List<ImportTransformer>>> getTransforms(); Map<String, List<ImportTransformer>> getTransforms(String typeName); Set<String> getTypes(); void addParentTransformsToSubTypes(String parentType, Set<String> subTypes); AtlasEntity.AtlasEntityWithExtInfo apply(AtlasEntity.AtlasEntityWithExtInfo entityWithExtInfo); AtlasEntity apply(AtlasEntity entity); }### Answer: @Test public void transformEntityWith2Transforms() throws AtlasBaseException { AtlasEntity entity = getHiveTableAtlasEntity(); String attrValue = (String) entity.getAttribute(ATTR_NAME_QUALIFIED_NAME); transform.apply(entity); assertEquals(entity.getAttribute(ATTR_NAME_QUALIFIED_NAME), applyDefaultTransform(attrValue)); } @Test public void transformEntityWithExtInfo() throws AtlasBaseException { addColumnTransform(transform); AtlasEntityWithExtInfo entityWithExtInfo = getAtlasEntityWithExtInfo(); AtlasEntity entity = entityWithExtInfo.getEntity(); String attrValue = (String) entity.getAttribute(ATTR_NAME_QUALIFIED_NAME); String[] expectedValues = getExtEntityExpectedValues(entityWithExtInfo); transform.apply(entityWithExtInfo); assertEquals(entityWithExtInfo.getEntity().getAttribute(ATTR_NAME_QUALIFIED_NAME), applyDefaultTransform(attrValue)); for (int i = 0; i < expectedValues.length; i++) { assertEquals(entityWithExtInfo.getReferredEntities().get(Integer.toString(i)).getAttribute(ATTR_NAME_QUALIFIED_NAME), expectedValues[i]); } } @Test public void transformEntityWithExtInfoNullCheck() throws AtlasBaseException { addColumnTransform(transform); AtlasEntityWithExtInfo entityWithExtInfo = getAtlasEntityWithExtInfo(); entityWithExtInfo.setReferredEntities(null); AtlasEntityWithExtInfo transformedEntityWithExtInfo = transform.apply(entityWithExtInfo); assertNotNull(transformedEntityWithExtInfo); assertEquals(entityWithExtInfo.getEntity().getGuid(), transformedEntityWithExtInfo.getEntity().getGuid()); }
### Question: ImportService { public AtlasImportResult run(InputStream inputStream, String userName, String hostName, String requestingIP) throws AtlasBaseException { return run(inputStream, null, userName, hostName, requestingIP); } @Inject ImportService(AtlasTypeDefStore typeDefStore, AtlasTypeRegistry typeRegistry, BulkImporter bulkImporter, AuditsWriter auditsWriter, ImportTransformsShaper importTransformsShaper, TableReplicationRequestProcessor tableReplicationRequestProcessor); AtlasImportResult run(InputStream inputStream, String userName, String hostName, String requestingIP); AtlasImportResult run(InputStream inputStream, AtlasImportRequest request, String userName, String hostName, String requestingIP); AtlasImportResult run(AtlasImportRequest request, String userName, String hostName, String requestingIP); }### Answer: @Test public void importServiceProcessesIOException() { ImportService importService = new ImportService(typeDefStore, typeRegistry, null,null, null,null); AtlasImportRequest req = mock(AtlasImportRequest.class); Answer<Map> answer = invocationOnMock -> { throw new IOException("file is read only"); }; when(req.getFileName()).thenReturn("some-file.zip"); when(req.getOptions()).thenAnswer(answer); try { importService.run(req, "a", "b", "c"); } catch (AtlasBaseException ex) { assertEquals(ex.getAtlasErrorCode().getErrorCode(), AtlasErrorCode.INVALID_PARAMETERS.getErrorCode()); } }
### Question: ImportService { @VisibleForTesting void setImportTransform(EntityImportStream source, String transforms) throws AtlasBaseException { ImportTransforms importTransform = ImportTransforms.fromJson(transforms); if (importTransform == null) { return; } importTransformsShaper.shape(importTransform, source.getExportResult().getRequest()); source.setImportTransform(importTransform); if(LOG.isDebugEnabled()) { debugLog(" => transforms: {}", AtlasType.toJson(importTransform)); } } @Inject ImportService(AtlasTypeDefStore typeDefStore, AtlasTypeRegistry typeRegistry, BulkImporter bulkImporter, AuditsWriter auditsWriter, ImportTransformsShaper importTransformsShaper, TableReplicationRequestProcessor tableReplicationRequestProcessor); AtlasImportResult run(InputStream inputStream, String userName, String hostName, String requestingIP); AtlasImportResult run(InputStream inputStream, AtlasImportRequest request, String userName, String hostName, String requestingIP); AtlasImportResult run(AtlasImportRequest request, String userName, String hostName, String requestingIP); }### Answer: @Test(dataProvider = "salesNewTypeAttrs-next") public void transformUpdatesForSubTypes(InputStream inputStream) throws IOException, AtlasBaseException { loadBaseModel(); loadHiveModel(); String transformJSON = "{ \"Asset\": { \"qualifiedName\":[ \"lowercase\", \"replace:@cl1:@cl2\" ] } }"; ZipSource zipSource = new ZipSource(inputStream); importService.setImportTransform(zipSource, transformJSON); ImportTransforms importTransforms = zipSource.getImportTransform(); assertTrue(importTransforms.getTransforms().containsKey("Asset")); assertTrue(importTransforms.getTransforms().containsKey("hive_table")); assertTrue(importTransforms.getTransforms().containsKey("hive_column")); } @Test(dataProvider = "salesNewTypeAttrs-next") public void transformUpdatesForSubTypesAddsToExistingTransforms(InputStream inputStream) throws IOException, AtlasBaseException { loadBaseModel(); loadHiveModel(); String transformJSON = "{ \"Asset\": { \"qualifiedName\":[ \"replace:@cl1:@cl2\" ] }, \"hive_table\": { \"qualifiedName\":[ \"lowercase\" ] } }"; ZipSource zipSource = new ZipSource(inputStream); importService.setImportTransform(zipSource, transformJSON); ImportTransforms importTransforms = zipSource.getImportTransform(); assertTrue(importTransforms.getTransforms().containsKey("Asset")); assertTrue(importTransforms.getTransforms().containsKey("hive_table")); assertTrue(importTransforms.getTransforms().containsKey("hive_column")); assertEquals(importTransforms.getTransforms().get("hive_table").get("qualifiedName").size(), 2); }
### Question: ImportService { @VisibleForTesting boolean checkHiveTableIncrementalSkipLineage(AtlasImportRequest importRequest, AtlasExportRequest exportRequest) { if (exportRequest == null || CollectionUtils.isEmpty(exportRequest.getItemsToExport())) { return false; } for (AtlasObjectId itemToExport : exportRequest.getItemsToExport()) { if (!itemToExport.getTypeName().equalsIgnoreCase(ATLAS_TYPE_HIVE_TABLE)){ return false; } } return importRequest.isReplicationOptionSet() && exportRequest.isReplicationOptionSet() && exportRequest.getFetchTypeOptionValue().equalsIgnoreCase(AtlasExportRequest.FETCH_TYPE_INCREMENTAL) && exportRequest.getSkipLineageOptionValue(); } @Inject ImportService(AtlasTypeDefStore typeDefStore, AtlasTypeRegistry typeRegistry, BulkImporter bulkImporter, AuditsWriter auditsWriter, ImportTransformsShaper importTransformsShaper, TableReplicationRequestProcessor tableReplicationRequestProcessor); AtlasImportResult run(InputStream inputStream, String userName, String hostName, String requestingIP); AtlasImportResult run(InputStream inputStream, AtlasImportRequest request, String userName, String hostName, String requestingIP); AtlasImportResult run(AtlasImportRequest request, String userName, String hostName, String requestingIP); }### Answer: @Test public void testCheckHiveTableIncrementalSkipLineage() { AtlasImportRequest importRequest; AtlasExportRequest exportRequest; importRequest = getImportRequest("cl1"); exportRequest = getExportRequest(FETCH_TYPE_INCREMENTAL, "cl2", true, getItemsToExport("hive_table", "hive_table")); assertTrue(importService.checkHiveTableIncrementalSkipLineage(importRequest, exportRequest)); exportRequest = getExportRequest(FETCH_TYPE_INCREMENTAL, "cl2", true, getItemsToExport("hive_table", "hive_db", "hive_table")); assertFalse(importService.checkHiveTableIncrementalSkipLineage(importRequest, exportRequest)); exportRequest = getExportRequest(FETCH_TYPE_FULL, "cl2", true, getItemsToExport("hive_table", "hive_table")); assertFalse(importService.checkHiveTableIncrementalSkipLineage(importRequest, exportRequest)); exportRequest = getExportRequest(FETCH_TYPE_FULL, "", true, getItemsToExport("hive_table", "hive_table")); assertFalse(importService.checkHiveTableIncrementalSkipLineage(importRequest, exportRequest)); importRequest = getImportRequest(""); exportRequest = getExportRequest(FETCH_TYPE_INCREMENTAL, "cl2", true, getItemsToExport("hive_table", "hive_table")); assertFalse(importService.checkHiveTableIncrementalSkipLineage(importRequest, exportRequest)); }
### Question: StartEntityFetchByExportRequest { public List<AtlasObjectId> get(AtlasExportRequest exportRequest) { List<AtlasObjectId> list = new ArrayList<>(); for(AtlasObjectId objectId : exportRequest.getItemsToExport()) { List<String> guids = get(exportRequest, objectId); if (guids.isEmpty()) { continue; } objectId.setGuid(guids.get(0)); list.add(objectId); } return list; } StartEntityFetchByExportRequest(AtlasGraph atlasGraph, AtlasTypeRegistry typeRegistry, AtlasGremlinQueryProvider gremlinQueryProvider); List<AtlasObjectId> get(AtlasExportRequest exportRequest); List<String> get(AtlasExportRequest exportRequest, AtlasObjectId item); ScriptEngine getScriptEngine(); }### Answer: @Test public void fetchTypeGuid() { String exportRequestJson = "{ \"itemsToExport\": [ { \"typeName\": \"hive_db\", \"guid\": \"111-222-333\" } ]}"; AtlasExportRequest exportRequest = AtlasType.fromJson(exportRequestJson, AtlasExportRequest.class); List<AtlasObjectId> objectGuidMap = startEntityFetchByExportRequestSpy.get(exportRequest); assertEquals(objectGuidMap.get(0).getGuid(), "111-222-333"); }
### Question: AtlasStructType extends AtlasType { @Override public AtlasStruct createDefaultValue() { AtlasStruct ret = new AtlasStruct(structDef.getName()); populateDefaultValues(ret); return ret; } AtlasStructType(AtlasStructDef structDef); AtlasStructType(AtlasStructDef structDef, AtlasTypeRegistry typeRegistry); AtlasStructDef getStructDef(); AtlasType getAttributeType(String attributeName); AtlasAttributeDef getAttributeDef(String attributeName); @Override AtlasStruct createDefaultValue(); @Override Object createDefaultValue(Object defaultValue); Map<String, AtlasAttribute> getAllAttributes(); Map<String, AtlasAttribute> getUniqAttributes(); AtlasAttribute getAttribute(String attributeName); AtlasAttribute getSystemAttribute(String attributeName); AtlasAttribute getBusinesAAttribute(String attributeName); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); void normalizeAttributeValues(AtlasStruct obj); void normalizeAttributeValuesForUpdate(AtlasStruct obj); void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasStruct obj); String getVertexPropertyName(String attrName); String getQualifiedAttributePropertyKey(String attrName); static final String UNIQUE_ATTRIBUTE_SHADE_PROPERTY_PREFIX; }### Answer: @Test public void testStructTypeDefaultValue() { AtlasStruct defValue = structType.createDefaultValue(); assertNotNull(defValue); assertEquals(defValue.getTypeName(), structType.getTypeName()); }
### Question: AtlasAuditService { public AtlasAuditEntry get(AtlasAuditEntry entry) throws AtlasBaseException { if(entry.getGuid() == null) { throw new AtlasBaseException("Entity does not have GUID set. load cannot proceed."); } return dataAccess.load(entry); } @Inject AtlasAuditService(DataAccess dataAccess, AtlasDiscoveryService discoveryService); @GraphTransaction void save(AtlasAuditEntry entry); void add(String userName, AuditOperation operation, String clientId, Date startTime, Date endTime, String params, String result, long resultCount); AtlasAuditEntry get(AtlasAuditEntry entry); List<AtlasAuditEntry> get(AuditSearchParameters auditSearchParameters); AtlasAuditEntry toAtlasAuditEntry(AtlasEntity.AtlasEntityWithExtInfo entityWithExtInfo); static final String ENTITY_TYPE_AUDIT_ENTRY; }### Answer: @Test public void checkStoringMultipleAuditEntries() throws AtlasBaseException, InterruptedException { final String clientId = "client1"; final int MAX_ENTRIES = 5; final int LIMIT_PARAM = 3; for (int i = 0; i < MAX_ENTRIES; i++) { saveEntry(AuditOperation.PURGE, clientId); } waitForIndexCreation(); AuditSearchParameters auditSearchParameters = createAuditParameter("audit-search-parameter-purge"); auditSearchParameters.setLimit(LIMIT_PARAM); auditSearchParameters.setOffset(0); List<AtlasAuditEntry> resultLimitedByParam = auditService.get(auditSearchParameters); assertTrue(resultLimitedByParam.size() == LIMIT_PARAM); auditSearchParameters.setLimit(MAX_ENTRIES); auditSearchParameters.setOffset(LIMIT_PARAM); List<AtlasAuditEntry> results = auditService.get(auditSearchParameters); assertTrue(results.size() == (MAX_ENTRIES - LIMIT_PARAM)); }
### Question: AtlasStructType extends AtlasType { @Override public boolean isValidValue(Object obj) { if (obj != null) { if (obj instanceof AtlasStruct) { AtlasStruct structObj = (AtlasStruct) obj; for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { if (!isAssignableValue(structObj.getAttribute(attributeDef.getName()), attributeDef)) { return false; } } } else if (obj instanceof Map) { Map map = AtlasTypeUtil.toStructAttributes((Map) obj); for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { if (!isAssignableValue(map.get(attributeDef.getName()), attributeDef)) { return false; } } } else { return false; } } return true; } AtlasStructType(AtlasStructDef structDef); AtlasStructType(AtlasStructDef structDef, AtlasTypeRegistry typeRegistry); AtlasStructDef getStructDef(); AtlasType getAttributeType(String attributeName); AtlasAttributeDef getAttributeDef(String attributeName); @Override AtlasStruct createDefaultValue(); @Override Object createDefaultValue(Object defaultValue); Map<String, AtlasAttribute> getAllAttributes(); Map<String, AtlasAttribute> getUniqAttributes(); AtlasAttribute getAttribute(String attributeName); AtlasAttribute getSystemAttribute(String attributeName); AtlasAttribute getBusinesAAttribute(String attributeName); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); void normalizeAttributeValues(AtlasStruct obj); void normalizeAttributeValuesForUpdate(AtlasStruct obj); void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasStruct obj); String getVertexPropertyName(String attrName); String getQualifiedAttributePropertyKey(String attrName); static final String UNIQUE_ATTRIBUTE_SHADE_PROPERTY_PREFIX; }### Answer: @Test public void testStructTypeIsValidValue() { for (Object value : validValues) { assertTrue(structType.isValidValue(value), "value=" + value); } for (Object value : invalidValues) { assertFalse(structType.isValidValue(value), "value=" + value); } }
### Question: AtlasStructType extends AtlasType { @Override public Object getNormalizedValue(Object obj) { Object ret = null; if (obj != null) { if (isValidValue(obj)) { if (obj instanceof AtlasStruct) { normalizeAttributeValues((AtlasStruct) obj); ret = obj; } else if (obj instanceof Map) { normalizeAttributeValues((Map) obj); ret = obj; } } } return ret; } AtlasStructType(AtlasStructDef structDef); AtlasStructType(AtlasStructDef structDef, AtlasTypeRegistry typeRegistry); AtlasStructDef getStructDef(); AtlasType getAttributeType(String attributeName); AtlasAttributeDef getAttributeDef(String attributeName); @Override AtlasStruct createDefaultValue(); @Override Object createDefaultValue(Object defaultValue); Map<String, AtlasAttribute> getAllAttributes(); Map<String, AtlasAttribute> getUniqAttributes(); AtlasAttribute getAttribute(String attributeName); AtlasAttribute getSystemAttribute(String attributeName); AtlasAttribute getBusinesAAttribute(String attributeName); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); void normalizeAttributeValues(AtlasStruct obj); void normalizeAttributeValuesForUpdate(AtlasStruct obj); void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasStruct obj); String getVertexPropertyName(String attrName); String getQualifiedAttributePropertyKey(String attrName); static final String UNIQUE_ATTRIBUTE_SHADE_PROPERTY_PREFIX; }### Answer: @Test public void testStructTypeGetNormalizedValue() { assertNull(structType.getNormalizedValue(null), "value=" + null); for (Object value : validValues) { if (value == null) { continue; } Object normalizedValue = structType.getNormalizedValue(value); assertNotNull(normalizedValue, "value=" + value); } for (Object value : invalidValues) { assertNull(structType.getNormalizedValue(value), "value=" + value); } }
### Question: HiveMetaStoreBridge { @VisibleForTesting public void importHiveMetadata(String databaseToImport, String tableToImport, boolean failOnError) throws Exception { LOG.info("Importing Hive metadata"); importDatabases(failOnError, databaseToImport, tableToImport); } HiveMetaStoreBridge(Configuration atlasProperties, HiveConf hiveConf, AtlasClientV2 atlasClientV2); HiveMetaStoreBridge(Configuration atlasProperties, HiveConf hiveConf); HiveMetaStoreBridge(String metadataNamespace, Hive hiveClient, AtlasClientV2 atlasClientV2); HiveMetaStoreBridge(String metadataNamespace, Hive hiveClient, AtlasClientV2 atlasClientV2, boolean convertHdfsPathToLowerCase); static void main(String[] args); String getMetadataNamespace(Configuration config); String getMetadataNamespace(); Hive getHiveClient(); boolean isConvertHdfsPathToLowerCase(); @VisibleForTesting void importHiveMetadata(String databaseToImport, String tableToImport, boolean failOnError); @VisibleForTesting int importTable(AtlasEntity dbEntity, String databaseName, String tableName, final boolean failOnError); static String getDatabaseName(Database hiveDB); static String getDBQualifiedName(String metadataNamespace, String dbName); static String getTableQualifiedName(String metadataNamespace, String dbName, String tableName, boolean isTemporaryTable); static String getTableProcessQualifiedName(String metadataNamespace, Table table); static String getTableQualifiedName(String metadataNamespace, String dbName, String tableName); static String getStorageDescQFName(String tableQualifiedName); static String getColumnQualifiedName(final String tableQualifiedName, final String colName); static long getTableCreatedTime(Table table); static final String CONF_PREFIX; static final String CLUSTER_NAME_KEY; static final String HIVE_METADATA_NAMESPACE; static final String HDFS_PATH_CONVERT_TO_LOWER_CASE; static final String HOOK_AWS_S3_ATLAS_MODEL_VERSION; static final String DEFAULT_CLUSTER_NAME; static final String TEMP_TABLE_PREFIX; static final String ATLAS_ENDPOINT; static final String SEP; static final String HDFS_PATH; static final String DEFAULT_METASTORE_CATALOG; static final String HOOK_AWS_S3_ATLAS_MODEL_VERSION_V2; }### Answer: @Test public void testImportThatUpdatesRegisteredDatabase() throws Exception { when(hiveClient.getAllDatabases()).thenReturn(Arrays.asList(new String[]{TEST_DB_NAME})); String description = "This is a default database"; Database db = new Database(TEST_DB_NAME, description, "/user/hive/default", null); when(hiveClient.getDatabase(TEST_DB_NAME)).thenReturn(db); when(hiveClient.getAllTables(TEST_DB_NAME)).thenReturn(Arrays.asList(new String[]{})); returnExistingDatabase(TEST_DB_NAME, atlasClientV2, METADATA_NAMESPACE); when(atlasEntityWithExtInfo.getEntity("72e06b34-9151-4023-aa9d-b82103a50e76")) .thenReturn((new AtlasEntity.AtlasEntityWithExtInfo( getEntity(HiveDataTypes.HIVE_DB.getName(), AtlasClient.GUID, "72e06b34-9151-4023-aa9d-b82103a50e76"))).getEntity()); HiveMetaStoreBridge bridge = new HiveMetaStoreBridge(METADATA_NAMESPACE, hiveClient, atlasClientV2); bridge.importHiveMetadata(null, null, true); verify(atlasClientV2).updateEntity(anyObject()); }
### Question: HAConfiguration { public static ZookeeperProperties getZookeeperProperties(Configuration configuration) { String[] zkServers; if (configuration.containsKey(HA_ZOOKEEPER_CONNECT)) { zkServers = configuration.getStringArray(HA_ZOOKEEPER_CONNECT); } else { zkServers = configuration.getStringArray("atlas.kafka." + ZOOKEEPER_PREFIX + "connect"); } String zkRoot = configuration.getString(ATLAS_SERVER_HA_ZK_ROOT_KEY, ATLAS_SERVER_ZK_ROOT_DEFAULT); int retriesSleepTimeMillis = configuration.getInt(HA_ZOOKEEPER_RETRY_SLEEPTIME_MILLIS, DEFAULT_ZOOKEEPER_CONNECT_SLEEPTIME_MILLIS); int numRetries = configuration.getInt(HA_ZOOKEEPER_NUM_RETRIES, DEFAULT_ZOOKEEPER_CONNECT_NUM_RETRIES); int sessionTimeout = configuration.getInt(HA_ZOOKEEPER_SESSION_TIMEOUT_MS, DEFAULT_ZOOKEEPER_SESSION_TIMEOUT_MILLIS); String acl = configuration.getString(HA_ZOOKEEPER_ACL); String auth = configuration.getString(HA_ZOOKEEPER_AUTH); return new ZookeeperProperties(StringUtils.join(zkServers, ','), zkRoot, retriesSleepTimeMillis, numRetries, sessionTimeout, acl, auth); } private HAConfiguration(); static boolean isHAEnabled(Configuration configuration); static String getBoundAddressForId(Configuration configuration, String serverId); static List<String> getServerInstances(Configuration configuration); static ZookeeperProperties getZookeeperProperties(Configuration configuration); static final String ATLAS_SERVER_ZK_ROOT_DEFAULT; static final String ATLAS_SERVER_HA_PREFIX; static final String ZOOKEEPER_PREFIX; static final String ATLAS_SERVER_HA_ZK_ROOT_KEY; static final String ATLAS_SERVER_HA_ENABLED_KEY; static final String ATLAS_SERVER_ADDRESS_PREFIX; static final String ATLAS_SERVER_IDS; static final String HA_ZOOKEEPER_CONNECT; static final int DEFAULT_ZOOKEEPER_CONNECT_SLEEPTIME_MILLIS; static final String HA_ZOOKEEPER_RETRY_SLEEPTIME_MILLIS; static final String HA_ZOOKEEPER_NUM_RETRIES; static final int DEFAULT_ZOOKEEPER_CONNECT_NUM_RETRIES; static final String HA_ZOOKEEPER_SESSION_TIMEOUT_MS; static final int DEFAULT_ZOOKEEPER_SESSION_TIMEOUT_MILLIS; static final String HA_ZOOKEEPER_ACL; static final String HA_ZOOKEEPER_AUTH; }### Answer: @Test public void testShouldGetZookeeperAcl() { when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("sasl:[email protected]"); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); assertTrue(zookeeperProperties.hasAcl()); } @Test public void testShouldGetZookeeperAuth() { when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_AUTH)).thenReturn("sasl:[email protected]"); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); assertTrue(zookeeperProperties.hasAuth()); }
### Question: AtlasStructType extends AtlasType { @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasStruct) { AtlasStruct structObj = (AtlasStruct) obj; for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { String attrName = attributeDef.getName(); AtlasAttribute attribute = allAttributes.get(attributeDef.getName()); if (attribute != null) { AtlasType dataType = attribute.getAttributeType(); Object value = structObj.getAttribute(attrName); String fieldName = objName + "." + attrName; if (value != null) { ret = dataType.validateValue(value, fieldName, messages) && ret; } else if (!attributeDef.getIsOptional()) { if (structObj instanceof AtlasEntity) { AtlasEntity entityObj = (AtlasEntity) structObj; if (entityObj.getRelationshipAttribute(attrName) == null) { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } else { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } } } } else if (obj instanceof Map) { Map attributes = AtlasTypeUtil.toStructAttributes((Map)obj); Map relationshipAttributes = AtlasTypeUtil.toRelationshipAttributes((Map)obj); for (AtlasAttributeDef attributeDef : structDef.getAttributeDefs()) { String attrName = attributeDef.getName(); AtlasAttribute attribute = allAttributes.get(attributeDef.getName()); if (attribute != null) { AtlasType dataType = attribute.getAttributeType(); Object value = attributes.get(attrName); String fieldName = objName + "." + attrName; if (value != null) { ret = dataType.validateValue(value, fieldName, messages) && ret; } else if (!attributeDef.getIsOptional()) { if (MapUtils.isEmpty(relationshipAttributes) || !relationshipAttributes.containsKey(attrName)) { ret = false; messages.add(fieldName + ": mandatory attribute value missing in type " + getTypeName()); } } } } } else { ret = false; messages.add(objName + "=" + obj + ": invalid value for type " + getTypeName()); } } return ret; } AtlasStructType(AtlasStructDef structDef); AtlasStructType(AtlasStructDef structDef, AtlasTypeRegistry typeRegistry); AtlasStructDef getStructDef(); AtlasType getAttributeType(String attributeName); AtlasAttributeDef getAttributeDef(String attributeName); @Override AtlasStruct createDefaultValue(); @Override Object createDefaultValue(Object defaultValue); Map<String, AtlasAttribute> getAllAttributes(); Map<String, AtlasAttribute> getUniqAttributes(); AtlasAttribute getAttribute(String attributeName); AtlasAttribute getSystemAttribute(String attributeName); AtlasAttribute getBusinesAAttribute(String attributeName); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); void normalizeAttributeValues(AtlasStruct obj); void normalizeAttributeValuesForUpdate(AtlasStruct obj); void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasStruct obj); String getVertexPropertyName(String attrName); String getQualifiedAttributePropertyKey(String attrName); static final String UNIQUE_ATTRIBUTE_SHADE_PROPERTY_PREFIX; }### Answer: @Test public void testStructTypeValidateValue() { List<String> messages = new ArrayList<>(); for (Object value : validValues) { assertTrue(structType.validateValue(value, "testObj", messages)); assertEquals(messages.size(), 0, "value=" + value); } for (Object value : invalidValues) { assertFalse(structType.validateValue(value, "testObj", messages)); assertTrue(messages.size() > 0, "value=" + value); messages.clear(); } }
### Question: AtlasEntityType extends AtlasStructType { @Override public AtlasEntity createDefaultValue() { AtlasEntity ret = new AtlasEntity(entityDef.getName()); populateDefaultValues(ret); return ret; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); AtlasEntityDef getEntityDef(); static AtlasEntityType getEntityRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); @Override AtlasBusinessAttribute getBusinesAAttribute(String bmAttrQualifiedName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); Map<String, AtlasAttribute> getHeaderAttributes(); Map<String, AtlasAttribute> getMinInfoAttributes(); boolean isSuperTypeOf(AtlasEntityType entityType); boolean isSuperTypeOf(String entityTypeName); boolean isTypeOrSuperTypeOf(String entityTypeName); boolean isSubTypeOf(AtlasEntityType entityType); boolean isSubTypeOf(String entityTypeName); boolean isInternalType(); Map<String, Map<String, AtlasAttribute>> getRelationshipAttributes(); List<AtlasAttribute> getOwnedRefAttributes(); String getDisplayTextAttribute(); List<AtlasAttribute> getDynEvalAttributes(); @VisibleForTesting void setDynEvalAttributes(List<AtlasAttribute> dynAttributes); List<AtlasAttribute> getDynEvalTriggerAttributes(); @VisibleForTesting void setDynEvalTriggerAttributes(List<AtlasAttribute> dynEvalTriggerAttributes); Set<String> getTagPropagationEdges(); String[] getTagPropagationEdgesArray(); Map<String,List<TemplateToken>> getParsedTemplates(); AtlasAttribute getRelationshipAttribute(String attributeName, String relationshipType); Set<String> getAttributeRelationshipTypes(String attributeName); Map<String, Map<String, AtlasBusinessAttribute>> getBusinessAttributes(); Map<String, AtlasBusinessAttribute> getBusinessAttributes(String bmName); AtlasBusinessAttribute getBusinessAttribute(String bmName, String bmAttrName); void addBusinessAttribute(AtlasBusinessAttribute attribute); String getTypeAndAllSubTypesQryStr(); String getTypeQryStr(); boolean hasAttribute(String attributeName); boolean hasRelationshipAttribute(String attributeName); String getVertexPropertyName(String attrName); @Override AtlasEntity createDefaultValue(); @Override AtlasEntity createDefaultValue(Object defaultValue); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); void normalizeAttributeValues(AtlasEntity ent); void normalizeAttributeValuesForUpdate(AtlasEntity ent); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasEntity ent); static Set<String> getEntityTypesAndAllSubTypes(Set<String> entityTypes, AtlasTypeRegistry typeRegistry); void normalizeRelationshipAttributeValues(Map<String, Object> obj, boolean isUpdate); static final AtlasEntityType ENTITY_ROOT; }### Answer: @Test public void testEntityTypeDefaultValue() { AtlasEntity defValue = entityType.createDefaultValue(); assertNotNull(defValue); assertEquals(defValue.getTypeName(), entityType.getTypeName()); }
### Question: AtlasEntityType extends AtlasStructType { @Override public boolean isValidValue(Object obj) { if (obj != null) { for (AtlasEntityType superType : superTypes) { if (!superType.isValidValue(obj)) { return false; } } return super.isValidValue(obj) && validateRelationshipAttributes(obj); } return true; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); AtlasEntityDef getEntityDef(); static AtlasEntityType getEntityRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); @Override AtlasBusinessAttribute getBusinesAAttribute(String bmAttrQualifiedName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); Map<String, AtlasAttribute> getHeaderAttributes(); Map<String, AtlasAttribute> getMinInfoAttributes(); boolean isSuperTypeOf(AtlasEntityType entityType); boolean isSuperTypeOf(String entityTypeName); boolean isTypeOrSuperTypeOf(String entityTypeName); boolean isSubTypeOf(AtlasEntityType entityType); boolean isSubTypeOf(String entityTypeName); boolean isInternalType(); Map<String, Map<String, AtlasAttribute>> getRelationshipAttributes(); List<AtlasAttribute> getOwnedRefAttributes(); String getDisplayTextAttribute(); List<AtlasAttribute> getDynEvalAttributes(); @VisibleForTesting void setDynEvalAttributes(List<AtlasAttribute> dynAttributes); List<AtlasAttribute> getDynEvalTriggerAttributes(); @VisibleForTesting void setDynEvalTriggerAttributes(List<AtlasAttribute> dynEvalTriggerAttributes); Set<String> getTagPropagationEdges(); String[] getTagPropagationEdgesArray(); Map<String,List<TemplateToken>> getParsedTemplates(); AtlasAttribute getRelationshipAttribute(String attributeName, String relationshipType); Set<String> getAttributeRelationshipTypes(String attributeName); Map<String, Map<String, AtlasBusinessAttribute>> getBusinessAttributes(); Map<String, AtlasBusinessAttribute> getBusinessAttributes(String bmName); AtlasBusinessAttribute getBusinessAttribute(String bmName, String bmAttrName); void addBusinessAttribute(AtlasBusinessAttribute attribute); String getTypeAndAllSubTypesQryStr(); String getTypeQryStr(); boolean hasAttribute(String attributeName); boolean hasRelationshipAttribute(String attributeName); String getVertexPropertyName(String attrName); @Override AtlasEntity createDefaultValue(); @Override AtlasEntity createDefaultValue(Object defaultValue); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); void normalizeAttributeValues(AtlasEntity ent); void normalizeAttributeValuesForUpdate(AtlasEntity ent); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasEntity ent); static Set<String> getEntityTypesAndAllSubTypes(Set<String> entityTypes, AtlasTypeRegistry typeRegistry); void normalizeRelationshipAttributeValues(Map<String, Object> obj, boolean isUpdate); static final AtlasEntityType ENTITY_ROOT; }### Answer: @Test public void testEntityTypeIsValidValue() { for (Object value : validValues) { assertTrue(entityType.isValidValue(value), "value=" + value); } for (Object value : invalidValues) { assertFalse(entityType.isValidValue(value), "value=" + value); } }
### Question: AtlasEntityType extends AtlasStructType { @Override public Object getNormalizedValue(Object obj) { Object ret = null; if (obj != null) { if (isValidValue(obj)) { if (obj instanceof AtlasEntity) { normalizeAttributeValues((AtlasEntity) obj); ret = obj; } else if (obj instanceof Map) { normalizeAttributeValues((Map) obj); ret = obj; } } } return ret; } AtlasEntityType(AtlasEntityDef entityDef); AtlasEntityType(AtlasEntityDef entityDef, AtlasTypeRegistry typeRegistry); AtlasEntityDef getEntityDef(); static AtlasEntityType getEntityRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); @Override AtlasBusinessAttribute getBusinesAAttribute(String bmAttrQualifiedName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); Map<String, AtlasAttribute> getHeaderAttributes(); Map<String, AtlasAttribute> getMinInfoAttributes(); boolean isSuperTypeOf(AtlasEntityType entityType); boolean isSuperTypeOf(String entityTypeName); boolean isTypeOrSuperTypeOf(String entityTypeName); boolean isSubTypeOf(AtlasEntityType entityType); boolean isSubTypeOf(String entityTypeName); boolean isInternalType(); Map<String, Map<String, AtlasAttribute>> getRelationshipAttributes(); List<AtlasAttribute> getOwnedRefAttributes(); String getDisplayTextAttribute(); List<AtlasAttribute> getDynEvalAttributes(); @VisibleForTesting void setDynEvalAttributes(List<AtlasAttribute> dynAttributes); List<AtlasAttribute> getDynEvalTriggerAttributes(); @VisibleForTesting void setDynEvalTriggerAttributes(List<AtlasAttribute> dynEvalTriggerAttributes); Set<String> getTagPropagationEdges(); String[] getTagPropagationEdgesArray(); Map<String,List<TemplateToken>> getParsedTemplates(); AtlasAttribute getRelationshipAttribute(String attributeName, String relationshipType); Set<String> getAttributeRelationshipTypes(String attributeName); Map<String, Map<String, AtlasBusinessAttribute>> getBusinessAttributes(); Map<String, AtlasBusinessAttribute> getBusinessAttributes(String bmName); AtlasBusinessAttribute getBusinessAttribute(String bmName, String bmAttrName); void addBusinessAttribute(AtlasBusinessAttribute attribute); String getTypeAndAllSubTypesQryStr(); String getTypeQryStr(); boolean hasAttribute(String attributeName); boolean hasRelationshipAttribute(String attributeName); String getVertexPropertyName(String attrName); @Override AtlasEntity createDefaultValue(); @Override AtlasEntity createDefaultValue(Object defaultValue); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); @Override Object getNormalizedValue(Object obj); @Override Object getNormalizedValueForUpdate(Object obj); @Override boolean validateValue(Object obj, String objName, List<String> messages); @Override boolean validateValueForUpdate(Object obj, String objName, List<String> messages); @Override AtlasType getTypeForAttribute(); void normalizeAttributeValues(AtlasEntity ent); void normalizeAttributeValuesForUpdate(AtlasEntity ent); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasEntity ent); static Set<String> getEntityTypesAndAllSubTypes(Set<String> entityTypes, AtlasTypeRegistry typeRegistry); void normalizeRelationshipAttributeValues(Map<String, Object> obj, boolean isUpdate); static final AtlasEntityType ENTITY_ROOT; }### Answer: @Test public void testEntityTypeGetNormalizedValue() { assertNull(entityType.getNormalizedValue(null), "value=" + null); for (Object value : validValues) { if (value == null) { continue; } Object normalizedValue = entityType.getNormalizedValue(value); assertNotNull(normalizedValue, "value=" + value); } for (Object value : invalidValues) { assertNull(entityType.getNormalizedValue(value), "value=" + value); } }
### Question: AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting protected static String generateSuggestionsString(List<String> suggestionIndexFieldNames) { StringBuilder ret = new StringBuilder(); Iterator<String> iterator = suggestionIndexFieldNames.iterator(); while(iterator.hasNext()) { ret.append("'").append(iterator.next()).append("'"); if(iterator.hasNext()) { ret.append(", "); } } if (LOG.isDebugEnabled()) { LOG.debug("generateSuggestionsString(fieldsCount={}): ret={}", suggestionIndexFieldNames.size(), ret.toString()); } return ret.toString(); } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); }### Answer: @Test public void testGenerateSuggestionString() { List<String> fields = new ArrayList<>(); fields.add("one"); fields.add("two"); fields.add("three"); String generatedString = AtlasJanusGraphIndexClient.generateSuggestionsString(fields); Assert.assertEquals(generatedString, "'one', 'two', 'three'"); }
### Question: AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting protected static String generateSearchWeightString(Map<String, Integer> indexFieldName2SearchWeightMap) { StringBuilder searchWeightBuilder = new StringBuilder(); for (Map.Entry<String, Integer> entry : indexFieldName2SearchWeightMap.entrySet()) { searchWeightBuilder.append(" ") .append(entry.getKey()) .append("^") .append(entry.getValue().intValue()); } if (LOG.isDebugEnabled()) { LOG.debug("generateSearchWeightString(fieldsCount={}): ret={}", indexFieldName2SearchWeightMap.size(), searchWeightBuilder.toString()); } return searchWeightBuilder.toString(); } AtlasJanusGraphIndexClient(Configuration configuration); @Override void applySearchWeight(String collectionName, Map<String, Integer> indexFieldName2SearchWeightMap); @Override Map<String, List<AtlasAggregationEntry>> getAggregatedMetrics(AggregationContext aggregationContext); @Override void applySuggestionFields(String collectionName, List<String> suggestionProperties); @Override List<String> getSuggestions(String prefixString, String indexFieldName); }### Answer: @Test public void testGenerateSearchWeightString() { Map<String, Integer> fields = new HashMap<>(); fields.put("one", 10); fields.put("two", 1); fields.put("three", 15); String generatedString = AtlasJanusGraphIndexClient.generateSearchWeightString(fields); Assert.assertEquals(generatedString, " one^10 two^1 three^15"); }
### Question: MappedElementCache { public Vertex getMappedVertex(Graph gr, Object key) { try { Vertex ret = lruVertexCache.get(key); if (ret == null) { synchronized (lruVertexCache) { ret = lruVertexCache.get(key); if(ret == null) { ret = fetchVertex(gr, key); lruVertexCache.put(key, ret); } } } return ret; } catch (Exception ex) { LOG.error("getMappedVertex: {}", key, ex); return null; } } Vertex getMappedVertex(Graph gr, Object key); void clearAll(); }### Answer: @Test public void vertexFetch() { JsonNode node = getCol1(); MappedElementCache cache = new MappedElementCache(); TinkerGraph tg = TinkerGraph.open(); addVertex(tg, node); Vertex vx = cache.getMappedVertex(tg, 98336); assertNotNull(vx); assertEquals(cache.lruVertexCache.size(), 1); }
### Question: GraphSONUtility { static Object getTypedValueFromJsonNode(final JsonNode node) { Object theValue = null; if (node != null && !node.isNull()) { if (node.isBoolean()) { theValue = node.booleanValue(); } else if (node.isDouble()) { theValue = node.doubleValue(); } else if (node.isFloatingPointNumber()) { theValue = node.floatValue(); } else if (node.isInt()) { theValue = node.intValue(); } else if (node.isLong()) { theValue = node.longValue(); } else if (node.isTextual()) { theValue = node.textValue(); } else if (node.isBigDecimal()) { theValue = node.decimalValue(); } else if (node.isBigInteger()) { theValue = node.bigIntegerValue(); } else if (node.isArray()) { theValue = node; } else if (node.isObject()) { theValue = node; } else { theValue = node.textValue(); } } return theValue; } GraphSONUtility(final ElementProcessors elementProcessors); Map<String, Object> vertexFromJson(Graph g, final JsonNode json); Map<String, Object> edgeFromJson(Graph g, MappedElementCache cache, final JsonNode json); }### Answer: @Test public void idFetch() { JsonNode node = getCol1(); final int EXPECTED_ID = 98336; Object o = GraphSONUtility.getTypedValueFromJsonNode(node.get(GraphSONTokensTP2._ID)); assertNotNull(o); assertEquals((int) o, EXPECTED_ID); }