src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
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; }
@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()); }
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); }
@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); }
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(); }
@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)); }
IndexingBolt extends AbstractDpsBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { final String useAltEnv = stormTaskTuple .getParameter(PluginParameterKeys.METIS_USE_ALT_INDEXING_ENV); final String datasetId = stormTaskTuple.getParameter(PluginParameterKeys.METIS_DATASET_ID); final String database = stormTaskTuple .getParameter(PluginParameterKeys.METIS_TARGET_INDEXING_DATABASE); final boolean preserveTimestampsString = Boolean .parseBoolean(stormTaskTuple.getParameter(PluginParameterKeys.METIS_PRESERVE_TIMESTAMPS)); final String datasetIdsToRedirectFrom = stormTaskTuple .getParameter(PluginParameterKeys.DATASET_IDS_TO_REDIRECT_FROM); final List<String> datasetIdsToRedirectFromList = datasetIdsToRedirectFrom == null ? null : Arrays.asList(datasetIdsToRedirectFrom.trim().split("\\s*,\\s*")); final boolean performRedirects = Boolean .parseBoolean(stormTaskTuple.getParameter(PluginParameterKeys.PERFORM_REDIRECTS)); String dpsURL = indexingProperties.getProperty(PluginParameterKeys.DPS_URL); DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US); final Date recordDate; try { final IndexerPool indexerPool = indexerPoolWrapper.getIndexerPool(useAltEnv, database); recordDate = dateFormat .parse(stormTaskTuple.getParameter(PluginParameterKeys.METIS_RECORD_DATE)); final String document = new String(stormTaskTuple.getFileData()); indexerPool .index(document, recordDate, preserveTimestampsString, datasetIdsToRedirectFromList, performRedirects); prepareTuple(stormTaskTuple, useAltEnv, datasetId, database, recordDate, dpsURL); outputCollector.emit(anchorTuple, stormTaskTuple.toStormTuple()); LOGGER.info( "Indexing bolt executed for: {} (alternative environment: {}, record date: {}, preserve timestamps: {}).", database, useAltEnv, recordDate, preserveTimestampsString); } catch (RuntimeException e) { logAndEmitError(anchorTuple, e, e.getMessage(), stormTaskTuple); } catch (ParseException e) { logAndEmitError(anchorTuple, e, PARSE_RECORD_DATE_ERROR_MESSAGE, stormTaskTuple); } catch (IndexingException e) { logAndEmitError(anchorTuple, e, INDEXING_FILE_ERROR_MESSAGE, stormTaskTuple); } outputCollector.ack(anchorTuple); } IndexingBolt(Properties indexingProperties); @Override void prepare(); @Override void cleanup(); @Override void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple); static final String DATE_FORMAT; static final String PARSE_RECORD_DATE_ERROR_MESSAGE; static final String INDEXING_FILE_ERROR_MESSAGE; }
@Test public void shouldIndexFileForPreviewEnv() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); String targetIndexingEnv = "PREVIEW"; StormTaskTuple tuple = mockStormTupleFor(targetIndexingEnv); mockIndexerFactoryFor(null); indexingBolt.execute(anchorTuple, tuple); Mockito.verify(outputCollector, Mockito.times(1)).emit(any(Tuple.class), captor.capture()); Values capturedValues = captor.getValue(); assertEquals(8, capturedValues.size()); assertEquals("sampleResourceUrl", capturedValues.get(2)); Map<String, String> parameters = (Map<String, String>) capturedValues.get(4); assertEquals(5, parameters.size()); DataSetCleanerParameters dataSetCleanerParameters = new Gson().fromJson(parameters.get(PluginParameterKeys.DATA_SET_CLEANING_PARAMETERS), DataSetCleanerParameters.class); assertFalse(dataSetCleanerParameters.isUsingAltEnv()); assertEquals(targetIndexingEnv, dataSetCleanerParameters.getTargetIndexingEnv()); } @Test public void shouldIndexFilePublishEnv() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); String targetIndexingEnv = "PUBLISH"; StormTaskTuple tuple = mockStormTupleFor(targetIndexingEnv); mockIndexerFactoryFor(null); indexingBolt.execute(anchorTuple, tuple); Mockito.verify(outputCollector, Mockito.times(1)).emit(any(Tuple.class), captor.capture()); Values capturedValues = captor.getValue(); assertEquals(8, capturedValues.size()); assertEquals("sampleResourceUrl", capturedValues.get(2)); Map<String, String> parameters = (Map<String, String>) capturedValues.get(4); assertEquals(5, parameters.size()); DataSetCleanerParameters dataSetCleanerParameters = new Gson().fromJson(parameters.get(PluginParameterKeys.DATA_SET_CLEANING_PARAMETERS), DataSetCleanerParameters.class); assertFalse(dataSetCleanerParameters.isUsingAltEnv()); assertEquals(targetIndexingEnv, dataSetCleanerParameters.getTargetIndexingEnv()); } @Test public void shouldEmitErrorNotificationForIndexerConfiguration() throws IndexingException { Tuple anchorTuple = mock(TupleImpl.class); StormTaskTuple tuple = mockStormTupleFor("PREVIEW"); mockIndexerFactoryFor(IndexerRelatedIndexingException.class); indexingBolt.execute(anchorTuple, tuple); Mockito.verify(outputCollector, Mockito.times(1)).emit(any(String.class), any(Tuple.class), captor.capture()); Values capturedValues = captor.getValue(); Map val = (Map) capturedValues.get(2); assertEquals("sampleResourceUrl", val.get("resource")); Assert.assertTrue(val.get("additionalInfo").toString().contains("Error while indexing")); } @Test public void shouldEmitErrorNotificationForIndexing() throws IndexingException { Tuple anchorTuple = mock(TupleImpl.class); StormTaskTuple tuple = mockStormTupleFor("PUBLISH"); mockIndexerFactoryFor(IndexerRelatedIndexingException.class); indexingBolt.execute(anchorTuple, tuple); Mockito.verify(outputCollector, Mockito.times(1)).emit(any(String.class), any(Tuple.class), captor.capture()); Values capturedValues = captor.getValue(); Map val = (Map) capturedValues.get(2); assertEquals("sampleResourceUrl", val.get("resource")); Assert.assertTrue(val.get("additionalInfo").toString().contains("Error while indexing")); } @Test public void shouldThrowExceptionWhenDateIsUnParsable() throws IndexingException { Tuple anchorTuple = mock(TupleImpl.class); StormTaskTuple tuple = mockStormTupleFor("PREVIEW"); tuple.getParameters().remove(PluginParameterKeys.METIS_RECORD_DATE); tuple.addParameter(PluginParameterKeys.METIS_RECORD_DATE, "UN_PARSABLE_DATE"); indexingBolt.execute(anchorTuple, tuple); Mockito.verify(outputCollector, Mockito.times(1)).emit(any(String.class), any(Tuple.class), captor.capture()); Values capturedValues = captor.getValue(); Map val = (Map) capturedValues.get(2); assertEquals("sampleResourceUrl", val.get("resource")); Assert.assertTrue(val.get("info_text").toString().contains("Could not parse RECORD_DATE parameter")); Assert.assertTrue(val.get("state").toString().equals("ERROR")); } @Test public void shouldThrowExceptionForUnknownEnv() throws IndexingException { Tuple anchorTuple = mock(TupleImpl.class); StormTaskTuple tuple = mockStormTupleFor("UNKNOWN_ENVIRONMENT"); mockIndexerFactoryFor(RuntimeException.class); indexingBolt.execute(anchorTuple, tuple); Mockito.verify(outputCollector, Mockito.times(1)).emit(any(String.class), any(Tuple.class), captor.capture()); Values capturedValues = captor.getValue(); Map val = (Map) capturedValues.get(2); assertEquals("sampleResourceUrl", val.get("resource")); Assert.assertTrue(val.get("state").toString().equals("ERROR")); }
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); }
@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); } }
EntitySearchProcessor extends SearchProcessor { @Override public List<AtlasVertex> execute() { if (LOG.isDebugEnabled()) { LOG.debug("==> EntitySearchProcessor.execute({})", context); } List<AtlasVertex> ret = new ArrayList<>(); AtlasPerfTracer perf = null; if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntitySearchProcessor.execute(" + context + ")"); } try { final int startIdx = context.getSearchParameters().getOffset(); final int limit = context.getSearchParameters().getLimit(); int qryOffset = (nextProcessor != null || (graphQuery != null && indexQuery != null)) ? 0 : startIdx; int resultIdx = qryOffset; final List<AtlasVertex> entityVertices = new ArrayList<>(); SortOrder sortOrder = context.getSearchParameters().getSortOrder(); String sortBy = context.getSearchParameters().getSortBy(); final AtlasEntityType entityType = context.getEntityTypes().iterator().next(); AtlasAttribute sortByAttribute = entityType.getAttribute(sortBy); if (sortByAttribute == null) { sortBy = null; } else { sortBy = sortByAttribute.getVertexPropertyName(); } if (sortOrder == null) { sortOrder = ASCENDING; } for (; ret.size() < limit; qryOffset += limit) { entityVertices.clear(); if (context.terminateSearch()) { LOG.warn("query terminated: {}", context.getSearchParameters()); break; } final boolean isLastResultPage; if (indexQuery != null) { Iterator<AtlasIndexQuery.Result> idxQueryResult = executeIndexQuery(context, indexQuery, qryOffset, limit); getVerticesFromIndexQueryResult(idxQueryResult, entityVertices); isLastResultPage = entityVertices.size() < limit; CollectionUtils.filter(entityVertices, inMemoryPredicate); if (graphQueryPredicate != null) { CollectionUtils.filter(entityVertices, graphQueryPredicate); } } else { Iterator<AtlasVertex> queryResult = graphQuery.vertices(qryOffset, limit).iterator(); getVertices(queryResult, entityVertices); isLastResultPage = entityVertices.size() < limit; CollectionUtils.filter(entityVertices, inMemoryPredicate); if (graphQueryPredicate != null) { CollectionUtils.filter(entityVertices, graphQueryPredicate); } } super.filter(entityVertices); resultIdx = collectResultVertices(ret, startIdx, limit, resultIdx, entityVertices); if (isLastResultPage) { break; } } } finally { AtlasPerfTracer.log(perf); } if (LOG.isDebugEnabled()) { LOG.debug("<== EntitySearchProcessor.execute({}): ret.size()={}", context, ret.size()); } return ret; } EntitySearchProcessor(SearchContext context); @Override List<AtlasVertex> execute(); @Override void filter(List<AtlasVertex> entityVertices); @Override long getResultCount(); }
@Test public void ALLEntityType() throws AtlasBaseException { SearchParameters params = new SearchParameters(); params.setTypeName(SearchParameters.ALL_ENTITY_TYPES); params.setLimit(20); SearchContext context = new SearchContext(params, typeRegistry, graph, Collections.<String>emptySet()); EntitySearchProcessor processor = new EntitySearchProcessor(context); assertEquals(processor.execute().size(), 20); } @Test public void ALLEntityTypeWithTag() throws AtlasBaseException { SearchParameters params = new SearchParameters(); params.setTypeName(SearchParameters.ALL_ENTITY_TYPES); params.setClassification(FACT_CLASSIFICATION); params.setLimit(20); SearchContext context = new SearchContext(params, typeRegistry, graph, Collections.<String>emptySet()); EntitySearchProcessor processor = new EntitySearchProcessor(context); assertEquals(processor.execute().size(), 5); } @Test public void entityType() throws AtlasBaseException { SearchParameters params = new SearchParameters(); params.setTypeName(DATABASE_TYPE); params.setLimit(20); SearchContext context = new SearchContext(params, typeRegistry, graph, Collections.<String>emptySet()); EntitySearchProcessor processor = new EntitySearchProcessor(context); assertEquals(processor.execute().size(), 3); } @Test public void entityTypes() throws AtlasBaseException { SearchParameters params = new SearchParameters(); params.setTypeName(DATABASE_TYPE+","+HIVE_TABLE_TYPE); params.setLimit(20); SearchContext context = new SearchContext(params, typeRegistry, graph, Collections.<String>emptySet()); EntitySearchProcessor processor = new EntitySearchProcessor(context); assertEquals(processor.execute().size(), 14); } @Test public void entityTypesAndTag() throws AtlasBaseException { SearchParameters params = new SearchParameters(); params.setTypeName(DATABASE_TYPE+","+HIVE_TABLE_TYPE); params.setClassification(FACT_CLASSIFICATION); params.setLimit(20); SearchContext context = new SearchContext(params, typeRegistry, graph, Collections.<String>emptySet()); EntitySearchProcessor processor = new EntitySearchProcessor(context); assertEquals(processor.execute().size(), 3); } @Test public void searchWithEntityTypesAndEntityFilters() throws AtlasBaseException { SearchParameters params = new SearchParameters(); params.setTypeName(DATABASE_TYPE+","+HIVE_TABLE_TYPE); SearchParameters.FilterCriteria filterCriteria = getSingleFilterCondition("owner", SearchParameters.Operator.CONTAINS, "ETL"); params.setEntityFilters(filterCriteria); params.setLimit(20); SearchContext context = new SearchContext(params, typeRegistry, graph, Collections.<String>emptySet()); EntitySearchProcessor processor = new EntitySearchProcessor(context); assertEquals(processor.execute().size(), 4); } @Test public void searchWithEntityTypesAndEntityFiltersAndTag() throws AtlasBaseException { SearchParameters params = new SearchParameters(); params.setTypeName(DATABASE_TYPE+","+HIVE_TABLE_TYPE); SearchParameters.FilterCriteria filterCriteria = getSingleFilterCondition("owner", SearchParameters.Operator.CONTAINS, "ETL"); params.setEntityFilters(filterCriteria); params.setClassification(LOGDATA_CLASSIFICATION); params.setLimit(20); SearchContext context = new SearchContext(params, typeRegistry, graph, Collections.<String>emptySet()); EntitySearchProcessor processor = new EntitySearchProcessor(context); assertEquals(processor.execute().size(), 2); } @Test public void searchWithNotContains_stringAttr() throws AtlasBaseException { SearchParameters params = new SearchParameters(); params.setTypeName(HIVE_TABLE_TYPE); SearchParameters.FilterCriteria filterCriteria = getSingleFilterCondition("tableType", SearchParameters.Operator.NOT_CONTAINS, "Managed"); params.setEntityFilters(filterCriteria); params.setLimit(20); SearchContext context = new SearchContext(params, typeRegistry, graph, indexer.getVertexIndexKeys()); EntitySearchProcessor processor = new EntitySearchProcessor(context); List<AtlasVertex> vertices = processor.execute(); assertEquals(vertices.size(), 3); List<String> nameList = new ArrayList<>(); for (AtlasVertex vertex : vertices) { nameList.add((String) entityRetriever.toAtlasEntityHeader(vertex, Collections.singleton("name")).getAttribute("name")); } assertTrue(nameList.contains(expectedEntityName)); } @Test public void searchWithNotContains_pipeSeperatedAttr() throws AtlasBaseException { SearchParameters params = new SearchParameters(); params.setTypeName(HIVE_TABLE_TYPE); SearchParameters.FilterCriteria filterCriteria = getSingleFilterCondition("__classificationNames", SearchParameters.Operator.NOT_CONTAINS, METRIC_CLASSIFICATION); params.setEntityFilters(filterCriteria); params.setLimit(20); SearchContext context = new SearchContext(params, typeRegistry, graph, indexer.getVertexIndexKeys()); EntitySearchProcessor processor = new EntitySearchProcessor(context); List<AtlasVertex> vertices = processor.execute(); assertEquals(vertices.size(), 7); List<String> nameList = new ArrayList<>(); for (AtlasVertex vertex : vertices) { nameList.add((String) entityRetriever.toAtlasEntityHeader(vertex, Collections.singleton("name")).getAttribute("name")); } assertTrue(nameList.contains(expectedEntityName)); } @Test(priority = -1) public void searchWithNEQ_stringAttr() throws AtlasBaseException { createDummyEntity(expectedEntityName,HIVE_TABLE_TYPE); SearchParameters params = new SearchParameters(); params.setTypeName(HIVE_TABLE_TYPE); SearchParameters.FilterCriteria filterCriteria = getSingleFilterCondition("tableType", SearchParameters.Operator.NEQ, "Managed"); params.setEntityFilters(filterCriteria); params.setLimit(20); SearchContext context = new SearchContext(params, typeRegistry, graph, indexer.getVertexIndexKeys()); EntitySearchProcessor processor = new EntitySearchProcessor(context); List<AtlasVertex> vertices = processor.execute(); assertEquals(vertices.size(), 3); List<String> nameList = new ArrayList<>(); for (AtlasVertex vertex : vertices) { nameList.add((String) entityRetriever.toAtlasEntityHeader(vertex, Collections.singleton("name")).getAttribute("name")); } assertTrue(nameList.contains(expectedEntityName)); } @Test public void searchWithNEQ_pipeSeperatedAttr() throws AtlasBaseException { SearchParameters params = new SearchParameters(); params.setTypeName(HIVE_TABLE_TYPE); SearchParameters.FilterCriteria filterCriteria = getSingleFilterCondition("__classificationNames", SearchParameters.Operator.NEQ, METRIC_CLASSIFICATION); params.setEntityFilters(filterCriteria); params.setLimit(20); SearchContext context = new SearchContext(params, typeRegistry, graph, indexer.getVertexIndexKeys()); EntitySearchProcessor processor = new EntitySearchProcessor(context); List<AtlasVertex> vertices = processor.execute(); assertEquals(vertices.size(), 7); List<String> nameList = new ArrayList<>(); for (AtlasVertex vertex : vertices) { nameList.add((String) entityRetriever.toAtlasEntityHeader(vertex, Collections.singleton("name")).getAttribute("name")); } assertTrue(nameList.contains(expectedEntityName)); } @Test public void searchWithNEQ_doubleAttr() throws AtlasBaseException { SearchParameters params = new SearchParameters(); params.setTypeName(HIVE_TABLE_TYPE); SearchParameters.FilterCriteria filterCriteria = getSingleFilterCondition("retention", SearchParameters.Operator.NEQ, "5"); params.setEntityFilters(filterCriteria); params.setLimit(20); SearchContext context = new SearchContext(params, typeRegistry, graph, indexer.getVertexIndexKeys()); EntitySearchProcessor processor = new EntitySearchProcessor(context); List<AtlasVertex> vertices = processor.execute(); assertEquals(vertices.size(), 1); List<String> nameList = new ArrayList<>(); for (AtlasVertex vertex : vertices) { nameList.add((String) entityRetriever.toAtlasEntityHeader(vertex, Collections.singleton("name")).getAttribute("name")); } assertTrue(nameList.contains("hive_Table_Null_tableType")); }
MetricsService { @SuppressWarnings("unchecked") @GraphTransaction public AtlasMetrics getMetrics() { final AtlasTypesDef typesDef = getTypesDef(); Collection<AtlasEntityDef> entityDefs = typesDef.getEntityDefs(); Collection<AtlasClassificationDef> classificationDefs = typesDef.getClassificationDefs(); Map<String, Long> activeEntityCount = new HashMap<>(); Map<String, Long> deletedEntityCount = new HashMap<>(); Map<String, Long> shellEntityCount = new HashMap<>(); Map<String, Long> taggedEntityCount = new HashMap<>(); Map<String, Long> activeEntityCountTypeAndSubTypes = new HashMap<>(); Map<String, Long> deletedEntityCountTypeAndSubTypes = new HashMap<>(); Map<String, Long> shellEntityCountTypeAndSubTypes = new HashMap<>(); long unusedTypeCount = 0; long totalEntities = 0; if (entityDefs != null) { for (AtlasEntityDef entityDef : entityDefs) { long activeCount = getTypeCount(entityDef.getName(), ACTIVE); long deletedCount = getTypeCount(entityDef.getName(), DELETED); long shellCount = getTypeShellCount(entityDef.getName()); if (activeCount > 0) { activeEntityCount.put(entityDef.getName(), activeCount); totalEntities += activeCount; } if (deletedCount > 0) { deletedEntityCount.put(entityDef.getName(), deletedCount); totalEntities += deletedCount; } if (activeCount == 0 && deletedCount == 0) { unusedTypeCount++; } if (shellCount > 0) { shellEntityCount.put(entityDef.getName(), shellCount); } } for (AtlasEntityDef entityDef : entityDefs) { AtlasEntityType entityType = typeRegistry.getEntityTypeByName(entityDef.getName()); long entityActiveCount = 0; long entityDeletedCount = 0; long entityShellCount = 0; for (String type : entityType.getTypeAndAllSubTypes()) { entityActiveCount += activeEntityCount.get(type) == null ? 0 : activeEntityCount.get(type); entityDeletedCount += deletedEntityCount.get(type) == null ? 0 : deletedEntityCount.get(type); entityShellCount += shellEntityCount.get(type) == null ? 0 : shellEntityCount.get(type); } if (entityActiveCount > 0) { activeEntityCountTypeAndSubTypes.put(entityType.getTypeName(), entityActiveCount); } if (entityDeletedCount > 0) { deletedEntityCountTypeAndSubTypes.put(entityType.getTypeName(), entityDeletedCount); } if (entityShellCount > 0) { shellEntityCountTypeAndSubTypes.put(entityType.getTypeName(), entityShellCount); } } } if (classificationDefs != null) { for (AtlasClassificationDef classificationDef : classificationDefs) { long count = getTypeCount(classificationDef.getName(), ACTIVE); if (count > 0) { taggedEntityCount.put(classificationDef.getName(), count); } } } AtlasMetrics metrics = new AtlasMetrics(); metrics.addMetric(GENERAL, METRIC_COLLECTION_TIME, System.currentTimeMillis()); metrics.addMetric(GENERAL, METRIC_STATS, metricsUtil.getStats()); metrics.addMetric(GENERAL, METRIC_TYPE_COUNT, getAllTypesCount()); metrics.addMetric(GENERAL, METRIC_TAG_COUNT, getAllTagsCount()); metrics.addMetric(GENERAL, METRIC_TYPE_UNUSED_COUNT, unusedTypeCount); metrics.addMetric(GENERAL, METRIC_ENTITY_COUNT, totalEntities); metrics.addMetric(ENTITY, METRIC_ENTITY_ACTIVE, activeEntityCount); metrics.addMetric(ENTITY, METRIC_ENTITY_DELETED, deletedEntityCount); metrics.addMetric(ENTITY, METRIC_ENTITY_SHELL, shellEntityCount); metrics.addMetric(ENTITY, METRIC_ENTITY_ACTIVE_INCL_SUBTYPES, activeEntityCountTypeAndSubTypes); metrics.addMetric(ENTITY, METRIC_ENTITY_DELETED_INCL_SUBTYPES, deletedEntityCountTypeAndSubTypes); metrics.addMetric(ENTITY, METRIC_ENTITY_SHELL_INCL_SUBTYPES, shellEntityCountTypeAndSubTypes); metrics.addMetric(TAG, METRIC_ENTITIES_PER_TAG, taggedEntityCount); metrics.addMetric(SYSTEM, METRIC_MEMORY, AtlasMetricJVMUtil.getMemoryDetails()); metrics.addMetric(SYSTEM, METRIC_OS, AtlasMetricJVMUtil.getSystemInfo()); metrics.addMetric(SYSTEM, METRIC_RUNTIME, AtlasMetricJVMUtil.getRuntimeInfo()); return metrics; } @Inject MetricsService(final AtlasGraph graph, final AtlasTypeRegistry typeRegistry, AtlasMetricsUtil metricsUtil); @SuppressWarnings("unchecked") @GraphTransaction AtlasMetrics getMetrics(); static final String TYPE; static final String TYPE_SUBTYPES; static final String ENTITY; static final String TAG; static final String GENERAL; static final String SYSTEM; }
@Test public void testGetMetrics() { AtlasMetrics metrics = metricsService.getMetrics(); assertNotNull(metrics); assertEquals(metrics.getNumericMetric(GENERAL, METRIC_ENTITY_COUNT).intValue(), 43); assertEquals(metrics.getNumericMetric(GENERAL, METRIC_TAG_COUNT).intValue(), 1); assertTrue(metrics.getNumericMetric(GENERAL, METRIC_TYPE_UNUSED_COUNT).intValue() >= 10); assertTrue(metrics.getNumericMetric(GENERAL, METRIC_TYPE_COUNT).intValue() >= 44); Map tagMetricsActual = (Map) metrics.getMetric(TAG, METRIC_ENTITIES_PER_TAG); Map activeEntityMetricsActual = (Map) metrics.getMetric(ENTITY, METRIC_ENTITY_ACTIVE); Map deletedEntityMetricsActual = (Map) metrics.getMetric(ENTITY, METRIC_ENTITY_DELETED); assertEquals(tagMetricsActual.size(), 1); assertEquals(activeEntityMetricsActual.size(), 8); assertEquals(deletedEntityMetricsActual.size(), 4); assertEquals(tagMetricsActual, tagMetricsExpected); assertEquals(activeEntityMetricsActual, activeEntityMetricsExpected); assertEquals(deletedEntityMetricsActual, deletedEntityMetricsExpected); }
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(); }
@Test public void testMapTypeIsValidValue() { for (Object value : validValues) { assertTrue(intIntMapType.isValidValue(value), "value=" + value); } for (Object value : invalidValues) { assertFalse(intIntMapType.isValidValue(value), "value=" + value); } }
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); }
@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()); } }
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); }
@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()); } }
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); }
@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); } }
AtlasEntityStoreV2 implements AtlasEntityStore { @Override @GraphTransaction public EntityMutationResponse createOrUpdate(EntityStream entityStream, boolean isPartialUpdate) throws AtlasBaseException { return createOrUpdate(entityStream, isPartialUpdate, false, false); } @Inject AtlasEntityStoreV2(AtlasGraph graph, DeleteHandlerDelegate deleteDelegate, AtlasTypeRegistry typeRegistry, IAtlasEntityChangeNotifier entityChangeNotifier, EntityGraphMapper entityGraphMapper); @Override @GraphTransaction List<String> getEntityGUIDS(final String typename); @Override @GraphTransaction AtlasEntityWithExtInfo getById(String guid); @Override @GraphTransaction AtlasEntityWithExtInfo getById(final String guid, final boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityHeader getHeaderById(final String guid); @Override @GraphTransaction AtlasEntitiesWithExtInfo getByIds(List<String> guids); @Override @GraphTransaction AtlasEntitiesWithExtInfo getByIds(List<String> guids, boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntitiesWithExtInfo getEntitiesByUniqueAttributes(AtlasEntityType entityType, List<Map<String, Object>> uniqueAttributes , boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityWithExtInfo getByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction AtlasEntityWithExtInfo getByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes, boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityHeader getEntityHeaderByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction AtlasCheckStateResult checkState(AtlasCheckStateRequest request); @Override @GraphTransaction EntityMutationResponse createOrUpdate(EntityStream entityStream, boolean isPartialUpdate); @Override @GraphTransaction(logRollback = false) EntityMutationResponse createOrUpdateForImport(EntityStream entityStream); @Override EntityMutationResponse createOrUpdateForImportNoCommit(EntityStream entityStream); @Override @GraphTransaction EntityMutationResponse updateEntity(AtlasObjectId objectId, AtlasEntityWithExtInfo updatedEntityInfo, boolean isPartialUpdate); @Override @GraphTransaction EntityMutationResponse updateByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes, AtlasEntityWithExtInfo updatedEntityInfo); @Override @GraphTransaction EntityMutationResponse updateEntityAttributeByGuid(String guid, String attrName, Object attrValue); @Override @GraphTransaction EntityMutationResponse deleteById(final String guid); @Override @GraphTransaction EntityMutationResponse deleteByIds(final List<String> guids); @Override @GraphTransaction EntityMutationResponse purgeByIds(Set<String> guids); @Override @GraphTransaction EntityMutationResponse deleteByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction String getGuidByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction void addClassifications(final String guid, final List<AtlasClassification> classifications); @Override @GraphTransaction void updateClassifications(String guid, List<AtlasClassification> classifications); @Override @GraphTransaction void addClassification(final List<String> guids, final AtlasClassification classification); @Override @GraphTransaction void deleteClassification(final String guid, final String classificationName); @Override @GraphTransaction void deleteClassification(final String guid, final String classificationName, final String associatedEntityGuid); @GraphTransaction List<AtlasClassification> retrieveClassifications(String guid); @Override @GraphTransaction List<AtlasClassification> getClassifications(String guid); @Override @GraphTransaction AtlasClassification getClassification(String guid, String classificationName); @Override @GraphTransaction String setClassifications(AtlasEntityHeaders entityHeaders); @Override @GraphTransaction void addOrUpdateBusinessAttributes(String guid, Map<String, Map<String, Object>> businessAttrbutes, boolean isOverwrite); @Override @GraphTransaction void removeBusinessAttributes(String guid, Map<String, Map<String, Object>> businessAttributes); @Override @GraphTransaction void setLabels(String guid, Set<String> labels); @Override @GraphTransaction void removeLabels(String guid, Set<String> labels); @Override @GraphTransaction void addLabels(String guid, Set<String> labels); @Override @GraphTransaction BulkImportResponse bulkCreateOrUpdateBusinessAttributes(InputStream inputStream, String fileName); }
@Test public void testDefaultValueForPrimitiveTypes() throws Exception { init(); EntityMutationResponse response = entityStore.createOrUpdate(new AtlasEntityStream(primitiveEntity), false); List<AtlasEntityHeader> entitiesCreatedResponse = response.getEntitiesByOperation(EntityOperation.CREATE); List<AtlasEntityHeader> entitiesCreatedwithdefault = response.getMutatedEntities().get(EntityOperation.CREATE); AtlasEntity entityCreated = getEntityFromStore(entitiesCreatedResponse.get(0)); Map attributesMap = entityCreated.getAttributes(); String description = (String) attributesMap.get("description"); String check = (String) attributesMap.get("check"); String sourceCode = (String) attributesMap.get("sourcecode"); float diskUsage = (float) attributesMap.get("diskUsage"); boolean isstoreUse = (boolean) attributesMap.get("isstoreUse"); int cost = (int) attributesMap.get("Cost"); assertEquals(description,"test"); assertEquals(check,"check"); assertEquals(diskUsage,70.5f); assertEquals(isstoreUse,true); assertEquals(sourceCode,"Hello World"); assertEquals(cost,30); } @Test(priority = -1) public void testCreate() throws Exception { init(); EntityMutationResponse response = entityStore.createOrUpdate(new AtlasEntityStream(deptEntity), false); validateMutationResponse(response, EntityOperation.CREATE, 5); AtlasEntityHeader dept1 = response.getFirstCreatedEntityByTypeName(TestUtilsV2.DEPARTMENT_TYPE); validateEntity(deptEntity, getEntityFromStore(dept1), deptEntity.getEntities().get(0)); final Map<EntityOperation, List<AtlasEntityHeader>> entitiesMutated = response.getMutatedEntities(); List<AtlasEntityHeader> entitiesCreated = entitiesMutated.get(EntityOperation.CREATE); assertTrue(entitiesCreated.size() >= deptEntity.getEntities().size()); for (int i = 0; i < deptEntity.getEntities().size(); i++) { AtlasEntity expected = deptEntity.getEntities().get(i); AtlasEntity actual = getEntityFromStore(entitiesCreated.get(i)); validateEntity(deptEntity, actual, expected); } init(); EntityMutationResponse dbCreationResponse = entityStore.createOrUpdate(new AtlasEntityStream(dbEntity), false); validateMutationResponse(dbCreationResponse, EntityOperation.CREATE, 1); dbEntityGuid = dbCreationResponse.getCreatedEntities().get(0).getGuid(); AtlasEntityHeader db1 = dbCreationResponse.getFirstCreatedEntityByTypeName(TestUtilsV2.DATABASE_TYPE); validateEntity(dbEntity, getEntityFromStore(db1)); AtlasObjectId dbObjectId = (AtlasObjectId) tblEntity.getEntity().getAttribute("database"); dbObjectId.setGuid(db1.getGuid()); tblEntity.addReferredEntity(dbEntity.getEntity()); init(); EntityMutationResponse tableCreationResponse = entityStore.createOrUpdate(new AtlasEntityStream(tblEntity), false); validateMutationResponse(tableCreationResponse, EntityOperation.CREATE, 1); tblEntityGuid = tableCreationResponse.getCreatedEntities().get(0).getGuid(); AtlasEntityHeader tableEntity = tableCreationResponse.getFirstCreatedEntityByTypeName(TABLE_TYPE); validateEntity(tblEntity, getEntityFromStore(tableEntity)); init(); EntityMutationResponse entityMutationResponse = entityStore.createOrUpdate(new AtlasEntityStream(nestedCollectionAttrEntity), false); validateMutationResponse(entityMutationResponse, EntityOperation.CREATE, 1); AtlasEntityHeader createdEntity = entityMutationResponse.getFirstCreatedEntityByTypeName(TestUtilsV2.ENTITY_TYPE_WITH_NESTED_COLLECTION_ATTR); validateEntity(nestedCollectionAttrEntity, getEntityFromStore(createdEntity)); } @Test(dependsOnMethods = "testCreate") public void testMapOfPrimitivesUpdate() throws Exception { AtlasEntity tableEntity = new AtlasEntity(tblEntity.getEntity()); AtlasEntitiesWithExtInfo entitiesInfo = new AtlasEntitiesWithExtInfo(tableEntity); entitiesInfo.addReferredEntity(tableEntity); Map<String, String> paramsMap = (Map<String, String>) tableEntity.getAttribute("parametersMap"); paramsMap.put("newParam", "value"); init(); EntityMutationResponse response = entityStore.createOrUpdate(new AtlasEntityStream(entitiesInfo), false); validateMutationResponse(response, EntityMutations.EntityOperation.UPDATE, 1); AtlasEntityHeader updatedTable = response.getFirstUpdatedEntityByTypeName(TABLE_TYPE); validateEntity(entitiesInfo, getEntityFromStore(updatedTable)); paramsMap.remove("key1"); tableEntity.setAttribute("parametersMap", paramsMap); init(); response = entityStore.createOrUpdate(new AtlasEntityStream(entitiesInfo), false); validateMutationResponse(response, EntityMutations.EntityOperation.UPDATE, 1); updatedTable = response.getFirstUpdatedEntityByTypeName(TABLE_TYPE); validateEntity(entitiesInfo, getEntityFromStore(updatedTable)); } @Test(dependsOnMethods = "testCreate") public void testArrayOfStructs() throws Exception { AtlasEntity tableEntity = new AtlasEntity(tblEntity.getEntity()); AtlasEntitiesWithExtInfo entitiesInfo = new AtlasEntitiesWithExtInfo(tableEntity); List<AtlasStruct> partitions = new ArrayList<AtlasStruct>(){{ add(new AtlasStruct(TestUtilsV2.PARTITION_STRUCT_TYPE, NAME, "part1")); add(new AtlasStruct(TestUtilsV2.PARTITION_STRUCT_TYPE, NAME, "part2")); }}; tableEntity.setAttribute("partitions", partitions); init(); EntityMutationResponse response = entityStore.createOrUpdate(new AtlasEntityStream(entitiesInfo), false); AtlasEntityHeader updatedTable = response.getFirstUpdatedEntityByTypeName(TABLE_TYPE); validateEntity(entitiesInfo, getEntityFromStore(updatedTable)); partitions.add(new AtlasStruct(TestUtilsV2.PARTITION_STRUCT_TYPE, NAME, "part3")); tableEntity.setAttribute("partitions", partitions); init(); response = entityStore.createOrUpdate(new AtlasEntityStream(entitiesInfo), false); updatedTable = response.getFirstUpdatedEntityByTypeName(TABLE_TYPE); validateEntity(entitiesInfo, getEntityFromStore(updatedTable)); partitions.remove(1); tableEntity.setAttribute("partitions", partitions); init(); response = entityStore.createOrUpdate(new AtlasEntityStream(entitiesInfo), false); updatedTable = response.getFirstUpdatedEntityByTypeName(TABLE_TYPE); validateEntity(entitiesInfo, getEntityFromStore(updatedTable)); partitions.get(0).setAttribute(NAME, "part4"); tableEntity.setAttribute("partitions", partitions); init(); response = entityStore.createOrUpdate(new AtlasEntityStream(entitiesInfo), false); updatedTable = response.getFirstUpdatedEntityByTypeName(TABLE_TYPE); validateEntity(entitiesInfo, getEntityFromStore(updatedTable)); partitions.add(new AtlasStruct(TestUtilsV2.PARTITION_STRUCT_TYPE, NAME, "part4")); tableEntity.setAttribute("partitions", partitions); init(); response = entityStore.createOrUpdate(new AtlasEntityStream(entitiesInfo), false); updatedTable = response.getFirstUpdatedEntityByTypeName(TABLE_TYPE); validateEntity(entitiesInfo, getEntityFromStore(updatedTable)); partitions.clear(); tableEntity.setAttribute("partitions", partitions); init(); response = entityStore.createOrUpdate(new AtlasEntityStream(entitiesInfo), false); updatedTable = response.getFirstUpdatedEntityByTypeName(TABLE_TYPE); validateEntity(entitiesInfo, getEntityFromStore(updatedTable)); } @Test(dependsOnMethods = "testCreate") public void testStructs() throws Exception { AtlasEntity databaseEntity = dbEntity.getEntity(); AtlasEntity tableEntity = new AtlasEntity(tblEntity.getEntity()); AtlasEntitiesWithExtInfo entitiesInfo = new AtlasEntitiesWithExtInfo(tableEntity); AtlasStruct serdeInstance = new AtlasStruct(TestUtilsV2.SERDE_TYPE, NAME, "serde1Name"); serdeInstance.setAttribute("serde", "test"); serdeInstance.setAttribute("description", "testDesc"); tableEntity.setAttribute("serde1", serdeInstance); tableEntity.setAttribute("database", new AtlasObjectId(databaseEntity.getTypeName(), NAME, databaseEntity.getAttribute(NAME))); init(); EntityMutationResponse response = entityStore.createOrUpdate(new AtlasEntityStream(entitiesInfo), false); AtlasEntityHeader updatedTable = response.getFirstUpdatedEntityByTypeName(TABLE_TYPE); validateEntity(entitiesInfo, getEntityFromStore(updatedTable)); serdeInstance.setAttribute("serde", "testUpdated"); init(); response = entityStore.createOrUpdate(new AtlasEntityStream(entitiesInfo), false); updatedTable = response.getFirstUpdatedEntityByTypeName(TABLE_TYPE); validateEntity(entitiesInfo, getEntityFromStore(updatedTable)); tableEntity.setAttribute("description", null); init(); response = entityStore.createOrUpdate(new AtlasEntityStream(entitiesInfo), false); updatedTable = response.getFirstUpdatedEntityByTypeName(TABLE_TYPE); Assert.assertNull(updatedTable.getAttribute("description")); validateEntity(entitiesInfo, getEntityFromStore(updatedTable)); } @Test(dependsOnMethods = "testCreate") public void testClassUpdate() throws Exception { init(); final AtlasEntity databaseInstance = TestUtilsV2.createDBEntity(); EntityMutationResponse response = entityStore.createOrUpdate(new AtlasEntityStream(databaseInstance), false); final AtlasEntityHeader dbCreated = response.getFirstCreatedEntityByTypeName(TestUtilsV2.DATABASE_TYPE); init(); Map<String, AtlasEntity> tableCloneMap = new HashMap<>(); AtlasEntity tableClone = new AtlasEntity(tblEntity.getEntity()); tableClone.setAttribute("database", new AtlasObjectId(dbCreated.getGuid(), TestUtilsV2.DATABASE_TYPE)); tableCloneMap.put(dbCreated.getGuid(), databaseInstance); tableCloneMap.put(tableClone.getGuid(), tableClone); response = entityStore.createOrUpdate(new InMemoryMapEntityStream(tableCloneMap), false); final AtlasEntityHeader tableDefinition = response.getFirstUpdatedEntityByTypeName(TABLE_TYPE); AtlasEntity updatedTableDefinition = getEntityFromStore(tableDefinition); assertNotNull(updatedTableDefinition.getAttribute("database")); Assert.assertEquals(((AtlasObjectId) updatedTableDefinition.getAttribute("database")).getGuid(), dbCreated.getGuid()); } @Test public void testCheckOptionalAttrValueRetention() throws Exception { AtlasEntity dbEntity = TestUtilsV2.createDBEntity(); init(); EntityMutationResponse response = entityStore.createOrUpdate(new AtlasEntityStream(dbEntity), false); AtlasEntity firstEntityCreated = getEntityFromStore(response.getFirstCreatedEntityByTypeName(TestUtilsV2.DATABASE_TYPE)); final String isReplicatedAttr = "isReplicated"; final String paramsAttr = "parameters"; assertNotNull(firstEntityCreated.getAttribute(isReplicatedAttr)); Assert.assertEquals(firstEntityCreated.getAttribute(isReplicatedAttr), Boolean.FALSE); Assert.assertNull(firstEntityCreated.getAttribute(paramsAttr)); dbEntity.setAttribute(isReplicatedAttr, Boolean.TRUE); final HashMap<String, String> params = new HashMap<String, String>() {{ put("param1", "val1"); put("param2", "val2"); }}; dbEntity.setAttribute(paramsAttr, params); init(); response = entityStore.createOrUpdate(new AtlasEntityStream(dbEntity), false); AtlasEntity firstEntityUpdated = getEntityFromStore(response.getFirstUpdatedEntityByTypeName(TestUtilsV2.DATABASE_TYPE)); assertNotNull(firstEntityUpdated); assertNotNull(firstEntityUpdated.getAttribute(isReplicatedAttr)); Assert.assertEquals(firstEntityUpdated.getAttribute(isReplicatedAttr), Boolean.TRUE); Assert.assertEquals(firstEntityUpdated.getAttribute(paramsAttr), params); } @Test(enabled = false) public void testSpecialCharacters() throws Exception { final String typeName = TestUtilsV2.randomString(10); String strAttrName = randomStrWithReservedChars(); String arrayAttrName = randomStrWithReservedChars(); String mapAttrName = randomStrWithReservedChars(); AtlasEntityDef typeDefinition = AtlasTypeUtil.createClassTypeDef(typeName, "Special chars test type", ImmutableSet.<String>of(), AtlasTypeUtil.createOptionalAttrDef(strAttrName, "string"), AtlasTypeUtil.createOptionalAttrDef(arrayAttrName, "array<string>"), AtlasTypeUtil.createOptionalAttrDef(mapAttrName, "map<string,string>")); AtlasTypesDef atlasTypesDef = new AtlasTypesDef(null, null, null, Arrays.asList(typeDefinition)); typeDefStore.createTypesDef(atlasTypesDef); AtlasEntity entity = new AtlasEntity(); entity.setAttribute(strAttrName, randomStrWithReservedChars()); entity.setAttribute(arrayAttrName, new String[]{randomStrWithReservedChars()}); entity.setAttribute(mapAttrName, new HashMap<String, String>() {{ put(randomStrWithReservedChars(), randomStrWithReservedChars()); }}); AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(entity); final EntityMutationResponse response = entityStore.createOrUpdate(new AtlasEntityStream(entityWithExtInfo), false); final AtlasEntityHeader firstEntityCreated = response.getFirstEntityCreated(); validateEntity(entityWithExtInfo, getEntityFromStore(firstEntityCreated)); } @Test(expectedExceptions = AtlasBaseException.class) public void testCreateRequiredAttrNull() throws Exception { Map<String, AtlasEntity> tableCloneMap = new HashMap<>(); AtlasEntity tableEntity = new AtlasEntity(TABLE_TYPE); tableEntity.setAttribute(NAME, "table_" + TestUtilsV2.randomString()); tableCloneMap.put(tableEntity.getGuid(), tableEntity); entityStore.createOrUpdate(new InMemoryMapEntityStream(tableCloneMap), false); Assert.fail("Expected exception while creating with required attribute null"); } @Test (dependsOnMethods = "testCreate") public void addCustomAttributesToEntity() throws AtlasBaseException { AtlasEntity tblEntity = getEntityFromStore(tblEntityGuid); Map<String, String> customAttributes = new HashMap<>(); customAttributes.put("key1", "val1"); customAttributes.put("key2", "val2"); customAttributes.put("key3", "val3"); customAttributes.put("key4", "val4"); customAttributes.put("key5", "val5"); tblEntity.setCustomAttributes(customAttributes); entityStore.createOrUpdate(new AtlasEntityStream(tblEntity), false); tblEntity = getEntityFromStore(tblEntityGuid); assertEquals(customAttributes, tblEntity.getCustomAttributes()); } @Test (dependsOnMethods = "addCustomAttributesToEntity") public void updateCustomAttributesToEntity() throws AtlasBaseException { AtlasEntity tblEntity = getEntityFromStore(tblEntityGuid); Map<String, String> customAttributes = new HashMap<>(); customAttributes.put("key1", "val1"); customAttributes.put("key2", "val2"); tblEntity.setCustomAttributes(customAttributes); entityStore.createOrUpdate(new AtlasEntityStream(tblEntity), false); tblEntity = getEntityFromStore(tblEntityGuid); assertEquals(customAttributes, tblEntity.getCustomAttributes()); } @Test (dependsOnMethods = "updateCustomAttributesToEntity") public void deleteCustomAttributesToEntity() throws AtlasBaseException { AtlasEntity tblEntity = getEntityFromStore(tblEntityGuid); Map<String, String> emptyCustomAttributes = new HashMap<>(); tblEntity.setCustomAttributes(emptyCustomAttributes); entityStore.createOrUpdate(new AtlasEntityStream(tblEntity), false); tblEntity = getEntityFromStore(tblEntityGuid); assertEquals(emptyCustomAttributes, tblEntity.getCustomAttributes()); } @Test (dependsOnMethods = "deleteCustomAttributesToEntity") public void nullCustomAttributesToEntity() throws AtlasBaseException { AtlasEntity tblEntity = getEntityFromStore(tblEntityGuid); Map<String, String> customAttributes = new HashMap<>(); customAttributes.put("key1", "val1"); customAttributes.put("key2", "val2"); tblEntity.setCustomAttributes(customAttributes); entityStore.createOrUpdate(new AtlasEntityStream(tblEntity), false); tblEntity.setCustomAttributes(null); entityStore.createOrUpdate(new AtlasEntityStream(tblEntity), false); tblEntity = getEntityFromStore(tblEntityGuid); assertEquals(customAttributes, tblEntity.getCustomAttributes()); } @Test (dependsOnMethods = "nullCustomAttributesToEntity") public void addInvalidKeysToEntityCustomAttributes() throws AtlasBaseException { AtlasEntity tblEntity = getEntityFromStore(tblEntityGuid); Map<String, String> invalidCustomAttributes = new HashMap<>(); invalidCustomAttributes.put("key0_65765-6565", "val0"); invalidCustomAttributes.put("key1-aaa_bbb-ccc", "val1"); invalidCustomAttributes.put("key2!@#$%&*()", "val2"); tblEntity.setCustomAttributes(invalidCustomAttributes); try { entityStore.createOrUpdate(new AtlasEntityStream(tblEntity), false); } catch (AtlasBaseException ex) { assertEquals(ex.getAtlasErrorCode(), INVALID_CUSTOM_ATTRIBUTE_KEY_CHARACTERS); } invalidCustomAttributes = new HashMap<>(); invalidCustomAttributes.put("bigValue_lengthEquals_50", randomAlphanumeric(50)); invalidCustomAttributes.put("bigValue_lengthEquals_51", randomAlphanumeric(51)); tblEntity.setCustomAttributes(invalidCustomAttributes); try { entityStore.createOrUpdate(new AtlasEntityStream(tblEntity), false); } catch (AtlasBaseException ex) { assertEquals(ex.getAtlasErrorCode(), INVALID_CUSTOM_ATTRIBUTE_KEY_LENGTH); } } @Test (dependsOnMethods = "addInvalidKeysToEntityCustomAttributes") public void addInvalidValuesToEntityCustomAttributes() throws AtlasBaseException { AtlasEntity tblEntity = getEntityFromStore(tblEntityGuid); Map<String, String> invalidCustomAttributes = new HashMap<>(); invalidCustomAttributes.put("key1", randomAlphanumeric(500)); invalidCustomAttributes.put("key2", randomAlphanumeric(501)); tblEntity.setCustomAttributes(invalidCustomAttributes); try { entityStore.createOrUpdate(new AtlasEntityStream(tblEntity), false); } catch (AtlasBaseException ex) { assertEquals(ex.getAtlasErrorCode(), INVALID_CUSTOM_ATTRIBUTE_VALUE); } }
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(); }
@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); } }
AtlasEntityStoreV2 implements AtlasEntityStore { @Override @GraphTransaction public void setLabels(String guid, Set<String> labels) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> setLabels()"); } if (StringUtils.isEmpty(guid)) { throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS, "guid is null/empty"); } AtlasVertex entityVertex = AtlasGraphUtilsV2.findByGuid(graph, guid); if (entityVertex == null) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guid); } validateLabels(labels); AtlasEntityHeader entityHeader = entityRetriever.toAtlasEntityHeaderWithClassifications(entityVertex); Set<String> addedLabels = Collections.emptySet(); Set<String> removedLabels = Collections.emptySet(); if (CollectionUtils.isEmpty(entityHeader.getLabels())) { addedLabels = labels; } else if (CollectionUtils.isEmpty(labels)) { removedLabels = entityHeader.getLabels(); } else { addedLabels = new HashSet<String>(CollectionUtils.subtract(labels, entityHeader.getLabels())); removedLabels = new HashSet<String>(CollectionUtils.subtract(entityHeader.getLabels(), labels)); } if (addedLabels != null) { AtlasEntityAccessRequestBuilder requestBuilder = new AtlasEntityAccessRequestBuilder(typeRegistry, AtlasPrivilege.ENTITY_ADD_LABEL, entityHeader); for (String label : addedLabels) { requestBuilder.setLabel(label); AtlasAuthorizationUtils.verifyAccess(requestBuilder.build(), "add label: guid=", guid, ", label=", label); } } if (removedLabels != null) { AtlasEntityAccessRequestBuilder requestBuilder = new AtlasEntityAccessRequestBuilder(typeRegistry, AtlasPrivilege.ENTITY_REMOVE_LABEL, entityHeader); for (String label : removedLabels) { requestBuilder.setLabel(label); AtlasAuthorizationUtils.verifyAccess(requestBuilder.build(), "remove label: guid=", guid, ", label=", label); } } entityGraphMapper.setLabels(entityVertex, labels); if (LOG.isDebugEnabled()) { LOG.debug("<== setLabels()"); } } @Inject AtlasEntityStoreV2(AtlasGraph graph, DeleteHandlerDelegate deleteDelegate, AtlasTypeRegistry typeRegistry, IAtlasEntityChangeNotifier entityChangeNotifier, EntityGraphMapper entityGraphMapper); @Override @GraphTransaction List<String> getEntityGUIDS(final String typename); @Override @GraphTransaction AtlasEntityWithExtInfo getById(String guid); @Override @GraphTransaction AtlasEntityWithExtInfo getById(final String guid, final boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityHeader getHeaderById(final String guid); @Override @GraphTransaction AtlasEntitiesWithExtInfo getByIds(List<String> guids); @Override @GraphTransaction AtlasEntitiesWithExtInfo getByIds(List<String> guids, boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntitiesWithExtInfo getEntitiesByUniqueAttributes(AtlasEntityType entityType, List<Map<String, Object>> uniqueAttributes , boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityWithExtInfo getByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction AtlasEntityWithExtInfo getByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes, boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityHeader getEntityHeaderByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction AtlasCheckStateResult checkState(AtlasCheckStateRequest request); @Override @GraphTransaction EntityMutationResponse createOrUpdate(EntityStream entityStream, boolean isPartialUpdate); @Override @GraphTransaction(logRollback = false) EntityMutationResponse createOrUpdateForImport(EntityStream entityStream); @Override EntityMutationResponse createOrUpdateForImportNoCommit(EntityStream entityStream); @Override @GraphTransaction EntityMutationResponse updateEntity(AtlasObjectId objectId, AtlasEntityWithExtInfo updatedEntityInfo, boolean isPartialUpdate); @Override @GraphTransaction EntityMutationResponse updateByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes, AtlasEntityWithExtInfo updatedEntityInfo); @Override @GraphTransaction EntityMutationResponse updateEntityAttributeByGuid(String guid, String attrName, Object attrValue); @Override @GraphTransaction EntityMutationResponse deleteById(final String guid); @Override @GraphTransaction EntityMutationResponse deleteByIds(final List<String> guids); @Override @GraphTransaction EntityMutationResponse purgeByIds(Set<String> guids); @Override @GraphTransaction EntityMutationResponse deleteByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction String getGuidByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction void addClassifications(final String guid, final List<AtlasClassification> classifications); @Override @GraphTransaction void updateClassifications(String guid, List<AtlasClassification> classifications); @Override @GraphTransaction void addClassification(final List<String> guids, final AtlasClassification classification); @Override @GraphTransaction void deleteClassification(final String guid, final String classificationName); @Override @GraphTransaction void deleteClassification(final String guid, final String classificationName, final String associatedEntityGuid); @GraphTransaction List<AtlasClassification> retrieveClassifications(String guid); @Override @GraphTransaction List<AtlasClassification> getClassifications(String guid); @Override @GraphTransaction AtlasClassification getClassification(String guid, String classificationName); @Override @GraphTransaction String setClassifications(AtlasEntityHeaders entityHeaders); @Override @GraphTransaction void addOrUpdateBusinessAttributes(String guid, Map<String, Map<String, Object>> businessAttrbutes, boolean isOverwrite); @Override @GraphTransaction void removeBusinessAttributes(String guid, Map<String, Map<String, Object>> businessAttributes); @Override @GraphTransaction void setLabels(String guid, Set<String> labels); @Override @GraphTransaction void removeLabels(String guid, Set<String> labels); @Override @GraphTransaction void addLabels(String guid, Set<String> labels); @Override @GraphTransaction BulkImportResponse bulkCreateOrUpdateBusinessAttributes(InputStream inputStream, String fileName); }
@Test(dependsOnMethods = "testCreate") public void addLabelsToEntity() throws AtlasBaseException { Set<String> labels = new HashSet<>(); labels.add("label_1"); labels.add("label_2"); labels.add("label_3"); labels.add("label_4"); labels.add("label_5"); entityStore.setLabels(tblEntityGuid, labels); AtlasEntity tblEntity = getEntityFromStore(tblEntityGuid); assertEquals(labels, tblEntity.getLabels()); } @Test (dependsOnMethods = "addLabelsToEntity") public void updateLabelsToEntity() throws AtlasBaseException { Set<String> labels = new HashSet<>(); labels.add("label_1_update"); labels.add("label_2_update"); labels.add("label_3_update"); entityStore.setLabels(tblEntityGuid, labels); AtlasEntity tblEntity = getEntityFromStore(tblEntityGuid); assertEquals(labels, tblEntity.getLabels()); } @Test (dependsOnMethods = "updateLabelsToEntity") public void clearLabelsToEntity() throws AtlasBaseException { HashSet<String> emptyLabels = new HashSet<>(); entityStore.setLabels(tblEntityGuid, emptyLabels); AtlasEntity tblEntity = getEntityFromStore(tblEntityGuid); Assert.assertTrue(tblEntity.getLabels().isEmpty()); } @Test (dependsOnMethods = "clearLabelsToEntity") public void emptyLabelsToEntity() throws AtlasBaseException { entityStore.setLabels(tblEntityGuid, null); AtlasEntity tblEntity = getEntityFromStore(tblEntityGuid); Assert.assertTrue(tblEntity.getLabels().isEmpty()); } @Test (dependsOnMethods = "emptyLabelsToEntity") public void invalidLabelLengthToEntity() throws AtlasBaseException { Set<String> labels = new HashSet<>(); labels.add(randomAlphanumeric(50)); labels.add(randomAlphanumeric(51)); try { entityStore.setLabels(tblEntityGuid, labels); } catch (AtlasBaseException ex) { assertEquals(ex.getAtlasErrorCode(), INVALID_LABEL_LENGTH); } } @Test (dependsOnMethods = "invalidLabelLengthToEntity") public void invalidLabelCharactersToEntity() { Set<String> labels = new HashSet<>(); labels.add("label-1_100_45"); labels.add("LABEL-1_200-55"); labels.add("LaBeL-1-)(*U&%^%#$@!~"); try { entityStore.setLabels(tblEntityGuid, labels); } catch (AtlasBaseException ex) { assertEquals(ex.getAtlasErrorCode(), INVALID_LABEL_CHARACTERS); } }
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(); }
@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(); } }
AtlasEntityStoreV2 implements AtlasEntityStore { @Override @GraphTransaction public void removeLabels(String guid, Set<String> labels) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> removeLabels()"); } if (StringUtils.isEmpty(guid)) { throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS, "guid is null/empty"); } if (CollectionUtils.isEmpty(labels)) { throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS, "labels is null/empty"); } AtlasVertex entityVertex = AtlasGraphUtilsV2.findByGuid(graph, guid); if (entityVertex == null) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guid); } AtlasEntityHeader entityHeader = entityRetriever.toAtlasEntityHeaderWithClassifications(entityVertex); AtlasEntityAccessRequestBuilder requestBuilder = new AtlasEntityAccessRequestBuilder(typeRegistry, AtlasPrivilege.ENTITY_REMOVE_LABEL, entityHeader); for (String label : labels) { requestBuilder.setLabel(label); AtlasAuthorizationUtils.verifyAccess(requestBuilder.build(), "remove label: guid=", guid, ", label=", label); } validateLabels(labels); entityGraphMapper.removeLabels(entityVertex, labels); if (LOG.isDebugEnabled()) { LOG.debug("<== removeLabels()"); } } @Inject AtlasEntityStoreV2(AtlasGraph graph, DeleteHandlerDelegate deleteDelegate, AtlasTypeRegistry typeRegistry, IAtlasEntityChangeNotifier entityChangeNotifier, EntityGraphMapper entityGraphMapper); @Override @GraphTransaction List<String> getEntityGUIDS(final String typename); @Override @GraphTransaction AtlasEntityWithExtInfo getById(String guid); @Override @GraphTransaction AtlasEntityWithExtInfo getById(final String guid, final boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityHeader getHeaderById(final String guid); @Override @GraphTransaction AtlasEntitiesWithExtInfo getByIds(List<String> guids); @Override @GraphTransaction AtlasEntitiesWithExtInfo getByIds(List<String> guids, boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntitiesWithExtInfo getEntitiesByUniqueAttributes(AtlasEntityType entityType, List<Map<String, Object>> uniqueAttributes , boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityWithExtInfo getByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction AtlasEntityWithExtInfo getByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes, boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityHeader getEntityHeaderByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction AtlasCheckStateResult checkState(AtlasCheckStateRequest request); @Override @GraphTransaction EntityMutationResponse createOrUpdate(EntityStream entityStream, boolean isPartialUpdate); @Override @GraphTransaction(logRollback = false) EntityMutationResponse createOrUpdateForImport(EntityStream entityStream); @Override EntityMutationResponse createOrUpdateForImportNoCommit(EntityStream entityStream); @Override @GraphTransaction EntityMutationResponse updateEntity(AtlasObjectId objectId, AtlasEntityWithExtInfo updatedEntityInfo, boolean isPartialUpdate); @Override @GraphTransaction EntityMutationResponse updateByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes, AtlasEntityWithExtInfo updatedEntityInfo); @Override @GraphTransaction EntityMutationResponse updateEntityAttributeByGuid(String guid, String attrName, Object attrValue); @Override @GraphTransaction EntityMutationResponse deleteById(final String guid); @Override @GraphTransaction EntityMutationResponse deleteByIds(final List<String> guids); @Override @GraphTransaction EntityMutationResponse purgeByIds(Set<String> guids); @Override @GraphTransaction EntityMutationResponse deleteByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction String getGuidByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction void addClassifications(final String guid, final List<AtlasClassification> classifications); @Override @GraphTransaction void updateClassifications(String guid, List<AtlasClassification> classifications); @Override @GraphTransaction void addClassification(final List<String> guids, final AtlasClassification classification); @Override @GraphTransaction void deleteClassification(final String guid, final String classificationName); @Override @GraphTransaction void deleteClassification(final String guid, final String classificationName, final String associatedEntityGuid); @GraphTransaction List<AtlasClassification> retrieveClassifications(String guid); @Override @GraphTransaction List<AtlasClassification> getClassifications(String guid); @Override @GraphTransaction AtlasClassification getClassification(String guid, String classificationName); @Override @GraphTransaction String setClassifications(AtlasEntityHeaders entityHeaders); @Override @GraphTransaction void addOrUpdateBusinessAttributes(String guid, Map<String, Map<String, Object>> businessAttrbutes, boolean isOverwrite); @Override @GraphTransaction void removeBusinessAttributes(String guid, Map<String, Map<String, Object>> businessAttributes); @Override @GraphTransaction void setLabels(String guid, Set<String> labels); @Override @GraphTransaction void removeLabels(String guid, Set<String> labels); @Override @GraphTransaction void addLabels(String guid, Set<String> labels); @Override @GraphTransaction BulkImportResponse bulkCreateOrUpdateBusinessAttributes(InputStream inputStream, String fileName); }
@Test (dependsOnMethods = "addMoreLabelsToEntity") public void deleteLabelsToEntity() throws AtlasBaseException { Set<String> labels = new HashSet<>(); labels.add("label_1_add"); labels.add("label_2_add"); entityStore.removeLabels(tblEntityGuid, labels); AtlasEntity tblEntity = getEntityFromStore(tblEntityGuid); assertNotNull(tblEntity.getLabels()); Assert.assertEquals(tblEntity.getLabels().size(), 1); labels.clear(); labels.add("label_4_add"); entityStore.removeLabels(tblEntityGuid, labels); tblEntity = getEntityFromStore(tblEntityGuid); assertNotNull(tblEntity.getLabels()); Assert.assertEquals(tblEntity.getLabels().size(), 1); labels.clear(); labels.add("label_3_add"); entityStore.removeLabels(tblEntityGuid, labels); tblEntity = getEntityFromStore(tblEntityGuid); Assert.assertTrue(tblEntity.getLabels().isEmpty()); }
AtlasEntityStoreV2 implements AtlasEntityStore { @Override @GraphTransaction public void addOrUpdateBusinessAttributes(String guid, Map<String, Map<String, Object>> businessAttrbutes, boolean isOverwrite) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> addOrUpdateBusinessAttributes(guid={}, businessAttributes={}, isOverwrite={})", guid, businessAttrbutes, isOverwrite); } if (StringUtils.isEmpty(guid)) { throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS, "guid is null/empty"); } if (MapUtils.isEmpty(businessAttrbutes)) { throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS, "businessAttributes is null/empty"); } AtlasVertex entityVertex = AtlasGraphUtilsV2.findByGuid(graph, guid); if (entityVertex == null) { throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND, guid); } String typeName = getTypeName(entityVertex); AtlasEntityType entityType = typeRegistry.getEntityTypeByName(typeName); AtlasEntityHeader entityHeader = entityRetriever.toAtlasEntityHeaderWithClassifications(entityVertex); Map<String, Map<String, Object>> currEntityBusinessAttributes = entityRetriever.getBusinessMetadata(entityVertex); Set<String> updatedBusinessMetadataNames = new HashSet<>(); for (String bmName : entityType.getBusinessAttributes().keySet()) { Map<String, Object> bmAttrs = businessAttrbutes.get(bmName); Map<String, Object> currBmAttrs = currEntityBusinessAttributes != null ? currEntityBusinessAttributes.get(bmName) : null; if (bmAttrs == null && !isOverwrite) { continue; } else if (MapUtils.isEmpty(bmAttrs) && MapUtils.isEmpty(currBmAttrs)) { continue; } else if (Objects.equals(bmAttrs, currBmAttrs)) { continue; } updatedBusinessMetadataNames.add(bmName); } AtlasEntityAccessRequestBuilder requestBuilder = new AtlasEntityAccessRequestBuilder(typeRegistry, AtlasPrivilege.ENTITY_UPDATE_BUSINESS_METADATA, entityHeader); for (String bmName : updatedBusinessMetadataNames) { requestBuilder.setBusinessMetadata(bmName); AtlasAuthorizationUtils.verifyAccess(requestBuilder.build(), "add/update business-metadata: guid=", guid, ", business-metadata-name=", bmName); } validateBusinessAttributes(entityVertex, entityType, businessAttrbutes, isOverwrite); if (isOverwrite) { entityGraphMapper.setBusinessAttributes(entityVertex, entityType, businessAttrbutes); } else { entityGraphMapper.addOrUpdateBusinessAttributes(entityVertex, entityType, businessAttrbutes); } if (LOG.isDebugEnabled()) { LOG.debug("<== addOrUpdateBusinessAttributes(guid={}, businessAttributes={}, isOverwrite={})", guid, businessAttrbutes, isOverwrite); } } @Inject AtlasEntityStoreV2(AtlasGraph graph, DeleteHandlerDelegate deleteDelegate, AtlasTypeRegistry typeRegistry, IAtlasEntityChangeNotifier entityChangeNotifier, EntityGraphMapper entityGraphMapper); @Override @GraphTransaction List<String> getEntityGUIDS(final String typename); @Override @GraphTransaction AtlasEntityWithExtInfo getById(String guid); @Override @GraphTransaction AtlasEntityWithExtInfo getById(final String guid, final boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityHeader getHeaderById(final String guid); @Override @GraphTransaction AtlasEntitiesWithExtInfo getByIds(List<String> guids); @Override @GraphTransaction AtlasEntitiesWithExtInfo getByIds(List<String> guids, boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntitiesWithExtInfo getEntitiesByUniqueAttributes(AtlasEntityType entityType, List<Map<String, Object>> uniqueAttributes , boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityWithExtInfo getByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction AtlasEntityWithExtInfo getByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes, boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityHeader getEntityHeaderByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction AtlasCheckStateResult checkState(AtlasCheckStateRequest request); @Override @GraphTransaction EntityMutationResponse createOrUpdate(EntityStream entityStream, boolean isPartialUpdate); @Override @GraphTransaction(logRollback = false) EntityMutationResponse createOrUpdateForImport(EntityStream entityStream); @Override EntityMutationResponse createOrUpdateForImportNoCommit(EntityStream entityStream); @Override @GraphTransaction EntityMutationResponse updateEntity(AtlasObjectId objectId, AtlasEntityWithExtInfo updatedEntityInfo, boolean isPartialUpdate); @Override @GraphTransaction EntityMutationResponse updateByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes, AtlasEntityWithExtInfo updatedEntityInfo); @Override @GraphTransaction EntityMutationResponse updateEntityAttributeByGuid(String guid, String attrName, Object attrValue); @Override @GraphTransaction EntityMutationResponse deleteById(final String guid); @Override @GraphTransaction EntityMutationResponse deleteByIds(final List<String> guids); @Override @GraphTransaction EntityMutationResponse purgeByIds(Set<String> guids); @Override @GraphTransaction EntityMutationResponse deleteByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction String getGuidByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction void addClassifications(final String guid, final List<AtlasClassification> classifications); @Override @GraphTransaction void updateClassifications(String guid, List<AtlasClassification> classifications); @Override @GraphTransaction void addClassification(final List<String> guids, final AtlasClassification classification); @Override @GraphTransaction void deleteClassification(final String guid, final String classificationName); @Override @GraphTransaction void deleteClassification(final String guid, final String classificationName, final String associatedEntityGuid); @GraphTransaction List<AtlasClassification> retrieveClassifications(String guid); @Override @GraphTransaction List<AtlasClassification> getClassifications(String guid); @Override @GraphTransaction AtlasClassification getClassification(String guid, String classificationName); @Override @GraphTransaction String setClassifications(AtlasEntityHeaders entityHeaders); @Override @GraphTransaction void addOrUpdateBusinessAttributes(String guid, Map<String, Map<String, Object>> businessAttrbutes, boolean isOverwrite); @Override @GraphTransaction void removeBusinessAttributes(String guid, Map<String, Map<String, Object>> businessAttributes); @Override @GraphTransaction void setLabels(String guid, Set<String> labels); @Override @GraphTransaction void removeLabels(String guid, Set<String> labels); @Override @GraphTransaction void addLabels(String guid, Set<String> labels); @Override @GraphTransaction BulkImportResponse bulkCreateOrUpdateBusinessAttributes(InputStream inputStream, String fileName); }
@Test public void testAddBusinessAttributesStringMaxLengthCheck_2() throws Exception { Map<String, Map<String, Object>> bmMapReq = new HashMap<>(); Map<String, Object> bmAttrMapReq = new HashMap<>(); bmAttrMapReq.put("attr8", "012345678901234567890"); bmMapReq.put("bmWithAllTypes", bmAttrMapReq); try { entityStore.addOrUpdateBusinessAttributes(dbEntity.getEntity().getGuid(), bmMapReq, false); } catch (AtlasBaseException e) { Assert.assertEquals(AtlasErrorCode.INSTANCE_CRUD_INVALID_PARAMS, e.getAtlasErrorCode()); return; } Assert.fail(); } @Test(dependsOnMethods = "testAddBusinessAttributesStringMaxLengthCheck") public void testUpdateBusinessAttributesStringMaxLengthCheck_2() throws Exception { Map<String, Map<String, Object>> bmMapReq = new HashMap<>(); Map<String, Object> bmAttrMapReq = new HashMap<>(); bmAttrMapReq.put("attr8", "012345678901234567890"); bmMapReq.put("bmWithAllTypes", bmAttrMapReq); try { entityStore.addOrUpdateBusinessAttributes(dbEntity.getEntity().getGuid(), bmMapReq, true); } catch (AtlasBaseException e) { Assert.assertEquals(AtlasErrorCode.INSTANCE_CRUD_INVALID_PARAMS, e.getAtlasErrorCode()); return; } Assert.fail(); } @Test(dependsOnMethods = "testAddBusinessAttributesStringMaxLengthCheck") public void testUpdateBusinessAttributesStringMaxLengthCheck_4() throws Exception { Map<String, Map<String, Object>> bmAttrMapReq = new HashMap<>(); Map<String, Object> attrValueMapReq = new HashMap<>(); List<String> stringList = new ArrayList<>(); stringList.add("0123456789"); stringList.add("012345678901234567890"); attrValueMapReq.put("attr18", stringList); bmAttrMapReq.put("bmWithAllTypesMV", attrValueMapReq); try { entityStore.addOrUpdateBusinessAttributes(dbEntity.getEntity().getGuid(), bmAttrMapReq, true); } catch (AtlasBaseException e) { Assert.assertEquals(AtlasErrorCode.INSTANCE_CRUD_INVALID_PARAMS, e.getAtlasErrorCode()); return; } Assert.fail(); }
AtlasEntityStoreV2 implements AtlasEntityStore { @Override @GraphTransaction public BulkImportResponse bulkCreateOrUpdateBusinessAttributes(InputStream inputStream, String fileName) throws AtlasBaseException { BulkImportResponse ret = new BulkImportResponse(); try { if (StringUtils.isBlank(fileName)) { throw new AtlasBaseException(AtlasErrorCode.FILE_NAME_NOT_FOUND, fileName); } List<String[]> fileData = FileUtils.readFileData(fileName, inputStream); Map<String, AtlasEntity> attributesToAssociate = getBusinessMetadataDefList(fileData, ret); for (AtlasEntity entity : attributesToAssociate.values()) { try { addOrUpdateBusinessAttributes(entity.getGuid(), entity.getBusinessAttributes(), true); BulkImportResponse.ImportInfo successImportInfo = new BulkImportResponse.ImportInfo(entity.getGuid(), entity.getBusinessAttributes().toString()); ret.setSuccessImportInfoList(successImportInfo); }catch (Exception e) { LOG.error("Error occurred while updating BusinessMetadata Attributes for Entity " + entity.getGuid()); BulkImportResponse.ImportInfo failedImportInfo = new BulkImportResponse.ImportInfo(entity.getGuid(), entity.getBusinessAttributes().toString(), BulkImportResponse.ImportStatus.FAILED, e.getMessage()); ret.getFailedImportInfoList().add(failedImportInfo); } } } catch (IOException e) { LOG.error("An Exception occurred while uploading the file {}", fileName, e); throw new AtlasBaseException(AtlasErrorCode.FAILED_TO_UPLOAD, e); } return ret; } @Inject AtlasEntityStoreV2(AtlasGraph graph, DeleteHandlerDelegate deleteDelegate, AtlasTypeRegistry typeRegistry, IAtlasEntityChangeNotifier entityChangeNotifier, EntityGraphMapper entityGraphMapper); @Override @GraphTransaction List<String> getEntityGUIDS(final String typename); @Override @GraphTransaction AtlasEntityWithExtInfo getById(String guid); @Override @GraphTransaction AtlasEntityWithExtInfo getById(final String guid, final boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityHeader getHeaderById(final String guid); @Override @GraphTransaction AtlasEntitiesWithExtInfo getByIds(List<String> guids); @Override @GraphTransaction AtlasEntitiesWithExtInfo getByIds(List<String> guids, boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntitiesWithExtInfo getEntitiesByUniqueAttributes(AtlasEntityType entityType, List<Map<String, Object>> uniqueAttributes , boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityWithExtInfo getByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction AtlasEntityWithExtInfo getByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes, boolean isMinExtInfo, boolean ignoreRelationships); @Override @GraphTransaction AtlasEntityHeader getEntityHeaderByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction AtlasCheckStateResult checkState(AtlasCheckStateRequest request); @Override @GraphTransaction EntityMutationResponse createOrUpdate(EntityStream entityStream, boolean isPartialUpdate); @Override @GraphTransaction(logRollback = false) EntityMutationResponse createOrUpdateForImport(EntityStream entityStream); @Override EntityMutationResponse createOrUpdateForImportNoCommit(EntityStream entityStream); @Override @GraphTransaction EntityMutationResponse updateEntity(AtlasObjectId objectId, AtlasEntityWithExtInfo updatedEntityInfo, boolean isPartialUpdate); @Override @GraphTransaction EntityMutationResponse updateByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes, AtlasEntityWithExtInfo updatedEntityInfo); @Override @GraphTransaction EntityMutationResponse updateEntityAttributeByGuid(String guid, String attrName, Object attrValue); @Override @GraphTransaction EntityMutationResponse deleteById(final String guid); @Override @GraphTransaction EntityMutationResponse deleteByIds(final List<String> guids); @Override @GraphTransaction EntityMutationResponse purgeByIds(Set<String> guids); @Override @GraphTransaction EntityMutationResponse deleteByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction String getGuidByUniqueAttributes(AtlasEntityType entityType, Map<String, Object> uniqAttributes); @Override @GraphTransaction void addClassifications(final String guid, final List<AtlasClassification> classifications); @Override @GraphTransaction void updateClassifications(String guid, List<AtlasClassification> classifications); @Override @GraphTransaction void addClassification(final List<String> guids, final AtlasClassification classification); @Override @GraphTransaction void deleteClassification(final String guid, final String classificationName); @Override @GraphTransaction void deleteClassification(final String guid, final String classificationName, final String associatedEntityGuid); @GraphTransaction List<AtlasClassification> retrieveClassifications(String guid); @Override @GraphTransaction List<AtlasClassification> getClassifications(String guid); @Override @GraphTransaction AtlasClassification getClassification(String guid, String classificationName); @Override @GraphTransaction String setClassifications(AtlasEntityHeaders entityHeaders); @Override @GraphTransaction void addOrUpdateBusinessAttributes(String guid, Map<String, Map<String, Object>> businessAttrbutes, boolean isOverwrite); @Override @GraphTransaction void removeBusinessAttributes(String guid, Map<String, Map<String, Object>> businessAttributes); @Override @GraphTransaction void setLabels(String guid, Set<String> labels); @Override @GraphTransaction void removeLabels(String guid, Set<String> labels); @Override @GraphTransaction void addLabels(String guid, Set<String> labels); @Override @GraphTransaction BulkImportResponse bulkCreateOrUpdateBusinessAttributes(InputStream inputStream, String fileName); }
@Test public void testEmptyFileException() { InputStream inputStream = getFile(CSV_FILES, "empty.csv"); try { entityStore.bulkCreateOrUpdateBusinessAttributes(inputStream, "empty.csv"); fail("Error occurred : Failed to recognize the empty file."); } catch (AtlasBaseException e) { assertEquals(e.getMessage(), "No data found in the uploaded file"); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { } } } } @Test(dependsOnMethods = "testCreate") public void testBulkAddOrUpdateBusinessAttributes() { try { AtlasEntity hive_db_1 = getEntityFromStore(dbEntityGuid); String dbName = (String) hive_db_1.getAttribute("name"); String data = TestUtilsV2.getFileData(CSV_FILES, "template_2.csv"); data = data.replaceAll("hive_db_1", dbName); InputStream inputStream1 = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); BulkImportResponse bulkImportResponse = entityStore.bulkCreateOrUpdateBusinessAttributes(inputStream1, "template_2.csv"); assertEquals(CollectionUtils.isEmpty(bulkImportResponse.getSuccessImportInfoList()), false); assertEquals(CollectionUtils.isEmpty(bulkImportResponse.getFailedImportInfoList()), true); } catch (Exception e) { fail("The BusinessMetadata Attribute should have been assigned " +e); } }
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(); }
@Test public void testArrayTypeDefaultValue() { Collection defValue = intArrayType.createDefaultValue(); assertEquals(defValue.size(), 1); }
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); }
@Test(dataProvider = "traitRegexString") public void testIsValidName(String data, boolean expected) { assertEquals(classificationDefStore.isValidName(data), expected); }
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); }
@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); } }
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); }
@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()); } } }
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); }
@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); } }
AtlasTypeDefGraphStore implements AtlasTypeDefStore { @Override public AtlasTypesDef searchTypesDef(SearchFilter searchFilter) throws AtlasBaseException { final AtlasTypesDef typesDef = new AtlasTypesDef(); Predicate searchPredicates = FilterUtil.getPredicateFromSearchFilter(searchFilter); for(AtlasEnumType enumType : typeRegistry.getAllEnumTypes()) { if (searchPredicates.evaluate(enumType)) { typesDef.getEnumDefs().add(enumType.getEnumDef()); } } for(AtlasStructType structType : typeRegistry.getAllStructTypes()) { if (searchPredicates.evaluate(structType)) { typesDef.getStructDefs().add(structType.getStructDef()); } } for(AtlasClassificationType classificationType : typeRegistry.getAllClassificationTypes()) { if (searchPredicates.evaluate(classificationType)) { typesDef.getClassificationDefs().add(classificationType.getClassificationDef()); } } for(AtlasEntityType entityType : typeRegistry.getAllEntityTypes()) { if (searchPredicates.evaluate(entityType)) { typesDef.getEntityDefs().add(entityType.getEntityDef()); } } for(AtlasRelationshipType relationshipType : typeRegistry.getAllRelationshipTypes()) { if (searchPredicates.evaluate(relationshipType)) { typesDef.getRelationshipDefs().add(relationshipType.getRelationshipDef()); } } for(AtlasBusinessMetadataType businessMetadataType : typeRegistry.getAllBusinessMetadataTypes()) { if (searchPredicates.evaluate(businessMetadataType)) { typesDef.getBusinessMetadataDefs().add(businessMetadataType.getBusinessMetadataDef()); } } AtlasAuthorizationUtils.filterTypesDef(new AtlasTypesDefFilterRequest(typesDef)); return typesDef; } 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(); }
@Test public void testGet() { try { AtlasTypesDef typesDef = typeDefStore.searchTypesDef(new SearchFilter()); assertNotNull(typesDef.getEnumDefs()); assertEquals(typesDef.getStructDefs().size(), 0); assertNotNull(typesDef.getStructDefs()); assertEquals(typesDef.getClassificationDefs().size(), 0); assertNotNull(typesDef.getClassificationDefs()); assertEquals(typesDef.getEntityDefs().size(), 0); assertNotNull(typesDef.getEntityDefs()); } catch (AtlasBaseException e) { fail("Search of types shouldn't have failed"); } } @Test(dependsOnMethods = "testGet") public void testSearchFunctionality() { SearchFilter searchFilter = new SearchFilter(); searchFilter.setParam(SearchFilter.PARAM_SUPERTYPE, "Person"); try { AtlasTypesDef typesDef = typeDefStore.searchTypesDef(searchFilter); assertNotNull(typesDef); assertNotNull(typesDef.getEntityDefs()); assertEquals(typesDef.getEntityDefs().size(), 3); } catch (AtlasBaseException e) { fail("Search should've succeeded", e); } }
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(); }
@Test public void testArrayTypeIsValidValue() { for (Object value : validValues) { assertTrue(intArrayType.isValidValue(value), "value=" + value); } for (Object value : invalidValues) { assertFalse(intArrayType.isValidValue(value), "value=" + value); } }
AtlasTypeDefGraphStore implements AtlasTypeDefStore { @Override @GraphTransaction public AtlasTypesDef updateTypesDef(AtlasTypesDef typesDef) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeDefGraphStore.updateTypesDef(enums={}, structs={}, classfications={}, entities={}, relationships{}, businessMetadataDefs={})", CollectionUtils.size(typesDef.getEnumDefs()), CollectionUtils.size(typesDef.getStructDefs()), CollectionUtils.size(typesDef.getClassificationDefs()), CollectionUtils.size(typesDef.getEntityDefs()), CollectionUtils.size(typesDef.getRelationshipDefs()), CollectionUtils.size(typesDef.getBusinessMetadataDefs())); } AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); try { ttr.updateTypes(typesDef); } catch (AtlasBaseException e) { if (AtlasErrorCode.TYPE_NAME_NOT_FOUND == e.getAtlasErrorCode()) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, e.getMessage()); } else { throw e; } } AtlasTypesDef ret = updateGraphStore(typesDef, ttr); try { ttr.updateTypes(ret); } catch (AtlasBaseException e) { LOG.error("failed to update the registry after updating the store", e); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeDefGraphStore.updateTypesDef(enums={}, structs={}, classfications={}, entities={}, relationships={}, businessMetadataDefs={})", CollectionUtils.size(typesDef.getEnumDefs()), CollectionUtils.size(typesDef.getStructDefs()), CollectionUtils.size(typesDef.getClassificationDefs()), CollectionUtils.size(typesDef.getEntityDefs()), CollectionUtils.size(typesDef.getRelationshipDefs()), CollectionUtils.size(typesDef.getBusinessMetadataDefs())); } 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(); }
@Test(enabled = false, dependsOnMethods = {"testCreateDept"}) public void testUpdateWithMandatoryFields(){ AtlasTypesDef atlasTypesDef = TestUtilsV2.defineInvalidUpdatedDeptEmployeeTypes(); List<AtlasEnumDef> enumDefsToUpdate = atlasTypesDef.getEnumDefs(); List<AtlasClassificationDef> classificationDefsToUpdate = atlasTypesDef.getClassificationDefs(); List<AtlasStructDef> structDefsToUpdate = atlasTypesDef.getStructDefs(); List<AtlasEntityDef> entityDefsToUpdate = atlasTypesDef.getEntityDefs(); AtlasTypesDef onlyEnums = new AtlasTypesDef(enumDefsToUpdate, Collections.EMPTY_LIST, Collections.EMPTY_LIST, Collections.EMPTY_LIST); AtlasTypesDef onlyStructs = new AtlasTypesDef(Collections.EMPTY_LIST, structDefsToUpdate, Collections.EMPTY_LIST, Collections.EMPTY_LIST); AtlasTypesDef onlyClassification = new AtlasTypesDef(Collections.EMPTY_LIST, Collections.EMPTY_LIST, classificationDefsToUpdate, Collections.EMPTY_LIST); AtlasTypesDef onlyEntities = new AtlasTypesDef(Collections.EMPTY_LIST, Collections.EMPTY_LIST, Collections.EMPTY_LIST, entityDefsToUpdate); try { AtlasTypesDef updated = typeDefStore.updateTypesDef(onlyEnums); assertNotNull(updated); } catch (AtlasBaseException ignored) {} try { AtlasTypesDef updated = typeDefStore.updateTypesDef(onlyClassification); assertNotNull(updated); assertEquals(updated.getClassificationDefs().size(), 0, "Updates should've failed"); } catch (AtlasBaseException ignored) {} try { AtlasTypesDef updated = typeDefStore.updateTypesDef(onlyStructs); assertNotNull(updated); assertEquals(updated.getStructDefs().size(), 0, "Updates should've failed"); } catch (AtlasBaseException ignored) {} try { AtlasTypesDef updated = typeDefStore.updateTypesDef(onlyEntities); assertNotNull(updated); assertEquals(updated.getEntityDefs().size(), 0, "Updates should've failed"); } catch (AtlasBaseException ignored) {} }
AtlasTypeDefGraphStore implements AtlasTypeDefStore { @Override @GraphTransaction public void deleteTypesDef(AtlasTypesDef typesDef) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeDefGraphStore.deleteTypesDef(enums={}, structs={}, classfications={}, entities={}, relationships={}, businessMetadataDefs={})", CollectionUtils.size(typesDef.getEnumDefs()), CollectionUtils.size(typesDef.getStructDefs()), CollectionUtils.size(typesDef.getClassificationDefs()), CollectionUtils.size(typesDef.getEntityDefs()), CollectionUtils.size(typesDef.getRelationshipDefs()), CollectionUtils.size(typesDef.getBusinessMetadataDefs())); } AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); AtlasDefStore<AtlasEnumDef> enumDefStore = getEnumDefStore(ttr); AtlasDefStore<AtlasStructDef> structDefStore = getStructDefStore(ttr); AtlasDefStore<AtlasClassificationDef> classifiDefStore = getClassificationDefStore(ttr); AtlasDefStore<AtlasEntityDef> entityDefStore = getEntityDefStore(ttr); AtlasDefStore<AtlasRelationshipDef> relationshipDefStore = getRelationshipDefStore(ttr); AtlasDefStore<AtlasBusinessMetadataDef> businessMetadataDefStore = getBusinessMetadataDefStore(ttr); List<AtlasVertex> preDeleteStructDefs = new ArrayList<>(); List<AtlasVertex> preDeleteClassifiDefs = new ArrayList<>(); List<AtlasVertex> preDeleteEntityDefs = new ArrayList<>(); List<AtlasVertex> preDeleteRelationshipDefs = new ArrayList<>(); if (CollectionUtils.isNotEmpty(typesDef.getRelationshipDefs())) { for (AtlasRelationshipDef relationshipDef : typesDef.getRelationshipDefs()) { if (StringUtils.isNotBlank(relationshipDef.getGuid())) { preDeleteRelationshipDefs.add(relationshipDefStore.preDeleteByGuid(relationshipDef.getGuid())); } else { preDeleteRelationshipDefs.add(relationshipDefStore.preDeleteByName(relationshipDef.getName())); } } } if (CollectionUtils.isNotEmpty(typesDef.getStructDefs())) { for (AtlasStructDef structDef : typesDef.getStructDefs()) { if (StringUtils.isNotBlank(structDef.getGuid())) { preDeleteStructDefs.add(structDefStore.preDeleteByGuid(structDef.getGuid())); } else { preDeleteStructDefs.add(structDefStore.preDeleteByName(structDef.getName())); } } } if (CollectionUtils.isNotEmpty(typesDef.getClassificationDefs())) { for (AtlasClassificationDef classifiDef : typesDef.getClassificationDefs()) { if (StringUtils.isNotBlank(classifiDef.getGuid())) { preDeleteClassifiDefs.add(classifiDefStore.preDeleteByGuid(classifiDef.getGuid())); } else { preDeleteClassifiDefs.add(classifiDefStore.preDeleteByName(classifiDef.getName())); } } } if (CollectionUtils.isNotEmpty(typesDef.getEntityDefs())) { for (AtlasEntityDef entityDef : typesDef.getEntityDefs()) { if (StringUtils.isNotBlank(entityDef.getGuid())) { preDeleteEntityDefs.add(entityDefStore.preDeleteByGuid(entityDef.getGuid())); } else { preDeleteEntityDefs.add(entityDefStore.preDeleteByName(entityDef.getName())); } } } if (CollectionUtils.isNotEmpty(typesDef.getRelationshipDefs())) { int i = 0; for (AtlasRelationshipDef relationshipDef : typesDef.getRelationshipDefs()) { if (StringUtils.isNotBlank(relationshipDef.getGuid())) { relationshipDefStore.deleteByGuid(relationshipDef.getGuid(), preDeleteRelationshipDefs.get(i)); } else { relationshipDefStore.deleteByName(relationshipDef.getName(), preDeleteRelationshipDefs.get(i)); } i++; } } if (CollectionUtils.isNotEmpty(typesDef.getStructDefs())) { int i = 0; for (AtlasStructDef structDef : typesDef.getStructDefs()) { if (StringUtils.isNotBlank(structDef.getGuid())) { structDefStore.deleteByGuid(structDef.getGuid(), preDeleteStructDefs.get(i)); } else { structDefStore.deleteByName(structDef.getName(), preDeleteStructDefs.get(i)); } i++; } } if (CollectionUtils.isNotEmpty(typesDef.getClassificationDefs())) { int i = 0; for (AtlasClassificationDef classifiDef : typesDef.getClassificationDefs()) { if (StringUtils.isNotBlank(classifiDef.getGuid())) { classifiDefStore.deleteByGuid(classifiDef.getGuid(), preDeleteClassifiDefs.get(i)); } else { classifiDefStore.deleteByName(classifiDef.getName(), preDeleteClassifiDefs.get(i)); } i++; } } if (CollectionUtils.isNotEmpty(typesDef.getEntityDefs())) { int i = 0; for (AtlasEntityDef entityDef : typesDef.getEntityDefs()) { if (StringUtils.isNotBlank(entityDef.getGuid())) { entityDefStore.deleteByGuid(entityDef.getGuid(), preDeleteEntityDefs.get(i)); } else { entityDefStore.deleteByName(entityDef.getName(), preDeleteEntityDefs.get(i)); } i++; } } if (CollectionUtils.isNotEmpty(typesDef.getEnumDefs())) { for (AtlasEnumDef enumDef : typesDef.getEnumDefs()) { if (StringUtils.isNotBlank(enumDef.getGuid())) { enumDefStore.deleteByGuid(enumDef.getGuid(), null); } else { enumDefStore.deleteByName(enumDef.getName(), null); } } } if (CollectionUtils.isNotEmpty(typesDef.getBusinessMetadataDefs())) { for (AtlasBusinessMetadataDef businessMetadataDef : typesDef.getBusinessMetadataDefs()) { if (StringUtils.isNotBlank(businessMetadataDef.getGuid())) { businessMetadataDefStore.deleteByGuid(businessMetadataDef.getGuid(), null); } else { businessMetadataDefStore.deleteByName(businessMetadataDef.getName(), null); } } } ttr.removeTypesDef(typesDef); if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeDefGraphStore.deleteTypesDef(enums={}, structs={}, classfications={}, entities={})", CollectionUtils.size(typesDef.getEnumDefs()), CollectionUtils.size(typesDef.getStructDefs()), CollectionUtils.size(typesDef.getClassificationDefs()), CollectionUtils.size(typesDef.getEntityDefs())); } } 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(); }
@Test(dependsOnMethods = {"testUpdate"}, dataProvider = "allCreatedTypes") public void testDelete(AtlasTypesDef atlasTypesDef){ try { typeDefStore.deleteTypesDef(atlasTypesDef); } catch (AtlasBaseException e) { fail("Deletion should've succeeded"); } }
AtlasTypeDefGraphStore implements AtlasTypeDefStore { @Override @GraphTransaction public void deleteTypeByName(String typeName) throws AtlasBaseException { AtlasType atlasType = typeRegistry.getType(typeName); if (atlasType == null) { throw new AtlasBaseException(AtlasErrorCode.INVALID_PARAMETERS.TYPE_NAME_NOT_FOUND, typeName); } AtlasTypesDef typesDef = new AtlasTypesDef(); AtlasBaseTypeDef baseTypeDef = getByNameNoAuthz(typeName); if (baseTypeDef instanceof AtlasClassificationDef) { typesDef.setClassificationDefs(Collections.singletonList((AtlasClassificationDef) baseTypeDef)); } else if (baseTypeDef instanceof AtlasEntityDef) { typesDef.setEntityDefs(Collections.singletonList((AtlasEntityDef) baseTypeDef)); } else if (baseTypeDef instanceof AtlasEnumDef) { typesDef.setEnumDefs(Collections.singletonList((AtlasEnumDef) baseTypeDef)); } else if (baseTypeDef instanceof AtlasRelationshipDef) { typesDef.setRelationshipDefs(Collections.singletonList((AtlasRelationshipDef) baseTypeDef)); } else if (baseTypeDef instanceof AtlasBusinessMetadataDef) { typesDef.setBusinessMetadataDefs(Collections.singletonList((AtlasBusinessMetadataDef) baseTypeDef)); } else if (baseTypeDef instanceof AtlasStructDef) { typesDef.setStructDefs(Collections.singletonList((AtlasStructDef) baseTypeDef)); } deleteTypesDef(typesDef); } 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(); }
@Test public void deleteTypeByName() throws IOException { try { final String HIVEDB_v2_JSON = "hiveDBv2"; final String hiveDB2 = "hive_db_v2"; final String relationshipDefName = "cluster_hosts_relationship"; final String hostEntityDef = "host"; final String clusterEntityDef = "cluster"; AtlasTypesDef typesDef = TestResourceFileUtils.readObjectFromJson(".", HIVEDB_v2_JSON, AtlasTypesDef.class); typeDefStore.createTypesDef(typesDef); typeDefStore.deleteTypeByName(hiveDB2); typeDefStore.deleteTypeByName(relationshipDefName); typeDefStore.deleteTypeByName(hostEntityDef); typeDefStore.deleteTypeByName(clusterEntityDef); } catch (AtlasBaseException e) { fail("Deletion should've succeeded"); } }
AtlasTypeDefGraphStore implements AtlasTypeDefStore { @Override @GraphTransaction public AtlasTypesDef createTypesDef(AtlasTypesDef typesDef) throws AtlasBaseException { if (LOG.isDebugEnabled()) { LOG.debug("==> AtlasTypeDefGraphStore.createTypesDef(enums={}, structs={}, classifications={}, entities={}, relationships={}, businessMetadataDefs={})", CollectionUtils.size(typesDef.getEnumDefs()), CollectionUtils.size(typesDef.getStructDefs()), CollectionUtils.size(typesDef.getClassificationDefs()), CollectionUtils.size(typesDef.getEntityDefs()), CollectionUtils.size(typesDef.getRelationshipDefs()), CollectionUtils.size(typesDef.getBusinessMetadataDefs())); } AtlasTransientTypeRegistry ttr = lockTypeRegistryAndReleasePostCommit(); tryTypeCreation(typesDef, ttr); AtlasTypesDef ret = addToGraphStore(typesDef, ttr); try { ttr.updateTypes(ret); } catch (AtlasBaseException e) { LOG.error("failed to update the registry after updating the store", e); } if (LOG.isDebugEnabled()) { LOG.debug("<== AtlasTypeDefGraphStore.createTypesDef(enums={}, structs={}, classfications={}, entities={}, relationships={}, businessMetadataDefs={})", CollectionUtils.size(typesDef.getEnumDefs()), CollectionUtils.size(typesDef.getStructDefs()), CollectionUtils.size(typesDef.getClassificationDefs()), CollectionUtils.size(typesDef.getEntityDefs()), CollectionUtils.size(typesDef.getRelationshipDefs()), CollectionUtils.size(typesDef.getBusinessMetadataDefs())); } 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(); }
@Test(dependsOnMethods = "testGet") public void testCreateWithValidAttributes(){ AtlasTypesDef hiveTypes = TestUtilsV2.defineHiveTypes(); try { AtlasTypesDef createdTypes = typeDefStore.createTypesDef(hiveTypes); assertEquals(hiveTypes.getEnumDefs(), createdTypes.getEnumDefs(), "Data integrity issue while persisting"); assertEquals(hiveTypes.getStructDefs(), createdTypes.getStructDefs(), "Data integrity issue while persisting"); assertEquals(hiveTypes.getClassificationDefs(), createdTypes.getClassificationDefs(), "Data integrity issue while persisting"); assertEquals(hiveTypes.getEntityDefs(), createdTypes.getEntityDefs(), "Data integrity issue while persisting"); } catch (AtlasBaseException e) { fail("Hive Type creation should've succeeded"); } } @Test(dependsOnMethods = "testGet") public void testCreateWithNestedContainerAttributes() { AtlasTypesDef typesDef = TestUtilsV2.defineTypeWithNestedCollectionAttributes(); try { AtlasTypesDef createdTypes = typeDefStore.createTypesDef(typesDef); assertEquals(typesDef.getEnumDefs(), createdTypes.getEnumDefs(), "Data integrity issue while persisting"); assertEquals(typesDef.getStructDefs(), createdTypes.getStructDefs(), "Data integrity issue while persisting"); assertEquals(typesDef.getClassificationDefs(), createdTypes.getClassificationDefs(), "Data integrity issue while persisting"); assertEquals(typesDef.getEntityDefs(), createdTypes.getEntityDefs(), "Data integrity issue while persisting"); } catch (AtlasBaseException e) { fail("creation of type with nested-container attributes should've succeeded"); } } @Test(dependsOnMethods = "testGet") public void testCreateWithValidSuperTypes(){ List<AtlasClassificationDef> classificationDefs = TestUtilsV2.getClassificationWithValidSuperType(); AtlasTypesDef toCreate = new AtlasTypesDef(Collections.<AtlasEnumDef>emptyList(), Collections.<AtlasStructDef>emptyList(), classificationDefs, Collections.<AtlasEntityDef>emptyList()); try { AtlasTypesDef created = typeDefStore.createTypesDef(toCreate); assertEquals(created.getClassificationDefs(), toCreate.getClassificationDefs(), "Classification creation with valid supertype should've succeeded"); } catch (AtlasBaseException e) { fail("Classification creation with valid supertype should've succeeded"); } List<AtlasEntityDef> entityDefs = TestUtilsV2.getEntityWithValidSuperType(); toCreate = new AtlasTypesDef(Collections.<AtlasEnumDef>emptyList(), Collections.<AtlasStructDef>emptyList(), Collections.<AtlasClassificationDef>emptyList(), entityDefs); try { AtlasTypesDef created = typeDefStore.createTypesDef(toCreate); assertEquals(created.getEntityDefs(), toCreate.getEntityDefs(), "Entity creation with valid supertype should've succeeded"); } catch (AtlasBaseException e) { fail("Entity creation with valid supertype should've succeeded"); } } @Test(dependsOnMethods = "testGet") public void testCreateWithInvalidSuperTypes(){ AtlasTypesDef typesDef; AtlasClassificationDef classificationDef = TestUtilsV2.getClassificationWithInvalidSuperType(); typesDef = new AtlasTypesDef(); typesDef.getClassificationDefs().add(classificationDef); try { AtlasTypesDef created = typeDefStore.createTypesDef(typesDef); fail("Classification creation with invalid supertype should've failed"); } catch (AtlasBaseException e) { typesDef = null; } AtlasEntityDef entityDef = TestUtilsV2.getEntityWithInvalidSuperType(); typesDef = new AtlasTypesDef(); typesDef.getEntityDefs().add(entityDef); try { AtlasTypesDef created = typeDefStore.createTypesDef(typesDef); fail("Entity creation with invalid supertype should've failed"); } catch (AtlasBaseException e) {} } @Test(dependsOnMethods = "testGet") public void testCreateClassificationDefWithValidEntityType(){ final String entityTypeName ="testCreateClassificationDefWithValidEntityTypeEntity1"; final String classificationTypeName ="testCreateClassificationDefWithValidEntityTypeClassification1"; List<AtlasEntityDef> entityDefs = TestUtilsV2.getEntityWithName(entityTypeName); List<AtlasClassificationDef> classificationDefs = TestUtilsV2.getClassificationWithName(classificationTypeName); Set<String> entityTypeNames = new HashSet<String>(); entityTypeNames.add(entityTypeName); classificationDefs.get(0).setEntityTypes(entityTypeNames); AtlasTypesDef toCreate = new AtlasTypesDef(Collections.<AtlasEnumDef>emptyList(), Collections.<AtlasStructDef>emptyList(), classificationDefs, entityDefs); try { AtlasTypesDef created = typeDefStore.createTypesDef(toCreate); assertEquals(created.getClassificationDefs(), toCreate.getClassificationDefs(), "Classification creation with valid entitytype should've succeeded"); } catch (AtlasBaseException e) { fail("Classification creation with valid entitytype should've succeeded. Failed with " + e.getMessage()); } } @Test(dependsOnMethods = "testGet") public void testCreateWithInvalidEntityType(){ final String classificationTypeName ="testCreateClassificationDefWithInvalidEntityTypeClassification1"; List<AtlasClassificationDef> classificationDefs = TestUtilsV2.getClassificationWithName(classificationTypeName); Set<String> entityTypeNames = new HashSet<String>(); entityTypeNames.add("cccc"); classificationDefs.get(0).setEntityTypes(entityTypeNames); AtlasTypesDef toCreate = new AtlasTypesDef(Collections.<AtlasEnumDef>emptyList(), Collections.<AtlasStructDef>emptyList(), classificationDefs, Collections.<AtlasEntityDef>emptyList()); try { AtlasTypesDef created = typeDefStore.createTypesDef(toCreate); fail("Classification creation with invalid entitytype should've failed"); } catch (AtlasBaseException e) { } } @Test(dependsOnMethods = "testGet") public void testCreateWithInvalidEntityType2(){ final String classificationTypeName1 ="testCreateClassificationDefWithInvalidEntityType2Classification1"; final String classificationTypeName2 ="testCreateClassificationDefWithInvalidEntityType2Classification2"; final String entityTypeName1 ="testCreateClassificationDefWithInvalidEntityType2Entity1"; AtlasClassificationDef classificationDef1 = TestUtilsV2.getSingleClassificationWithName(classificationTypeName1); AtlasClassificationDef classificationDef2 = TestUtilsV2.getSingleClassificationWithName(classificationTypeName2); List<AtlasEntityDef> entityDefs = TestUtilsV2.getEntityWithName(entityTypeName1); Set<String> entityTypeNames = new HashSet<String>(); entityTypeNames.add(entityTypeName1); Set<String> superTypes = new HashSet<String>(); superTypes.add(classificationTypeName1); classificationDef2.setSuperTypes(superTypes); classificationDef1.setEntityTypes(entityTypeNames); TestUtilsV2.populateSystemAttributes(classificationDef1); TestUtilsV2.populateSystemAttributes(classificationDef2); List<AtlasClassificationDef> classificationDefs = Arrays.asList(classificationDef1,classificationDef2); AtlasTypesDef toCreate = new AtlasTypesDef(Collections.<AtlasEnumDef>emptyList(), Collections.<AtlasStructDef>emptyList(), classificationDefs, Collections.<AtlasEntityDef>emptyList()); try { AtlasTypesDef created = typeDefStore.createTypesDef(toCreate); fail("Classification creation with invalid entitytype should've failed"); } catch (AtlasBaseException e) { } } @Test(dependsOnMethods = "testGet") public void testCreateWithInvalidEntityType3(){ final String classificationTypeName1 ="testCreateClassificationDefWithInvalidEntityType3Classification1"; final String classificationTypeName2 ="testCreateClassificationDefWithInvalidEntityType3Classification2"; final String entityTypeName1 ="testCreateClassificationDefWithInvalidEntityType3Entity1"; final String entityTypeName2 ="testCreateClassificationDefWithInvalidEntityType3Entity2"; AtlasClassificationDef classificationDef1 = TestUtilsV2.getSingleClassificationWithName(classificationTypeName1); AtlasClassificationDef classificationDef2 = TestUtilsV2.getSingleClassificationWithName(classificationTypeName2); AtlasEntityDef entityDef1 = TestUtilsV2.getSingleEntityWithName(entityTypeName1); AtlasEntityDef entityDef2 = TestUtilsV2.getSingleEntityWithName(entityTypeName2); Set<String> entityTypeNames1 = new HashSet<String>(); entityTypeNames1.add(entityTypeName1); Set<String> entityTypeNames2 = new HashSet<String>(); entityTypeNames2.add(entityTypeName2); Set<String> superTypes = new HashSet<String>(); superTypes.add(classificationTypeName1); classificationDef1.setEntityTypes(entityTypeNames1); classificationDef2.setSuperTypes(superTypes); classificationDef2.setEntityTypes(entityTypeNames2); TestUtilsV2.populateSystemAttributes(classificationDef1); TestUtilsV2.populateSystemAttributes(classificationDef2); TestUtilsV2.populateSystemAttributes(entityDef1); TestUtilsV2.populateSystemAttributes(entityDef2); List<AtlasClassificationDef> classificationDefs = Arrays.asList(classificationDef1,classificationDef2); List<AtlasEntityDef> entityDefs = Arrays.asList(entityDef1,entityDef2); AtlasTypesDef toCreate = new AtlasTypesDef(Collections.<AtlasEnumDef>emptyList(), Collections.<AtlasStructDef>emptyList(), classificationDefs, entityDefs); try { AtlasTypesDef created = typeDefStore.createTypesDef(toCreate); fail("Classification creation with invalid entitytype should've failed"); } catch (AtlasBaseException e) { } }
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(); }
@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); } }
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(); }
@Test public void testGetOnAllEntityTypes() throws AtlasBaseException { AtlasEntityDef entityDefByName = typeDefStore.getEntityDefByName("_ALL_ENTITY_TYPES"); assertNotNull(entityDefByName); assertEquals(entityDefByName, AtlasEntityType.getEntityRoot().getEntityDef()); }
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(); }
@Test public void testGetOnAllClassificationTypes() throws AtlasBaseException { AtlasClassificationDef classificationTypeDef = typeDefStore.getClassificationDefByName("_ALL_CLASSIFICATION_TYPES"); assertNotNull(classificationTypeDef); assertEquals(classificationTypeDef, AtlasClassificationType.getClassificationRoot().getClassificationDef()); }
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; }
@Test(dependsOnMethods = "verifyCreate") public void verifyGet() throws AtlasBaseException { AtlasEntity.AtlasEntityWithExtInfo entityWithExtInfo = hdfsPathEntityCreator.getCreateEntity(expectedPath, expectedClusterName); assertNotNull(entityWithExtInfo); }
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); }
@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); }
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); }
@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)); }
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); }
@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); }
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(); }
@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(); } }
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(); }
@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); }
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); }
@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()); }
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); }
@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()); } }
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); }
@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); }
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); }
@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)); }
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(); }
@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"); }
ImportTransformer { public static ImportTransformer getTransformer(String transformerSpec) throws AtlasBaseException { String[] params = StringUtils.split(transformerSpec, TRANSFORMER_PARAMETER_SEPARATOR); String key = (params == null || params.length < 1) ? transformerSpec : params[0]; final ImportTransformer ret; if (StringUtils.isEmpty(key)) { throw new AtlasBaseException(AtlasErrorCode.INVALID_VALUE, "Error creating ImportTransformer. Invalid transformer-specification: {}.", transformerSpec); } else if (key.equals(TRANSFORMER_NAME_REPLACE)) { String toFindStr = (params == null || params.length < 2) ? "" : params[1]; String replaceStr = (params == null || params.length < 3) ? "" : params[2]; ret = new Replace(toFindStr, replaceStr); } else if (key.equals(TRANSFORMER_NAME_LOWERCASE)) { ret = new Lowercase(); } else if (key.equals(TRANSFORMER_NAME_UPPERCASE)) { ret = new Uppercase(); } else if (key.equals(TRANSFORMER_NAME_REMOVE_CLASSIFICATION)) { String name = (params == null || params.length < 1) ? "" : StringUtils.join(params, ":", 1, params.length); ret = new RemoveClassification(name); } else if (key.equals(TRANSFORMER_NAME_ADD)) { String name = (params == null || params.length < 1) ? "" : StringUtils.join(params, ":", 1, params.length); ret = new AddValueToAttribute(name); } else if (key.equals(TRANSFORMER_NAME_CLEAR_ATTR)) { String name = (params == null || params.length < 1) ? "" : StringUtils.join(params, ":", 1, params.length); ret = new ClearAttributes(name); } else if (key.equals(TRANSFORMER_SET_DELETED)) { ret = new SetDeleted(); } else if (key.equals(TRANSFORMER_NAME_ADD_CLASSIFICATION)) { String name = (params == null || params.length < 1) ? "" : params[1]; ret = new AddClassification(name, (params != null && params.length == 3) ? params[2] : ""); } else { throw new AtlasBaseException(AtlasErrorCode.INVALID_VALUE, "Error creating ImportTransformer. Unknown transformer: {}.", transformerSpec); } return ret; } protected ImportTransformer(String transformType); static ImportTransformer getTransformer(String transformerSpec); String getTransformType(); abstract Object apply(Object o); }
@Test public void createWithCorrectParameters() throws AtlasBaseException, IllegalAccessException { String param1 = "@cl1"; String param2 = "@cl2"; ImportTransformer e = ImportTransformer.getTransformer(String.format("%s:%s:%s", "replace", param1, param2)); assertTrue(e instanceof ImportTransformer.Replace); assertEquals(((ImportTransformer.Replace)e).getToFindStr(), param1); assertEquals(((ImportTransformer.Replace)e).getReplaceStr(), param2); } @Test public void createSeveralWithCorrectParameters() throws AtlasBaseException, IllegalAccessException { String param1 = "@cl1"; String param2 = "@cl2"; ImportTransformer e1 = ImportTransformer.getTransformer(String.format("%s:%s:%s", "replace", param1, param2)); ImportTransformer e2 = ImportTransformer.getTransformer(String.format("replace:tt1:tt2")); assertTrue(e1 instanceof ImportTransformer.Replace); assertEquals(((ImportTransformer.Replace)e1).getToFindStr(), param1); assertEquals(((ImportTransformer.Replace)e1).getReplaceStr(), param2); assertTrue(e2 instanceof ImportTransformer.Replace); assertEquals(((ImportTransformer.Replace)e2).getToFindStr(), "tt1"); assertEquals(((ImportTransformer.Replace)e2).getReplaceStr(), "tt2"); } @Test public void createWithDefaultParameters() throws AtlasBaseException { ImportTransformer e1 = ImportTransformer.getTransformer("replace:@cl1"); ImportTransformer e2 = ImportTransformer.getTransformer("replace"); assertTrue(e1 instanceof ImportTransformer.Replace); assertEquals(((ImportTransformer.Replace)e1).getToFindStr(), "@cl1"); assertEquals(((ImportTransformer.Replace)e1).getReplaceStr(), ""); assertTrue(e2 instanceof ImportTransformer.Replace); assertEquals(((ImportTransformer.Replace)e2).getToFindStr(), ""); assertEquals(((ImportTransformer.Replace)e2).getReplaceStr(), ""); }
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; }
@Test public void testStructTypeDefaultValue() { AtlasStruct defValue = structType.createDefaultValue(); assertNotNull(defValue); assertEquals(defValue.getTypeName(), structType.getTypeName()); }
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; }
@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)); }
GlossaryService { @GraphTransaction public AtlasGlossary createGlossary(AtlasGlossary atlasGlossary) throws AtlasBaseException { if (DEBUG_ENABLED) { LOG.debug("==> GlossaryService.createGlossary({})", atlasGlossary); } if (Objects.isNull(atlasGlossary)) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "Glossary definition missing"); } if (StringUtils.isEmpty(atlasGlossary.getQualifiedName())) { if (StringUtils.isEmpty(atlasGlossary.getName())) { throw new AtlasBaseException(AtlasErrorCode.GLOSSARY_QUALIFIED_NAME_CANT_BE_DERIVED); } if (isNameInvalid(atlasGlossary.getName())){ throw new AtlasBaseException(AtlasErrorCode.INVALID_DISPLAY_NAME); } else { atlasGlossary.setQualifiedName(atlasGlossary.getName()); } } if (glossaryExists(atlasGlossary)) { throw new AtlasBaseException(AtlasErrorCode.GLOSSARY_ALREADY_EXISTS, atlasGlossary.getQualifiedName()); } AtlasGlossary storeObject = dataAccess.save(atlasGlossary); if (DEBUG_ENABLED) { LOG.debug("<== GlossaryService.createGlossary() : {}", storeObject); } return storeObject; } @Inject GlossaryService(DataAccess dataAccess, final AtlasRelationshipStore relationshipStore, final AtlasTypeRegistry typeRegistry, AtlasEntityChangeNotifier entityChangeNotifier); @GraphTransaction List<AtlasGlossary> getGlossaries(int limit, int offset, SortOrder sortOrder); @GraphTransaction AtlasGlossary createGlossary(AtlasGlossary atlasGlossary); @GraphTransaction AtlasGlossary getGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary.AtlasGlossaryExtInfo getDetailedGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary updateGlossary(AtlasGlossary atlasGlossary); @GraphTransaction void deleteGlossary(String glossaryGuid); @GraphTransaction AtlasGlossaryTerm getTerm(String termGuid); @GraphTransaction AtlasGlossaryTerm createTerm(AtlasGlossaryTerm glossaryTerm); @GraphTransaction List<AtlasGlossaryTerm> createTerms(List<AtlasGlossaryTerm> glossaryTerm); @GraphTransaction AtlasGlossaryTerm updateTerm(AtlasGlossaryTerm atlasGlossaryTerm); @GraphTransaction void deleteTerm(String termGuid); @GraphTransaction void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction void removeTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction AtlasGlossaryCategory getCategory(String categoryGuid); @GraphTransaction AtlasGlossaryCategory createCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction List<AtlasGlossaryCategory> createCategories(List<AtlasGlossaryCategory> glossaryCategory); @GraphTransaction AtlasGlossaryCategory updateCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction void deleteCategory(String categoryGuid); @GraphTransaction List<AtlasRelatedTermHeader> getGlossaryTermsHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedCategoryHeader> getGlossaryCategoriesHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedObjectId> getAssignedEntities(final String termGuid, int offset, int limit, SortOrder sortOrder); static boolean isNameInvalid(String name); List<AtlasGlossaryTerm> importGlossaryData(InputStream inputStream, String fileName); }
@Test(groups = "Glossary.CREATE") public void testCreateGlossary() { try { AtlasGlossary created = glossaryService.createGlossary(bankGlossary); bankGlossary.setGuid(created.getGuid()); created = glossaryService.createGlossary(creditUnionGlossary); creditUnionGlossary.setGuid(created.getGuid()); } catch (AtlasBaseException e) { fail("Glossary creation should've succeeded", e); } try { glossaryService.createGlossary(bankGlossary); fail("Glossary duplicate creation should've failed"); } catch (AtlasBaseException e) { assertEquals(e.getAtlasErrorCode(), AtlasErrorCode.GLOSSARY_ALREADY_EXISTS); } try { glossaryService.createGlossary(creditUnionGlossary); fail("Glossary duplicate creation should've failed"); } catch (AtlasBaseException e) { assertEquals(e.getAtlasErrorCode(), AtlasErrorCode.GLOSSARY_ALREADY_EXISTS); } try { List<AtlasRelatedCategoryHeader> glossaryCategories = glossaryService.getGlossaryCategoriesHeaders(bankGlossary.getGuid(), 0, 10, SortOrder.ASCENDING); assertNotNull(glossaryCategories); assertEquals(glossaryCategories.size(), 0); glossaryCategories = glossaryService.getGlossaryCategoriesHeaders(creditUnionGlossary.getGuid(), 0, 10, SortOrder.ASCENDING); assertNotNull(glossaryCategories); assertEquals(glossaryCategories.size(), 0); } catch (AtlasBaseException e) { fail("Get glossary categories calls should've succeeded", e); } try { List<AtlasRelatedTermHeader> glossaryCategories = glossaryService.getGlossaryTermsHeaders(bankGlossary.getGuid(), 0, 10, SortOrder.ASCENDING); assertNotNull(glossaryCategories); assertEquals(glossaryCategories.size(), 0); glossaryCategories = glossaryService.getGlossaryTermsHeaders(creditUnionGlossary.getGuid(), 0, 10, SortOrder.ASCENDING); assertNotNull(glossaryCategories); assertEquals(glossaryCategories.size(), 0); } catch (AtlasBaseException e) { fail("Get glossary categories calls should've succeeded", e); } AtlasGlossaryHeader glossaryId = new AtlasGlossaryHeader(); glossaryId.setGlossaryGuid(bankGlossary.getGuid()); checkingAccount.setAnchor(glossaryId); savingsAccount.setAnchor(glossaryId); fixedRateMortgage.setAnchor(glossaryId); adjustableRateMortgage.setAnchor(glossaryId); accountCategory.setAnchor(glossaryId); customerCategory.setAnchor(glossaryId); mortgageCategory.setAnchor(glossaryId); }
GlossaryService { @GraphTransaction public AtlasGlossaryTerm createTerm(AtlasGlossaryTerm glossaryTerm) throws AtlasBaseException { if (DEBUG_ENABLED) { LOG.debug("==> GlossaryService.create({})", glossaryTerm); } if (Objects.isNull(glossaryTerm)) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "GlossaryTerm definition missing"); } if (Objects.isNull(glossaryTerm.getAnchor())) { throw new AtlasBaseException(AtlasErrorCode.MISSING_MANDATORY_ANCHOR); } if (StringUtils.isEmpty(glossaryTerm.getName())) { throw new AtlasBaseException(AtlasErrorCode.GLOSSARY_TERM_QUALIFIED_NAME_CANT_BE_DERIVED); } if (isNameInvalid(glossaryTerm.getName())){ throw new AtlasBaseException(AtlasErrorCode.INVALID_DISPLAY_NAME); } else { String anchorGlossaryGuid = glossaryTerm.getAnchor().getGlossaryGuid(); AtlasGlossary glossary = dataAccess.load(getGlossarySkeleton(anchorGlossaryGuid)); glossaryTerm.setQualifiedName(glossaryTerm.getName() + "@" + glossary.getQualifiedName()); if (LOG.isDebugEnabled()) { LOG.debug("Derived qualifiedName = {}", glossaryTerm.getQualifiedName()); } } if (termExists(glossaryTerm)) { throw new AtlasBaseException(AtlasErrorCode.GLOSSARY_TERM_ALREADY_EXISTS, glossaryTerm.getQualifiedName()); } AtlasGlossaryTerm storeObject = dataAccess.save(glossaryTerm); glossaryTermUtils.processTermRelations(storeObject, glossaryTerm, GlossaryUtils.RelationshipOperation.CREATE); storeObject = dataAccess.load(glossaryTerm); setInfoForRelations(storeObject); if (DEBUG_ENABLED) { LOG.debug("<== GlossaryService.create() : {}", storeObject); } return storeObject; } @Inject GlossaryService(DataAccess dataAccess, final AtlasRelationshipStore relationshipStore, final AtlasTypeRegistry typeRegistry, AtlasEntityChangeNotifier entityChangeNotifier); @GraphTransaction List<AtlasGlossary> getGlossaries(int limit, int offset, SortOrder sortOrder); @GraphTransaction AtlasGlossary createGlossary(AtlasGlossary atlasGlossary); @GraphTransaction AtlasGlossary getGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary.AtlasGlossaryExtInfo getDetailedGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary updateGlossary(AtlasGlossary atlasGlossary); @GraphTransaction void deleteGlossary(String glossaryGuid); @GraphTransaction AtlasGlossaryTerm getTerm(String termGuid); @GraphTransaction AtlasGlossaryTerm createTerm(AtlasGlossaryTerm glossaryTerm); @GraphTransaction List<AtlasGlossaryTerm> createTerms(List<AtlasGlossaryTerm> glossaryTerm); @GraphTransaction AtlasGlossaryTerm updateTerm(AtlasGlossaryTerm atlasGlossaryTerm); @GraphTransaction void deleteTerm(String termGuid); @GraphTransaction void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction void removeTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction AtlasGlossaryCategory getCategory(String categoryGuid); @GraphTransaction AtlasGlossaryCategory createCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction List<AtlasGlossaryCategory> createCategories(List<AtlasGlossaryCategory> glossaryCategory); @GraphTransaction AtlasGlossaryCategory updateCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction void deleteCategory(String categoryGuid); @GraphTransaction List<AtlasRelatedTermHeader> getGlossaryTermsHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedCategoryHeader> getGlossaryCategoriesHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedObjectId> getAssignedEntities(final String termGuid, int offset, int limit, SortOrder sortOrder); static boolean isNameInvalid(String name); List<AtlasGlossaryTerm> importGlossaryData(InputStream inputStream, String fileName); }
@Test(groups = "Glossary.CREATE" , dependsOnMethods = "testCategoryCreation") public void testTermCreationWithoutAnyRelations() { try { checkingAccount = glossaryService.createTerm(checkingAccount); assertNotNull(checkingAccount); assertNotNull(checkingAccount.getGuid()); } catch (AtlasBaseException e) { fail("Term creation should've succeeded", e); } } @Test(groups = "Glossary.CREATE" , dependsOnMethods = "testTermCreationWithoutAnyRelations") public void testTermCreateWithRelation() { try { AtlasRelatedTermHeader relatedTermHeader = new AtlasRelatedTermHeader(); relatedTermHeader.setTermGuid(checkingAccount.getGuid()); relatedTermHeader.setDescription("test description"); relatedTermHeader.setExpression("test expression"); relatedTermHeader.setSource("UT"); relatedTermHeader.setSteward("UT"); relatedTermHeader.setStatus(AtlasTermRelationshipStatus.ACTIVE); savingsAccount.setSeeAlso(Collections.singleton(relatedTermHeader)); savingsAccount = glossaryService.createTerm(savingsAccount); assertNotNull(savingsAccount); assertNotNull(savingsAccount.getGuid()); } catch (AtlasBaseException e) { fail("Term creation with relation should've succeeded", e); } }
GlossaryService { @GraphTransaction public List<AtlasGlossaryTerm> createTerms(List<AtlasGlossaryTerm> glossaryTerm) throws AtlasBaseException { if (DEBUG_ENABLED) { LOG.debug("==> GlossaryService.create({})", glossaryTerm); } if (Objects.isNull(glossaryTerm)) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "glossaryTerm(s) is null/empty"); } List<AtlasGlossaryTerm> ret = new ArrayList<>(); for (AtlasGlossaryTerm atlasGlossaryTerm : glossaryTerm) { ret.add(createTerm(atlasGlossaryTerm)); } if (LOG.isDebugEnabled()) { LOG.debug("<== GlossaryService.createTerms() : {}", ret); } return ret; } @Inject GlossaryService(DataAccess dataAccess, final AtlasRelationshipStore relationshipStore, final AtlasTypeRegistry typeRegistry, AtlasEntityChangeNotifier entityChangeNotifier); @GraphTransaction List<AtlasGlossary> getGlossaries(int limit, int offset, SortOrder sortOrder); @GraphTransaction AtlasGlossary createGlossary(AtlasGlossary atlasGlossary); @GraphTransaction AtlasGlossary getGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary.AtlasGlossaryExtInfo getDetailedGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary updateGlossary(AtlasGlossary atlasGlossary); @GraphTransaction void deleteGlossary(String glossaryGuid); @GraphTransaction AtlasGlossaryTerm getTerm(String termGuid); @GraphTransaction AtlasGlossaryTerm createTerm(AtlasGlossaryTerm glossaryTerm); @GraphTransaction List<AtlasGlossaryTerm> createTerms(List<AtlasGlossaryTerm> glossaryTerm); @GraphTransaction AtlasGlossaryTerm updateTerm(AtlasGlossaryTerm atlasGlossaryTerm); @GraphTransaction void deleteTerm(String termGuid); @GraphTransaction void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction void removeTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction AtlasGlossaryCategory getCategory(String categoryGuid); @GraphTransaction AtlasGlossaryCategory createCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction List<AtlasGlossaryCategory> createCategories(List<AtlasGlossaryCategory> glossaryCategory); @GraphTransaction AtlasGlossaryCategory updateCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction void deleteCategory(String categoryGuid); @GraphTransaction List<AtlasRelatedTermHeader> getGlossaryTermsHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedCategoryHeader> getGlossaryCategoriesHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedObjectId> getAssignedEntities(final String termGuid, int offset, int limit, SortOrder sortOrder); static boolean isNameInvalid(String name); List<AtlasGlossaryTerm> importGlossaryData(InputStream inputStream, String fileName); }
@Test(groups = "Glossary.CREATE" , dependsOnMethods = "testCategoryCreation") public void testTermCreationWithCategory() { try { AtlasTermCategorizationHeader termCategorizationHeader = new AtlasTermCategorizationHeader(); termCategorizationHeader.setCategoryGuid(mortgageCategory.getGuid()); termCategorizationHeader.setDescription("Test description"); termCategorizationHeader.setStatus(AtlasTermRelationshipStatus.DRAFT); fixedRateMortgage.setCategories(Collections.singleton(termCategorizationHeader)); adjustableRateMortgage.setCategories(Collections.singleton(termCategorizationHeader)); List<AtlasGlossaryTerm> terms = glossaryService.createTerms(Arrays.asList(fixedRateMortgage, adjustableRateMortgage)); fixedRateMortgage.setGuid(terms.get(0).getGuid()); adjustableRateMortgage.setGuid(terms.get(1).getGuid()); } catch (AtlasBaseException e) { fail("Term creation should've succeeded", e); } }
GlossaryService { @GraphTransaction public List<AtlasGlossary> getGlossaries(int limit, int offset, SortOrder sortOrder) throws AtlasBaseException { if (DEBUG_ENABLED) { LOG.debug("==> GlossaryService.getGlossaries({}, {}, {})", limit, offset, sortOrder); } List<String> glossaryGuids = AtlasGraphUtilsV2.findEntityGUIDsByType(GlossaryUtils.ATLAS_GLOSSARY_TYPENAME, sortOrder); PaginationHelper paginationHelper = new PaginationHelper<>(glossaryGuids, offset, limit); List<AtlasGlossary> ret; List<String> guidsToLoad = paginationHelper.getPaginatedList(); if (CollectionUtils.isNotEmpty(guidsToLoad)) { ret = guidsToLoad.stream().map(GlossaryUtils::getGlossarySkeleton).collect(Collectors.toList()); Iterable<AtlasGlossary> glossaries = dataAccess.load(ret); ret.clear(); for (AtlasGlossary glossary : glossaries) { setInfoForRelations(glossary); ret.add(glossary); } } else { ret = Collections.emptyList(); } if (DEBUG_ENABLED) { LOG.debug("<== GlossaryService.getGlossaries() : {}", ret); } return ret; } @Inject GlossaryService(DataAccess dataAccess, final AtlasRelationshipStore relationshipStore, final AtlasTypeRegistry typeRegistry, AtlasEntityChangeNotifier entityChangeNotifier); @GraphTransaction List<AtlasGlossary> getGlossaries(int limit, int offset, SortOrder sortOrder); @GraphTransaction AtlasGlossary createGlossary(AtlasGlossary atlasGlossary); @GraphTransaction AtlasGlossary getGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary.AtlasGlossaryExtInfo getDetailedGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary updateGlossary(AtlasGlossary atlasGlossary); @GraphTransaction void deleteGlossary(String glossaryGuid); @GraphTransaction AtlasGlossaryTerm getTerm(String termGuid); @GraphTransaction AtlasGlossaryTerm createTerm(AtlasGlossaryTerm glossaryTerm); @GraphTransaction List<AtlasGlossaryTerm> createTerms(List<AtlasGlossaryTerm> glossaryTerm); @GraphTransaction AtlasGlossaryTerm updateTerm(AtlasGlossaryTerm atlasGlossaryTerm); @GraphTransaction void deleteTerm(String termGuid); @GraphTransaction void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction void removeTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction AtlasGlossaryCategory getCategory(String categoryGuid); @GraphTransaction AtlasGlossaryCategory createCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction List<AtlasGlossaryCategory> createCategories(List<AtlasGlossaryCategory> glossaryCategory); @GraphTransaction AtlasGlossaryCategory updateCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction void deleteCategory(String categoryGuid); @GraphTransaction List<AtlasRelatedTermHeader> getGlossaryTermsHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedCategoryHeader> getGlossaryCategoriesHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedObjectId> getAssignedEntities(final String termGuid, int offset, int limit, SortOrder sortOrder); static boolean isNameInvalid(String name); List<AtlasGlossaryTerm> importGlossaryData(InputStream inputStream, String fileName); }
@Test(dataProvider = "getAllGlossaryDataProvider", groups = "Glossary.GET", dependsOnGroups = "Glossary.CREATE") public void testGetAllGlossaries(int limit, int offset, SortOrder sortOrder, int expected) { try { List<AtlasGlossary> glossaries = glossaryService.getGlossaries(limit, offset, sortOrder); assertEquals(glossaries.size(), expected); } catch (AtlasBaseException e) { fail("Get glossaries should've succeeded", e); } }
GlossaryService { @GraphTransaction public AtlasGlossary updateGlossary(AtlasGlossary atlasGlossary) throws AtlasBaseException { if (DEBUG_ENABLED) { LOG.debug("==> GlossaryService.updateGlossary({})", atlasGlossary); } if (Objects.isNull(atlasGlossary)) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "Glossary is null/empty"); } if (StringUtils.isEmpty(atlasGlossary.getName())) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "DisplayName can't be null/empty"); } if (isNameInvalid(atlasGlossary.getName())) { throw new AtlasBaseException(AtlasErrorCode.INVALID_DISPLAY_NAME); } AtlasGlossary storeObject = dataAccess.load(atlasGlossary); if (!storeObject.equals(atlasGlossary)) { atlasGlossary.setGuid(storeObject.getGuid()); atlasGlossary.setQualifiedName(storeObject.getQualifiedName()); storeObject = dataAccess.save(atlasGlossary); setInfoForRelations(storeObject); } if (DEBUG_ENABLED) { LOG.debug("<== GlossaryService.updateGlossary() : {}", storeObject); } return storeObject; } @Inject GlossaryService(DataAccess dataAccess, final AtlasRelationshipStore relationshipStore, final AtlasTypeRegistry typeRegistry, AtlasEntityChangeNotifier entityChangeNotifier); @GraphTransaction List<AtlasGlossary> getGlossaries(int limit, int offset, SortOrder sortOrder); @GraphTransaction AtlasGlossary createGlossary(AtlasGlossary atlasGlossary); @GraphTransaction AtlasGlossary getGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary.AtlasGlossaryExtInfo getDetailedGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary updateGlossary(AtlasGlossary atlasGlossary); @GraphTransaction void deleteGlossary(String glossaryGuid); @GraphTransaction AtlasGlossaryTerm getTerm(String termGuid); @GraphTransaction AtlasGlossaryTerm createTerm(AtlasGlossaryTerm glossaryTerm); @GraphTransaction List<AtlasGlossaryTerm> createTerms(List<AtlasGlossaryTerm> glossaryTerm); @GraphTransaction AtlasGlossaryTerm updateTerm(AtlasGlossaryTerm atlasGlossaryTerm); @GraphTransaction void deleteTerm(String termGuid); @GraphTransaction void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction void removeTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction AtlasGlossaryCategory getCategory(String categoryGuid); @GraphTransaction AtlasGlossaryCategory createCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction List<AtlasGlossaryCategory> createCategories(List<AtlasGlossaryCategory> glossaryCategory); @GraphTransaction AtlasGlossaryCategory updateCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction void deleteCategory(String categoryGuid); @GraphTransaction List<AtlasRelatedTermHeader> getGlossaryTermsHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedCategoryHeader> getGlossaryCategoriesHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedObjectId> getAssignedEntities(final String termGuid, int offset, int limit, SortOrder sortOrder); static boolean isNameInvalid(String name); List<AtlasGlossaryTerm> importGlossaryData(InputStream inputStream, String fileName); }
@Test(groups = "Glossary.UPDATE", dependsOnGroups = "Glossary.CREATE") public void testUpdateGlossary() { try { bankGlossary = glossaryService.getGlossary(bankGlossary.getGuid()); bankGlossary.setShortDescription("Updated short description"); bankGlossary.setLongDescription("Updated long description"); AtlasGlossary updatedGlossary = glossaryService.updateGlossary(bankGlossary); assertNotNull(updatedGlossary); assertEquals(updatedGlossary.getGuid(), bankGlossary.getGuid()); ArrayList<AtlasRelatedCategoryHeader> a = new ArrayList<>(updatedGlossary.getCategories()); ArrayList<AtlasRelatedCategoryHeader> b = new ArrayList<>(bankGlossary.getCategories()); assertEquals(a, b); } catch (AtlasBaseException e) { fail("Glossary fetch/update should've succeeded", e); } }
GlossaryService { @GraphTransaction public void deleteGlossary(String glossaryGuid) throws AtlasBaseException { if (DEBUG_ENABLED) { LOG.debug("==> GlossaryService.deleteGlossary({})", glossaryGuid); } if (Objects.isNull(glossaryGuid)) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "glossaryGuid is null/empty"); } AtlasGlossary storeObject = dataAccess.load(getGlossarySkeleton(glossaryGuid)); Set<AtlasRelatedTermHeader> terms = storeObject.getTerms(); deleteTerms(storeObject, terms); Set<AtlasRelatedCategoryHeader> categories = storeObject.getCategories(); deleteCategories(storeObject, categories); dataAccess.delete(glossaryGuid); if (DEBUG_ENABLED) { LOG.debug("<== GlossaryService.deleteGlossary()"); } } @Inject GlossaryService(DataAccess dataAccess, final AtlasRelationshipStore relationshipStore, final AtlasTypeRegistry typeRegistry, AtlasEntityChangeNotifier entityChangeNotifier); @GraphTransaction List<AtlasGlossary> getGlossaries(int limit, int offset, SortOrder sortOrder); @GraphTransaction AtlasGlossary createGlossary(AtlasGlossary atlasGlossary); @GraphTransaction AtlasGlossary getGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary.AtlasGlossaryExtInfo getDetailedGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary updateGlossary(AtlasGlossary atlasGlossary); @GraphTransaction void deleteGlossary(String glossaryGuid); @GraphTransaction AtlasGlossaryTerm getTerm(String termGuid); @GraphTransaction AtlasGlossaryTerm createTerm(AtlasGlossaryTerm glossaryTerm); @GraphTransaction List<AtlasGlossaryTerm> createTerms(List<AtlasGlossaryTerm> glossaryTerm); @GraphTransaction AtlasGlossaryTerm updateTerm(AtlasGlossaryTerm atlasGlossaryTerm); @GraphTransaction void deleteTerm(String termGuid); @GraphTransaction void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction void removeTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction AtlasGlossaryCategory getCategory(String categoryGuid); @GraphTransaction AtlasGlossaryCategory createCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction List<AtlasGlossaryCategory> createCategories(List<AtlasGlossaryCategory> glossaryCategory); @GraphTransaction AtlasGlossaryCategory updateCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction void deleteCategory(String categoryGuid); @GraphTransaction List<AtlasRelatedTermHeader> getGlossaryTermsHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedCategoryHeader> getGlossaryCategoriesHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedObjectId> getAssignedEntities(final String termGuid, int offset, int limit, SortOrder sortOrder); static boolean isNameInvalid(String name); List<AtlasGlossaryTerm> importGlossaryData(InputStream inputStream, String fileName); }
@Test(dependsOnMethods = "testInvalidFetches") public void testDeleteGlossary() { try { glossaryService.deleteGlossary(bankGlossary.getGuid()); try { glossaryService.getGlossary(bankGlossary.getGuid()); } catch (AtlasBaseException e) { assertEquals(e.getAtlasErrorCode(), AtlasErrorCode.INSTANCE_GUID_NOT_FOUND); } try { glossaryService.getTerm(fixedRateMortgage.getGuid()); } catch (AtlasBaseException e) { assertEquals(e.getAtlasErrorCode(), AtlasErrorCode.INSTANCE_GUID_NOT_FOUND); } try { glossaryService.getTerm(adjustableRateMortgage.getGuid()); } catch (AtlasBaseException e) { assertEquals(e.getAtlasErrorCode(), AtlasErrorCode.INSTANCE_GUID_NOT_FOUND); } try { glossaryService.getTerm(savingsAccount.getGuid()); } catch (AtlasBaseException e) { assertEquals(e.getAtlasErrorCode(), AtlasErrorCode.INSTANCE_GUID_NOT_FOUND); } try { glossaryService.getTerm(checkingAccount.getGuid()); } catch (AtlasBaseException e) { assertEquals(e.getAtlasErrorCode(), AtlasErrorCode.INSTANCE_GUID_NOT_FOUND); } try { glossaryService.getCategory(customerCategory.getGuid()); } catch (AtlasBaseException e) { assertEquals(e.getAtlasErrorCode(), AtlasErrorCode.INSTANCE_GUID_NOT_FOUND); } try { glossaryService.getCategory(accountCategory.getGuid()); } catch (AtlasBaseException e) { assertEquals(e.getAtlasErrorCode(), AtlasErrorCode.INSTANCE_GUID_NOT_FOUND); } try { glossaryService.getCategory(mortgageCategory.getGuid()); } catch (AtlasBaseException e) { assertEquals(e.getAtlasErrorCode(), AtlasErrorCode.INSTANCE_GUID_NOT_FOUND); } } catch (AtlasBaseException e) { fail("Glossary delete should've succeeded", e); } }
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; }
@Test public void testStructTypeIsValidValue() { for (Object value : validValues) { assertTrue(structType.isValidValue(value), "value=" + value); } for (Object value : invalidValues) { assertFalse(structType.isValidValue(value), "value=" + value); } }
GlossaryService { @GraphTransaction public List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, int offset, int limit, SortOrder sortOrder) throws AtlasBaseException { if (Objects.isNull(glossaryGuid)) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "glossaryGuid is null/empty"); } if (DEBUG_ENABLED) { LOG.debug("==> GlossaryService.getGlossaryTerms({}, {}, {}, {})", glossaryGuid, offset, limit, sortOrder); } List<AtlasGlossaryTerm> ret = new ArrayList<>(); List<AtlasRelatedTermHeader> termHeaders = getGlossaryTermsHeaders(glossaryGuid, offset, limit, sortOrder); for (AtlasRelatedTermHeader header : termHeaders) { ret.add(dataAccess.load(getAtlasGlossaryTermSkeleton(header.getTermGuid()))); } if (DEBUG_ENABLED) { LOG.debug("<== GlossaryService.getGlossaryTerms() : {}", ret); } return ret; } @Inject GlossaryService(DataAccess dataAccess, final AtlasRelationshipStore relationshipStore, final AtlasTypeRegistry typeRegistry, AtlasEntityChangeNotifier entityChangeNotifier); @GraphTransaction List<AtlasGlossary> getGlossaries(int limit, int offset, SortOrder sortOrder); @GraphTransaction AtlasGlossary createGlossary(AtlasGlossary atlasGlossary); @GraphTransaction AtlasGlossary getGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary.AtlasGlossaryExtInfo getDetailedGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary updateGlossary(AtlasGlossary atlasGlossary); @GraphTransaction void deleteGlossary(String glossaryGuid); @GraphTransaction AtlasGlossaryTerm getTerm(String termGuid); @GraphTransaction AtlasGlossaryTerm createTerm(AtlasGlossaryTerm glossaryTerm); @GraphTransaction List<AtlasGlossaryTerm> createTerms(List<AtlasGlossaryTerm> glossaryTerm); @GraphTransaction AtlasGlossaryTerm updateTerm(AtlasGlossaryTerm atlasGlossaryTerm); @GraphTransaction void deleteTerm(String termGuid); @GraphTransaction void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction void removeTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction AtlasGlossaryCategory getCategory(String categoryGuid); @GraphTransaction AtlasGlossaryCategory createCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction List<AtlasGlossaryCategory> createCategories(List<AtlasGlossaryCategory> glossaryCategory); @GraphTransaction AtlasGlossaryCategory updateCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction void deleteCategory(String categoryGuid); @GraphTransaction List<AtlasRelatedTermHeader> getGlossaryTermsHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedCategoryHeader> getGlossaryCategoriesHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedObjectId> getAssignedEntities(final String termGuid, int offset, int limit, SortOrder sortOrder); static boolean isNameInvalid(String name); List<AtlasGlossaryTerm> importGlossaryData(InputStream inputStream, String fileName); }
@Test(dataProvider = "getGlossaryTermsProvider" , groups = "Glossary.GET.postUpdate", dependsOnGroups = "Glossary.UPDATE") public void testGetGlossaryTerms(int offset, int limit, int expected) { String guid = bankGlossary.getGuid(); SortOrder sortOrder = SortOrder.ASCENDING; try { List<AtlasRelatedTermHeader> glossaryTerms = glossaryService.getGlossaryTermsHeaders(guid, offset, limit, sortOrder); assertNotNull(glossaryTerms); assertEquals(glossaryTerms.size(), expected); } catch (AtlasBaseException e) { fail("Glossary term fetching should've succeeded", e); } }
GlossaryService { @GraphTransaction public List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, int offset, int limit, SortOrder sortOrder) throws AtlasBaseException { if (Objects.isNull(glossaryGuid)) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "glossaryGuid is null/empty"); } if (DEBUG_ENABLED) { LOG.debug("==> GlossaryService.getGlossaryCategories({}, {}, {}, {})", glossaryGuid, offset, limit, sortOrder); } List<AtlasGlossaryCategory> ret = new ArrayList<>(); List<AtlasRelatedCategoryHeader> categoryHeaders = getGlossaryCategoriesHeaders(glossaryGuid, offset, limit, sortOrder); for (AtlasRelatedCategoryHeader header : categoryHeaders) { ret.add(dataAccess.load(getAtlasGlossaryCategorySkeleton(header.getCategoryGuid()))); } if (DEBUG_ENABLED) { LOG.debug("<== GlossaryService.getGlossaryCategories() : {}", ret); } return ret; } @Inject GlossaryService(DataAccess dataAccess, final AtlasRelationshipStore relationshipStore, final AtlasTypeRegistry typeRegistry, AtlasEntityChangeNotifier entityChangeNotifier); @GraphTransaction List<AtlasGlossary> getGlossaries(int limit, int offset, SortOrder sortOrder); @GraphTransaction AtlasGlossary createGlossary(AtlasGlossary atlasGlossary); @GraphTransaction AtlasGlossary getGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary.AtlasGlossaryExtInfo getDetailedGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary updateGlossary(AtlasGlossary atlasGlossary); @GraphTransaction void deleteGlossary(String glossaryGuid); @GraphTransaction AtlasGlossaryTerm getTerm(String termGuid); @GraphTransaction AtlasGlossaryTerm createTerm(AtlasGlossaryTerm glossaryTerm); @GraphTransaction List<AtlasGlossaryTerm> createTerms(List<AtlasGlossaryTerm> glossaryTerm); @GraphTransaction AtlasGlossaryTerm updateTerm(AtlasGlossaryTerm atlasGlossaryTerm); @GraphTransaction void deleteTerm(String termGuid); @GraphTransaction void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction void removeTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction AtlasGlossaryCategory getCategory(String categoryGuid); @GraphTransaction AtlasGlossaryCategory createCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction List<AtlasGlossaryCategory> createCategories(List<AtlasGlossaryCategory> glossaryCategory); @GraphTransaction AtlasGlossaryCategory updateCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction void deleteCategory(String categoryGuid); @GraphTransaction List<AtlasRelatedTermHeader> getGlossaryTermsHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedCategoryHeader> getGlossaryCategoriesHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedObjectId> getAssignedEntities(final String termGuid, int offset, int limit, SortOrder sortOrder); static boolean isNameInvalid(String name); List<AtlasGlossaryTerm> importGlossaryData(InputStream inputStream, String fileName); }
@Test(dataProvider = "getGlossaryCategoriesProvider" , groups = "Glossary.GET.postUpdate", dependsOnGroups = "Glossary.UPDATE") public void testGetGlossaryCategories(int offset, int limit, int expected) { String guid = bankGlossary.getGuid(); SortOrder sortOrder = SortOrder.ASCENDING; try { List<AtlasRelatedCategoryHeader> glossaryCategories = glossaryService.getGlossaryCategoriesHeaders(guid, offset, limit, sortOrder); assertNotNull(glossaryCategories); assertEquals(glossaryCategories.size(), expected); } catch (AtlasBaseException e) { fail("Glossary term fetching should've succeeded"); } }
GlossaryService { @GraphTransaction public List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, int offset, int limit, SortOrder sortOrder) throws AtlasBaseException { if (Objects.isNull(categoryGuid)) { throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "categoryGuid is null/empty"); } if (DEBUG_ENABLED) { LOG.debug("==> GlossaryService.getCategoryTerms({}, {}, {}, {})", categoryGuid, offset, limit, sortOrder); } List<AtlasRelatedTermHeader> ret; AtlasGlossaryCategory glossaryCategory = getCategory(categoryGuid); if (CollectionUtils.isNotEmpty(glossaryCategory.getTerms())) { List<AtlasRelatedTermHeader> terms = new ArrayList<>(glossaryCategory.getTerms()); if (sortOrder != null) { terms.sort((o1, o2) -> sortOrder == SortOrder.ASCENDING ? o1.getDisplayText().compareTo(o2.getDisplayText()) : o2.getDisplayText().compareTo(o1.getDisplayText())); } ret = new PaginationHelper<>(terms, offset, limit).getPaginatedList(); } else { ret = Collections.emptyList(); } if (DEBUG_ENABLED) { LOG.debug("<== GlossaryService.getCategoryTerms() : {}", ret); } return ret; } @Inject GlossaryService(DataAccess dataAccess, final AtlasRelationshipStore relationshipStore, final AtlasTypeRegistry typeRegistry, AtlasEntityChangeNotifier entityChangeNotifier); @GraphTransaction List<AtlasGlossary> getGlossaries(int limit, int offset, SortOrder sortOrder); @GraphTransaction AtlasGlossary createGlossary(AtlasGlossary atlasGlossary); @GraphTransaction AtlasGlossary getGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary.AtlasGlossaryExtInfo getDetailedGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary updateGlossary(AtlasGlossary atlasGlossary); @GraphTransaction void deleteGlossary(String glossaryGuid); @GraphTransaction AtlasGlossaryTerm getTerm(String termGuid); @GraphTransaction AtlasGlossaryTerm createTerm(AtlasGlossaryTerm glossaryTerm); @GraphTransaction List<AtlasGlossaryTerm> createTerms(List<AtlasGlossaryTerm> glossaryTerm); @GraphTransaction AtlasGlossaryTerm updateTerm(AtlasGlossaryTerm atlasGlossaryTerm); @GraphTransaction void deleteTerm(String termGuid); @GraphTransaction void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction void removeTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction AtlasGlossaryCategory getCategory(String categoryGuid); @GraphTransaction AtlasGlossaryCategory createCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction List<AtlasGlossaryCategory> createCategories(List<AtlasGlossaryCategory> glossaryCategory); @GraphTransaction AtlasGlossaryCategory updateCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction void deleteCategory(String categoryGuid); @GraphTransaction List<AtlasRelatedTermHeader> getGlossaryTermsHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedCategoryHeader> getGlossaryCategoriesHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedObjectId> getAssignedEntities(final String termGuid, int offset, int limit, SortOrder sortOrder); static boolean isNameInvalid(String name); List<AtlasGlossaryTerm> importGlossaryData(InputStream inputStream, String fileName); }
@Test(dataProvider = "getCategoryTermsProvider", dependsOnGroups = "Glossary.CREATE") public void testGetCategoryTerms(int offset, int limit, int expected) { for (AtlasGlossaryCategory c : Arrays.asList(accountCategory, mortgageCategory)) { try { List<AtlasRelatedTermHeader> categoryTerms = glossaryService.getCategoryTerms(c.getGuid(), offset, limit, SortOrder.ASCENDING); assertNotNull(categoryTerms); assertEquals(categoryTerms.size(), expected); } catch (AtlasBaseException e) { fail("Category term retrieval should've been a success", e); } } }
GlossaryService { public List<AtlasGlossaryTerm> importGlossaryData(InputStream inputStream, String fileName) throws AtlasBaseException { List<AtlasGlossaryTerm> ret; try { if (StringUtils.isBlank(fileName)) { throw new AtlasBaseException(AtlasErrorCode.INVALID_FILE_TYPE, fileName); } List<String[]> fileData = FileUtils.readFileData(fileName, inputStream); List<String> failedTermMsgs = new ArrayList<>(); ret = glossaryTermUtils.getGlossaryTermDataList(fileData, failedTermMsgs); ret = createGlossaryTerms(ret); } catch (IOException e) { throw new AtlasBaseException(AtlasErrorCode.FAILED_TO_UPLOAD, e); } return ret; } @Inject GlossaryService(DataAccess dataAccess, final AtlasRelationshipStore relationshipStore, final AtlasTypeRegistry typeRegistry, AtlasEntityChangeNotifier entityChangeNotifier); @GraphTransaction List<AtlasGlossary> getGlossaries(int limit, int offset, SortOrder sortOrder); @GraphTransaction AtlasGlossary createGlossary(AtlasGlossary atlasGlossary); @GraphTransaction AtlasGlossary getGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary.AtlasGlossaryExtInfo getDetailedGlossary(String glossaryGuid); @GraphTransaction AtlasGlossary updateGlossary(AtlasGlossary atlasGlossary); @GraphTransaction void deleteGlossary(String glossaryGuid); @GraphTransaction AtlasGlossaryTerm getTerm(String termGuid); @GraphTransaction AtlasGlossaryTerm createTerm(AtlasGlossaryTerm glossaryTerm); @GraphTransaction List<AtlasGlossaryTerm> createTerms(List<AtlasGlossaryTerm> glossaryTerm); @GraphTransaction AtlasGlossaryTerm updateTerm(AtlasGlossaryTerm atlasGlossaryTerm); @GraphTransaction void deleteTerm(String termGuid); @GraphTransaction void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction void removeTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); @GraphTransaction AtlasGlossaryCategory getCategory(String categoryGuid); @GraphTransaction AtlasGlossaryCategory createCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction List<AtlasGlossaryCategory> createCategories(List<AtlasGlossaryCategory> glossaryCategory); @GraphTransaction AtlasGlossaryCategory updateCategory(AtlasGlossaryCategory glossaryCategory); @GraphTransaction void deleteCategory(String categoryGuid); @GraphTransaction List<AtlasRelatedTermHeader> getGlossaryTermsHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedCategoryHeader> getGlossaryCategoriesHeaders(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, int offset, int limit, SortOrder sortOrder); @GraphTransaction List<AtlasRelatedObjectId> getAssignedEntities(final String termGuid, int offset, int limit, SortOrder sortOrder); static boolean isNameInvalid(String name); List<AtlasGlossaryTerm> importGlossaryData(InputStream inputStream, String fileName); }
@Test( dependsOnGroups = "Glossary.CREATE" ) public void testImportGlossaryData(){ try { InputStream inputStream = getFile(CSV_FILES,"template_1.csv"); List<AtlasGlossaryTerm> atlasGlossaryTermList = glossaryService.importGlossaryData(inputStream,"template_1.csv"); assertNotNull(atlasGlossaryTermList); assertEquals(atlasGlossaryTermList.size(), 1); InputStream inputStream1 = getFile(EXCEL_FILES,"template_1.xlsx"); List<AtlasGlossaryTerm> atlasGlossaryTermList1 = glossaryService.importGlossaryData(inputStream1,"template_1.xlsx"); assertNotNull(atlasGlossaryTermList1); assertEquals(atlasGlossaryTermList1.size(), 1); } catch (AtlasBaseException e){ fail("The GlossaryTerm should have been created "+e); } } @Test public void testEmptyFileException() { InputStream inputStream = getFile(CSV_FILES, "empty.csv"); try { glossaryService.importGlossaryData(inputStream, "empty.csv"); fail("Error occurred : Failed to recognize the empty file."); } catch (AtlasBaseException e) { assertEquals(e.getMessage(),"No data found in the uploaded file"); } } @Test public void testIncorrectFileException() { InputStream inputStream = getFile(CSV_FILES, "incorrectFile.csv"); try { glossaryService.importGlossaryData(inputStream, "incorrectFile.csv"); fail("Error occurred : Failed to recognize the incorrect file."); } catch (AtlasBaseException e) { assertEquals(e.getMessage(),"The uploaded file has not been processed due to the following errors : \n" + "[\n" + "The provided Reference Glossary and TermName does not exist in the system GentsFootwear: for record with TermName : BankBranch1 and GlossaryName : testBankingGlossary]"); } }
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; }
@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); } }
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; }
@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()); }
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; }
@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()); }
AtlasPathExtractorUtil { public static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context) { AtlasEntityWithExtInfo entityWithExtInfo = new AtlasEntityWithExtInfo(); AtlasEntity ret; String strPath = path.toString(); if (context.isConvertPathToLowerCase()) { strPath = strPath.toLowerCase(); } if (isS3Path(strPath)) { ret = isAwsS3AtlasModelVersionV2(context) ? addS3PathEntityV2(path, entityWithExtInfo, context) : addS3PathEntityV1(path, entityWithExtInfo, context); } else if (isAbfsPath(strPath)) { ret = addAbfsPathEntity(path, entityWithExtInfo, context); } else if (isOzonePath(strPath)) { ret = addOzonePathEntity(path, entityWithExtInfo, context); } else { ret = addHDFSPathEntity(path, context); } entityWithExtInfo.setEntity(ret); return entityWithExtInfo; } static AtlasEntityWithExtInfo getPathEntity(Path path, PathExtractorContext context); static final char QNAME_SEP_METADATA_NAMESPACE; static final char QNAME_SEP_ENTITY_NAME; static final String SCHEME_SEPARATOR; static final String ATTRIBUTE_QUALIFIED_NAME; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_BUCKET; static final String HDFS_TYPE_PATH; static final String ATTRIBUTE_PATH; static final String ATTRIBUTE_CLUSTER_NAME; static final String ATTRIBUTE_NAMESERVICE_ID; static final String AWS_S3_ATLAS_MODEL_VERSION_V2; static final String AWS_S3_BUCKET; static final String AWS_S3_PSEUDO_DIR; static final String AWS_S3_V2_BUCKET; static final String AWS_S3_V2_PSEUDO_DIR; static final String S3_SCHEME; static final String S3A_SCHEME; static final String ATTRIBUTE_CONTAINER; static final String ATTRIBUTE_OBJECT_PREFIX; static final String RELATIONSHIP_AWS_S3_BUCKET_S3_PSEUDO_DIRS; static final String RELATIONSHIP_AWS_S3_V2_CONTAINER_CONTAINED; static final String ADLS_GEN2_ACCOUNT; static final String ADLS_GEN2_CONTAINER; static final String ADLS_GEN2_DIRECTORY; static final String ADLS_GEN2_ACCOUNT_HOST_SUFFIX; static final String ABFS_SCHEME; static final String ABFSS_SCHEME; static final String ATTRIBUTE_ACCOUNT; static final String ATTRIBUTE_PARENT; static final String RELATIONSHIP_ADLS_GEN2_ACCOUNT_CONTAINERS; static final String RELATIONSHIP_ADLS_GEN2_PARENT_CHILDREN; static final String OZONE_VOLUME; static final String OZONE_BUCKET; static final String OZONE_KEY; static final String OZONE_SCHEME; static final String OZONE_3_SCHEME; static final String ATTRIBUTE_VOLUME; static final String RELATIONSHIP_OZONE_VOLUME_BUCKET; static final String RELATIONSHIP_OZONE_PARENT_CHILDREN; }
@Test(dataProvider = "ozonePathProvider") public void testGetPathEntityOzone3Path(OzoneKeyValidator validator) { String scheme = validator.scheme; String ozonePath = scheme + validator.location; PathExtractorContext extractorContext = new PathExtractorContext(METADATA_NAMESPACE); Path path = new Path(ozonePath); AtlasEntityWithExtInfo entityWithExtInfo = AtlasPathExtractorUtil.getPathEntity(path, extractorContext); AtlasEntity entity = entityWithExtInfo.getEntity(); assertNotNull(entity); verifyOzoneKeyEntity(entity, validator); assertEquals(entityWithExtInfo.getReferredEntities().size(), 2); verifyOzoneEntities(entityWithExtInfo.getReferredEntities(), validator); assertEquals(extractorContext.getKnownEntities().size(), validator.knownEntitiesCount); verifyOzoneEntities(extractorContext.getKnownEntities(), validator); } @Test public void testGetPathEntityHdfsPath() { PathExtractorContext extractorContext = new PathExtractorContext(METADATA_NAMESPACE); Path path = new Path(HDFS_PATH); AtlasEntityWithExtInfo entityWithExtInfo = AtlasPathExtractorUtil.getPathEntity(path, extractorContext); AtlasEntity entity = entityWithExtInfo.getEntity(); assertNotNull(entity); assertEquals(entity.getTypeName(), HDFS_PATH_TYPE); verifyHDFSEntity(entity, false); assertNull(entityWithExtInfo.getReferredEntities()); assertEquals(extractorContext.getKnownEntities().size(), 1); extractorContext.getKnownEntities().values().forEach(x -> verifyHDFSEntity(x, false)); } @Test public void testGetPathEntityHdfsPathLowerCase() { PathExtractorContext extractorContext = new PathExtractorContext(METADATA_NAMESPACE, true, null); Path path = new Path(HDFS_PATH); AtlasEntityWithExtInfo entityWithExtInfo = AtlasPathExtractorUtil.getPathEntity(path, extractorContext); AtlasEntity entity = entityWithExtInfo.getEntity(); assertNotNull(entity); assertEquals(entity.getTypeName(), HDFS_PATH_TYPE); verifyHDFSEntity(entity, true); assertNull(entityWithExtInfo.getReferredEntities()); assertEquals(extractorContext.getKnownEntities().size(), 1); extractorContext.getKnownEntities().values().forEach(x -> verifyHDFSEntity(x, true)); } @Test public void testGetPathEntityABFSPath() { PathExtractorContext extractorContext = new PathExtractorContext(METADATA_NAMESPACE); Path path = new Path(ABFS_PATH); AtlasEntityWithExtInfo entityWithExtInfo = AtlasPathExtractorUtil.getPathEntity(path, extractorContext); AtlasEntity entity = entityWithExtInfo.getEntity(); assertNotNull(entity); assertEquals(entity.getTypeName(), ADLS_GEN2_DIRECTORY); assertEquals(entityWithExtInfo.getReferredEntities().size(), 2); verifyABFSAdlsGen2Dir(ABFS_SCHEME, ABFS_PATH, entity); verifyABFSKnownEntities(ABFS_SCHEME, ABFS_PATH, extractorContext.getKnownEntities()); } @Test public void testGetPathEntityABFSSPath() { PathExtractorContext extractorContext = new PathExtractorContext(METADATA_NAMESPACE); Path path = new Path(ABFSS_PATH); AtlasEntityWithExtInfo entityWithExtInfo = AtlasPathExtractorUtil.getPathEntity(path, extractorContext); AtlasEntity entity = entityWithExtInfo.getEntity(); assertNotNull(entity); assertEquals(entity.getTypeName(), ADLS_GEN2_DIRECTORY); assertEquals(entityWithExtInfo.getReferredEntities().size(), 2); verifyABFSAdlsGen2Dir(ABFSS_SCHEME, ABFSS_PATH, entity); verifyABFSKnownEntities(ABFSS_SCHEME, ABFSS_PATH, extractorContext.getKnownEntities()); } @Test public void testGetPathEntityS3V2Path() { PathExtractorContext extractorContext = new PathExtractorContext(METADATA_NAMESPACE, AWS_S3_ATLAS_MODEL_VERSION_V2); Path path = new Path(S3_PATH); AtlasEntityWithExtInfo entityWithExtInfo = AtlasPathExtractorUtil.getPathEntity(path, extractorContext); AtlasEntity entity = entityWithExtInfo.getEntity(); assertNotNull(entity); assertEquals(entity.getTypeName(), AWS_S3_V2_PSEUDO_DIR); assertEquals(entityWithExtInfo.getReferredEntities().size(), 1); verifyS3V2PseudoDir(S3A_SCHEME, S3_PATH, entity); verifyS3V2KnownEntities(S3_SCHEME, S3_PATH, extractorContext.getKnownEntities()); } @Test public void testGetPathEntityS3AV2Path() { PathExtractorContext extractorContext = new PathExtractorContext(METADATA_NAMESPACE, AWS_S3_ATLAS_MODEL_VERSION_V2); Path path = new Path(S3A_PATH); AtlasEntityWithExtInfo entityWithExtInfo = AtlasPathExtractorUtil.getPathEntity(path, extractorContext); AtlasEntity entity = entityWithExtInfo.getEntity(); assertNotNull(entity); assertEquals(entity.getTypeName(), AWS_S3_V2_PSEUDO_DIR); assertEquals(entityWithExtInfo.getReferredEntities().size(), 1); verifyS3V2PseudoDir(S3A_SCHEME, S3A_PATH, entity); verifyS3V2KnownEntities(S3A_SCHEME, S3A_PATH, extractorContext.getKnownEntities()); } @Test public void testGetPathEntityS3Path() { PathExtractorContext extractorContext = new PathExtractorContext(METADATA_NAMESPACE); Path path = new Path(S3_PATH); AtlasEntityWithExtInfo entityWithExtInfo = AtlasPathExtractorUtil.getPathEntity(path, extractorContext); AtlasEntity entity = entityWithExtInfo.getEntity(); assertNotNull(entity); assertEquals(entity.getTypeName(), AWS_S3_PSEUDO_DIR); assertEquals(entityWithExtInfo.getReferredEntities().size(), 1); verifyS3PseudoDir(S3_PATH, entity); verifyS3KnownEntities(S3_SCHEME, S3_PATH, extractorContext.getKnownEntities()); } @Test public void testGetPathEntityS3APath() { PathExtractorContext extractorContext = new PathExtractorContext(METADATA_NAMESPACE); Path path = new Path(S3A_PATH); AtlasEntityWithExtInfo entityWithExtInfo = AtlasPathExtractorUtil.getPathEntity(path, extractorContext); AtlasEntity entity = entityWithExtInfo.getEntity(); assertNotNull(entity); assertEquals(entity.getTypeName(), AWS_S3_PSEUDO_DIR); assertEquals(entityWithExtInfo.getReferredEntities().size(), 1); verifyS3PseudoDir(S3A_PATH, entity); verifyS3KnownEntities(S3A_SCHEME, S3A_PATH, extractorContext.getKnownEntities()); }
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; }
@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(); } }
AtlasClientV2 extends AtlasBaseClient { public void updateClassifications(String guid, List<AtlasClassification> classifications) throws AtlasServiceException { callAPI(formatPathParameters(API_V2.UPDATE_CLASSIFICATIONS, guid), (Class<?>)null, classifications); } AtlasClientV2(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClientV2(String... baseUrls); AtlasClientV2(UserGroupInformation ugi, String doAsUser, String... baseUrls); AtlasClientV2(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClientV2(String[] baseUrl, Cookie cookie); AtlasClientV2(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClientV2(WebResource service, Configuration configuration); AtlasTypesDef getAllTypeDefs(SearchFilter searchFilter); List<AtlasTypeDefHeader> getAllTypeDefHeaders(SearchFilter searchFilter); boolean typeWithGuidExists(String guid); boolean typeWithNameExists(String name); AtlasEnumDef getEnumDefByName(String name); AtlasEnumDef getEnumDefByGuid(String guid); AtlasStructDef getStructDefByName(String name); AtlasStructDef getStructDefByGuid(String guid); AtlasClassificationDef getClassificationDefByName(String name); AtlasClassificationDef getClassificationDefByGuid(String guid); AtlasEntityDef getEntityDefByName(String name); AtlasEntityDef getEntityDefByGuid(String guid); AtlasRelationshipDef getRelationshipDefByName(String name); AtlasRelationshipDef getRelationshipDefByGuid(String guid); AtlasBusinessMetadataDef getBusinessMetadataDefByName(String name); AtlasBusinessMetadataDef getBusinessMetadataDefGuid(String guid); @Deprecated AtlasEnumDef createEnumDef(AtlasEnumDef enumDef); @Deprecated AtlasStructDef createStructDef(AtlasStructDef structDef); @Deprecated AtlasEntityDef createEntityDef(AtlasEntityDef entityDef); @Deprecated AtlasClassificationDef createClassificationDef(AtlasClassificationDef classificationDef); AtlasTypesDef createAtlasTypeDefs(AtlasTypesDef typesDef); AtlasTypesDef updateAtlasTypeDefs(AtlasTypesDef typesDef); void deleteAtlasTypeDefs(AtlasTypesDef typesDef); void deleteTypeByName(String typeName); AtlasEntityWithExtInfo getEntityByGuid(String guid); AtlasEntityWithExtInfo getEntityByGuid(String guid, boolean minExtInfo, boolean ignoreRelationships); AtlasEntityWithExtInfo getEntityByAttribute(String typeName, Map<String, String> uniqAttributes); AtlasEntityWithExtInfo getEntityByAttribute(String typeName, Map<String, String> uniqAttributes, boolean minExtInfo, boolean ignoreRelationship); AtlasEntitiesWithExtInfo getEntitiesByGuids(List<String> guids); AtlasEntitiesWithExtInfo getEntitiesByGuids(List<String> guids, boolean minExtInfo, boolean ignoreRelationships); AtlasEntitiesWithExtInfo getEntitiesByAttribute(String typeName, List<Map<String,String>> uniqAttributesList); AtlasEntitiesWithExtInfo getEntitiesByAttribute(String typeName, List<Map<String, String>> uniqAttributesList, boolean minExtInfo, boolean ignoreRelationship); AtlasEntityHeader getEntityHeaderByGuid(String entityGuid); AtlasEntityHeader getEntityHeaderByAttribute(String typeName, Map<String, String> uniqAttributes); List<EntityAuditEventV2> getAuditEvents(String guid, String startKey, EntityAuditEventV2.EntityAuditActionV2 auditAction, short count); EntityMutationResponse createEntity(AtlasEntityWithExtInfo entity); EntityMutationResponse createEntities(AtlasEntitiesWithExtInfo atlasEntities); EntityMutationResponse updateEntity(AtlasEntityWithExtInfo entity); EntityMutationResponse updateEntities(AtlasEntitiesWithExtInfo atlasEntities); EntityMutationResponse updateEntityByAttribute(String typeName, Map<String, String> uniqAttributes, AtlasEntityWithExtInfo entityInfo); EntityMutationResponse partialUpdateEntityByGuid(String entityGuid, Object attrValue, String attrName); EntityMutationResponse deleteEntityByGuid(String guid); EntityMutationResponse deleteEntityByAttribute(String typeName, Map<String, String> uniqAttributes); EntityMutationResponse deleteEntitiesByGuids(List<String> guids); EntityMutationResponse purgeEntitiesByGuids(Set<String> guids); AtlasClassifications getClassifications(String guid); AtlasClassifications getEntityClassifications(String entityGuid, String classificationName); void addClassification(ClassificationAssociateRequest request); void addClassifications(String guid, List<AtlasClassification> classifications); void addClassifications(String typeName, Map<String, String> uniqAttributes, List<AtlasClassification> classifications); void updateClassifications(String guid, List<AtlasClassification> classifications); void updateClassifications(String typeName, Map<String, String> uniqAttributes, List<AtlasClassification> classifications); String setClassifications(AtlasEntityHeaders entityHeaders); void deleteClassification(String guid, String classificationName); void deleteClassifications(String guid, List<AtlasClassification> classifications); void removeClassification(String entityGuid, String classificationName, String associatedEntityGuid); void removeClassification(String typeName, Map<String, String> uniqAttributes, String classificationName); AtlasEntityHeaders getEntityHeaders(long tagUpdateStartTime); void addOrUpdateBusinessAttributes(String entityGuid, boolean isOverwrite, Map<String, Map<String, Object>> businessAttributes); void addOrUpdateBusinessAttributes(String entityGuid, String bmName, Map<String, Map<String, Object>> businessAttributes); void removeBusinessAttributes(String entityGuid, Map<String, Map<String, Object>> businessAttributes); void removeBusinessAttributes(String entityGuid, String bmName, Map<String, Map<String, Object>> businessAttributes); String getTemplateForBulkUpdateBusinessAttributes(); BulkImportResponse bulkUpdateBusinessAttributes(String fileName); void addLabels(String entityGuid, Set<String> labels); void addLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); void removeLabels(String entityGuid, Set<String> labels); void removeLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); void setLabels(String entityGuid, Set<String> labels); void setLabels(String typeName, Map<String, String> uniqAttributes, Set<String> labels); AtlasLineageInfo getLineageInfo(String guid, LineageDirection direction, int depth); AtlasLineageInfo getLineageInfo(String typeName, Map<String, String> attributes, LineageDirection direction, int depth); AtlasSearchResult dslSearch(String query); AtlasSearchResult dslSearchWithParams(String query, int limit, int offset); AtlasSearchResult fullTextSearch(String query); AtlasSearchResult fullTextSearchWithParams(String query, int limit, int offset); AtlasSearchResult basicSearch(String typeName, String classification, String query, boolean excludeDeletedEntities, int limit, int offset); AtlasSearchResult facetedSearch(SearchParameters searchParameters); AtlasSearchResult attributeSearch(String typeName, String attrName, String attrValuePrefix, int limit, int offset); AtlasSearchResult relationshipSearch(String guid, String relation, String sortByAttribute, SortOrder sortOrder, boolean excludeDeletedEntities, int limit, int offset); AtlasQuickSearchResult quickSearch(String query, String typeName, boolean excludeDeletedEntities, int limit, int offset); AtlasQuickSearchResult quickSearch(QuickSearchParameters quickSearchParameters); AtlasSuggestionsResult getSuggestions(String prefixString, String fieldName); List<AtlasUserSavedSearch> getSavedSearches(String userName); AtlasUserSavedSearch getSavedSearch(String userName, String searchName); AtlasUserSavedSearch addSavedSearch(AtlasUserSavedSearch savedSearch); AtlasUserSavedSearch updateSavedSearch(AtlasUserSavedSearch savedSearch); void deleteSavedSearch(String guid); AtlasSearchResult executeSavedSearch(String userName, String searchName); AtlasSearchResult executeSavedSearch(String searchGuid); AtlasRelationshipWithExtInfo getRelationshipByGuid(String guid); AtlasRelationshipWithExtInfo getRelationshipByGuid(String guid, boolean extendedInfo); AtlasRelationship createRelationship(AtlasRelationship relationship); AtlasRelationship updateRelationship(AtlasRelationship relationship); void deleteRelationshipByGuid(String guid); List<AtlasAuditEntry> getAtlasAuditByOperation(AuditSearchParameters auditSearchParameters); List<AtlasGlossary> getAllGlossaries(String sortByAttribute, int limit, int offset); AtlasGlossary getGlossaryByGuid(String glossaryGuid); AtlasGlossary.AtlasGlossaryExtInfo getGlossaryExtInfo(String glossaryGuid); AtlasGlossaryTerm getGlossaryTerm(String termGuid); List<AtlasGlossaryTerm> getGlossaryTerms(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedTermHeader> getGlossaryTermHeaders(String glossaryGuid, String sortByAttribute, int limit, int offset); AtlasGlossaryCategory getGlossaryCategory(String categoryGuid); List<AtlasGlossaryCategory> getGlossaryCategories(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedCategoryHeader> getGlossaryCategoryHeaders(String glossaryGuid, String sortByAttribute, int limit, int offset); List<AtlasRelatedTermHeader> getCategoryTerms(String categoryGuid, String sortByAttribute, int limit, int offset); Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, String sortByAttribute, int limit, int offset); Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(String categoryGuid, String sortByAttribute, int limit, int offset); AtlasGlossary createGlossary(AtlasGlossary glossary); AtlasGlossaryTerm createGlossaryTerm(AtlasGlossaryTerm glossaryTerm); List<AtlasGlossaryTerm> createGlossaryTerms(List<AtlasGlossaryTerm> glossaryTerms); AtlasGlossaryCategory createGlossaryCategory(AtlasGlossaryCategory glossaryCategory); List<AtlasGlossaryCategory> createGlossaryCategories(List<AtlasGlossaryCategory> glossaryCategories); AtlasGlossary updateGlossaryByGuid(String glossaryGuid, AtlasGlossary updatedGlossary); AtlasGlossary partialUpdateGlossaryByGuid(String glossaryGuid, Map<String, String> attributes); AtlasGlossaryTerm updateGlossaryTermByGuid(String termGuid, AtlasGlossaryTerm glossaryTerm); AtlasGlossaryTerm partialUpdateTermByGuid(String termGuid, Map<String, String> attributes); AtlasGlossaryCategory updateGlossaryCategoryByGuid(String categoryGuid, AtlasGlossaryCategory glossaryCategory); AtlasGlossaryCategory partialUpdateCategoryByGuid(String categoryGuid, Map<String, String> attributes); void deleteGlossaryByGuid(String glossaryGuid); void deleteGlossaryTermByGuid(String termGuid); void deleteGlossaryCategoryByGuid(String categoryGuid); List<AtlasRelatedObjectId> getEntitiesAssignedWithTerm(String termGuid, String sortByAttribute, int limit, int offset); void assignTermToEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); void disassociateTermFromEntities(String termGuid, List<AtlasRelatedObjectId> relatedObjectIds); String getGlossaryImportTemplate(); List<AtlasGlossaryTerm> importGlossary(String fileName); static final String TYPES_API; static final String ENTITY_API; }
@Test public void updateClassificationsShouldNotThrowExceptionIfResponseIs204() { AtlasClientV2 atlasClient = new AtlasClientV2(service, configuration); AtlasClassification atlasClassification = new AtlasClassification("Testdb"); atlasClassification.setEntityGuid("abb672b1-e4bd-402d-a98f-73cd8f775e2a"); WebResource.Builder builder = setupBuilder(AtlasClientV2.API_V2.UPDATE_CLASSIFICATIONS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.NO_CONTENT.getStatusCode()); when(builder.method(anyString(), Matchers.<Class>any(), anyString())).thenReturn(response); try { atlasClient.updateClassifications("abb672b1-e4bd-402d-a98f-73cd8f775e2a", Collections.singletonList(atlasClassification)); } catch (AtlasServiceException e) { Assert.fail("Failed with Exception"); } } @Test public void updateClassificationsShouldThrowExceptionIfResponseIsNot204() { AtlasClientV2 atlasClient = new AtlasClientV2(service, configuration); AtlasClassification atlasClassification = new AtlasClassification("Testdb"); atlasClassification.setEntityGuid("abb672b1-e4bd-402d-a98f-73cd8f775e2a"); WebResource.Builder builder = setupBuilder(AtlasClientV2.API_V2.UPDATE_CLASSIFICATIONS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(builder.method(anyString(), Matchers.<Class>any(), anyString())).thenReturn(response); try { atlasClient.updateClassifications("abb672b1-e4bd-402d-a98f-73cd8f775e2a", Collections.singletonList(atlasClassification)); Assert.fail("Failed with Exception"); } catch (AtlasServiceException e) { Assert.assertTrue(e.getMessage().contains(" failed with status 200 ")); } }
AtlasClient extends AtlasBaseClient { public Referenceable getEntity(String guid) throws AtlasServiceException { ObjectNode jsonResponse = callAPIWithBodyAndParams(API_V1.GET_ENTITY, null, guid); String entityInstanceDefinition = AtlasType.toJson(jsonResponse.get(AtlasClient.DEFINITION)); return AtlasType.fromV1Json(entityInstanceDefinition, Referenceable.class); } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType, final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName, final String uniqueAttributeValue, Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); static final String TYPE; static final String TYPENAME; static final String GUID; static final String ENTITIES; static final String GUID_ASSIGNMENTS; static final String DEFINITION; static final String ERROR; static final String STACKTRACE; static final String REQUEST_ID; static final String RESULTS; static final String COUNT; static final String ROWS; static final String DATATYPE; static final String STATUS; static final String EVENTS; static final String START_KEY; static final String NUM_RESULTS; static final String URI_ENTITY; static final String URI_ENTITY_AUDIT; static final String URI_SEARCH; static final String URI_NAME_LINEAGE; static final String URI_LINEAGE; static final String URI_TRAITS; static final String TRAITS; static final String TRAIT_DEFINITIONS; static final String QUERY_TYPE; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_VALUE; static final String SUPERTYPE; static final String NOT_SUPERTYPE; static final String ASSET_TYPE; static final String NAME; static final String DESCRIPTION; static final String OWNER; static final String CREATE_TIME; static final String INFRASTRUCTURE_SUPER_TYPE; static final String DATA_SET_SUPER_TYPE; static final String PROCESS_SUPER_TYPE; static final String PROCESS_ATTRIBUTE_INPUTS; static final String PROCESS_ATTRIBUTE_OUTPUTS; static final String REFERENCEABLE_SUPER_TYPE; static final String QUALIFIED_NAME; static final String REFERENCEABLE_ATTRIBUTE_NAME; static final String UNKNOWN_STATUS; }
@Test public void shouldVerifyServerIsReady() throws AtlasServiceException { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.VERSION, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"Version\":\"version-rrelease\",\"Name\":\"apache-atlas\"," + "\"Description\":\"Metadata Management and Data Governance Platform over Hadoop\"}"); when(builder.method(AtlasClient.API_V1.VERSION.getMethod(), ClientResponse.class, null)).thenReturn(response); assertTrue(atlasClient.isServerReady()); } @Test public void shouldGetAdminStatus() throws AtlasServiceException { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"Active\"}"; when(response.getEntity(String.class)).thenReturn(activeStatus); when(response.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)).thenReturn(response); String status = atlasClient.getAdminStatus(); assertEquals(status, "Active"); } @Test public void shouldReturnStatusAsUnknownIfJSONIsInvalid() throws AtlasServiceException { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"status\":\"Active\"}"); when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)).thenReturn(response); String status = atlasClient.getAdminStatus(); assertEquals(status, AtlasClient.UNKNOWN_STATUS); } @Test public void shouldSelectActiveAmongMultipleServersIfHAIsEnabled() { setupRetryParams(); when(client.resource(UriBuilder.fromUri("http: when(client.resource(UriBuilder.fromUri("http: WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service); ClientResponse firstResponse = mock(ClientResponse.class); when(firstResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String passiveStatus = "{\"Status\":\"PASSIVE\"}"; when(firstResponse.getEntity(String.class)).thenReturn(passiveStatus); when(firstResponse.getLength()).thenReturn(passiveStatus.length()); ClientResponse secondResponse = mock(ClientResponse.class); when(secondResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"ACTIVE\"}"; when(secondResponse.getEntity(String.class)).thenReturn(activeStatus); when(secondResponse.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)). thenReturn(firstResponse).thenReturn(firstResponse).thenReturn(firstResponse). thenReturn(secondResponse); AtlasClient atlasClient = new AtlasClient(service, configuration); String serviceURL = atlasClient.determineActiveServiceURL( new String[]{"http: client); assertEquals(serviceURL, "http: } @Test public void shouldRetryUntilServiceBecomesActive() { setupRetryParams(); when(client.resource(UriBuilder.fromUri("http: WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"Status\":\"BECOMING_ACTIVE\"}"); ClientResponse nextResponse = mock(ClientResponse.class); when(nextResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"ACTIVE\"}"; when(response.getEntity(String.class)).thenReturn(activeStatus); when(response.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)). thenReturn(response).thenReturn(response).thenReturn(nextResponse); AtlasClient atlasClient = new AtlasClient(service, configuration); String serviceURL = atlasClient.determineActiveServiceURL( new String[] {"http: client); assertEquals(serviceURL, "http: } @Test public void shouldRetryIfCannotConnectToServiceInitially() { setupRetryParams(); when(client.resource(UriBuilder.fromUri("http: WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"Status\":\"BECOMING_ACTIVE\"}"); ClientResponse nextResponse = mock(ClientResponse.class); when(nextResponse.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); String activeStatus = "{\"Status\":\"ACTIVE\"}"; when(response.getEntity(String.class)).thenReturn(activeStatus); when(response.getLength()).thenReturn(activeStatus.length()); when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)). thenThrow(new ClientHandlerException("Simulating connection exception")). thenReturn(response). thenReturn(nextResponse); AtlasClient atlasClient = new AtlasClient(service, configuration); atlasClient.setService(service); atlasClient.setConfiguration(configuration); String serviceURL = atlasClient.determineActiveServiceURL( new String[] {"http: client); assertEquals(serviceURL, "http: } @Test(expectedExceptions = IllegalArgumentException.class) public void shouldThrowExceptionIfActiveServerIsNotFound() { setupRetryParams(); when(client.resource(UriBuilder.fromUri("http: WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.STATUS, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.OK.getStatusCode()); when(response.getEntity(String.class)).thenReturn("{\"Status\":\"BECOMING_ACTIVE\"}"); when(builder.method(AtlasClient.API_V1.STATUS.getMethod(), ClientResponse.class, null)). thenThrow(new ClientHandlerException("Simulating connection exception")). thenReturn(response). thenReturn(response); AtlasClient atlasClient = new AtlasClient(service, configuration); String serviceURL = atlasClient.determineActiveServiceURL( new String[] {"http: client); assertNull(serviceURL); }
AtlasClient extends AtlasBaseClient { protected List<String> createEntity(ArrayNode entities) throws AtlasServiceException { LOG.debug("Creating entities: {}", entities); ObjectNode response = callAPIWithBody(API_V1.CREATE_ENTITY, entities.toString()); List<String> results = extractEntityResult(response).getCreatedEntities(); LOG.debug("Create entities returned results: {}", results); return results; } AtlasClient(String[] baseUrl, String cookieName, String value, String path, String domain); AtlasClient(String[] baseUrl, Cookie cookie); AtlasClient(String[] baseUrl, String[] basicAuthUserNamePassword); AtlasClient(String... baseUrls); AtlasClient(UserGroupInformation ugi, String doAsUser, String... baseUrls); private AtlasClient(UserGroupInformation ugi, String[] baseUrls); protected AtlasClient(); @VisibleForTesting AtlasClient(Configuration configuration, String[] baseUrl, String[] basicAuthUserNamePassword); @VisibleForTesting AtlasClient(Configuration configuration, String... baseUrls); @VisibleForTesting AtlasClient(WebResource service, Configuration configuration); WebResource getResource(); List<String> createType(String typeAsJson); List<String> createType(TypesDef typeDef); List<String> createTraitType(String traitName, Set<String> superTraits, AttributeDefinition... attributeDefinitions); List<String> createTraitType(String traitName); List<String> updateType(String typeAsJson); List<String> updateType(TypesDef typeDef); List<String> listTypes(); List<String> listTypes(final DataTypes.TypeCategory category); List<String> listTypes(final DataTypes.TypeCategory category, final String superType, final String notSupertype); TypesDef getType(String typeName); List<String> createEntity(String... entitiesAsJson); List<String> createEntity(Referenceable... entities); List<String> createEntity(Collection<Referenceable> entities); EntityResult updateEntities(Referenceable... entities); EntityResult updateEntities(Collection<Referenceable> entities); EntityResult updateEntityAttribute(final String guid, final String attribute, String value); EntityResult updateEntity(String guid, Referenceable entity); void addTrait(String guid, Struct traitDefinition); void deleteTrait(String guid, String traitName); EntityResult updateEntity(final String entityType, final String uniqueAttributeName, final String uniqueAttributeValue, Referenceable entity); EntityResult deleteEntities(final String... guids); EntityResult deleteEntity(String entityType, String uniqueAttributeName, String uniqueAttributeValue); Referenceable getEntity(String guid); static String toString(ArrayNode jsonArray); Referenceable getEntity(final String entityType, final String attribute, final String value); List<String> listEntities(final String entityType); List<String> listTraits(final String guid); List<Struct> listTraitDefinitions(final String guid); Struct getTraitDefinition(final String guid, final String traitName); List<EntityAuditEvent> getEntityAuditEvents(String entityId, short numResults); List<EntityAuditEvent> getEntityAuditEvents(String entityId, String startKey, short numResults); JsonNode search(final String searchQuery, final int limit, final int offset); ArrayNode searchByDSL(final String query, final int limit, final int offset); ObjectNode searchByFullText(final String query, final int limit, final int offset); ObjectNode getInputGraph(String datasetName); ObjectNode getOutputGraph(String datasetName); ObjectNode getInputGraphForEntity(String entityId); ObjectNode getOutputGraphForEntity(String datasetId); ObjectNode getSchemaForEntity(String datasetId); @VisibleForTesting ObjectNode callAPIWithResource(API api, WebResource resource); @VisibleForTesting ObjectNode callAPIWithResource(API_V1 apiV1, WebResource resource); @VisibleForTesting WebResource getResource(API api, String... params); @VisibleForTesting WebResource getResource(API_V1 apiV1, String... params); @VisibleForTesting ObjectNode callAPIWithBody(API api, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBody(API_V1 apiV1, Object requestObject); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API api, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithBodyAndParams(API_V1 apiV1, Object requestObject, String... params); @VisibleForTesting ObjectNode callAPIWithQueryParams(API api, MultivaluedMap<String, String> queryParams); @VisibleForTesting ObjectNode callAPIWithQueryParams(API_V1 apiV1, MultivaluedMap<String, String> queryParams); static final String TYPE; static final String TYPENAME; static final String GUID; static final String ENTITIES; static final String GUID_ASSIGNMENTS; static final String DEFINITION; static final String ERROR; static final String STACKTRACE; static final String REQUEST_ID; static final String RESULTS; static final String COUNT; static final String ROWS; static final String DATATYPE; static final String STATUS; static final String EVENTS; static final String START_KEY; static final String NUM_RESULTS; static final String URI_ENTITY; static final String URI_ENTITY_AUDIT; static final String URI_SEARCH; static final String URI_NAME_LINEAGE; static final String URI_LINEAGE; static final String URI_TRAITS; static final String TRAITS; static final String TRAIT_DEFINITIONS; static final String QUERY_TYPE; static final String ATTRIBUTE_NAME; static final String ATTRIBUTE_VALUE; static final String SUPERTYPE; static final String NOT_SUPERTYPE; static final String ASSET_TYPE; static final String NAME; static final String DESCRIPTION; static final String OWNER; static final String CREATE_TIME; static final String INFRASTRUCTURE_SUPER_TYPE; static final String DATA_SET_SUPER_TYPE; static final String PROCESS_SUPER_TYPE; static final String PROCESS_ATTRIBUTE_INPUTS; static final String PROCESS_ATTRIBUTE_OUTPUTS; static final String REFERENCEABLE_SUPER_TYPE; static final String QUALIFIED_NAME; static final String REFERENCEABLE_ATTRIBUTE_NAME; static final String UNKNOWN_STATUS; }
@Test public void testCreateEntity() throws Exception { setupRetryParams(); AtlasClient atlasClient = new AtlasClient(service, configuration); WebResource.Builder builder = setupBuilder(AtlasClient.API_V1.CREATE_ENTITY, service); ClientResponse response = mock(ClientResponse.class); when(response.getStatus()).thenReturn(Response.Status.CREATED.getStatusCode()); String jsonResponse = AtlasType.toV1Json(new EntityResult(Arrays.asList("id"), null, null)); when(response.getEntity(String.class)).thenReturn(jsonResponse.toString()); when(response.getLength()).thenReturn(jsonResponse.length()); String entityJson = AtlasType.toV1Json(new Referenceable("type")); when(builder.method(anyString(), Matchers.<Class>any(), anyString())).thenReturn(response); List<String> ids = atlasClient.createEntity(entityJson); assertEquals(ids.size(), 1); assertEquals(ids.get(0), "id"); }
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; }
@Test public void testEntityTypeDefaultValue() { AtlasEntity defValue = entityType.createDefaultValue(); assertNotNull(defValue); assertEquals(defValue.getTypeName(), entityType.getTypeName()); }
AtlasHook { @VisibleForTesting static void notifyEntitiesInternal(List<HookNotification> messages, int maxRetries, UserGroupInformation ugi, NotificationInterface notificationInterface, boolean shouldLogFailedMessages, FailedMessagesLogger logger) { if (messages == null || messages.isEmpty()) { return; } final int maxAttempts = maxRetries < 1 ? 1 : maxRetries; Exception notificationFailure = null; for (int numAttempt = 1; numAttempt <= maxAttempts; numAttempt++) { if (numAttempt > 1) { try { LOG.debug("Sleeping for {} ms before retry", notificationRetryInterval); Thread.sleep(notificationRetryInterval); } catch (InterruptedException ie) { LOG.error("Notification hook thread sleep interrupted"); break; } } try { if (ugi == null) { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); } else { PrivilegedExceptionAction<Object> privilegedNotify = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { notificationInterface.send(NotificationInterface.NotificationType.HOOK, messages); return messages; } }; ugi.doAs(privilegedNotify); } notificationFailure = null; break; } catch (Exception e) { notificationFailure = e; LOG.error("Failed to send notification - attempt #{}; error={}", numAttempt, e.getMessage()); } } if (notificationFailure != null) { if (shouldLogFailedMessages && notificationFailure instanceof NotificationException) { final List<String> failedMessages = ((NotificationException) notificationFailure).getFailedMessages(); for (String msg : failedMessages) { logger.log(msg); } } LOG.error("Giving up after {} failed attempts to send notification to Atlas: {}", maxAttempts, messages.toString(), notificationFailure); } } static void notifyEntities(List<HookNotification> messages, UserGroupInformation ugi, int maxRetries); static String getUser(); static String getUser(String userName); static String getUser(String userName, UserGroupInformation ugi); String getMetadataNamespace(); static final String ATLAS_NOTIFICATION_ASYNCHRONOUS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MIN_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_MAX_THREADS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_KEEP_ALIVE_TIME_MS; static final String ATLAS_NOTIFICATION_ASYNCHRONOUS_QUEUE_SIZE; static final String ATLAS_NOTIFICATION_MAX_RETRIES; static final String ATLAS_NOTIFICATION_RETRY_INTERVAL; static final String ATLAS_NOTIFICATION_FAILED_MESSAGES_FILENAME_KEY; static final String ATLAS_NOTIFICATION_LOG_FAILED_MESSAGES_ENABLED_KEY; static final String ATLAS_HOOK_FAILED_MESSAGES_LOG_DEFAULT_NAME; static final String CONF_METADATA_NAMESPACE; static final String CLUSTER_NAME_KEY; static final String DEFAULT_CLUSTER_NAME; }
@Test (timeOut = 10000) public void testNotifyEntitiesDoesNotHangOnException() throws Exception { List<HookNotification> hookNotifications = new ArrayList<>(); doThrow(new NotificationException(new Exception())).when(notificationInterface) .send(NotificationInterface.NotificationType.HOOK, hookNotifications); AtlasHook.notifyEntitiesInternal(hookNotifications, 0, null, notificationInterface, false, failedMessagesLogger); } @Test public void testNotifyEntitiesRetriesOnException() throws NotificationException { List<HookNotification> hookNotifications = new ArrayList<HookNotification>() {{ add(new EntityCreateRequest("user")); } }; doThrow(new NotificationException(new Exception())).when(notificationInterface) .send(NotificationInterface.NotificationType.HOOK, hookNotifications); AtlasHook.notifyEntitiesInternal(hookNotifications, 2, null, notificationInterface, false, failedMessagesLogger); verify(notificationInterface, times(2)). send(NotificationInterface.NotificationType.HOOK, hookNotifications); } @Test public void testFailedMessageIsLoggedIfRequired() throws NotificationException { List<HookNotification> hookNotifications = new ArrayList<HookNotification>() {{ add(new EntityCreateRequest("user")); } }; doThrow(new NotificationException(new Exception(), Arrays.asList("test message"))) .when(notificationInterface) .send(NotificationInterface.NotificationType.HOOK, hookNotifications); AtlasHook.notifyEntitiesInternal(hookNotifications, 2, null, notificationInterface, true, failedMessagesLogger); verify(failedMessagesLogger, times(1)).log("test message"); } @Test public void testFailedMessageIsNotLoggedIfNotRequired() throws NotificationException { List<HookNotification> hookNotifications = new ArrayList<>(); doThrow(new NotificationException(new Exception(), Arrays.asList("test message"))) .when(notificationInterface) .send(NotificationInterface.NotificationType.HOOK, hookNotifications); AtlasHook.notifyEntitiesInternal(hookNotifications, 2, null, notificationInterface, false, failedMessagesLogger); verifyZeroInteractions(failedMessagesLogger); } @Test public void testAllFailedMessagesAreLogged() throws NotificationException { List<HookNotification> hookNotifications = new ArrayList<HookNotification>() {{ add(new EntityCreateRequest("user")); } }; doThrow(new NotificationException(new Exception(), Arrays.asList("test message1", "test message2"))) .when(notificationInterface) .send(NotificationInterface.NotificationType.HOOK, hookNotifications); AtlasHook.notifyEntitiesInternal(hookNotifications, 2, null, notificationInterface, true, failedMessagesLogger); verify(failedMessagesLogger, times(1)).log("test message1"); verify(failedMessagesLogger, times(1)).log("test message2"); } @Test public void testFailedMessageIsNotLoggedIfNotANotificationException() throws Exception { List<HookNotification> hookNotifications = new ArrayList<>(); doThrow(new RuntimeException("test message")).when(notificationInterface) .send(NotificationInterface.NotificationType.HOOK, hookNotifications); AtlasHook.notifyEntitiesInternal(hookNotifications, 2, null, notificationInterface, true, failedMessagesLogger); verifyZeroInteractions(failedMessagesLogger); }
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; }
@Test public void testEntityTypeIsValidValue() { for (Object value : validValues) { assertTrue(entityType.isValidValue(value), "value=" + value); } for (Object value : invalidValues) { assertFalse(entityType.isValidValue(value), "value=" + value); } }
AtlasSimpleAuthorizer implements AtlasAuthorizer { @Override public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException { if (LOG.isDebugEnabled()) { LOG.debug("==> SimpleAtlasAuthorizer.isAccessAllowed({})", request); } boolean ret = false; Set<String> roles = getRoles(request.getUser(), request.getUserGroups()); for (String role : roles) { List<AtlasAdminPermission> permissions = getAdminPermissionsForRole(role); if (permissions != null) { final String action = request.getAction() != null ? request.getAction().getType() : null; for (AtlasAdminPermission permission : permissions) { if (isMatch(action, permission.getPrivileges())) { ret = true; break; } } } } if (LOG.isDebugEnabled()) { LOG.debug("<== SimpleAtlasAuthorizer.isAccessAllowed({}): {}", request, ret); } return ret; } AtlasSimpleAuthorizer(); @Override void init(); @Override void cleanUp(); @Override boolean isAccessAllowed(AtlasAdminAccessRequest request); @Override boolean isAccessAllowed(AtlasTypeAccessRequest request); @Override boolean isAccessAllowed(AtlasRelationshipAccessRequest request); @Override boolean isAccessAllowed(AtlasEntityAccessRequest request); @Override void scrubSearchResults(AtlasSearchResultScrubRequest request); @Override void filterTypesDef(AtlasTypesDefFilterRequest request); }
@Test(enabled = true) public void testAccessAllowedForUserAndGroup() { try { AtlasEntityAccessRequest request = new AtlasEntityAccessRequest(null, AtlasPrivilege.ENTITY_UPDATE); request.setUser("admin", Collections.singleton("ROLE_ADMIN")); boolean isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals(true, isAccessAllowed); } catch (Exception e) { LOG.error("Exception in AtlasSimpleAuthorizerTest", e); AssertJUnit.fail(); } } @Test(enabled = true) public void testAccessAllowedForGroup() { try { AtlasEntityAccessRequest request = new AtlasEntityAccessRequest(null, AtlasPrivilege.ENTITY_UPDATE); request.setUser("nonmappeduser", Collections.singleton("ROLE_ADMIN")); boolean isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals(true, isAccessAllowed); } catch (AtlasAuthorizationException e) { LOG.error("Exception in AtlasSimpleAuthorizerTest", e); AssertJUnit.fail(); } } @Test(enabled = true) public void testAccessNotAllowedForUserAndGroup() { try { AtlasEntityAccessRequest request = new AtlasEntityAccessRequest(null, AtlasPrivilege.ENTITY_UPDATE); request.setUser("nonmappeduser", Collections.singleton("GROUP-NOT-IN-POLICYFILE")); boolean isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals(false, isAccessAllowed); } catch (AtlasAuthorizationException e) { LOG.error("Exception in AtlasSimpleAuthorizerTest", e); AssertJUnit.fail(); } } @Test(enabled = true) public void testLabels() { try { AtlasEntityAccessRequest request = new AtlasEntityAccessRequest(null, AtlasPrivilege.ENTITY_ADD_LABEL); request.setUser(USER_DATA_SCIENTIST, Collections.emptySet()); boolean isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals("user " + USER_DATA_SCIENTIST + " shouldn't be allowed to add label", false, isAccessAllowed); request.setUser(USER_DATA_STEWARD, Collections.emptySet()); isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals("user " + USER_DATA_STEWARD + " should be allowed to add label", true, isAccessAllowed); request = new AtlasEntityAccessRequest(null, AtlasPrivilege.ENTITY_REMOVE_LABEL); request.setUser(USER_DATA_SCIENTIST, Collections.emptySet()); isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals("user " + USER_DATA_SCIENTIST + " shouldn't be allowed to remove label", false, isAccessAllowed); request.setUser(USER_DATA_STEWARD, Collections.emptySet()); isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals("user " + USER_DATA_STEWARD + " should be allowed to remove label", true, isAccessAllowed); } catch (AtlasAuthorizationException e) { LOG.error("Exception in AtlasSimpleAuthorizerTest", e); AssertJUnit.fail(); } } @Test(enabled = true) public void testBusinessMetadata() { try { AtlasEntityAccessRequest request = new AtlasEntityAccessRequest(null, AtlasPrivilege.ENTITY_UPDATE_BUSINESS_METADATA); request.setUser(USER_DATA_SCIENTIST, Collections.emptySet()); boolean isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals("user " + USER_DATA_SCIENTIST + " shouldn't be allowed to update business-metadata", false, isAccessAllowed); request.setUser(USER_DATA_STEWARD, Collections.emptySet()); isAccessAllowed = authorizer.isAccessAllowed(request); AssertJUnit.assertEquals("user " + USER_DATA_STEWARD + " should be allowed to update business-metadata", true, isAccessAllowed); } catch (AtlasAuthorizationException e) { LOG.error("Exception in AtlasSimpleAuthorizerTest", e); AssertJUnit.fail(); } }
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; }
@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); } }
AtlasJanusGraphIndexClient implements AtlasGraphIndexClient { @VisibleForTesting static List<String> getTopTerms(Map<String, TermFreq> termsMap) { final List<String> ret; if (MapUtils.isNotEmpty(termsMap)) { PriorityQueue<TermFreq> termsQueue = new PriorityQueue(termsMap.size(), FREQ_COMPARATOR); for (TermFreq term : termsMap.values()) { termsQueue.add(term); } ret = new ArrayList<>(DEFAULT_SUGGESTION_COUNT); while (!termsQueue.isEmpty()) { ret.add(termsQueue.poll().getTerm()); if (ret.size() >= DEFAULT_SUGGESTION_COUNT) { break; } } } else { ret = Collections.EMPTY_LIST; } return ret; } 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); }
@Test public void testGetTopTermsAsendingInput() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 10, 12, 15); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 2,1,0); } @Test public void testGetTopTermsAsendingInput2() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 10, 12, 15, 20, 25, 26, 30, 40); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 7, 6, 5, 4, 3); } @Test public void testGetTopTermsDescendingInput() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 10, 9, 8); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 0, 1, 2); } @Test public void testGetTopTermsDescendingInput2() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 10, 9, 8, 7, 6, 5, 4, 3, 2); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 0, 1, 2, 3, 4); } @Test public void testGetTopTermsRandom() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 10, 19, 28, 27, 16, 1, 30, 3, 36); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 8, 6, 2, 3, 1); } @Test public void testGetTopTermsRandom2() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 36, 19, 28, 27, 16, 1, 30, 3, 10); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 0, 6, 2, 3, 1); } @Test public void testGetTopTermsRandom3() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 36, 36, 28, 27, 16, 1, 30, 3, 10); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 0, 1, 6, 2, 3); } @Test public void testGetTopTermsRandom4() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 10, 10, 28, 27, 16, 1, 30, 36, 36); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 7, 8, 6, 2, 3); } @Test public void testGetTopTermsRandom5() { Map<String, AtlasJanusGraphIndexClient.TermFreq> terms = generateTerms( 36, 10, 28, 27, 16, 1, 30, 36, 36); List<String> top5Terms = AtlasJanusGraphIndexClient.getTopTerms(terms); assertOrder(top5Terms, 0, 7, 8, 6, 2); }
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); }
@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'"); }
AtlasEntityType extends AtlasStructType { @Override public boolean validateValue(Object obj, String objName, List<String> messages) { boolean ret = true; if (obj != null) { if (obj instanceof AtlasEntity || obj instanceof Map) { for (AtlasEntityType superType : superTypes) { ret = superType.validateValue(obj, objName, messages) && ret; } ret = super.validateValue(obj, objName, messages) && validateRelationshipAttributes(obj, objName, messages) && ret; } else { ret = false; messages.add(objName + ": invalid value type '" + obj.getClass().getName()); } } 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; }
@Test public void testEntityTypeValidateValue() { List<String> messages = new ArrayList<>(); for (Object value : validValues) { assertTrue(entityType.validateValue(value, "testObj", messages)); assertEquals(messages.size(), 0, "value=" + value); } for (Object value : invalidValues) { assertFalse(entityType.validateValue(value, "testObj", messages)); assertTrue(messages.size() > 0, "value=" + value); messages.clear(); } }
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); }
@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"); }
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(); }
@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); }
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); }
@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); }
GraphSONUtility { static Map<String, Object> readProperties(final JsonNode node) { final Map<String, Object> map = new HashMap<>(); final Iterator<Map.Entry<String, JsonNode>> iterator = node.fields(); while (iterator.hasNext()) { final Map.Entry<String, JsonNode> entry = iterator.next(); if (!isReservedKey(entry.getKey())) { final Object o = readProperty(entry.getValue()); if (o != null) { map.put(entry.getKey(), o); } } } return map; } GraphSONUtility(final ElementProcessors elementProcessors); Map<String, Object> vertexFromJson(Graph g, final JsonNode json); Map<String, Object> edgeFromJson(Graph g, MappedElementCache cache, final JsonNode json); }
@Test public void verifyReadProperties() { JsonNode node = getCol1(); Map<String, Object> props = GraphSONUtility.readProperties(node); assertEquals(props.get("__superTypeNames").getClass(), ArrayList.class); assertEquals(props.get("Asset.name").getClass(), String.class); assertEquals(props.get("hive_column.position").getClass(), Integer.class); assertEquals(props.get("__timestamp").getClass(), Long.class); assertNotNull(props); }
GraphSONUtility { public Map<String, Object> vertexFromJson(Graph g, final JsonNode json) { final Map<String, Object> props = readProperties(json); if (props.containsKey(Constants.TYPENAME_PROPERTY_KEY)) { return null; } Map<String, Object> schemaUpdate = null; VertexFeatures vertexFeatures = g.features().vertex(); Object vertexId = getTypedValueFromJsonNode(json.get(GraphSONTokensTP2._ID)); Vertex vertex = vertexFeatures.willAllowId(vertexId) ? g.addVertex(T.id, vertexId) : g.addVertex(); props.put(Constants.VERTEX_ID_IN_IMPORT_KEY, vertexId); elementProcessors.processCollections(Constants.ENTITY_TYPE_PROPERTY_KEY, props); for (Map.Entry<String, Object> entry : props.entrySet()) { try { final Cardinality cardinality = vertexFeatures.getCardinality(entry.getKey()); final String key = entry.getKey(); final Object val = entry.getValue(); if ((cardinality == Cardinality.list || cardinality == Cardinality.set) && (val instanceof Collection)) { for (Object elem : (Collection) val) { vertex.property(key, elem); } } else { vertex.property(key, val); } } catch (IllegalArgumentException ex) { schemaUpdate = getSchemaUpdateMap(schemaUpdate); if (!schemaUpdate.containsKey("id")) { schemaUpdate.put("id", vertex.id()); } schemaUpdate.put(entry.getKey(), entry.getValue()); } } return schemaUpdate; } GraphSONUtility(final ElementProcessors elementProcessors); Map<String, Object> vertexFromJson(Graph g, final JsonNode json); Map<String, Object> edgeFromJson(Graph g, MappedElementCache cache, final JsonNode json); }
@Test public void dataNodeReadAndVertexAddedToGraph() { JsonNode entityNode = getCol1(); TinkerGraph tg = TinkerGraph.open(); GraphSONUtility gu = new GraphSONUtility(emptyRelationshipCache); Map<String, Object> map = gu.vertexFromJson(tg, entityNode); assertNull(map); assertEquals((long) tg.traversal().V().count().next(), 1L); Vertex v = tg.vertices().next(); assertTrue(v.property(VERTEX_ID_IN_IMPORT_KEY).isPresent()); } @Test public void typeNodeReadAndVertexNotAddedToGraph() { JsonNode entityNode = getDbType(); TinkerGraph tg = TinkerGraph.open(); GraphSONUtility gu = new GraphSONUtility(emptyRelationshipCache); gu.vertexFromJson(tg, entityNode); Assert.assertEquals((long) tg.traversal().V().count().next(), 0L); }
AtlasSolrQueryBuilder { public String build() throws AtlasBaseException { StringBuilder queryBuilder = new StringBuilder(); boolean isAndNeeded = false; if (queryString != null ) { if (LOG.isDebugEnabled()) { LOG.debug("Initial query string is {}.", queryString); } queryBuilder.append("+").append(queryString.trim()).append(" "); isAndNeeded = true; } if (excludeDeletedEntities) { if (isAndNeeded) { queryBuilder.append(" AND "); } dropDeletedEntities(queryBuilder); isAndNeeded = true; } if (CollectionUtils.isNotEmpty(entityTypes)) { if (isAndNeeded) { queryBuilder.append(" AND "); } buildForEntityType(queryBuilder); isAndNeeded = true; } if (criteria != null) { StringBuilder attrFilterQueryBuilder = new StringBuilder(); withCriteria(attrFilterQueryBuilder, criteria); if (attrFilterQueryBuilder.length() != 0) { if (isAndNeeded) { queryBuilder.append(" AND "); } queryBuilder.append(" ").append(attrFilterQueryBuilder.toString()); } } return queryBuilder.toString(); } AtlasSolrQueryBuilder(); AtlasSolrQueryBuilder withEntityTypes(Set<AtlasEntityType> searchForEntityTypes); AtlasSolrQueryBuilder withQueryString(String queryString); AtlasSolrQueryBuilder withCriteria(FilterCriteria criteria); AtlasSolrQueryBuilder withExcludedDeletedEntities(boolean excludeDeletedEntities); AtlasSolrQueryBuilder withIncludeSubTypes(boolean includeSubTypes); AtlasSolrQueryBuilder withCommonIndexFieldNames(Map<String, String> indexFieldNameCache); String build(); static final char CUSTOM_ATTR_SEPARATOR; static final String CUSTOM_ATTR_SEARCH_FORMAT; }
@Test public void testGenerateSolrQueryString() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters2OR.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +name_index:t10 ) OR ( +comment_index:*t10* ) )"); } @Test public void testGenerateSolrQueryString2() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters1OR.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +name_index:t10 ) )"); } @Test public void testGenerateSolrQueryString3() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters2AND.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +name_index:t10 ) AND ( +comment_index:*t10* ) )"); } @Test public void testGenerateSolrQueryString4() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters1AND.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +name_index:t10 ) )"); } @Test public void testGenerateSolrQueryString5() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters0.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( +name_index:t10 )"); } @Test public void testGenerateSolrQueryString6() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters3.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t10 AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +comment_index:*United States* ) AND ( +descrption__index:*nothing* ) AND ( +name_index:*t100* ) )"); } @Test public void testGenerateSolrQueryStringGT() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparametersGT.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t10 AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +created__index:{ 100 TO * ] ) )"); } @Test public void testGenerateSolrQueryStringGTE() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparametersGTE.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t10 AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +created__index:[ 100 TO * ] ) AND ( +started__index:[ 100 TO * ] ) )"); } @Test public void testGenerateSolrQueryStringLT() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparametersLT.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t10 AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +created__index:[ * TO100} ) )"); } @Test public void testGenerateSolrQueryStringLE() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparametersLTE.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), "+t10 AND -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +created__index:[ * TO 100 ] ) AND ( +started__index:[ * TO 100 ] ) )"); } @Test public void testGenerateSolrQueryStartsWith() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparametersStartsWith.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParameters(fileName, underTest); Assert.assertEquals(underTest.build(), " -__state_index:DELETED AND +__typeName__index:(hive_table ) AND ( ( +qualifiedName__index:testdb.t1* ) )"); } @Test public void testGenerateSolrQueryString2TypeNames() throws IOException, AtlasBaseException { final String fileName = "src/test/resources/searchparameters2Types.json"; AtlasSolrQueryBuilder underTest = new AtlasSolrQueryBuilder(); processSearchParametersForMultipleTypeNames(fileName, underTest); Assert.assertEquals(underTest.build(), "+t AND -__state_index:DELETED AND +__typeName__index:(hive_table hive_db ) "); }
AtlasEntityType extends AtlasStructType { private List<AtlasAttribute> reorderDynAttributes() { Map<AtlasAttribute, List<AtlasAttribute>> adj = createTokenAttributesMap(); return topologicalSort(adj); } 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; }
@Test public void testReorderDynAttributes() { AtlasTypeRegistry typeRegistry = new AtlasTypeRegistry(); AtlasTransientTypeRegistry ttr = null; boolean commit = false; List<AtlasEntityDef> entityDefs = new ArrayList<>(); String failureMsg = null; entityDefs.add(createTableEntityDefForTopSort()); try { ttr = typeRegistry.lockTypeRegistryForUpdate(); ttr.addTypes(entityDefs); AtlasEntityType typeTable = ttr.getEntityTypeByName(TYPE_TABLE); assertEquals(typeTable.getDynEvalAttributes().get(0).getName(), ATTR_DESCRIPTION); assertEquals(typeTable.getDynEvalAttributes().get(1).getName(), ATTR_OWNER); assertEquals(typeTable.getDynEvalAttributes().get(2).getName(), ATTR_NAME); assertEquals(typeTable.getDynEvalAttributes().get(3).getName(), ATTR_LOCATION); commit = true; } catch (AtlasBaseException excp) { failureMsg = excp.getMessage(); } finally { typeRegistry.releaseTypeRegistryForUpdate(ttr, commit); } assertNull(failureMsg, "failed to create types " + TYPE_TABLE + " and " + TYPE_COLUMN); }
ApplicationProperties extends PropertiesConfiguration { public static InputStream getFileAsInputStream(Configuration configuration, String propertyName, String defaultFileName) throws AtlasException { File fileToLoad = null; String fileName = configuration.getString(propertyName); if (fileName == null) { if (defaultFileName == null) { throw new AtlasException(propertyName + " property not set and no default value specified"); } LOG.info("{} property not set; defaulting to {}", propertyName, defaultFileName); fileName = defaultFileName; String atlasConfDir = System.getProperty(ATLAS_CONFIGURATION_DIRECTORY_PROPERTY); if (atlasConfDir != null) { fileToLoad = new File(atlasConfDir, fileName); } else { fileToLoad = new File(fileName); } } else { fileToLoad = new File(fileName); } InputStream inStr = null; if (fileToLoad.exists()) { try { LOG.info("Loading file {} from {}", fileName, fileToLoad.getPath()); inStr = new FileInputStream(fileToLoad); } catch (FileNotFoundException e) { throw new AtlasException("Error loading file " + fileName, e); } } else { inStr = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); if (inStr == null) { String msg = fileName + " not found in file system or as class loader resource"; LOG.error(msg); throw new AtlasException(msg); } LOG.info("Loaded {} as resource from {}", fileName, Thread.currentThread().getContextClassLoader().getResource(fileName).toString()); } return inStr; } private ApplicationProperties(URL url); static void forceReload(); static Configuration get(); static Configuration set(Configuration configuration); static Configuration get(String fileName); static Configuration getSubsetConfiguration(Configuration inConf, String prefix); static Properties getSubsetAsProperties(Configuration inConf, String prefix); static Class getClass(Configuration configuration, String propertyName, String defaultValue, Class assignableClass); static Class getClass(String fullyQualifiedClassName, Class assignableClass); static InputStream getFileAsInputStream(Configuration configuration, String propertyName, String defaultFileName); static final String ATLAS_CONFIGURATION_DIRECTORY_PROPERTY; static final String APPLICATION_PROPERTIES; static final String GRAPHDB_BACKEND_CONF; static final String STORAGE_BACKEND_CONF; static final String INDEX_BACKEND_CONF; static final String INDEX_MAP_NAME_CONF; static final String SOLR_WAIT_SEARCHER_CONF; static final String ENABLE_FULLTEXT_SEARCH_CONF; static final String ENABLE_FREETEXT_SEARCH_CONF; static final String ATLAS_RUN_MODE; static final String GRAPHBD_BACKEND_JANUS; static final String STORAGE_BACKEND_HBASE; static final String STORAGE_BACKEND_HBASE2; static final String INDEX_BACKEND_SOLR; static final String LDAP_TYPE; static final String LDAP_AD_BIND_PASSWORD; static final String LDAP_BIND_PASSWORD; static final String MASK_LDAP_PASSWORD; static final String DEFAULT_GRAPHDB_BACKEND; static final boolean DEFAULT_SOLR_WAIT_SEARCHER; static final boolean DEFAULT_INDEX_MAP_NAME; static final AtlasRunMode DEFAULT_ATLAS_RUN_MODE; static final String INDEX_SEARCH_MAX_RESULT_SET_SIZE; static final SimpleEntry<String, String> DB_CACHE_CONF; static final SimpleEntry<String, String> DB_CACHE_CLEAN_WAIT_CONF; static final SimpleEntry<String, String> DB_CACHE_SIZE_CONF; static final SimpleEntry<String, String> DB_TX_CACHE_SIZE_CONF; static final SimpleEntry<String, String> DB_CACHE_TX_DIRTY_SIZE_CONF; }
@Test public void testGetFileAsInputStream() throws Exception { Configuration props = ApplicationProperties.get("test.properties"); InputStream inStr = null; try { inStr = ApplicationProperties.getFileAsInputStream(props, "jaas.properties.file", null); assertNotNull(inStr); } finally { if (inStr != null) { inStr.close(); } } props.setProperty("jaas.properties.file", "src/test/resources/atlas-jaas.properties"); try { inStr = ApplicationProperties.getFileAsInputStream(props, "jaas.properties.file", null); assertNotNull(inStr); } finally { if (inStr != null) { inStr.close(); } } try { inStr = ApplicationProperties.getFileAsInputStream(props, "property.not.specified.in.config", "atlas-jaas.properties"); assertNotNull(inStr); } finally { if (inStr != null) { inStr.close(); } } try { inStr = ApplicationProperties.getFileAsInputStream(props, "property.not.specified.in.config", "src/test/resources/atlas-jaas.properties"); assertNotNull(inStr); } finally { if (inStr != null) { inStr.close(); } } String originalConfDirSetting = System.setProperty(ApplicationProperties.ATLAS_CONFIGURATION_DIRECTORY_PROPERTY, "src/test/resources"); try { inStr = ApplicationProperties.getFileAsInputStream(props, "property.not.specified.in.config", "atlas-jaas.properties"); assertNotNull(inStr); } finally { if (inStr != null) { inStr.close(); } if (originalConfDirSetting != null) { System.setProperty(ApplicationProperties.ATLAS_CONFIGURATION_DIRECTORY_PROPERTY, originalConfDirSetting); } else { System.clearProperty(ApplicationProperties.ATLAS_CONFIGURATION_DIRECTORY_PROPERTY); } } try { inStr = ApplicationProperties.getFileAsInputStream(props, "property.not.specified.in.config", null); fail("Expected " + AtlasException.class.getSimpleName() + " but none thrown"); } catch (AtlasException e) { } finally { if (inStr != null) { inStr.close(); } } props.setProperty("jaas.properties.file", "does_not_exist.txt"); try { inStr = ApplicationProperties.getFileAsInputStream(props, "jaas.properties.file", null); fail("Expected " + AtlasException.class.getSimpleName() + " but none thrown"); } catch (AtlasException e) { } finally { if (inStr != null) { inStr.close(); } } }
AtlasRelationshipType extends AtlasStructType { public static void validateAtlasRelationshipDef(AtlasRelationshipDef relationshipDef) throws AtlasBaseException { AtlasRelationshipEndDef endDef1 = relationshipDef.getEndDef1(); AtlasRelationshipEndDef endDef2 = relationshipDef.getEndDef2(); RelationshipCategory relationshipCategory = relationshipDef.getRelationshipCategory(); String name = relationshipDef.getName(); boolean isContainer1 = endDef1.getIsContainer(); boolean isContainer2 = endDef2.getIsContainer(); if ((endDef1.getCardinality() == AtlasAttributeDef.Cardinality.LIST) || (endDef2.getCardinality() == AtlasAttributeDef.Cardinality.LIST)) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_LIST_ON_END, name); } if (isContainer1 && isContainer2) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_DOUBLE_CONTAINERS, name); } if ((isContainer1 || isContainer2)) { if (relationshipCategory == RelationshipCategory.ASSOCIATION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_ASSOCIATION_AND_CONTAINER, name); } } else { if (relationshipCategory == RelationshipCategory.COMPOSITION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_NO_CONTAINER, name); } else if (relationshipCategory == RelationshipCategory.AGGREGATION) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_AGGREGATION_NO_CONTAINER, name); } } if (relationshipCategory == RelationshipCategory.COMPOSITION) { if (endDef1.getCardinality() == AtlasAttributeDef.Cardinality.SET && !endDef1.getIsContainer()) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS, name); } if ((endDef2.getCardinality() == AtlasAttributeDef.Cardinality.SET) && !endDef2.getIsContainer()) { throw new AtlasBaseException(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS, name); } } } AtlasRelationshipType(AtlasRelationshipDef relationshipDef); AtlasRelationshipType(AtlasRelationshipDef relationshipDef, AtlasTypeRegistry typeRegistry); AtlasRelationshipDef getRelationshipDef(); boolean hasLegacyAttributeEnd(); String getRelationshipLabel(); @Override boolean isValidValue(Object obj); @Override boolean areEqualValues(Object val1, Object val2, Map<String, String> guidAssignments); @Override boolean isValidValueForUpdate(Object obj); AtlasEntityType getEnd1Type(); AtlasEntityType getEnd2Type(); static void validateAtlasRelationshipDef(AtlasRelationshipDef relationshipDef); }
@Test public void testvalidateAtlasRelationshipDef() throws AtlasBaseException { AtlasRelationshipEndDef ep_single = new AtlasRelationshipEndDef("typeA", "attr1", Cardinality.SINGLE); AtlasRelationshipEndDef ep_single_container = new AtlasRelationshipEndDef("typeB", "attr2", Cardinality.SINGLE); AtlasRelationshipEndDef ep_single_container_2 = new AtlasRelationshipEndDef("typeC", "attr3", Cardinality.SINGLE, true); AtlasRelationshipEndDef ep_single_container_3 = new AtlasRelationshipEndDef("typeD", "attr4", Cardinality.SINGLE, true); AtlasRelationshipEndDef ep_SET = new AtlasRelationshipEndDef("typeD", "attr4", Cardinality.SET,false); AtlasRelationshipEndDef ep_LIST = new AtlasRelationshipEndDef("typeE", "attr5", Cardinality.LIST,true); AtlasRelationshipEndDef ep_SET_container = new AtlasRelationshipEndDef("typeF", "attr6", Cardinality.SET,true); AtlasRelationshipDef relationshipDef1 = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.ASSOCIATION, PropagateTags.ONE_TO_TWO, ep_single, ep_SET); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef1); AtlasRelationshipDef relationshipDef2 = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.COMPOSITION, PropagateTags.ONE_TO_TWO, ep_SET_container, ep_single); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef2); AtlasRelationshipDef relationshipDef3 = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.AGGREGATION, PropagateTags.ONE_TO_TWO, ep_SET_container, ep_single); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef3); try { AtlasRelationshipDef relationshipDef = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.ASSOCIATION, PropagateTags.ONE_TO_TWO, ep_single_container_2, ep_single_container); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef); fail("This call is expected to fail"); } catch (AtlasBaseException abe) { if (!abe.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_ASSOCIATION_AND_CONTAINER)) { fail("This call expected a different error"); } } try { AtlasRelationshipDef relationshipDef = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.COMPOSITION, PropagateTags.ONE_TO_TWO, ep_single, ep_single_container); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef); fail("This call is expected to fail"); } catch (AtlasBaseException abe) { if (!abe.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_NO_CONTAINER)) { fail("This call expected a different error"); } } try { AtlasRelationshipDef relationshipDef = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.AGGREGATION, PropagateTags.ONE_TO_TWO, ep_single, ep_single_container); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef); fail("This call is expected to fail"); } catch (AtlasBaseException abe) { if (!abe.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_AGGREGATION_NO_CONTAINER)) { fail("This call expected a different error"); } } try { AtlasRelationshipDef relationshipDef = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.COMPOSITION, PropagateTags.ONE_TO_TWO, ep_SET_container, ep_SET); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef); fail("This call is expected to fail"); } catch (AtlasBaseException abe) { if (!abe.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_COMPOSITION_MULTIPLE_PARENTS)) { fail("This call expected a different error"); } } try { AtlasRelationshipDef relationshipDef = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.COMPOSITION, PropagateTags.ONE_TO_TWO, ep_single, ep_LIST); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef); fail("This call is expected to fail"); } catch (AtlasBaseException abe) { if (!abe.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_LIST_ON_END)) { fail("This call expected a different error"); } } try { AtlasRelationshipDef relationshipDef = new AtlasRelationshipDef("emptyRelationshipDef", "desc 1", "version1", RelationshipCategory.COMPOSITION, PropagateTags.ONE_TO_TWO, ep_LIST, ep_single); AtlasRelationshipType.validateAtlasRelationshipDef(relationshipDef); fail("This call is expected to fail"); } catch (AtlasBaseException abe) { if (!abe.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIPDEF_LIST_ON_END)) { fail("This call expected a different error"); } } }
FixedBufferList { public List<T> toList() { return this.buffer.subList(0, this.length); } FixedBufferList(Class<T> clazz); FixedBufferList(Class<T> clazz, int incrementCapacityBy); T next(); List<T> toList(); void reset(); }
@Test public void createdBasedOnInitialSize() { Spying.resetCounters(); int incrementByFactor = 2; SpyingFixedBufferList fixedBufferList = new SpyingFixedBufferList(incrementByFactor); addElements(fixedBufferList, 0, 3); List<Spying> list = fixedBufferList.toList(); assertSpyingList(list, 3); assertEquals(Spying.callsToCtor.get(), incrementByFactor * 2); } @Test public void retrieveEmptyList() { int size = 5; SpyingFixedBufferList fixedBufferList = new SpyingFixedBufferList(size); List<Spying> list = fixedBufferList.toList(); assertEquals(list.size(), 0); addElements(fixedBufferList, 0, 3); list = fixedBufferList.toList(); assertEquals(list.size(), 3); }
NotificationEntityChangeListener implements EntityChangeListener { @VisibleForTesting public static List<Struct> getAllTraits(Referenceable entityDefinition, AtlasTypeRegistry typeRegistry) throws AtlasException { List<Struct> ret = new ArrayList<>(); for (String traitName : entityDefinition.getTraitNames()) { Struct trait = entityDefinition.getTrait(traitName); AtlasClassificationType traitType = typeRegistry.getClassificationTypeByName(traitName); Set<String> superTypeNames = traitType != null ? traitType.getAllSuperTypes() : null; ret.add(trait); if (CollectionUtils.isNotEmpty(superTypeNames)) { for (String superTypeName : superTypeNames) { Struct superTypeTrait = new Struct(superTypeName); if (MapUtils.isNotEmpty(trait.getValues())) { AtlasClassificationType superType = typeRegistry.getClassificationTypeByName(superTypeName); if (superType != null && MapUtils.isNotEmpty(superType.getAllAttributes())) { Map<String, Object> superTypeTraitAttributes = new HashMap<>(); for (Map.Entry<String, Object> attrEntry : trait.getValues().entrySet()) { String attrName = attrEntry.getKey(); if (superType.getAllAttributes().containsKey(attrName)) { superTypeTraitAttributes.put(attrName, attrEntry.getValue()); } } superTypeTrait.setValues(superTypeTraitAttributes); } } ret.add(superTypeTrait); } } } return ret; } @Inject NotificationEntityChangeListener(NotificationInterface notificationInterface, AtlasTypeRegistry typeRegistry, Configuration configuration); @Override void onEntitiesAdded(Collection<Referenceable> entities, boolean isImport); @Override void onEntitiesUpdated(Collection<Referenceable> entities, boolean isImport); @Override void onTraitsAdded(Referenceable entity, Collection<? extends Struct> traits); @Override void onTraitsDeleted(Referenceable entity, Collection<? extends Struct> traits); @Override void onTraitsUpdated(Referenceable entity, Collection<? extends Struct> traits); @Override void onEntitiesDeleted(Collection<Referenceable> entities, boolean isImport); @Override void onTermAdded(Collection<Referenceable> entities, AtlasGlossaryTerm term); @Override void onTermDeleted(Collection<Referenceable> entities, AtlasGlossaryTerm term); @VisibleForTesting static List<Struct> getAllTraits(Referenceable entityDefinition, AtlasTypeRegistry typeRegistry); }
@Test public void testGetAllTraitsSuperTraits() throws Exception { AtlasTypeRegistry typeSystem = mock(AtlasTypeRegistry.class); String traitName = "MyTrait"; Struct myTrait = new Struct(traitName); String superTraitName = "MySuperTrait"; AtlasClassificationType traitDef = mock(AtlasClassificationType.class); Set<String> superTypeNames = Collections.singleton(superTraitName); AtlasClassificationType superTraitDef = mock(AtlasClassificationType.class); Set<String> superSuperTypeNames = Collections.emptySet(); Referenceable entity = getEntity("id", myTrait); when(typeSystem.getClassificationTypeByName(traitName)).thenReturn(traitDef); when(typeSystem.getClassificationTypeByName(superTraitName)).thenReturn(superTraitDef); when(traitDef.getAllSuperTypes()).thenReturn(superTypeNames); when(superTraitDef.getAllSuperTypes()).thenReturn(superSuperTypeNames); List<Struct> allTraits = NotificationEntityChangeListener.getAllTraits(entity, typeSystem); assertEquals(2, allTraits.size()); for (Struct trait : allTraits) { String typeName = trait.getTypeName(); assertTrue(typeName.equals(traitName) || typeName.equals(superTraitName)); } }
NotificationHookConsumer implements Service, ActiveStateChangeHandler { void startInternal(Configuration configuration, ExecutorService executorService) { if (consumers == null) { consumers = new ArrayList<>(); } if (executorService != null) { executors = executorService; } if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is disabled, starting consumers inline."); startConsumers(executorService); } } @Inject NotificationHookConsumer(NotificationInterface notificationInterface, AtlasEntityStore atlasEntityStore, ServiceState serviceState, AtlasInstanceConverter instanceConverter, AtlasTypeRegistry typeRegistry, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void instanceIsActive(); @Override void instanceIsPassive(); @Override int getHandlerOrder(); static final String DUMMY_DATABASE; static final String DUMMY_TABLE; static final String VALUES_TMP_TABLE_NAME_PREFIX; static final String CONSUMER_THREADS_PROPERTY; static final String CONSUMER_RETRIES_PROPERTY; static final String CONSUMER_FAILEDCACHESIZE_PROPERTY; static final String CONSUMER_RETRY_INTERVAL; static final String CONSUMER_MIN_RETRY_INTERVAL; static final String CONSUMER_MAX_RETRY_INTERVAL; static final String CONSUMER_COMMIT_BATCH_SIZE; static final String CONSUMER_DISABLED; static final String CONSUMER_SKIP_HIVE_COLUMN_LINEAGE_HIVE_20633; static final String CONSUMER_SKIP_HIVE_COLUMN_LINEAGE_HIVE_20633_INPUTS_THRESHOLD; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_PATTERN; static final String CONSUMER_PREPROCESS_HIVE_TABLE_PRUNE_PATTERN; static final String CONSUMER_PREPROCESS_HIVE_TABLE_CACHE_SIZE; static final String CONSUMER_PREPROCESS_HIVE_DB_IGNORE_DUMMY_ENABLED; static final String CONSUMER_PREPROCESS_HIVE_DB_IGNORE_DUMMY_NAMES; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_DUMMY_ENABLED; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_DUMMY_NAMES; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_NAME_PREFIXES_ENABLED; static final String CONSUMER_PREPROCESS_HIVE_TABLE_IGNORE_NAME_PREFIXES; static final String CONSUMER_PREPROCESS_HIVE_PROCESS_UPD_NAME_WITH_QUALIFIED_NAME; static final String CONSUMER_PREPROCESS_HIVE_TYPES_REMOVE_OWNEDREF_ATTRS; static final String CONSUMER_PREPROCESS_RDBMS_TYPES_REMOVE_OWNEDREF_ATTRS; static final String CONSUMER_AUTHORIZE_USING_MESSAGE_USER; static final String CONSUMER_AUTHORIZE_AUTHN_CACHE_TTL_SECONDS; static final int SERVER_READY_WAIT_TIME_MS; }
@Test public void testConsumersStartedIfHAIsDisabled() throws Exception { List<NotificationConsumer<Object>> consumers = new ArrayList(); NotificationConsumer notificationConsumerMock = mock(NotificationConsumer.class); consumers.add(notificationConsumerMock); when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY, false)).thenReturn(false); when(configuration.getInt(NotificationHookConsumer.CONSUMER_THREADS_PROPERTY, 1)).thenReturn(1); when(notificationInterface.createConsumers(NotificationType.HOOK, 1)).thenReturn(consumers); NotificationHookConsumer notificationHookConsumer = new NotificationHookConsumer(notificationInterface, atlasEntityStore, serviceState, instanceConverter, typeRegistry, metricsUtil); notificationHookConsumer.startInternal(configuration, executorService); verify(notificationInterface).createConsumers(NotificationType.HOOK, 1); verify(executorService).submit(any(NotificationHookConsumer.HookConsumer.class)); } @Test public void testConsumersAreNotStartedIfHAIsEnabled() throws Exception { List<NotificationConsumer<Object>> consumers = new ArrayList(); NotificationConsumer notificationConsumerMock = mock(NotificationConsumer.class); consumers.add(notificationConsumerMock); when(configuration.containsKey(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getInt(NotificationHookConsumer.CONSUMER_THREADS_PROPERTY, 1)).thenReturn(1); when(notificationInterface.createConsumers(NotificationType.HOOK, 1)).thenReturn(consumers); NotificationHookConsumer notificationHookConsumer = new NotificationHookConsumer(notificationInterface, atlasEntityStore, serviceState, instanceConverter, typeRegistry, metricsUtil); notificationHookConsumer.startInternal(configuration, executorService); verifyZeroInteractions(notificationInterface); }
AdminResource { @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) public Response getStatus() { if (LOG.isDebugEnabled()) { LOG.debug("==> AdminResource.getStatus()"); } Map<String, Object> responseData = new HashMap() {{ put(AtlasClient.STATUS, serviceState.getState().toString()); }}; if(serviceState.isInstanceInMigration()) { MigrationStatus status = migrationProgressService.getStatus(); if (status != null) { responseData.put("MigrationStatus", status); } } Response response = Response.ok(AtlasJson.toV1Json(responseData)).build(); if (LOG.isDebugEnabled()) { LOG.debug("<== AdminResource.getStatus()"); } return response; } @Inject AdminResource(ServiceState serviceState, MetricsService metricsService, AtlasTypeRegistry typeRegistry, ExportService exportService, ImportService importService, SearchTracker activeSearches, MigrationProgressService migrationProgressService, AtlasServerService serverService, ExportImportAuditService exportImportAuditService, AtlasEntityStore entityStore, AtlasPatchManager patchManager, AtlasAuditService auditService, EntityAuditRepository auditRepository); @GET @Path("stack") @Produces(MediaType.TEXT_PLAIN) String getThreadDump(); @GET @Path("version") @Produces(Servlets.JSON_MEDIA_TYPE) Response getVersion(); @GET @Path("status") @Produces(Servlets.JSON_MEDIA_TYPE) Response getStatus(); @GET @Path("session") @Produces(Servlets.JSON_MEDIA_TYPE) Response getUserProfile(); @GET @Path("metrics") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasMetrics getMetrics(); @POST @Path("/export") @Consumes(Servlets.JSON_MEDIA_TYPE) Response export(AtlasExportRequest request); @POST @Path("/import") @Produces(Servlets.JSON_MEDIA_TYPE) @Consumes(MediaType.MULTIPART_FORM_DATA) AtlasImportResult importData(@DefaultValue("{}") @FormDataParam("request") String jsonData, @FormDataParam("data") InputStream inputStream); @PUT @Path("/purge") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) EntityMutationResponse purgeByIds(Set<String> guids); @POST @Path("/importfile") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasImportResult importFile(String jsonData); @GET @Path("/server/{serverName}") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) AtlasServer getCluster(@PathParam("serverName") String serverName); @GET @Path("/expimp/audit") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<ExportImportAuditEntry> getExportImportAudit(@QueryParam("serverName") String serverName, @QueryParam("userName") String userName, @QueryParam("operation") String operation, @QueryParam("startTime") String startTime, @QueryParam("endTime") String endTime, @QueryParam("limit") int limit, @QueryParam("offset") int offset); @POST @Path("/audits") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<AtlasAuditEntry> getAtlasAudits(AuditSearchParameters auditSearchParameters); @GET @Path("/audit/{auditGuid}/details") @Consumes(Servlets.JSON_MEDIA_TYPE) @Produces(Servlets.JSON_MEDIA_TYPE) List<AtlasEntityHeader> getAuditDetails(@PathParam("auditGuid") String auditGuid, @QueryParam("limit") @DefaultValue("10") int limit, @QueryParam("offset") @DefaultValue("0") int offset); @GET @Path("activeSearches") @Produces(Servlets.JSON_MEDIA_TYPE) Set<String> getActiveSearches(); @DELETE @Path("activeSearches/{id}") @Produces(Servlets.JSON_MEDIA_TYPE) boolean terminateActiveSearch(@PathParam("id") String searchId); @POST @Path("checkstate") @Produces(Servlets.JSON_MEDIA_TYPE) @Consumes(Servlets.JSON_MEDIA_TYPE) AtlasCheckStateResult checkState(AtlasCheckStateRequest request); @GET @Path("patches") @Produces(Servlets.JSON_MEDIA_TYPE) AtlasPatches getAtlasPatches(); }
@Test public void testStatusOfActiveServerIsReturned() throws IOException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.ACTIVE); AdminResource adminResource = new AdminResource(serviceState, null, null, null, null, null, null, null, null, null, null, null, null); Response response = adminResource.getStatus(); assertEquals(response.getStatus(), HttpServletResponse.SC_OK); JsonNode entity = AtlasJson.parseToV1JsonNode((String) response.getEntity()); assertEquals(entity.get("Status").asText(), "ACTIVE"); } @Test public void testResourceGetsValueFromServiceState() throws IOException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); AdminResource adminResource = new AdminResource(serviceState, null, null, null, null, null, null, null, null, null, null, null, null); Response response = adminResource.getStatus(); verify(serviceState).getState(); JsonNode entity = AtlasJson.parseToV1JsonNode((String) response.getEntity()); assertEquals(entity.get("Status").asText(), "PASSIVE"); }
ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void start() throws AtlasException { metricsUtil.onServerStart(); if (!HAConfiguration.isHAEnabled(configuration)) { metricsUtil.onServerActivation(); LOG.info("HA is not enabled, no need to start leader election service"); return; } cacheActiveStateChangeHandlers(); serverId = AtlasServerIdSelector.selectServerId(configuration); joinElection(); } @Inject ActiveInstanceElectorService(Configuration configuration, Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders, CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState, ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); }
@Test public void testLeaderElectionIsJoinedOnStart() throws Exception { when(configuration.containsKey(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getStringArray(HAConfiguration.ATLAS_SERVER_IDS)).thenReturn(new String[] {"id1"}); when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn("127.0.0.1:21000"); when(configuration.getString( HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)). thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT); LeaderLatch leaderLatch = mock(LeaderLatch.class); when(curatorFactory.leaderLatchInstance("id1", HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).thenReturn(leaderLatch); ActiveInstanceElectorService activeInstanceElectorService = new ActiveInstanceElectorService(configuration, new HashSet<ActiveStateChangeHandler>(), curatorFactory, activeInstanceState, serviceState, metricsUtil); activeInstanceElectorService.start(); verify(leaderLatch).start(); } @Test public void testListenerIsAddedForActiveInstanceCallbacks() throws Exception { when(configuration.containsKey(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY)).thenReturn(true); when(configuration.getStringArray(HAConfiguration.ATLAS_SERVER_IDS)).thenReturn(new String[] {"id1"}); when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn("127.0.0.1:21000"); when(configuration.getString( HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)). thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT); LeaderLatch leaderLatch = mock(LeaderLatch.class); when(curatorFactory.leaderLatchInstance("id1", HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)).thenReturn(leaderLatch); ActiveInstanceElectorService activeInstanceElectorService = new ActiveInstanceElectorService(configuration, new HashSet<ActiveStateChangeHandler>(), curatorFactory, activeInstanceState, serviceState, metricsUtil); activeInstanceElectorService.start(); verify(leaderLatch).addListener(activeInstanceElectorService); } @Test public void testLeaderElectionIsNotStartedIfNotInHAMode() throws AtlasException { when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY, false)).thenReturn(false); ActiveInstanceElectorService activeInstanceElectorService = new ActiveInstanceElectorService(configuration, new HashSet<ActiveStateChangeHandler>(), curatorFactory, activeInstanceState, serviceState, metricsUtil); activeInstanceElectorService.start(); verifyZeroInteractions(curatorFactory); }
AtlasClassificationType extends AtlasStructType { @Override public AtlasClassification createDefaultValue() { AtlasClassification ret = new AtlasClassification(classificationDef.getName()); populateDefaultValues(ret); return ret; } AtlasClassificationType(AtlasClassificationDef classificationDef); AtlasClassificationType(AtlasClassificationDef classificationDef, AtlasTypeRegistry typeRegistry); AtlasClassificationDef getClassificationDef(); static AtlasClassificationType getClassificationRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); String getTypeQryStr(); String getTypeAndAllSubTypesQryStr(); boolean isSuperTypeOf(AtlasClassificationType classificationType); boolean isSuperTypeOf(String classificationName); boolean isSubTypeOf(AtlasClassificationType classificationType); boolean isSubTypeOf(String classificationName); boolean hasAttribute(String attrName); Set<String> getEntityTypes(); @Override AtlasClassification createDefaultValue(); @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(AtlasClassification classification); void normalizeAttributeValuesForUpdate(AtlasClassification classification); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasClassification classification); boolean canApplyToEntityType(AtlasEntityType entityType); static boolean isValidTimeZone(final String timeZone); static final AtlasClassificationType CLASSIFICATION_ROOT; }
@Test public void testClassificationTypeDefaultValue() { AtlasClassification defValue = classificationType.createDefaultValue(); assertNotNull(defValue); assertEquals(defValue.getTypeName(), classificationType.getTypeName()); }
ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void stop() { if (!HAConfiguration.isHAEnabled(configuration)) { LOG.info("HA is not enabled, no need to stop leader election service"); return; } try { leaderLatch.close(); curatorFactory.close(); } catch (IOException e) { LOG.error("Error closing leader latch", e); } } @Inject ActiveInstanceElectorService(Configuration configuration, Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders, CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState, ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); }
@Test public void testNoActionOnStopIfHAModeIsDisabled() { when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY, false)).thenReturn(false); ActiveInstanceElectorService activeInstanceElectorService = new ActiveInstanceElectorService(configuration, new HashSet<ActiveStateChangeHandler>(), curatorFactory, activeInstanceState, serviceState, metricsUtil); activeInstanceElectorService.stop(); verifyZeroInteractions(curatorFactory); }
ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void isLeader() { LOG.warn("Server instance with server id {} is elected as leader", serverId); serviceState.becomingActive(); try { for (ActiveStateChangeHandler handler : activeStateChangeHandlers) { handler.instanceIsActive(); } activeInstanceState.update(serverId); serviceState.setActive(); metricsUtil.onServerActivation(); } catch (Exception e) { LOG.error("Got exception while activating", e); notLeader(); rejoinElection(); } } @Inject ActiveInstanceElectorService(Configuration configuration, Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders, CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState, ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); }
@Test public void testActiveStateSetOnBecomingLeader() { ActiveInstanceElectorService activeInstanceElectorService = new ActiveInstanceElectorService(configuration, new HashSet<ActiveStateChangeHandler>(), curatorFactory, activeInstanceState, serviceState, metricsUtil); activeInstanceElectorService.isLeader(); InOrder inOrder = inOrder(serviceState); inOrder.verify(serviceState).becomingActive(); inOrder.verify(serviceState).setActive(); }
ActiveInstanceElectorService implements Service, LeaderLatchListener { @Override public void notLeader() { LOG.warn("Server instance with server id {} is removed as leader", serverId); serviceState.becomingPassive(); for (int idx = activeStateChangeHandlers.size() - 1; idx >= 0; idx--) { try { activeStateChangeHandlers.get(idx).instanceIsPassive(); } catch (AtlasException e) { LOG.error("Error while reacting to passive state.", e); } } serviceState.setPassive(); } @Inject ActiveInstanceElectorService(Configuration configuration, Set<ActiveStateChangeHandler> activeStateChangeHandlerProviders, CuratorFactory curatorFactory, ActiveInstanceState activeInstanceState, ServiceState serviceState, AtlasMetricsUtil metricsUtil); @Override void start(); @Override void stop(); @Override void isLeader(); @Override void notLeader(); }
@Test public void testPassiveStateSetOnLoosingLeadership() { ActiveInstanceElectorService activeInstanceElectorService = new ActiveInstanceElectorService(configuration, new HashSet<ActiveStateChangeHandler>(), curatorFactory, activeInstanceState, serviceState, metricsUtil); activeInstanceElectorService.notLeader(); InOrder inOrder = inOrder(serviceState); inOrder.verify(serviceState).becomingPassive(); inOrder.verify(serviceState).setPassive(); }
AtlasClassificationType extends AtlasStructType { public boolean canApplyToEntityType(AtlasEntityType entityType) { return CollectionUtils.isEmpty(this.entityTypes) || this.entityTypes.contains(entityType.getTypeName()); } AtlasClassificationType(AtlasClassificationDef classificationDef); AtlasClassificationType(AtlasClassificationDef classificationDef, AtlasTypeRegistry typeRegistry); AtlasClassificationDef getClassificationDef(); static AtlasClassificationType getClassificationRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); String getTypeQryStr(); String getTypeAndAllSubTypesQryStr(); boolean isSuperTypeOf(AtlasClassificationType classificationType); boolean isSuperTypeOf(String classificationName); boolean isSubTypeOf(AtlasClassificationType classificationType); boolean isSubTypeOf(String classificationName); boolean hasAttribute(String attrName); Set<String> getEntityTypes(); @Override AtlasClassification createDefaultValue(); @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(AtlasClassification classification); void normalizeAttributeValuesForUpdate(AtlasClassification classification); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasClassification classification); boolean canApplyToEntityType(AtlasEntityType entityType); static boolean isValidTimeZone(final String timeZone); static final AtlasClassificationType CLASSIFICATION_ROOT; }
@Test public void testcanApplyToEntityType() throws AtlasBaseException { AtlasEntityDef entityDefA = new AtlasEntityDef("EntityA"); AtlasEntityDef entityDefB = new AtlasEntityDef("EntityB"); AtlasEntityDef entityDefC = new AtlasEntityDef("EntityC", null, null, null, new HashSet<>(Arrays.asList(entityDefA.getName()))); AtlasEntityDef entityDefD = new AtlasEntityDef("EntityD", null, null, null, new HashSet<>(Arrays.asList(entityDefC.getName()))); AtlasEntityDef entityDefE = new AtlasEntityDef("EntityE"); AtlasEntityDef entityDefF = new AtlasEntityDef("EntityF", null, null, null, new HashSet<>(Arrays.asList(entityDefB.getName(),entityDefE.getName()))); AtlasClassificationDef classifyDef1 = new AtlasClassificationDef("Classify1", null, null, null, null, new HashSet<>(Arrays.asList(entityDefA.getName())), null); AtlasClassificationDef classifyDef2 = new AtlasClassificationDef("Classify2"); AtlasClassificationDef classifyDef3 = new AtlasClassificationDef("Classify3", null, null, null, new HashSet<>(Arrays.asList(classifyDef1.getName())), null, null); AtlasClassificationDef classifyDef4 = new AtlasClassificationDef("Classify4", null, null, null, new HashSet<>(Arrays.asList(classifyDef1.getName())), new HashSet<>(Arrays.asList(entityDefD.getName())), null); AtlasClassificationDef classifyDef5 = new AtlasClassificationDef("Classify5", null, null, null, null, new HashSet<>(Arrays.asList(entityDefA.getName(),entityDefC.getName())), null); AtlasClassificationDef classifyDef6 = new AtlasClassificationDef("Classify6", null, null, null, null, new HashSet<>(Arrays.asList(entityDefB.getName())), null); AtlasClassificationDef classifyDef7 = new AtlasClassificationDef("Classify7", null, null, null, new HashSet<>(Arrays.asList(classifyDef1.getName(),classifyDef6.getName())),null, null); AtlasClassificationDef classifyDef8 = new AtlasClassificationDef("Classify8", null, null, null, new HashSet<>(Arrays.asList(classifyDef6.getName())),new HashSet<>(Arrays.asList(entityDefA.getName())), null); AtlasClassificationDef classifyDef9 = new AtlasClassificationDef("Classify9", null, null, null, null, new HashSet<>(Arrays.asList(entityDefE.getName())), null); AtlasClassificationDef classifyDef10 = new AtlasClassificationDef("Classify10", null, null, null, null, new HashSet<>(Arrays.asList(entityDefC.getName(),entityDefA.getName())), null); AtlasTypeRegistry registry = ModelTestUtil.getTypesRegistry(); AtlasTransientTypeRegistry ttr = registry.lockTypeRegistryForUpdate(); ttr.addType(entityDefA); ttr.addType(entityDefB); ttr.addType(entityDefC); ttr.addType(entityDefD); ttr.addType(entityDefE); ttr.addType(entityDefF); ttr.addType(classifyDef1); ttr.addType(classifyDef2); ttr.addType(classifyDef3); ttr.addType(classifyDef4); ttr.addType(classifyDef5); ttr.addType(classifyDef6); ttr.addType(classifyDef9); ttr.addType(classifyDef10); registry.releaseTypeRegistryForUpdate(ttr, true); ttr = registry.lockTypeRegistryForUpdate(); try { ttr.addType(classifyDef7); fail("Fail disjoined parent case"); } catch (AtlasBaseException ae) { registry.releaseTypeRegistryForUpdate(ttr, false); } ttr = registry.lockTypeRegistryForUpdate(); try { ttr.addType(classifyDef8); fail("Fail trying to add an entity type that is not in the parent"); } catch (AtlasBaseException ae) { registry.releaseTypeRegistryForUpdate(ttr, false); } AtlasEntityType entityTypeA = registry.getEntityTypeByName(entityDefA.getName()); AtlasEntityType entityTypeB = registry.getEntityTypeByName(entityDefB.getName()); AtlasEntityType entityTypeC = registry.getEntityTypeByName(entityDefC.getName()); AtlasEntityType entityTypeD = registry.getEntityTypeByName(entityDefD.getName()); AtlasEntityType entityTypeE = registry.getEntityTypeByName(entityDefE.getName()); AtlasEntityType entityTypeF = registry.getEntityTypeByName(entityDefF.getName()); AtlasClassificationType classifyType1 = registry.getClassificationTypeByName(classifyDef1.getName()); AtlasClassificationType classifyType2 = registry.getClassificationTypeByName(classifyDef2.getName()); AtlasClassificationType classifyType3 = registry.getClassificationTypeByName(classifyDef3.getName()); AtlasClassificationType classifyType4 = registry.getClassificationTypeByName(classifyDef4.getName()); AtlasClassificationType classifyType5 = registry.getClassificationTypeByName(classifyDef5.getName()); AtlasClassificationType classifyType6 = registry.getClassificationTypeByName(classifyDef6.getName()); AtlasClassificationType classifyType9 = registry.getClassificationTypeByName(classifyDef9.getName()); AtlasClassificationType classifyType10 = registry.getClassificationTypeByName(classifyDef10.getName()); assertTrue(classifyType1.canApplyToEntityType(entityTypeA)); assertFalse(classifyType1.canApplyToEntityType(entityTypeB)); assertTrue(classifyType1.canApplyToEntityType(entityTypeC)); assertTrue(classifyType1.canApplyToEntityType(entityTypeD)); assertTrue(classifyType2.canApplyToEntityType(entityTypeA)); assertTrue(classifyType2.canApplyToEntityType(entityTypeB)); assertTrue(classifyType2.canApplyToEntityType(entityTypeC)); assertTrue(classifyType2.canApplyToEntityType(entityTypeD)); assertTrue(classifyType3.canApplyToEntityType(entityTypeA)); assertFalse(classifyType3.canApplyToEntityType(entityTypeB)); assertTrue(classifyType3.canApplyToEntityType(entityTypeC)); assertTrue(classifyType3.canApplyToEntityType(entityTypeD)); assertFalse(classifyType4.canApplyToEntityType(entityTypeA)); assertFalse(classifyType4.canApplyToEntityType(entityTypeB)); assertFalse(classifyType4.canApplyToEntityType(entityTypeC)); assertTrue(classifyType4.canApplyToEntityType(entityTypeD)); assertTrue(classifyType6.canApplyToEntityType(entityTypeF)); assertTrue(classifyType9.canApplyToEntityType(entityTypeF)); assertTrue(classifyType5.canApplyToEntityType(entityTypeA)); assertTrue(classifyType5.canApplyToEntityType(entityTypeC)); assertTrue(classifyType10.canApplyToEntityType(entityTypeA)); assertTrue(classifyType10.canApplyToEntityType(entityTypeC)); }
ServiceState { public ServiceStateValue getState() { return state; } ServiceState(); ServiceState(Configuration configuration); ServiceStateValue getState(); void becomingActive(); void setActive(); void becomingPassive(); void setPassive(); boolean isInstanceInTransition(); void setMigration(); boolean isInstanceInMigration(); }
@Test public void testShouldBeActiveIfHAIsDisabled() { when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY, false)).thenReturn(false); ServiceState serviceState = new ServiceState(configuration); assertEquals(ServiceState.ServiceStateValue.ACTIVE, serviceState.getState()); }
ServiceState { public void becomingPassive() { LOG.warn("Instance becoming passive from {}", state); setState(ServiceStateValue.BECOMING_PASSIVE); } ServiceState(); ServiceState(Configuration configuration); ServiceStateValue getState(); void becomingActive(); void setActive(); void becomingPassive(); void setPassive(); boolean isInstanceInTransition(); void setMigration(); boolean isInstanceInMigration(); }
@Test(expectedExceptions = IllegalStateException.class) public void testShouldDisallowTransitionIfHAIsDisabled() { when(configuration.getBoolean(HAConfiguration.ATLAS_SERVER_HA_ENABLED_KEY, false)).thenReturn(false); ServiceState serviceState = new ServiceState(configuration); serviceState.becomingPassive(); fail("Should not allow transition"); }
ActiveInstanceState { public void update(String serverId) throws AtlasBaseException { try { CuratorFramework client = curatorFactory.clientInstance(); HAConfiguration.ZookeeperProperties zookeeperProperties = HAConfiguration.getZookeeperProperties(configuration); String atlasServerAddress = HAConfiguration.getBoundAddressForId(configuration, serverId); List<ACL> acls = new ArrayList<ACL>(); ACL parsedACL = AtlasZookeeperSecurityProperties.parseAcl(zookeeperProperties.getAcl(), ZooDefs.Ids.OPEN_ACL_UNSAFE.get(0)); acls.add(parsedACL); if (StringUtils.isNotEmpty(zookeeperProperties.getAcl())) { ACL worldReadPermissionACL = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); acls.add(worldReadPermissionACL); } Stat serverInfo = client.checkExists().forPath(getZnodePath(zookeeperProperties)); if (serverInfo == null) { client.create(). withMode(CreateMode.EPHEMERAL). withACL(acls). forPath(getZnodePath(zookeeperProperties)); } client.setData().forPath(getZnodePath(zookeeperProperties), atlasServerAddress.getBytes(Charset.forName("UTF-8"))); } catch (Exception e) { throw new AtlasBaseException(AtlasErrorCode.CURATOR_FRAMEWORK_UPDATE, e, "forPath: getZnodePath"); } } @Inject ActiveInstanceState(CuratorFactory curatorFactory); ActiveInstanceState(Configuration configuration, CuratorFactory curatorFactory); void update(String serverId); String getActiveServerAddress(); static final String APACHE_ATLAS_ACTIVE_SERVER_INFO; }
@Test public void testSharedPathIsCreatedIfNotExists() throws Exception { when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn(HOST_PORT); when(configuration.getString( HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)). thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT); when(curatorFactory.clientInstance()).thenReturn(curatorFramework); ExistsBuilder existsBuilder = mock(ExistsBuilder.class); when(curatorFramework.checkExists()).thenReturn(existsBuilder); when(existsBuilder.forPath(getPath())).thenReturn(null); CreateBuilder createBuilder = mock(CreateBuilder.class); when(curatorFramework.create()).thenReturn(createBuilder); when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(createBuilder); when(createBuilder.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)).thenReturn(createBuilder); SetDataBuilder setDataBuilder = mock(SetDataBuilder.class); when(curatorFramework.setData()).thenReturn(setDataBuilder); ActiveInstanceState activeInstanceState = new ActiveInstanceState(configuration, curatorFactory); activeInstanceState.update("id1"); verify(createBuilder).forPath(getPath()); } @Test public void testSharedPathIsCreatedWithRightACLIfNotExists() throws Exception { when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn(HOST_PORT); when(configuration.getString(HAConfiguration.HA_ZOOKEEPER_ACL)).thenReturn("sasl:[email protected]"); when(configuration.getString( HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)). thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT); when(curatorFactory.clientInstance()).thenReturn(curatorFramework); ExistsBuilder existsBuilder = mock(ExistsBuilder.class); when(curatorFramework.checkExists()).thenReturn(existsBuilder); when(existsBuilder.forPath(getPath())).thenReturn(null); CreateBuilder createBuilder = mock(CreateBuilder.class); when(curatorFramework.create()).thenReturn(createBuilder); when(createBuilder.withMode(CreateMode.EPHEMERAL)).thenReturn(createBuilder); ACL expectedAcl = new ACL(ZooDefs.Perms.ALL, new Id("sasl", "[email protected]")); ACL expectedAcl1 = new ACL(ZooDefs.Perms.READ, new Id("world", "anyone")); when(createBuilder. withACL(Arrays.asList(new ACL[]{expectedAcl,expectedAcl1}))).thenReturn(createBuilder); SetDataBuilder setDataBuilder = mock(SetDataBuilder.class); when(curatorFramework.setData()).thenReturn(setDataBuilder); ActiveInstanceState activeInstanceState = new ActiveInstanceState(configuration, curatorFactory); activeInstanceState.update("id1"); verify(createBuilder).forPath(getPath()); } @Test public void testDataIsUpdatedWithAtlasServerAddress() throws Exception { when(configuration.getString(HAConfiguration.ATLAS_SERVER_ADDRESS_PREFIX +"id1")).thenReturn(HOST_PORT); when(configuration.getString( HAConfiguration.ATLAS_SERVER_HA_ZK_ROOT_KEY, HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT)). thenReturn(HAConfiguration.ATLAS_SERVER_ZK_ROOT_DEFAULT); when(curatorFactory.clientInstance()).thenReturn(curatorFramework); ExistsBuilder existsBuilder = mock(ExistsBuilder.class); when(curatorFramework.checkExists()).thenReturn(existsBuilder); when(existsBuilder.forPath(getPath())).thenReturn(new Stat()); SetDataBuilder setDataBuilder = mock(SetDataBuilder.class); when(curatorFramework.setData()).thenReturn(setDataBuilder); ActiveInstanceState activeInstanceState = new ActiveInstanceState(configuration, curatorFactory); activeInstanceState.update("id1"); verify(setDataBuilder).forPath( getPath(), SERVER_ADDRESS.getBytes(Charset.forName("UTF-8"))); }
ActiveServerFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (isFilteredURI(servletRequest)) { LOG.debug("Is a filtered URI: {}. Passing request downstream.", ((HttpServletRequest)servletRequest).getRequestURI()); filterChain.doFilter(servletRequest, servletResponse); } else if (isInstanceActive()) { LOG.debug("Active. Passing request downstream"); filterChain.doFilter(servletRequest, servletResponse); } else if (serviceState.isInstanceInTransition()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in transition. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else if (serviceState.isInstanceInMigration()) { if (isRootURI(servletRequest)) { handleMigrationRedirect(servletRequest, servletResponse); } HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; LOG.error("Instance in migration. Service may not be ready to return a result"); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String activeServerAddress = activeInstanceState.getActiveServerAddress(); if (activeServerAddress == null) { LOG.error("Could not retrieve active server address as it is null. Cannot redirect request {}", ((HttpServletRequest)servletRequest).getRequestURI()); httpServletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { handleRedirect((HttpServletRequest) servletRequest, httpServletResponse, activeServerAddress); } } } @Inject ActiveServerFilter(ActiveInstanceState activeInstanceState, ServiceState serviceState); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain); @Override void destroy(); }
@Test public void testShouldPassThroughRequestsIfActive() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.ACTIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(filterChain).doFilter(servletRequest, servletResponse); } @Test public void testShouldFailIfCannotRetrieveActiveServerAddress() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(null); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } @Test public void testShouldRedirectRequestToActiveServerAddress() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getRequestURI()).thenReturn("types"); when(servletRequest.getMethod()).thenReturn(HttpMethod.GET); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).sendRedirect(ACTIVE_SERVER_ADDRESS + "types"); } @Test public void adminImportRequestsToPassiveServerShouldToActiveServerAddress() throws IOException, ServletException { String importExportUrls[] = {"api/admin/export", "api/admin/import", "api/admin/importfile"}; for (String partialUrl : importExportUrls) { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn(partialUrl); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getRequestURI()).thenReturn(partialUrl); when(servletRequest.getMethod()).thenReturn(HttpMethod.GET); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).sendRedirect(ACTIVE_SERVER_ADDRESS + partialUrl); } } @Test public void testRedirectedRequestShouldContainQueryParameters() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getMethod()).thenReturn(HttpMethod.GET); when(servletRequest.getRequestURI()).thenReturn("types"); when(servletRequest.getQueryString()).thenReturn("query=TRAIT"); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).sendRedirect(ACTIVE_SERVER_ADDRESS + "types?query=TRAIT"); } @Test public void testRedirectedRequestShouldContainEncodeQueryParameters() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getMethod()).thenReturn(HttpMethod.GET); when(servletRequest.getRequestURI()).thenReturn("api/atlas/v2/search/basic"); when(servletRequest.getQueryString()).thenReturn("limit=25&excludeDeletedEntities=true&spaceParam=firstpart secondpart&_=1500969656054&listParam=value1,value2"); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).sendRedirect(ACTIVE_SERVER_ADDRESS + "api/atlas/v2/search/basic?limit=25&excludeDeletedEntities=true&spaceParam=firstpart%20secondpart&_=1500969656054&listParam=value1,value2"); } @Test public void testShouldRedirectPOSTRequest() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getMethod()).thenReturn(HttpMethod.POST); when(servletRequest.getRequestURI()).thenReturn("types"); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).setHeader("Location", ACTIVE_SERVER_ADDRESS + "types"); verify(servletResponse).setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); } @Test public void testShouldRedirectPUTRequest() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getMethod()).thenReturn(HttpMethod.PUT); when(servletRequest.getRequestURI()).thenReturn("types"); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).setHeader("Location", ACTIVE_SERVER_ADDRESS + "types"); verify(servletResponse).setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); } @Test public void testShouldRedirectDELETERequest() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); when(activeInstanceState.getActiveServerAddress()).thenReturn(ACTIVE_SERVER_ADDRESS); when(servletRequest.getMethod()).thenReturn(HttpMethod.DELETE); when(servletRequest.getRequestURI()). thenReturn("api/atlas/entities/6ebb039f-eaa5-4b9c-ae44-799c7910545d/traits/test_tag_ha3"); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).setHeader("Location", ACTIVE_SERVER_ADDRESS + "api/atlas/entities/6ebb039f-eaa5-4b9c-ae44-799c7910545d/traits/test_tag_ha3"); verify(servletResponse).setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); } @Test public void testShouldReturnServiceUnavailableIfStateBecomingActive() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.BECOMING_ACTIVE); when(servletRequest.getRequestURI()).thenReturn("api/atlas/types"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(servletResponse).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } @Test public void testShouldNotRedirectAdminAPIs() throws IOException, ServletException { when(serviceState.getState()).thenReturn(ServiceState.ServiceStateValue.PASSIVE); when(servletRequest.getMethod()).thenReturn(HttpMethod.GET); when(servletRequest.getRequestURI()). thenReturn("api/atlas/admin/asmasn"); ActiveServerFilter activeServerFilter = new ActiveServerFilter(activeInstanceState, serviceState); activeServerFilter.doFilter(servletRequest, servletResponse, filterChain); verify(filterChain).doFilter(servletRequest, servletResponse); verifyZeroInteractions(activeInstanceState); }
AtlasClassificationType extends AtlasStructType { @Override public boolean isValidValue(Object obj) { if (obj != null) { for (AtlasClassificationType superType : superTypes) { if (!superType.isValidValue(obj)) { return false; } } if (!validateTimeBoundaries(obj, null)) { return false; } return super.isValidValue(obj); } return true; } AtlasClassificationType(AtlasClassificationDef classificationDef); AtlasClassificationType(AtlasClassificationDef classificationDef, AtlasTypeRegistry typeRegistry); AtlasClassificationDef getClassificationDef(); static AtlasClassificationType getClassificationRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); String getTypeQryStr(); String getTypeAndAllSubTypesQryStr(); boolean isSuperTypeOf(AtlasClassificationType classificationType); boolean isSuperTypeOf(String classificationName); boolean isSubTypeOf(AtlasClassificationType classificationType); boolean isSubTypeOf(String classificationName); boolean hasAttribute(String attrName); Set<String> getEntityTypes(); @Override AtlasClassification createDefaultValue(); @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(AtlasClassification classification); void normalizeAttributeValuesForUpdate(AtlasClassification classification); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasClassification classification); boolean canApplyToEntityType(AtlasEntityType entityType); static boolean isValidTimeZone(final String timeZone); static final AtlasClassificationType CLASSIFICATION_ROOT; }
@Test public void testClassificationTypeIsValidValue() { for (Object value : validValues) { assertTrue(classificationType.isValidValue(value), "value=" + value); } for (Object value : invalidValues) { assertFalse(classificationType.isValidValue(value), "value=" + value); } }
AtlasCSRFPreventionFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse); HeadersUtil.setHeaderMapAttributes(responseWrapper, HeadersUtil.X_FRAME_OPTIONS_KEY); if (isCSRF_ENABLED){ handleHttpInteraction(new ServletFilterHttpInteraction(httpRequest, httpResponse, chain)); }else{ chain.doFilter(request, response); } } AtlasCSRFPreventionFilter(); void init(FilterConfig filterConfig); void handleHttpInteraction(HttpInteraction httpInteraction); void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); void destroy(); static final boolean isCSRF_ENABLED; static final String BROWSER_USER_AGENT_PARAM; static final String BROWSER_USER_AGENTS_DEFAULT; static final String CUSTOM_METHODS_TO_IGNORE_PARAM; static final String METHODS_TO_IGNORE_DEFAULT; static final String CUSTOM_HEADER_PARAM; static final String HEADER_DEFAULT; static final String HEADER_USER_AGENT; }
@Test public void testNoHeaderDefaultConfig_badRequest() throws ServletException, IOException { HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); Mockito.when(mockReq.getHeader(AtlasCSRFPreventionFilter.HEADER_DEFAULT)).thenReturn(null); Mockito.when(mockReq.getHeader(AtlasCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); PrintWriter mockWriter = Mockito.mock(PrintWriter.class); Mockito.when(mockRes.getWriter()).thenReturn(mockWriter); FilterChain mockChain = Mockito.mock(FilterChain.class); AtlasCSRFPreventionFilter filter = new AtlasCSRFPreventionFilter(); filter.doFilter(mockReq, mockRes, mockChain); verify(mockRes, atLeastOnce()).setStatus(HttpServletResponse.SC_BAD_REQUEST); Mockito.verifyZeroInteractions(mockChain); } @Test public void testHeaderPresentDefaultConfig_goodRequest() throws ServletException, IOException { HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); Mockito.when(mockReq.getHeader(AtlasCSRFPreventionFilter.HEADER_DEFAULT)).thenReturn("valueUnimportant"); Mockito.when(mockReq.getHeader(AtlasCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); FilterChain mockChain = Mockito.mock(FilterChain.class); AtlasCSRFPreventionFilter filter = new AtlasCSRFPreventionFilter(); filter.doFilter(mockReq, mockRes, mockChain); Mockito.verify(mockChain).doFilter(mockReq, mockRes); } @Test public void testHeaderPresentCustomHeaderConfig_goodRequest() throws ServletException, IOException { HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); Mockito.when(mockReq.getHeader(X_CUSTOM_HEADER)).thenReturn("valueUnimportant"); HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); FilterChain mockChain = Mockito.mock(FilterChain.class); AtlasCSRFPreventionFilter filter = new AtlasCSRFPreventionFilter(); filter.doFilter(mockReq, mockRes, mockChain); Mockito.verify(mockChain).doFilter(mockReq, mockRes); } @Test public void testMissingHeaderWithCustomHeaderConfig_badRequest() throws ServletException, IOException { HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); Mockito.when(mockReq.getHeader(X_CUSTOM_HEADER)).thenReturn(null); Mockito.when(mockReq.getHeader(AtlasCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); PrintWriter mockWriter = Mockito.mock(PrintWriter.class); Mockito.when(mockRes.getWriter()).thenReturn(mockWriter); FilterChain mockChain = Mockito.mock(FilterChain.class); AtlasCSRFPreventionFilter filter = new AtlasCSRFPreventionFilter(); filter.doFilter(mockReq, mockRes, mockChain); Mockito.verifyZeroInteractions(mockChain); } @Test public void testMissingHeaderIgnoreGETMethodConfig_goodRequest() throws ServletException, IOException { HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); Mockito.when(mockReq.getHeader(AtlasCSRFPreventionFilter.HEADER_DEFAULT)).thenReturn(null); Mockito.when(mockReq.getMethod()).thenReturn("GET"); Mockito.when(mockReq.getHeader(AtlasCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); FilterChain mockChain = Mockito.mock(FilterChain.class); AtlasCSRFPreventionFilter filter = new AtlasCSRFPreventionFilter(); filter.doFilter(mockReq, mockRes, mockChain); Mockito.verify(mockChain).doFilter(mockReq, mockRes); } @Test public void testMissingHeaderMultipleIgnoreMethodsConfig_badRequest() throws ServletException, IOException { HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); Mockito.when(mockReq.getHeader(AtlasCSRFPreventionFilter.HEADER_DEFAULT)) .thenReturn(null); Mockito.when(mockReq.getMethod()).thenReturn("PUT"); Mockito.when(mockReq.getHeader(AtlasCSRFPreventionFilter.HEADER_USER_AGENT)).thenReturn(userAgent); HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class); PrintWriter mockWriter = Mockito.mock(PrintWriter.class); Mockito.when(mockRes.getWriter()).thenReturn(mockWriter); FilterChain mockChain = Mockito.mock(FilterChain.class); AtlasCSRFPreventionFilter filter = new AtlasCSRFPreventionFilter(); filter.doFilter(mockReq, mockRes, mockChain); Mockito.verifyZeroInteractions(mockChain); }
AtlasClassificationType extends AtlasStructType { @Override public Object getNormalizedValue(Object obj) { Object ret = null; if (obj != null) { if (isValidValue(obj)) { if (obj instanceof AtlasClassification) { normalizeAttributeValues((AtlasClassification) obj); ret = obj; } else if (obj instanceof Map) { normalizeAttributeValues((Map) obj); ret = obj; } } } return ret; } AtlasClassificationType(AtlasClassificationDef classificationDef); AtlasClassificationType(AtlasClassificationDef classificationDef, AtlasTypeRegistry typeRegistry); AtlasClassificationDef getClassificationDef(); static AtlasClassificationType getClassificationRoot(); @Override AtlasAttribute getSystemAttribute(String attributeName); Set<String> getSuperTypes(); Set<String> getAllSuperTypes(); Set<String> getSubTypes(); Set<String> getAllSubTypes(); Set<String> getTypeAndAllSubTypes(); Set<String> getTypeAndAllSuperTypes(); String getTypeQryStr(); String getTypeAndAllSubTypesQryStr(); boolean isSuperTypeOf(AtlasClassificationType classificationType); boolean isSuperTypeOf(String classificationName); boolean isSubTypeOf(AtlasClassificationType classificationType); boolean isSubTypeOf(String classificationName); boolean hasAttribute(String attrName); Set<String> getEntityTypes(); @Override AtlasClassification createDefaultValue(); @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(AtlasClassification classification); void normalizeAttributeValuesForUpdate(AtlasClassification classification); @Override void normalizeAttributeValues(Map<String, Object> obj); void normalizeAttributeValuesForUpdate(Map<String, Object> obj); void populateDefaultValues(AtlasClassification classification); boolean canApplyToEntityType(AtlasEntityType entityType); static boolean isValidTimeZone(final String timeZone); static final AtlasClassificationType CLASSIFICATION_ROOT; }
@Test public void testClassificationTypeGetNormalizedValue() { assertNull(classificationType.getNormalizedValue(null), "value=" + null); for (Object value : validValues) { if (value == null) { continue; } Object normalizedValue = classificationType.getNormalizedValue(value); assertNotNull(normalizedValue, "value=" + value); } for (Object value : invalidValues) { assertNull(classificationType.getNormalizedValue(value), "value=" + value); } }
AuditFilter implements Filter { boolean isOperationExcludedFromAudit(String requestHttpMethod, String requestOperation, Configuration config) { try { return AtlasRepositoryConfiguration.isExcludedFromAudit(config, requestHttpMethod, requestOperation); } catch (AtlasException e) { return false; } } @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain); static void audit(AuditLog auditLog); @Override void destroy(); }
@Test public void testVerifyExcludedOperations() { AtlasRepositoryConfiguration.resetExcludedOperations(); when(configuration.getStringArray(AtlasRepositoryConfiguration.AUDIT_EXCLUDED_OPERATIONS)).thenReturn(new String[]{"GET:Version", "GET:Ping"}); AuditFilter auditFilter = new AuditFilter(); assertTrue(auditFilter.isOperationExcludedFromAudit("GET", "Version", configuration)); assertTrue(auditFilter.isOperationExcludedFromAudit("get", "Version", configuration)); assertTrue(auditFilter.isOperationExcludedFromAudit("GET", "Ping", configuration)); assertFalse(auditFilter.isOperationExcludedFromAudit("GET", "Types", configuration)); } @Test public void testVerifyNotExcludedOperations() { AtlasRepositoryConfiguration.resetExcludedOperations(); when(configuration.getStringArray(AtlasRepositoryConfiguration.AUDIT_EXCLUDED_OPERATIONS)).thenReturn(new String[]{"Version", "Ping"}); AuditFilter auditFilter = new AuditFilter(); assertFalse(auditFilter.isOperationExcludedFromAudit("GET", "Version", configuration)); assertFalse(auditFilter.isOperationExcludedFromAudit("GET", "Ping", configuration)); assertFalse(auditFilter.isOperationExcludedFromAudit("GET", "Types", configuration)); } @Test public void testNullConfig() { AtlasRepositoryConfiguration.resetExcludedOperations(); AuditFilter auditFilter = new AuditFilter(); assertFalse(auditFilter.isOperationExcludedFromAudit("GET", "Version", null)); }