Commit 75415862 by apoorvnaik Committed by Madhan Neethiraj

ATLAS-2534: Atlas Glossary - REST API

Change-Id: I47210446be9e38c274bae0ee4a688187ba6e4fd0 Signed-off-by: 's avatarMadhan Neethiraj <madhan@apache.org>
parent 6812a7d5
{
"enumDefs": [
{
"name": "__AtlasGlossaryTermRelationshipStatus",
"description": "TermRelationshipStatus defines how reliable the relationship is between two glossary terms",
"typeVersion": "1.0",
"elementDefs": [
{
"ordinal": 0,
"value": "DRAFT",
"description": "DRAFT means the relationship is under development."
},
{
"ordinal": 1,
"value": "ACTIVE",
"description": "ACTIVE means the relationship is validated and in use."
},
{
"ordinal": 2,
"value": "DEPRECATED",
"description": "DEPRECATED means the the relationship is being phased out."
},
{
"ordinal": 3,
"value": "OBSOLETE",
"description": "OBSOLETE means that the relationship should not be used anymore."
},
{
"ordinal": 99,
"value": "OTHER",
"description": "OTHER means that there is another status."
}
]
},
{
"name": "__AtlasGlossaryTermAssignmentStatus",
"description": "TermAssignmentStatus defines how much the semantic assignment should be trusted.",
"typeVersion": "1.0",
"elementDefs": [
{
"value": "DISCOVERED",
"ordinal": 0,
"description": "DISCOVERED means that the semantic assignment was added by a discovery engine."
},
{
"value": "PROPOSED",
"ordinal": 1,
"description": "PROPOSED means that the semantic assignment was proposed by person - they may be a subject matter expert, or consumer of the Referenceable asset"
},
{
"value": "IMPORTED",
"ordinal": 2,
"description": "IMPORTED means that the semantic assignment has been imported from outside of the open metadata cluster"
},
{
"value": "VALIDATED",
"ordinal": 3,
"description": "VALIDATED means that the semantic assignment has been reviewed and is highly trusted."
},
{
"value": "DEPRECATED",
"ordinal": 4,
"description": "DEPRECATED means that the semantic assignment is being phased out. There may be another semantic assignment to the Referenceable that will ultimately replace this one."
},
{
"value": "OBSOLETE",
"ordinal": 5,
"description": "OBSOLETE means that the semantic assignment is no longer in use,"
},
{
"value": "OTHER",
"ordinal": 6,
"description": "OTHER means that the semantic assignment value does not match any of the other Term Assignment Status values"
}
]
}
],
"structDefs": [],
"classificationDefs": [],
"entityDefs": [
{
"name": "__AtlasGlossary",
"superTypes": [
"__internal"
],
"typeVersion": "1.0",
"attributeDefs": [
{
"name": "qualifiedName",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": false,
"isUnique": true
},
{
"name": "displayName",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": false,
"isUnique": false
},
{
"name": "shortDescription",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": false,
"isOptional": true,
"isUnique": false
},
{
"name": "longDescription",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": false,
"isOptional": true,
"isUnique": false
},
{
"name": "language",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": false,
"isOptional": true,
"isUnique": false
},
{
"name": "usage",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": false,
"isOptional": true,
"isUnique": false
}
]
},
{
"name": "__AtlasGlossaryTerm",
"superTypes": [
"__internal"
],
"typeVersion": "1.0",
"attributeDefs": [
{
"name": "qualifiedName",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": false,
"isUnique": true
},
{
"name": "displayName",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": false,
"isUnique": false
},
{
"name": "shortDescription",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": false,
"isOptional": true,
"isUnique": false
},
{
"name": "longDescription",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": false,
"isOptional": true,
"isUnique": false
},
{
"name": "examples",
"typeName": "array<string>",
"cardinality": "SINGLE",
"isIndexable": false,
"isOptional": true,
"isUnique": false
},
{
"name": "abbreviation",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": false,
"isOptional": true,
"isUnique": false
},
{
"name": "usage",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": false,
"isOptional": true,
"isUnique": false
}
]
},
{
"name": "__AtlasGlossaryCategory",
"superTypes": [
"__internal"
],
"typeVersion": "1.0",
"attributeDefs": [
{
"name": "qualifiedName",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": false,
"isUnique": true
},
{
"name": "displayName",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": false,
"isUnique": false
},
{
"name": "shortDescription",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": false,
"isOptional": true,
"isUnique": false
},
{
"name": "longDescription",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": false,
"isOptional": true,
"isUnique": false
}
]
}
],
"relationshipDefs": [
{
"name": "__AtlasGlossarySemanticAssignment",
"description": "SemanticAssignment is a relationship used to assign a term to a referenceable object. This means that the term describes the meaning of the referenceable object. The semantic assignment needs to be a controlled relationship when glossary definitions are used to provide classifications for the data assets and hence define how the data is to be governed.",
"typeVersion": "1.0",
"attributeDefs": [
{
"name": "description",
"description": "The description field can be used to add details about the semantic assignment.",
"typeName": "string",
"isOptional": true,
"cardinality": "SINGLE",
"valuesMinCount": 0,
"valuesMaxCount": 1,
"isUnique": false,
"isIndexable": true
},
{
"name": "expression",
"typeName": "string",
"isOptional": true,
"cardinality": "SINGLE",
"valuesMinCount": 0,
"valuesMaxCount": 1,
"isUnique": false,
"isIndexable": true
},
{
"name": "status",
"typeName": "__AtlasGlossaryTermRelationshipStatus",
"isOptional": true,
"cardinality": "SINGLE",
"valuesMinCount": 0,
"valuesMaxCount": 1,
"isUnique": false,
"isIndexable": true
},
{
"name": "confidence",
"description": "The confidence attribute in the semantic assignment stores the level of confidence (0-100%) in the correctness of the semantic assignment - it is typically used by discovery engines.",
"typeName": "int",
"isOptional": true,
"cardinality": "SINGLE",
"valuesMinCount": 0,
"valuesMaxCount": 1,
"isUnique": false,
"isIndexable": true
},
{
"name": "createdBy",
"description": "The semantic assignment is created by the user (person or engine) identified by the createdBy attribute.",
"typeName": "string",
"isOptional": true,
"cardinality": "SINGLE",
"valuesMinCount": 0,
"valuesMaxCount": 1,
"isUnique": false,
"isIndexable": true
},
{
"name": "steward",
"description": "The steward is the person responsible for assessing the semantic assignment and deciding if it should be approved or not.",
"typeName": "string",
"isOptional": true,
"cardinality": "SINGLE",
"valuesMinCount": 0,
"valuesMaxCount": 1,
"isUnique": false,
"isIndexable": true
},
{
"name": "source",
"typeName": "string",
"isOptional": true,
"cardinality": "SINGLE",
"valuesMinCount": 0,
"valuesMaxCount": 1,
"isUnique": false,
"isIndexable": true
}
],
"relationshipCategory": "ASSOCIATION",
"propagateTags": "ONE_TO_TWO",
"endDef1": {
"type": "__AtlasGlossaryTerm",
"name": "assignedEntities",
"isContainer": false,
"cardinality": "SET"
},
"endDef2": {
"type": "Referenceable",
"name": "meanings",
"isContainer": false,
"cardinality": "SET"
}
},
{
"name": "__AtlasGlossaryTermAnchor",
"typeVersion": "1.0",
"description": "TermAnchor links each term to exactly one Glossary object. This means that this is its home glossary. If the Glossary object is deleted, then so are all of the terms linked to it.",
"endDef1": {
"name": "terms",
"type": "__AtlasGlossary",
"cardinality": "SET",
"isContainer": true
},
"endDef2": {
"name": "anchor",
"type": "__AtlasGlossaryTerm",
"cardinality": "SINGLE"
},
"relationshipCategory": "COMPOSITION",
"propagateTags": "NONE"
},
{
"name": "__AtlasGlossaryTermCategorization",
"typeVersion": "1.0",
"description": "TermCategorization is a relationship used to organize terms into categories. A term may be linked with many categories and a category may have many terms linked to it. This relationship may connect terms and categories both in the same glossary or in different glossaries.",
"endDef1": {
"name": "terms",
"type": "__AtlasGlossaryCategory",
"cardinality": "SET",
"isContainer": true
},
"endDef2": {
"name": "categories",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"relationshipCategory": "AGGREGATION",
"propagateTags": "NONE",
"attributeDefs": [
{
"name": "description",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true,
"isUnique": false
},
{
"name": "status",
"typeName": "__AtlasGlossaryTermRelationshipStatus",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true,
"isUnique": false
}
]
},
{
"name": "__AtlasGlossaryCategoryAnchor",
"typeVersion": "1.0",
"description": "CategoryAnchor links each category to exactly one Glossary object. This means that this is its home glossary. If the Glossary object is deleted then so are all of the categories linked to it.",
"endDef1": {
"name": "categories",
"type": "__AtlasGlossary",
"cardinality": "SET",
"isContainer": true
},
"endDef2": {
"name": "anchor",
"type": "__AtlasGlossaryCategory",
"cardinality": "SINGLE"
},
"relationshipCategory": "COMPOSITION",
"propagateTags": "NONE"
},
{
"name": "__AtlasGlossaryCategoryHierarchyLink",
"typeVersion": "1.0",
"description": "CategoryHierarchyLink is a relationship used to organize categories into a hierarchy to, for example, create a structure for a taxonomy. A category may have none or one super-categories. This super-category may be in a different glossary.",
"endDef1": {
"name": "childrenCategories",
"type": "__AtlasGlossaryCategory",
"cardinality": "SET",
"isContainer": true
},
"endDef2": {
"name": "parentCategory",
"type": "__AtlasGlossaryCategory",
"cardinality": "SINGLE"
},
"relationshipCategory": "AGGREGATION",
"propagateTags": "NONE"
},
{
"name": "__AtlasGlossaryRelatedTerm",
"typeVersion": "1.0",
"description": "RelatedTerm is a relationship used to say that the linked glossary term may also be of interest. It is like a 'see also' link in a dictionary.",
"endDef1": {
"name": "seeAlso",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"endDef2": {
"name": "seeAlso",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"relationshipCategory": "ASSOCIATION",
"propagateTags": "NONE",
"attributeDefs": [
{
"name": "description",
"description": "The description field can be used to explain why the linked term is of interest.",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "expression",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "status",
"typeName": "__AtlasGlossaryTermRelationshipStatus",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "steward",
"description": "The steward is the person responsible for assessing the relationship and deciding if it should be approved or not",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "source",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
}
]
},
{
"name": "__AtlasGlossarySynonym",
"typeVersion": "1.0",
"description": "Synonym is a relationship between glossary terms that have the same, or a very similar meaning in the same language. Notice that both ends of this relationship have the same name and refer to the same type; this results in one Synonym attribute being added to GlossaryTerm.",
"endDef1": {
"name": "synonyms",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"endDef2": {
"name": "synonyms",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"relationshipCategory": "ASSOCIATION",
"propagateTags": "NONE",
"attributeDefs": [
{
"name": "description",
"description": "The description field can be used to add details about the relationship.",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "expression",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "status",
"typeName": "__AtlasGlossaryTermRelationshipStatus",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "steward",
"description": "The steward is the person responsible for assessing the relationship and deciding if it should be approved or not.",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "source",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
}
]
},
{
"name": "__AtlasGlossaryAntonym",
"typeVersion": "1.0",
"description": "Antonym is a relationship between glossary terms that have the opposite (or near opposite) meaning, in the same language. Notice that both ends of this relationship have the same name and refer to the same type; this results in one Antonym attribute being added to GlossaryTerm.",
"endDef1": {
"name": "antonyms",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"endDef2": {
"name": "antonyms",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"relationshipCategory": "ASSOCIATION",
"propagateTags": "NONE",
"attributeDefs": [
{
"name": "description",
"description": "The description field can be used to add details about the relationship.",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "expression",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "status",
"typeName": "__AtlasGlossaryTermRelationshipStatus",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "steward",
"description": "The steward is the person responsible for assessing the relationship and deciding if it should be approved or not.",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "source",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
}
]
},
{
"name": "__AtlasGlossaryPreferredTerm",
"typeVersion": "1.0",
"description": "PreferredTerm is a relationship that indicates that the preferredTerm should be used in place of the preferredToTerm. This relationship can be used to encourage adoption of newer vocabularies. This is a weaker version of ReplacementTerm.",
"endDef1": {
"name": "preferredTerms",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"endDef2": {
"name": "preferredToTerms",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"relationshipCategory": "ASSOCIATION",
"propagateTags": "NONE",
"attributeDefs": [
{
"name": "description",
"description": "The description field can be used to add details about the relationship.",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "expression",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "status",
"typeName": "__AtlasGlossaryTermRelationshipStatus",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "steward",
"description": "The steward is the person responsible for assessing the relationship and deciding if it should be approved or not.",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "source",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
}
]
},
{
"name": "__AtlasGlossaryReplacementTerm",
"typeVersion": "1.0",
"description": "ReplacementTerm is a relationship that indicates that the replacementTerm must be used instead of the replacedByTerm. This is stronger version of the PreferredTerm.",
"endDef1": {
"name": "replacedBy",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"endDef2": {
"name": "replacementTerms",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"relationshipCategory": "ASSOCIATION",
"propagateTags": "NONE",
"attributeDefs": [
{
"name": "description",
"description": "The description field can be used to add details about the relationship.",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "expression",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "status",
"typeName": "__AtlasGlossaryTermRelationshipStatus",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "steward",
"description": "The steward is the person responsible for assessing the relationship and deciding if it should be approved or not",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "source",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
}
]
},
{
"name": "__AtlasGlossaryTranslation",
"typeVersion": "1.0",
"description": "Translation is a relationship that defines that the related terms represent the same meaning, but each are written in a different language. Hence one is a translation of the other. The language of each term is defined in the Glossary object that anchors the term.",
"endDef1": {
"name": "translatedTerms",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"endDef2": {
"name": "translationTerms",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"relationshipCategory": "ASSOCIATION",
"propagateTags": "NONE",
"attributeDefs": [
{
"name": "description",
"description": "The description field can be used to add details about the relationship.",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "expression",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "status",
"typeName": "__AtlasGlossaryTermRelationshipStatus",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "steward",
"description": "The steward is the person responsible for assessing the relationship and deciding if it should be approved or not",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "source",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
}
]
},
{
"name": "__AtlasGlossaryIsARelationship",
"typeVersion": "1.0",
"description": "IsA is a relationship that defines that the 'isA' term is a more generic term than the 'isOf' term. For example, this relationship would be use to say that 'Cat' ISA 'Animal'.",
"endDef1": {
"name": "classifies",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"endDef2": {
"name": "isA",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"relationshipCategory": "ASSOCIATION",
"propagateTags": "NONE",
"attributeDefs": [
{
"name": "description",
"description": "The description field can be used to add details about the relationship.",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "expression",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "status",
"typeName": "__AtlasGlossaryTermRelationshipStatus",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "steward",
"description": "The steward is the person responsible for assessing the relationship and deciding if it should be approved or not.",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "source",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
}
]
},
{
"name": "__AtlasGlossaryValidValue",
"typeVersion": "1.0",
"description": "ValidValue is a relationship that shows the validValue term represents one of the valid values that could be assigned to a data item that has the meaning described in the validValueFor term.",
"endDef1": {
"name": "validValuesFor",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"endDef2": {
"name": "validValues",
"type": "__AtlasGlossaryTerm",
"cardinality": "SET"
},
"relationshipCategory": "ASSOCIATION",
"propagateTags": "NONE",
"attributeDefs": [
{
"name": "description",
"description": "The description field can be used to add details about the relationship.",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "expression",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "status",
"typeName": "__AtlasGlossaryTermRelationshipStatus",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "steward",
"description": "The steward is the person responsible for assessing the relationship and deciding if it should be approved or not.",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
},
{
"name": "source",
"typeName": "string",
"cardinality": "SINGLE",
"isIndexable": true,
"isOptional": true
}
]
}
]
}
...@@ -30,6 +30,8 @@ import java.util.List; ...@@ -30,6 +30,8 @@ import java.util.List;
*/ */
public interface AtlasGraphQuery<V, E> { public interface AtlasGraphQuery<V, E> {
enum SortOrder { ASC, DESC }
/** /**
* Adds a predicate that the returned vertices must have the specified * Adds a predicate that the returned vertices must have the specified
* property and that one of the values of the property must be the * property and that one of the values of the property must be the
...@@ -106,6 +108,15 @@ public interface AtlasGraphQuery<V, E> { ...@@ -106,6 +108,15 @@ public interface AtlasGraphQuery<V, E> {
*/ */
AtlasGraphQuery<V, E> has(String propertyKey, QueryOperator op, Object values); AtlasGraphQuery<V, E> has(String propertyKey, QueryOperator op, Object values);
/**
* Adds a sorting predicate
* @param propertyKey property key to sort on
* @param order ASC or DESC
* @return
*/
AtlasGraphQuery<V, E> orderBy(String propertyKey, SortOrder order);
/** /**
* Adds a predicate that the vertices returned must satisfy the * Adds a predicate that the vertices returned must satisfy the
* conditions in at least one of the child queries provided. * conditions in at least one of the child queries provided.
......
...@@ -18,6 +18,7 @@ ...@@ -18,6 +18,7 @@
package org.apache.atlas.repository.graphdb.tinkerpop.query; package org.apache.atlas.repository.graphdb.tinkerpop.query;
import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasEdge;
import org.apache.atlas.repository.graphdb.AtlasGraphQuery;
import org.apache.atlas.repository.graphdb.AtlasGraphQuery.QueryOperator; import org.apache.atlas.repository.graphdb.AtlasGraphQuery.QueryOperator;
import org.apache.atlas.repository.graphdb.AtlasVertex; import org.apache.atlas.repository.graphdb.AtlasVertex;
...@@ -93,4 +94,11 @@ public interface NativeTinkerpopGraphQuery<V, E> { ...@@ -93,4 +94,11 @@ public interface NativeTinkerpopGraphQuery<V, E> {
* @param value * @param value
*/ */
void has(String propertyName, QueryOperator op, Object value); void has(String propertyName, QueryOperator op, Object value);
/**
* Add sort predicate for give property
* @param propertyName
* @param sortOrder
*/
void orderBy(String propertyName, AtlasGraphQuery.SortOrder sortOrder);
} }
...@@ -26,11 +26,13 @@ import org.apache.atlas.repository.graphdb.tinkerpop.query.expr.AndCondition; ...@@ -26,11 +26,13 @@ import org.apache.atlas.repository.graphdb.tinkerpop.query.expr.AndCondition;
import org.apache.atlas.repository.graphdb.tinkerpop.query.expr.HasPredicate; import org.apache.atlas.repository.graphdb.tinkerpop.query.expr.HasPredicate;
import org.apache.atlas.repository.graphdb.tinkerpop.query.expr.InPredicate; import org.apache.atlas.repository.graphdb.tinkerpop.query.expr.InPredicate;
import org.apache.atlas.repository.graphdb.tinkerpop.query.expr.OrCondition; import org.apache.atlas.repository.graphdb.tinkerpop.query.expr.OrCondition;
import org.apache.atlas.repository.graphdb.tinkerpop.query.expr.OrderByPredicate;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
...@@ -129,7 +131,8 @@ public abstract class TinkerpopGraphQuery<V, E> implements AtlasGraphQuery<V, E> ...@@ -129,7 +131,8 @@ public abstract class TinkerpopGraphQuery<V, E> implements AtlasGraphQuery<V, E>
} }
// Compute the overall result by combining the results of all the AndConditions (nested within OR) together. // Compute the overall result by combining the results of all the AndConditions (nested within OR) together.
Set<AtlasVertex<V, E>> result = new HashSet<>(); Set<AtlasVertex<V, E>> result = new LinkedHashSet<>();
for(AndCondition andExpr : queryCondition.getAndTerms()) { for(AndCondition andExpr : queryCondition.getAndTerms()) {
NativeTinkerpopGraphQuery<V, E> andQuery = andExpr.create(getQueryFactory()); NativeTinkerpopGraphQuery<V, E> andQuery = andExpr.create(getQueryFactory());
for(AtlasVertex<V, E> vertex : andQuery.vertices()) { for(AtlasVertex<V, E> vertex : andQuery.vertices()) {
...@@ -269,6 +272,12 @@ public abstract class TinkerpopGraphQuery<V, E> implements AtlasGraphQuery<V, E> ...@@ -269,6 +272,12 @@ public abstract class TinkerpopGraphQuery<V, E> implements AtlasGraphQuery<V, E>
return this; return this;
} }
@Override
public AtlasGraphQuery<V, E> orderBy(final String propertyKey, final SortOrder order) {
queryCondition.andWith(new OrderByPredicate(propertyKey, order));
return this;
}
private OrCondition getOrCondition() { private OrCondition getOrCondition() {
return queryCondition; return queryCondition;
} }
......
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.repository.graphdb.tinkerpop.query.expr;
import org.apache.atlas.repository.graphdb.AtlasGraphQuery;
import org.apache.atlas.repository.graphdb.tinkerpop.query.NativeTinkerpopGraphQuery;
public class OrderByPredicate implements QueryPredicate {
private final String propertyKey;
private final AtlasGraphQuery.SortOrder sortOrder;
public OrderByPredicate(final String propertyKey, final AtlasGraphQuery.SortOrder sortOrder) {
this.propertyKey = propertyKey;
this.sortOrder = sortOrder;
}
@Override
public void addTo(final NativeTinkerpopGraphQuery query) {
query.orderBy(propertyKey, sortOrder);
}
@Override
public String toString() {
return "OrderBy [ propertyKey = " + propertyKey + ", order = " + sortOrder + " ]";
}
}
...@@ -18,22 +18,11 @@ ...@@ -18,22 +18,11 @@
package org.apache.atlas.repository.graphdb.janus; package org.apache.atlas.repository.graphdb.janus;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import org.apache.atlas.ApplicationProperties; import org.apache.atlas.ApplicationProperties;
import org.apache.atlas.AtlasException;
import org.apache.atlas.type.AtlasType;
import org.apache.commons.configuration.Configuration;
import org.janusgraph.core.Cardinality;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.PropertyKey;
import org.janusgraph.core.SchemaViolationException;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphIndexQuery;
import org.janusgraph.core.schema.JanusGraphIndex;
import org.janusgraph.core.schema.JanusGraphManagement;
import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasErrorCode;
import org.apache.atlas.AtlasException;
import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.groovy.GroovyExpression; import org.apache.atlas.groovy.GroovyExpression;
import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasEdge;
...@@ -46,6 +35,8 @@ import org.apache.atlas.repository.graphdb.AtlasVertex; ...@@ -46,6 +35,8 @@ import org.apache.atlas.repository.graphdb.AtlasVertex;
import org.apache.atlas.repository.graphdb.GremlinVersion; import org.apache.atlas.repository.graphdb.GremlinVersion;
import org.apache.atlas.repository.graphdb.janus.query.AtlasJanusGraphQuery; import org.apache.atlas.repository.graphdb.janus.query.AtlasJanusGraphQuery;
import org.apache.atlas.repository.graphdb.utils.IteratorToIterableAdapter; import org.apache.atlas.repository.graphdb.utils.IteratorToIterableAdapter;
import org.apache.atlas.type.AtlasType;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.groovy.CompilerCustomizerProvider; import org.apache.tinkerpop.gremlin.groovy.CompilerCustomizerProvider;
import org.apache.tinkerpop.gremlin.groovy.DefaultImportCustomizerProvider; import org.apache.tinkerpop.gremlin.groovy.DefaultImportCustomizerProvider;
import org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine; import org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine;
...@@ -58,6 +49,14 @@ import org.apache.tinkerpop.gremlin.structure.Vertex; ...@@ -58,6 +49,14 @@ import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.io.IoCore; import org.apache.tinkerpop.gremlin.structure.io.IoCore;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper; import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter; import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter;
import org.janusgraph.core.Cardinality;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraphIndexQuery;
import org.janusgraph.core.PropertyKey;
import org.janusgraph.core.SchemaViolationException;
import org.janusgraph.core.schema.JanusGraphIndex;
import org.janusgraph.core.schema.JanusGraphManagement;
import org.janusgraph.diskstorage.BackendException; import org.janusgraph.diskstorage.BackendException;
import javax.script.Bindings; import javax.script.Bindings;
...@@ -72,6 +71,8 @@ import java.util.Iterator; ...@@ -72,6 +71,8 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.apache.atlas.repository.Constants.INDEX_SEARCH_VERTEX_PREFIX_DEFAULT; import static org.apache.atlas.repository.Constants.INDEX_SEARCH_VERTEX_PREFIX_DEFAULT;
import static org.apache.atlas.repository.Constants.INDEX_SEARCH_VERTEX_PREFIX_PROPERTY; import static org.apache.atlas.repository.Constants.INDEX_SEARCH_VERTEX_PREFIX_PROPERTY;
...@@ -406,13 +407,7 @@ public class AtlasJanusGraph implements AtlasGraph<AtlasJanusVertex, AtlasJanusE ...@@ -406,13 +407,7 @@ public class AtlasJanusGraph implements AtlasGraph<AtlasJanusVertex, AtlasJanusE
public Iterable<AtlasVertex<AtlasJanusVertex, AtlasJanusEdge>> wrapVertices(Iterable<? extends Vertex> it) { public Iterable<AtlasVertex<AtlasJanusVertex, AtlasJanusEdge>> wrapVertices(Iterable<? extends Vertex> it) {
return Iterables.transform(it, new Function<Vertex, AtlasVertex<AtlasJanusVertex, AtlasJanusEdge>>() { return StreamSupport.stream(it.spliterator(), false).map(input -> GraphDbObjectFactory.createVertex(AtlasJanusGraph.this, input)).collect(Collectors.toList());
@Override
public AtlasVertex<AtlasJanusVertex, AtlasJanusEdge> apply(Vertex input) {
return GraphDbObjectFactory.createVertex(AtlasJanusGraph.this, input);
}
});
} }
...@@ -423,13 +418,7 @@ public class AtlasJanusGraph implements AtlasGraph<AtlasJanusVertex, AtlasJanusE ...@@ -423,13 +418,7 @@ public class AtlasJanusGraph implements AtlasGraph<AtlasJanusVertex, AtlasJanusE
public Iterable<AtlasEdge<AtlasJanusVertex, AtlasJanusEdge>> wrapEdges(Iterable<? extends Edge> it) { public Iterable<AtlasEdge<AtlasJanusVertex, AtlasJanusEdge>> wrapEdges(Iterable<? extends Edge> it) {
return Iterables.transform(it, new Function<Edge, AtlasEdge<AtlasJanusVertex, AtlasJanusEdge>>() { return StreamSupport.stream(it.spliterator(), false).map(input -> GraphDbObjectFactory.createEdge(AtlasJanusGraph.this, input)).collect(Collectors.toList());
@Override
public AtlasEdge<AtlasJanusVertex, AtlasJanusEdge> apply(Edge input) {
return GraphDbObjectFactory.createEdge(AtlasJanusGraph.this, input);
}
});
} }
......
...@@ -17,6 +17,8 @@ ...@@ -17,6 +17,8 @@
*/ */
package org.apache.atlas.repository.graphdb.janus.query; package org.apache.atlas.repository.graphdb.janus.query;
import org.apache.atlas.repository.graphdb.AtlasGraphQuery;
import org.apache.tinkerpop.gremlin.process.traversal.Order;
import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Edge;
import org.janusgraph.core.JanusGraphEdge; import org.janusgraph.core.JanusGraphEdge;
import org.janusgraph.core.JanusGraphQuery; import org.janusgraph.core.JanusGraphQuery;
...@@ -126,6 +128,12 @@ public class NativeJanusGraphQuery implements NativeTinkerpopGraphQuery<AtlasJan ...@@ -126,6 +128,12 @@ public class NativeJanusGraphQuery implements NativeTinkerpopGraphQuery<AtlasJan
query.has(propertyName, pred, value); query.has(propertyName, pred, value);
} }
@Override
public void orderBy(final String propertyName, final AtlasGraphQuery.SortOrder sortOrder) {
Order order = sortOrder == AtlasGraphQuery.SortOrder.ASC ? Order.incr : Order.decr;
query.orderBy(propertyName, order);
}
private Text getGremlinPredicate(MatchingOperator op) { private Text getGremlinPredicate(MatchingOperator op) {
switch (op) { switch (op) {
case CONTAINS: case CONTAINS:
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
*/ */
package org.apache.atlas.repository.graphdb.titan0.query; package org.apache.atlas.repository.graphdb.titan0.query;
import com.google.common.collect.Lists; import com.thinkaurelius.titan.core.Order;
import com.thinkaurelius.titan.core.TitanGraphQuery; import com.thinkaurelius.titan.core.TitanGraphQuery;
import com.thinkaurelius.titan.core.attribute.Contain; import com.thinkaurelius.titan.core.attribute.Contain;
import com.thinkaurelius.titan.core.attribute.Text; import com.thinkaurelius.titan.core.attribute.Text;
...@@ -26,6 +26,7 @@ import com.tinkerpop.blueprints.Compare; ...@@ -26,6 +26,7 @@ import com.tinkerpop.blueprints.Compare;
import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.Vertex;
import org.apache.atlas.repository.graphdb.AtlasEdge; import org.apache.atlas.repository.graphdb.AtlasEdge;
import org.apache.atlas.repository.graphdb.AtlasGraphQuery;
import org.apache.atlas.repository.graphdb.AtlasGraphQuery.ComparisionOperator; import org.apache.atlas.repository.graphdb.AtlasGraphQuery.ComparisionOperator;
import org.apache.atlas.repository.graphdb.AtlasGraphQuery.MatchingOperator; import org.apache.atlas.repository.graphdb.AtlasGraphQuery.MatchingOperator;
import org.apache.atlas.repository.graphdb.AtlasGraphQuery.QueryOperator; import org.apache.atlas.repository.graphdb.AtlasGraphQuery.QueryOperator;
...@@ -36,7 +37,10 @@ import org.apache.atlas.repository.graphdb.titan0.Titan0Graph; ...@@ -36,7 +37,10 @@ import org.apache.atlas.repository.graphdb.titan0.Titan0Graph;
import org.apache.atlas.repository.graphdb.titan0.Titan0GraphDatabase; import org.apache.atlas.repository.graphdb.titan0.Titan0GraphDatabase;
import org.apache.atlas.repository.graphdb.titan0.Titan0Vertex; import org.apache.atlas.repository.graphdb.titan0.Titan0Vertex;
import java.util.*; import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/** /**
* Titan 0.5.4 implementation of NativeTitanGraphQuery. * Titan 0.5.4 implementation of NativeTitanGraphQuery.
...@@ -129,6 +133,11 @@ public class NativeTitan0GraphQuery implements NativeTinkerpopGraphQuery<Titan0V ...@@ -129,6 +133,11 @@ public class NativeTitan0GraphQuery implements NativeTinkerpopGraphQuery<Titan0V
query.has(propertyName, pred, value); query.has(propertyName, pred, value);
} }
@Override
public void orderBy(final String propertyName, final AtlasGraphQuery.SortOrder sortOrder) {
query.orderBy(propertyName, sortOrder == AtlasGraphQuery.SortOrder.ASC ? Order.ASC : Order.DESC);
}
private Text getGremlinPredicate(MatchingOperator op) { private Text getGremlinPredicate(MatchingOperator op) {
switch (op) { switch (op) {
case CONTAINS: case CONTAINS:
......
...@@ -128,6 +128,9 @@ public enum AtlasErrorCode { ...@@ -128,6 +128,9 @@ public enum AtlasErrorCode {
NO_CLASSIFICATIONS_FOUND_FOR_ENTITY(400, "ATLAS-400-00-06E", "No classifications associated with entity: {0}"), NO_CLASSIFICATIONS_FOUND_FOR_ENTITY(400, "ATLAS-400-00-06E", "No classifications associated with entity: {0}"),
INVALID_CLASSIFICATION_PARAMS(400, "ATLAS-400-00-06F", "Invalid classification parameters passed for {0} operation for entity: {1}"), INVALID_CLASSIFICATION_PARAMS(400, "ATLAS-400-00-06F", "Invalid classification parameters passed for {0} operation for entity: {1}"),
PROPAGATED_CLASSIFICATION_NOT_ASSOCIATED_WITH_ENTITY(400, "ATLAS-400-00-070", "Propagated classification {0} is not associated with entity"), PROPAGATED_CLASSIFICATION_NOT_ASSOCIATED_WITH_ENTITY(400, "ATLAS-400-00-070", "Propagated classification {0} is not associated with entity"),
// Glossary Related errors
INVALID_PARTIAL_UPDATE_ATTR_VAL(400, "ATLAS-400-00-071", "Invalid attrVal for partial update of {0}, expected = {1} found {2}"),
MISSING_MANDATORY_ANCHOR(400, "ATLAS-400-00-072", "Mandatory anchor attribute is missing"),
UNAUTHORIZED_ACCESS(403, "ATLAS-403-00-001", "{0} is not authorized to perform {1}"), UNAUTHORIZED_ACCESS(403, "ATLAS-403-00-001", "{0} is not authorized to perform {1}"),
...@@ -148,6 +151,7 @@ public enum AtlasErrorCode { ...@@ -148,6 +151,7 @@ public enum AtlasErrorCode {
RELATIONSHIP_ALREADY_DELETED(404, "ATLAS-404-00-00F", "Attempting to delete a relationship which is already deleted : {0}"), RELATIONSHIP_ALREADY_DELETED(404, "ATLAS-404-00-00F", "Attempting to delete a relationship which is already deleted : {0}"),
INVALID_ENTITY_GUID_FOR_CLASSIFICATION_UPDATE(404, "ATLAS-404-00-010", "Updating entityGuid of classification is not allowed."), INVALID_ENTITY_GUID_FOR_CLASSIFICATION_UPDATE(404, "ATLAS-404-00-010", "Updating entityGuid of classification is not allowed."),
INSTANCE_GUID_NOT_DATASET(404, "ATLAS-404-00-011", "Given instance guid {0} is not a dataset"), INSTANCE_GUID_NOT_DATASET(404, "ATLAS-404-00-011", "Given instance guid {0} is not a dataset"),
INSTANCE_GUID_DELETED(404, "ATLAS-404-00-012", "Given instance guid {0} has been deleted"),
// All data conflict errors go here // All data conflict errors go here
TYPE_ALREADY_EXISTS(409, "ATLAS-409-00-001", "Given type {0} already exists"), TYPE_ALREADY_EXISTS(409, "ATLAS-409-00-001", "Given type {0} already exists"),
...@@ -177,7 +181,7 @@ public enum AtlasErrorCode { ...@@ -177,7 +181,7 @@ public enum AtlasErrorCode {
HIVE_HOOK_METASTORE_BRIDGE(500, "ATLAS-500-00-011", "HiveHookMetaStoreBridge: {0}"), HIVE_HOOK_METASTORE_BRIDGE(500, "ATLAS-500-00-011", "HiveHookMetaStoreBridge: {0}"),
DATA_ACCESS_SAVE_FAILED(500, "ATLAS-500-00-012", "Save failed: {0}"), DATA_ACCESS_SAVE_FAILED(500, "ATLAS-500-00-012", "Save failed: {0}"),
DATA_ACCESS_LOAD_FAILED(500, "ATLAS-500-00-013", "Load failed: {0}"), DATA_ACCESS_LOAD_FAILED(500, "ATLAS-500-00-013", "Load failed: {0}"),
ENTITY_NOTIFICATION_FAILED(500, "ATLAS-500-00-014", "Notification failed for operation: {} : {}"); ENTITY_NOTIFICATION_FAILED(500, "ATLAS-500-00-014", "Notification failed for operation: {0} : {1}");
private String errorCode; private String errorCode;
private String errorMessage; private String errorMessage;
......
...@@ -17,32 +17,18 @@ ...@@ -17,32 +17,18 @@
*/ */
package org.apache.atlas.model; package org.apache.atlas.model;
import com.fasterxml.jackson.annotation.JsonAutoDetect; import org.apache.atlas.model.annotation.AtlasJSON;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable; import java.io.Serializable;
import java.util.Objects;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; @AtlasJSON
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;
@JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE)
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
public abstract class AtlasBaseModelObject implements Serializable { public abstract class AtlasBaseModelObject implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private String guid; private String guid;
protected AtlasBaseModelObject() {}
protected AtlasBaseModelObject() {
}
public String getGuid() { public String getGuid() {
return this.guid; return this.guid;
...@@ -52,7 +38,6 @@ public abstract class AtlasBaseModelObject implements Serializable { ...@@ -52,7 +38,6 @@ public abstract class AtlasBaseModelObject implements Serializable {
this.guid = guid; this.guid = guid;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
...@@ -63,5 +48,19 @@ public abstract class AtlasBaseModelObject implements Serializable { ...@@ -63,5 +48,19 @@ public abstract class AtlasBaseModelObject implements Serializable {
return sb.toString(); return sb.toString();
} }
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof AtlasBaseModelObject)) return false;
final AtlasBaseModelObject that = (AtlasBaseModelObject) o;
return Objects.equals(guid, that.guid);
}
@Override
public int hashCode() {
return Objects.hash(guid);
}
protected abstract StringBuilder toString(StringBuilder sb); protected abstract StringBuilder toString(StringBuilder sb);
} }
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.model.annotation;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown=true)
public @interface AtlasJSON {}
\ No newline at end of file
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.model.glossary;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.atlas.model.annotation.AtlasJSON;
import org.apache.atlas.model.glossary.relations.AtlasRelatedCategoryHeader;
import org.apache.atlas.model.glossary.relations.AtlasRelatedTermHeader;
import org.apache.commons.collections.CollectionUtils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@AtlasJSON
public class AtlasGlossary extends AtlasGlossaryBaseObject {
private String language;
private String usage;
private Set<AtlasRelatedTermHeader> terms;
private Set<AtlasRelatedCategoryHeader> categories;
public AtlasGlossary() {
}
public AtlasGlossary(final AtlasGlossary other) {
super.setQualifiedName(other.getQualifiedName());
super.setGuid(other.getGuid());
super.setDisplayName(other.displayName);
super.setShortDescription(other.shortDescription);
super.setLongDescription(other.longDescription);
this.language = other.language;
this.usage = other.usage;
this.terms = other.terms;
this.categories = other.categories;
}
public String getLanguage() {
return language;
}
public void setLanguage(final String language) {
this.language = language;
}
public String getUsage() {
return usage;
}
public void setUsage(final String usage) {
this.usage = usage;
}
public Set<AtlasRelatedCategoryHeader> getCategories() {
return categories;
}
public void setCategories(final Set<AtlasRelatedCategoryHeader> categories) {
this.categories = categories;
}
public Set<AtlasRelatedTermHeader> getTerms() {
return terms;
}
public void setTerms(final Set<AtlasRelatedTermHeader> terms) {
this.terms = terms;
}
@JsonIgnore
@Override
public void setAttribute(String attrName, String attrVal) {
Objects.requireNonNull(attrName, "AtlasGlossary attribute name");
switch (attrName) {
case "displayName":
setDisplayName(attrVal);
break;
case "shortDescription":
setShortDescription(attrVal);
break;
case "longDescription":
setLongDescription(attrVal);
break;
case "language":
setLanguage(attrVal);
break;
case "usage":
setUsage(attrVal);
break;
default:
throw new IllegalArgumentException("Invalid attribute '" + attrName + "' for object AtlasGlossary");
}
}
@JsonIgnore
public void addTerm(AtlasRelatedTermHeader relatedTermId) {
Set<AtlasRelatedTermHeader> terms = this.terms;
if (terms == null) {
terms = new HashSet<>();
}
terms.add(relatedTermId);
setTerms(terms);
}
@JsonIgnore
public void addCategory(AtlasRelatedCategoryHeader relatedCategoryId) {
Set<AtlasRelatedCategoryHeader> categories = this.categories;
if (categories == null) {
categories = new HashSet<>();
}
categories.add(relatedCategoryId);
setCategories(categories);
}
@JsonIgnore
public void removeTerm(AtlasRelatedTermHeader relatedTermId) {
if (CollectionUtils.isNotEmpty(terms)) {
terms.remove(relatedTermId);
}
}
@JsonIgnore
public void removeCategory(AtlasRelatedCategoryHeader relatedCategoryId) {
if (CollectionUtils.isNotEmpty(categories)) {
categories.remove(relatedCategoryId);
}
}
@Override
protected StringBuilder toString(final StringBuilder sb) {
return sb == null ? new StringBuilder(toString()) : sb.append(toString());
}
@AtlasJSON
public static class AtlasGlossaryExtInfo extends AtlasGlossary {
private Map<String, AtlasGlossaryTerm> termInfo;
private Map<String, AtlasGlossaryCategory> categoryInfo;
public AtlasGlossaryExtInfo() {
}
public AtlasGlossaryExtInfo(AtlasGlossary glossary) {
super(glossary);
}
public Map<String, AtlasGlossaryTerm> getTermInfo() {
return termInfo;
}
public void addTermInfo(final AtlasGlossaryTerm term) {
if (termInfo == null) {
termInfo = new HashMap<>();
}
termInfo.put(term.getGuid(), term);
}
public void setTermInfo(final Map<String, AtlasGlossaryTerm> termInfo) {
this.termInfo = termInfo;
}
public Map<String, AtlasGlossaryCategory> getCategoryInfo() {
return categoryInfo;
}
public void addCategoryInfo(final AtlasGlossaryCategory category) {
if (categoryInfo == null) {
categoryInfo = new HashMap<>();
}
categoryInfo.put(category.getGuid(), category);
}
public void setCategoryInfo(final Map<String, AtlasGlossaryCategory> categoryInfo) {
this.categoryInfo = categoryInfo;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof AtlasGlossaryExtInfo)) return false;
if (!super.equals(o)) return false;
final AtlasGlossaryExtInfo that = (AtlasGlossaryExtInfo) o;
return Objects.equals(termInfo, that.termInfo) &&
Objects.equals(categoryInfo, that.categoryInfo);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), termInfo, categoryInfo);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("AtlasGlossaryExtInfo{");
sb.append(super.toString());
sb.append(", termInfo=").append(termInfo);
sb.append(", categoryInfo=").append(categoryInfo);
sb.append('}');
return sb.toString();
}
}
}
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.model.glossary;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.atlas.model.AtlasBaseModelObject;
import org.apache.atlas.model.instance.AtlasClassification;
import org.apache.commons.collections.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public abstract class AtlasGlossaryBaseObject extends AtlasBaseModelObject {
// Core attributes
protected String displayName;
protected String shortDescription;
protected String longDescription;
// Classifications
protected List<AtlasClassification> classifications;
private String qualifiedName;
public String getQualifiedName() {
return qualifiedName;
}
public void setQualifiedName(final String qualifiedName) {
this.qualifiedName = qualifiedName;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(final String displayName) {
this.displayName = displayName;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(final String shortDescription) {
this.shortDescription = shortDescription;
}
public String getLongDescription() {
return longDescription;
}
public void setLongDescription(final String longDescription) {
this.longDescription = longDescription;
}
abstract public void setAttribute(String attrName, String attrVal);
public List<AtlasClassification> getClassifications() {
return classifications;
}
public void setClassifications(final List<AtlasClassification> classifications) {
this.classifications = classifications;
}
@JsonIgnore
public void addClassification(AtlasClassification classification) {
List<AtlasClassification> classifications = this.classifications;
if (classifications == null) {
classifications = new ArrayList<>();
}
classifications.add(classification);
setClassifications(classifications);
}
@JsonIgnore
public void removeClassification(AtlasClassification classification) {
if (CollectionUtils.isNotEmpty(classifications)) {
classifications.remove(classification);
}
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof AtlasGlossaryBaseObject)) return false;
if (!super.equals(o)) return false;
final AtlasGlossaryBaseObject that = (AtlasGlossaryBaseObject) o;
return Objects.equals(displayName, that.displayName) &&
Objects.equals(shortDescription, that.shortDescription) &&
Objects.equals(longDescription, that.longDescription) &&
Objects.equals(classifications, that.classifications) &&
Objects.equals(qualifiedName, that.qualifiedName);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), displayName, shortDescription, longDescription, classifications, qualifiedName);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("AtlasGlossaryBaseObject{");
sb.append("displayName='").append(displayName).append('\'');
sb.append(", shortDescription='").append(shortDescription).append('\'');
sb.append(", longDescription='").append(longDescription).append('\'');
sb.append(", classifications=").append(classifications);
sb.append(", qualifiedName='").append(qualifiedName).append('\'');
sb.append('}');
return sb.toString();
}
}
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.model.glossary;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.atlas.model.annotation.AtlasJSON;
import org.apache.atlas.model.glossary.relations.AtlasGlossaryHeader;
import org.apache.atlas.model.glossary.relations.AtlasRelatedCategoryHeader;
import org.apache.atlas.model.glossary.relations.AtlasRelatedTermHeader;
import org.apache.commons.collections.CollectionUtils;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@AtlasJSON
public class AtlasGlossaryCategory extends AtlasGlossaryBaseObject {
// Inherited attributes from relations
private AtlasGlossaryHeader anchor;
// Category hierarchy links
private AtlasRelatedCategoryHeader parentCategory;
private Set<AtlasRelatedCategoryHeader> childrenCategories;
// Terms associated with this category
private Set<AtlasRelatedTermHeader> terms;
public AtlasGlossaryCategory() {
}
public AtlasGlossaryHeader getAnchor() {
return anchor;
}
public void setAnchor(final AtlasGlossaryHeader anchor) {
this.anchor = anchor;
}
public AtlasRelatedCategoryHeader getParentCategory() {
return parentCategory;
}
public void setParentCategory(final AtlasRelatedCategoryHeader parentCategory) {
this.parentCategory = parentCategory;
}
public Set<AtlasRelatedCategoryHeader> getChildrenCategories() {
return childrenCategories;
}
public void setChildrenCategories(final Set<AtlasRelatedCategoryHeader> childrenCategories) {
this.childrenCategories = childrenCategories;
}
public Set<AtlasRelatedTermHeader> getTerms() {
return terms;
}
public void setTerms(final Set<AtlasRelatedTermHeader> terms) {
this.terms = terms;
}
@JsonIgnore
public void addChild(AtlasRelatedCategoryHeader child) {
Set<AtlasRelatedCategoryHeader> children = this.childrenCategories ;
if (children == null) {
children = new HashSet<>();
}
children.add(child);
setChildrenCategories(children);
}
@JsonIgnore
public void removeChild(AtlasRelatedCategoryHeader child) {
if (CollectionUtils.isNotEmpty(childrenCategories)) {
childrenCategories.remove(child);
}
}
@JsonIgnore
public void addTerm(AtlasRelatedTermHeader term) {
Set<AtlasRelatedTermHeader> terms = this.terms;
if (terms == null) {
terms = new HashSet<>();
}
terms.add(term);
setTerms(terms);
}
@JsonIgnore
public void removeTerm(AtlasRelatedTermHeader term) {
if (CollectionUtils.isNotEmpty(terms)) {
terms.remove(term);
}
}
@JsonIgnore
@Override
public void setAttribute(String attrName, String attrVal) {
Objects.requireNonNull(attrName, "AtlasGlossary attribute name");
switch(attrName) {
case "displayName":
setDisplayName(attrVal);
break;
case "shortDescription":
setShortDescription(attrVal);
break;
case "longDescription":
setLongDescription(attrVal);
break;
default:
throw new IllegalArgumentException("Invalid attribute '" + attrName + "' for object AtlasGlossaryCategory");
}
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("AtlasGlossaryCategory{");
sb.append("displayName='").append(getDisplayName()).append('\'');
sb.append(", shortDescription='").append(getShortDescription()).append('\'');
sb.append(", longDescription='").append(getLongDescription()).append('\'');
sb.append(", anchor=").append(anchor);
sb.append(", parentCategory=").append(parentCategory);
sb.append(", childrenCategories=").append(childrenCategories);
sb.append(", terms=").append(terms);
sb.append(", classifications=").append(getClassifications());
sb.append('}');
return sb.toString();
}
@Override
protected StringBuilder toString(final StringBuilder sb) {
return sb == null ? new StringBuilder(toString()) : sb.append(toString());
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof AtlasGlossaryCategory)) return false;
if (!super.equals(o)) return false;
final AtlasGlossaryCategory category = (AtlasGlossaryCategory) o;
return Objects.equals(getDisplayName(), category.getDisplayName()) &&
Objects.equals(getShortDescription(), category.getShortDescription()) &&
Objects.equals(getLongDescription(), category.getLongDescription()) &&
Objects.equals(anchor, category.anchor) &&
Objects.equals(parentCategory, category.parentCategory) &&
Objects.equals(childrenCategories, category.childrenCategories) &&
Objects.equals(terms, category.terms) &&
Objects.equals(getClassifications(), category.getClassifications());
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), getDisplayName(), getShortDescription(), getLongDescription(),
anchor, parentCategory, childrenCategories,
terms, getClassifications());
}
}
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.model.glossary;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonValue;
import org.apache.atlas.model.annotation.AtlasJSON;
import org.apache.atlas.model.glossary.relations.AtlasGlossaryHeader;
import org.apache.atlas.model.glossary.relations.AtlasRelatedTermHeader;
import org.apache.atlas.model.glossary.relations.AtlasTermCategorizationHeader;
import org.apache.atlas.model.instance.AtlasEntityHeader;
import org.apache.commons.collections.CollectionUtils;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@AtlasJSON
public class AtlasGlossaryTerm extends AtlasGlossaryBaseObject {
// Core attributes
private List<String> examples;
private String abbreviation;
private String usage;
// Attributes derived from relationships
private AtlasGlossaryHeader anchor;
private Set<AtlasEntityHeader> assignedEntities;
private Set<AtlasTermCategorizationHeader> categories;
// Related Terms
private Set<AtlasRelatedTermHeader> seeAlso;
// Term Synonyms
private Set<AtlasRelatedTermHeader> synonyms;
// Term antonyms
private Set<AtlasRelatedTermHeader> antonyms;
// Term preference
private Set<AtlasRelatedTermHeader> preferredTerms;
private Set<AtlasRelatedTermHeader> preferredToTerms;
// Term replacements
private Set<AtlasRelatedTermHeader> replacementTerms;
private Set<AtlasRelatedTermHeader> replacedBy;
// Term translations
private Set<AtlasRelatedTermHeader> translationTerms;
private Set<AtlasRelatedTermHeader> translatedTerms;
// Term classification
private Set<AtlasRelatedTermHeader> isA;
private Set<AtlasRelatedTermHeader> classifies;
// Values for terms
private Set<AtlasRelatedTermHeader> validValues;
private Set<AtlasRelatedTermHeader> validValuesFor;
private boolean hasTerms = false;
public AtlasGlossaryTerm() {
}
public List<String> getExamples() {
return examples;
}
public void setExamples(final List<String> examples) {
this.examples = examples;
}
public String getAbbreviation() {
return abbreviation;
}
public void setAbbreviation(final String abbreviation) {
this.abbreviation = abbreviation;
}
public String getUsage() {
return usage;
}
public void setUsage(final String usage) {
this.usage = usage;
}
public AtlasGlossaryHeader getAnchor() {
return anchor;
}
public void setAnchor(final AtlasGlossaryHeader anchor) {
this.anchor = anchor;
}
public Set<AtlasTermCategorizationHeader> getCategories() {
return categories;
}
public void setCategories(final Set<AtlasTermCategorizationHeader> categories) {
this.categories = categories;
}
public void addCategory(final AtlasTermCategorizationHeader category) {
Set<AtlasTermCategorizationHeader> categories = this.categories;
if (categories == null) {
categories = new HashSet<>();
}
categories.add(category);
setCategories(categories);
}
public Set<AtlasEntityHeader> getAssignedEntities() {
return assignedEntities;
}
public void setAssignedEntities(final Set<AtlasEntityHeader> assignedEntities) {
this.assignedEntities = assignedEntities;
}
public void addAssignedEntity(final AtlasEntityHeader entityHeader) {
Set<AtlasEntityHeader> entityHeaders = this.assignedEntities;
if (entityHeaders == null) {
entityHeaders = new HashSet<>();
}
entityHeaders.add(entityHeader);
setAssignedEntities(entityHeaders);
}
public Set<AtlasRelatedTermHeader> getSeeAlso() {
return seeAlso;
}
public void setSeeAlso(final Set<AtlasRelatedTermHeader> seeAlso) {
this.seeAlso = seeAlso;
hasTerms = true;
}
public Set<AtlasRelatedTermHeader> getSynonyms() {
return synonyms;
}
public void setSynonyms(final Set<AtlasRelatedTermHeader> synonyms) {
this.synonyms = synonyms;
hasTerms = true;
}
public Set<AtlasRelatedTermHeader> getAntonyms() {
return antonyms;
}
public void setAntonyms(final Set<AtlasRelatedTermHeader> antonyms) {
this.antonyms = antonyms;
hasTerms = true;
}
public Set<AtlasRelatedTermHeader> getPreferredTerms() {
return preferredTerms;
}
public void setPreferredTerms(final Set<AtlasRelatedTermHeader> preferredTerms) {
this.preferredTerms = preferredTerms;
hasTerms = true;
}
public Set<AtlasRelatedTermHeader> getPreferredToTerms() {
return preferredToTerms;
}
public void setPreferredToTerms(final Set<AtlasRelatedTermHeader> preferredToTerms) {
this.preferredToTerms = preferredToTerms;
}
public Set<AtlasRelatedTermHeader> getReplacementTerms() {
return replacementTerms;
}
public void setReplacementTerms(final Set<AtlasRelatedTermHeader> replacementTerms) {
this.replacementTerms = replacementTerms;
hasTerms = true;
}
public Set<AtlasRelatedTermHeader> getReplacedBy() {
return replacedBy;
}
public void setReplacedBy(final Set<AtlasRelatedTermHeader> replacedBy) {
this.replacedBy = replacedBy;
hasTerms = true;
}
public Set<AtlasRelatedTermHeader> getTranslationTerms() {
return translationTerms;
}
public void setTranslationTerms(final Set<AtlasRelatedTermHeader> translationTerms) {
this.translationTerms = translationTerms;
hasTerms = true;
}
public Set<AtlasRelatedTermHeader> getTranslatedTerms() {
return translatedTerms;
}
public void setTranslatedTerms(final Set<AtlasRelatedTermHeader> translatedTerms) {
this.translatedTerms = translatedTerms;
hasTerms = true;
}
public Set<AtlasRelatedTermHeader> getIsA() {
return isA;
}
public void setIsA(final Set<AtlasRelatedTermHeader> isA) {
this.isA = isA;
hasTerms = true;
}
public Set<AtlasRelatedTermHeader> getClassifies() {
return classifies;
}
public void setClassifies(final Set<AtlasRelatedTermHeader> classifies) {
this.classifies = classifies;
hasTerms = true;
}
public Set<AtlasRelatedTermHeader> getValidValues() {
return validValues;
}
public void setValidValues(final Set<AtlasRelatedTermHeader> validValues) {
this.validValues = validValues;
hasTerms = true;
}
public Set<AtlasRelatedTermHeader> getValidValuesFor() {
return validValuesFor;
}
public void setValidValuesFor(final Set<AtlasRelatedTermHeader> validValuesFor) {
this.validValuesFor = validValuesFor;
hasTerms = true;
}
@JsonIgnore
public boolean hasTerms() {
return hasTerms;
}
@JsonIgnore
@Override
public void setAttribute(String attrName, String attrVal) {
Objects.requireNonNull(attrName, "AtlasGlossaryTerm attribute name");
switch (attrName) {
case "displayName":
setDisplayName(attrVal);
break;
case "shortDescription":
setShortDescription(attrVal);
break;
case "longDescription":
setLongDescription(attrVal);
break;
case "abbreviation":
setAbbreviation(attrVal);
break;
case "usage":
setUsage(attrVal);
break;
default:
throw new IllegalArgumentException("Invalid attribute '" + attrName + "' for object AtlasGlossaryTerm");
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("AtlasGlossaryTerm{");
sb.append("examples=").append(examples);
sb.append(", abbreviation='").append(abbreviation).append('\'');
sb.append(", usage='").append(usage).append('\'');
sb.append(", anchor=").append(anchor);
sb.append(", assignedEntities=").append(assignedEntities);
sb.append(", categories=").append(categories);
sb.append(", seeAlso=").append(seeAlso);
sb.append(", synonyms=").append(synonyms);
sb.append(", antonyms=").append(antonyms);
sb.append(", preferredTerms=").append(preferredTerms);
sb.append(", preferredToTerms=").append(preferredToTerms);
sb.append(", replacementTerms=").append(replacementTerms);
sb.append(", replacedBy=").append(replacedBy);
sb.append(", translationTerms=").append(translationTerms);
sb.append(", translatedTerms=").append(translatedTerms);
sb.append(", isA=").append(isA);
sb.append(", classifies=").append(classifies);
sb.append(", validValues=").append(validValues);
sb.append(", validValuesFor=").append(validValuesFor);
sb.append(", hasTerms=").append(hasTerms);
sb.append('}');
return sb.toString();
}
@JsonIgnore
public Map<Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms() {
Map<Relation, Set<AtlasRelatedTermHeader>> ret = new HashMap<>();
if (CollectionUtils.isNotEmpty(seeAlso)) {
ret.put(Relation.SEE_ALSO, seeAlso);
}
if (CollectionUtils.isNotEmpty(synonyms)) {
ret.put(Relation.SYNONYMS, synonyms);
}
if (CollectionUtils.isNotEmpty(antonyms)) {
ret.put(Relation.ANTONYMS, antonyms);
}
if (CollectionUtils.isNotEmpty(preferredTerms)) {
ret.put(Relation.PREFERRED_TERMS, preferredTerms);
}
if (CollectionUtils.isNotEmpty(preferredToTerms)) {
ret.put(Relation.PREFERRED_TO_TERMS, preferredToTerms);
}
if (CollectionUtils.isNotEmpty(replacementTerms)) {
ret.put(Relation.REPLACEMENT_TERMS, replacementTerms);
}
if (CollectionUtils.isNotEmpty(replacedBy)) {
ret.put(Relation.REPLACED_BY, replacedBy);
}
if (CollectionUtils.isNotEmpty(translationTerms)) {
ret.put(Relation.TRANSLATION_TERMS, translationTerms);
}
if (CollectionUtils.isNotEmpty(translatedTerms)) {
ret.put(Relation.TRANSLATED_TERMS, translatedTerms);
}
if (CollectionUtils.isNotEmpty(isA)) {
ret.put(Relation.ISA, isA);
}
if (CollectionUtils.isNotEmpty(classifies)) {
ret.put(Relation.CLASSIFIES, classifies);
}
if (CollectionUtils.isNotEmpty(validValues)) {
ret.put(Relation.VALID_VALUES, validValues);
}
if (CollectionUtils.isNotEmpty(validValuesFor)) {
ret.put(Relation.VALID_VALUES_FOR, validValuesFor);
}
return ret;
}
@Override
protected StringBuilder toString(final StringBuilder sb) {
return sb == null ? new StringBuilder(toString()) : sb.append(toString());
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof AtlasGlossaryTerm)) return false;
if (!super.equals(o)) return false;
final AtlasGlossaryTerm that = (AtlasGlossaryTerm) o;
return Objects.equals(examples, that.examples) &&
Objects.equals(abbreviation, that.abbreviation) &&
Objects.equals(usage, that.usage) &&
Objects.equals(anchor, that.anchor) &&
Objects.equals(assignedEntities, that.assignedEntities) &&
Objects.equals(categories, that.categories) &&
Objects.equals(seeAlso, that.seeAlso) &&
Objects.equals(synonyms, that.synonyms) &&
Objects.equals(antonyms, that.antonyms) &&
Objects.equals(preferredTerms, that.preferredTerms) &&
Objects.equals(preferredToTerms, that.preferredToTerms) &&
Objects.equals(replacementTerms, that.replacementTerms) &&
Objects.equals(replacedBy, that.replacedBy) &&
Objects.equals(translationTerms, that.translationTerms) &&
Objects.equals(translatedTerms, that.translatedTerms) &&
Objects.equals(isA, that.isA) &&
Objects.equals(classifies, that.classifies) &&
Objects.equals(validValues, that.validValues) &&
Objects.equals(validValuesFor, that.validValuesFor);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), examples, abbreviation, usage, anchor, assignedEntities, categories,
seeAlso, synonyms, antonyms, preferredTerms, preferredToTerms, replacementTerms, replacedBy,
translationTerms, translatedTerms, isA, classifies, validValues, validValuesFor);
}
public enum Relation {
SEE_ALSO("__AtlasGlossaryRelatedTerm", "seeAlso"),
SYNONYMS("__AtlasGlossarySynonym", "synonyms"),
ANTONYMS("__AtlasGlossaryAntonym", "antonyms"),
PREFERRED_TERMS("__AtlasGlossaryPreferredTerm", "preferredTerms"),
PREFERRED_TO_TERMS("__AtlasGlossaryPreferredTerm", "preferredToTerms"),
REPLACEMENT_TERMS("__AtlasGlossaryReplacementTerm", "replacementTerms"),
REPLACED_BY("__AtlasGlossaryReplacementTerm", "replacedBy"),
TRANSLATION_TERMS("__AtlasGlossaryTranslation", "translationTerms"),
TRANSLATED_TERMS("__AtlasGlossaryTranslation", "translatedTerms"),
ISA("__AtlasGlossaryIsARelationship", "isA"),
CLASSIFIES("__AtlasGlossaryIsARelationship", "classifies"),
VALID_VALUES("__AtlasGlossaryValidValue", "validValues"),
VALID_VALUES_FOR("__AtlasGlossaryValidValue", "validValuesFor"),
;
private String relationName;
private String relationAttrName;
Relation(final String relationName, final String relationAttrName) {
this.relationName = relationName;
this.relationAttrName = relationAttrName;
}
public String getRelationName() {
return relationName;
}
@JsonValue
public String getRelationAttrName() {
return relationAttrName;
}
}
}
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.model.glossary.enums;
public enum AtlasTermAssignmentStatus {
DISCOVERED(0),
PROPOSED(1),
IMPORTED(2),
VALIDATED(3),
DEPRECATED(4),
OBSOLETE(5),
OTHER(6),
;
private int value;
AtlasTermAssignmentStatus(final int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.model.glossary.enums;
public enum AtlasTermRelationshipStatus {
DRAFT(0),
ACTIVE(1),
DEPRECATED(2),
OBSOLETE(3),
OTHER(99)
;
private int value;
AtlasTermRelationshipStatus(final int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.model.glossary.relations;
import org.apache.atlas.model.annotation.AtlasJSON;
import java.util.Objects;
@AtlasJSON
public class AtlasGlossaryHeader {
private String glossaryGuid;
private String relationGuid;
private String displayText;
public String getDisplayText() {
return displayText;
}
public void setDisplayText(final String displayText) {
this.displayText = displayText;
}
public String getGlossaryGuid() {
return glossaryGuid;
}
public void setGlossaryGuid(final String glossaryGuid) {
this.glossaryGuid = glossaryGuid;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof AtlasGlossaryHeader)) return false;
final AtlasGlossaryHeader that = (AtlasGlossaryHeader) o;
return Objects.equals(glossaryGuid, that.glossaryGuid) &&
Objects.equals(relationGuid, that.relationGuid) &&
Objects.equals(displayText, that.displayText);
}
@Override
public int hashCode() {
return Objects.hash(glossaryGuid, displayText);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("AtlasGlossaryId{");
sb.append("glossaryGuid='").append(glossaryGuid).append('\'');
sb.append(", relationGuid='").append(relationGuid).append('\'');
sb.append(", displayText='").append(displayText).append('\'');
sb.append('}');
return sb.toString();
}
public String getRelationGuid() {
return relationGuid;
}
public void setRelationGuid(final String relationGuid) {
this.relationGuid = relationGuid;
}
}
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.model.glossary.relations;
import org.apache.atlas.model.annotation.AtlasJSON;
import java.util.Objects;
@AtlasJSON
public class AtlasRelatedCategoryHeader {
private String categoryGuid;
private String relationGuid;
private String displayText;
private String description;
public AtlasRelatedCategoryHeader() {
}
public String getCategoryGuid() {
return categoryGuid;
}
public void setCategoryGuid(final String categoryGuid) {
this.categoryGuid = categoryGuid;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
public String getDisplayText() {
return displayText;
}
public void setDisplayText(final String displayText) {
this.displayText = displayText;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof AtlasRelatedCategoryHeader)) return false;
final AtlasRelatedCategoryHeader that = (AtlasRelatedCategoryHeader) o;
return Objects.equals(categoryGuid, that.categoryGuid) &&
Objects.equals(displayText, that.displayText) &&
Objects.equals(description, that.description);
}
@Override
public int hashCode() {
return Objects.hash(categoryGuid, displayText, description);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("AtlasRelatedCategoryId{");
sb.append("categoryGuid='").append(categoryGuid).append('\'');
sb.append(", relationGuid='").append(relationGuid).append('\'');
sb.append(", displayText='").append(displayText).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append('}');
return sb.toString();
}
public String getRelationGuid() {
return relationGuid;
}
public void setRelationGuid(final String relationGuid) {
this.relationGuid = relationGuid;
}
}
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.model.glossary.relations;
import org.apache.atlas.model.annotation.AtlasJSON;
import org.apache.atlas.model.glossary.enums.AtlasTermRelationshipStatus;
import java.util.Objects;
@AtlasJSON
public class AtlasRelatedTermHeader {
private String termGuid;
private String relationGuid;
private String displayText;
private String description;
private String expression;
private String steward;
private String source;
private AtlasTermRelationshipStatus status;
public AtlasRelatedTermHeader() {
}
public String getTermGuid() {
return termGuid;
}
public void setTermGuid(final String termGuid) {
this.termGuid = termGuid;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
public String getExpression() {
return expression;
}
public void setExpression(final String expression) {
this.expression = expression;
}
public String getSteward() {
return steward;
}
public void setSteward(final String steward) {
this.steward = steward;
}
public String getSource() {
return source;
}
public void setSource(final String source) {
this.source = source;
}
public AtlasTermRelationshipStatus getStatus() {
return status;
}
public void setStatus(final AtlasTermRelationshipStatus status) {
this.status = status;
}
@Override
public int hashCode() {
return Objects.hash(termGuid, displayText, description, expression, steward, source, status);
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof AtlasRelatedTermHeader)) return false;
final AtlasRelatedTermHeader that = (AtlasRelatedTermHeader) o;
return Objects.equals(termGuid, that.termGuid) &&
Objects.equals(relationGuid, that.relationGuid) &&
Objects.equals(description, that.description) &&
Objects.equals(displayText, that.displayText) &&
Objects.equals(expression, that.expression) &&
Objects.equals(steward, that.steward) &&
Objects.equals(source, that.source) &&
status == that.status;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("AtlasRelatedTermId{");
sb.append("termGuid='").append(termGuid).append('\'');
sb.append(", relationGuid='").append(relationGuid).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append(", displayText='").append(displayText).append('\'');
sb.append(", expression='").append(expression).append('\'');
sb.append(", steward='").append(steward).append('\'');
sb.append(", source='").append(source).append('\'');
sb.append(", status=").append(status);
sb.append('}');
return sb.toString();
}
public String getDisplayText() {
return displayText;
}
public void setDisplayText(final String displayText) {
this.displayText = displayText;
}
public String getRelationGuid() {
return relationGuid;
}
public void setRelationGuid(final String relationGuid) {
this.relationGuid = relationGuid;
}
}
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.model.glossary.relations;
import org.apache.atlas.model.annotation.AtlasJSON;
import org.apache.atlas.model.glossary.enums.AtlasTermAssignmentStatus;
import java.util.Objects;
@AtlasJSON
public class AtlasTermAssignmentHeader {
private String termGuid;
private String relationGuid;
private String description;
private String displayText;
private String expression;
private String createdBy;
private String steward;
private String source;
private int confidence;
private AtlasTermAssignmentStatus status;
public AtlasTermAssignmentHeader() {
}
public String getTermGuid() {
return termGuid;
}
public void setTermGuid(final String termGuid) {
this.termGuid = termGuid;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
public String getExpression() {
return expression;
}
public void setExpression(final String expression) {
this.expression = expression;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(final String createdBy) {
this.createdBy = createdBy;
}
public String getSteward() {
return steward;
}
public void setSteward(final String steward) {
this.steward = steward;
}
public String getSource() {
return source;
}
public void setSource(final String source) {
this.source = source;
}
public int getConfidence() {
return confidence;
}
public void setConfidence(final int confidence) {
this.confidence = confidence;
}
public AtlasTermAssignmentStatus getStatus() {
return status;
}
public void setStatus(final AtlasTermAssignmentStatus status) {
this.status = status;
}
public String getDisplayText() {
return displayText;
}
public void setDisplayText(final String displayText) {
this.displayText = displayText;
}
@Override
public int hashCode() {
return Objects.hash(termGuid, description, displayText, expression, createdBy, steward, source, confidence, status);
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof AtlasTermAssignmentHeader)) return false;
final AtlasTermAssignmentHeader that = (AtlasTermAssignmentHeader) o;
return confidence == that.confidence &&
Objects.equals(termGuid, that.termGuid) &&
Objects.equals(relationGuid, that.relationGuid) &&
Objects.equals(description, that.description) &&
Objects.equals(displayText, that.displayText) &&
Objects.equals(expression, that.expression) &&
Objects.equals(createdBy, that.createdBy) &&
Objects.equals(steward, that.steward) &&
Objects.equals(source, that.source) &&
status == that.status;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("AtlasTermAssignmentId{");
sb.append("termGuid='").append(termGuid).append('\'');
sb.append(", relationGuid='").append(relationGuid).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append(", displayText='").append(displayText).append('\'');
sb.append(", expression='").append(expression).append('\'');
sb.append(", createdBy='").append(createdBy).append('\'');
sb.append(", steward='").append(steward).append('\'');
sb.append(", source='").append(source).append('\'');
sb.append(", confidence=").append(confidence);
sb.append(", status=").append(status);
sb.append('}');
return sb.toString();
}
public String getRelationGuid() {
return relationGuid;
}
public void setRelationGuid(final String relationGuid) {
this.relationGuid = relationGuid;
}
}
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.model.glossary.relations;
import org.apache.atlas.model.annotation.AtlasJSON;
import org.apache.atlas.model.glossary.enums.AtlasTermRelationshipStatus;
import java.util.Objects;
@AtlasJSON
public class AtlasTermCategorizationHeader {
private String categoryGuid;
private String relationGuid;
private String description;
private String displayText;
private AtlasTermRelationshipStatus status;
public AtlasTermCategorizationHeader() {
}
public String getCategoryGuid() {
return categoryGuid;
}
public void setCategoryGuid(final String categoryGuid) {
this.categoryGuid = categoryGuid;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
public AtlasTermRelationshipStatus getStatus() {
return status;
}
public void setStatus(final AtlasTermRelationshipStatus status) {
this.status = status;
}
public String getDisplayText() {
return displayText;
}
public void setDisplayText(final String displayText) {
this.displayText = displayText;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof AtlasTermCategorizationHeader)) return false;
final AtlasTermCategorizationHeader that = (AtlasTermCategorizationHeader) o;
return Objects.equals(categoryGuid, that.categoryGuid) &&
Objects.equals(relationGuid, that.relationGuid) &&
Objects.equals(description, that.description) &&
Objects.equals(displayText, that.displayText) &&
status == that.status;
}
@Override
public int hashCode() {
return Objects.hash(categoryGuid, relationGuid, description, displayText, status);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("AtlasTermCategorizationId{");
sb.append("categoryGuid='").append(categoryGuid).append('\'');
sb.append(", relationGuid='").append(relationGuid).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append(", displayText='").append(displayText).append('\'');
sb.append(", status=").append(status);
sb.append('}');
return sb.toString();
}
public String getRelationGuid() {
return relationGuid;
}
public void setRelationGuid(final String relationGuid) {
this.relationGuid = relationGuid;
}
}
...@@ -22,9 +22,9 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect; ...@@ -22,9 +22,9 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.apache.atlas.model.PList; import org.apache.atlas.model.PList;
import org.apache.atlas.model.SearchFilter.SortType; import org.apache.atlas.model.SearchFilter.SortType;
import org.apache.atlas.model.glossary.relations.AtlasTermAssignmentHeader;
import org.apache.atlas.model.typedef.AtlasBaseTypeDef; import org.apache.atlas.model.typedef.AtlasBaseTypeDef;
import org.apache.atlas.model.typedef.AtlasEntityDef; import org.apache.atlas.model.typedef.AtlasEntityDef;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
...@@ -80,9 +80,10 @@ public class AtlasEntity extends AtlasStruct implements Serializable { ...@@ -80,9 +80,10 @@ public class AtlasEntity extends AtlasStruct implements Serializable {
private Date updateTime = null; private Date updateTime = null;
private Long version = 0L; private Long version = 0L;
private Map<String, Object> relationshipAttributes; private Map<String, Object> relationshipAttributes;
private List<AtlasClassification> classifications; private List<AtlasClassification> classifications;
private List<AtlasClassification> propagationDisabledClassifications; private List<AtlasClassification> propagationDisabledClassifications;
private List<AtlasTermAssignmentHeader> meanings;
@JsonIgnore @JsonIgnore
private static AtomicLong s_nextId = new AtomicLong(System.nanoTime()); private static AtomicLong s_nextId = new AtomicLong(System.nanoTime());
...@@ -280,6 +281,24 @@ public class AtlasEntity extends AtlasStruct implements Serializable { ...@@ -280,6 +281,24 @@ public class AtlasEntity extends AtlasStruct implements Serializable {
this.classifications = c; this.classifications = c;
} }
public List<AtlasTermAssignmentHeader> getMeanings() {
return meanings;
}
public void setMeanings(final List<AtlasTermAssignmentHeader> meanings) {
this.meanings = meanings;
}
public void addMeaning(AtlasTermAssignmentHeader meaning) {
List<AtlasTermAssignmentHeader> meanings = this.meanings;
if (meanings == null) {
meanings = new ArrayList<>();
}
meanings.add(meaning);
setMeanings(meanings);
}
private void init() { private void init() {
setGuid(nextInternalId()); setGuid(nextInternalId());
setStatus(null); setStatus(null);
...@@ -289,6 +308,7 @@ public class AtlasEntity extends AtlasStruct implements Serializable { ...@@ -289,6 +308,7 @@ public class AtlasEntity extends AtlasStruct implements Serializable {
setUpdateTime(null); setUpdateTime(null);
setClassifications(null); setClassifications(null);
setPropagationDisabledClassifications(null); setPropagationDisabledClassifications(null);
setMeanings(null);
} }
private static String nextInternalId() { private static String nextInternalId() {
...@@ -319,6 +339,9 @@ public class AtlasEntity extends AtlasStruct implements Serializable { ...@@ -319,6 +339,9 @@ public class AtlasEntity extends AtlasStruct implements Serializable {
sb.append(", propagationDisabledClassifications=["); sb.append(", propagationDisabledClassifications=[");
AtlasBaseTypeDef.dumpObjects(propagationDisabledClassifications, sb); AtlasBaseTypeDef.dumpObjects(propagationDisabledClassifications, sb);
sb.append(']'); sb.append(']');
sb.append(", meanings=[");
AtlasBaseTypeDef.dumpObjects(meanings, sb);
sb.append(']');
sb.append('}'); sb.append('}');
return sb; return sb;
......
...@@ -6,9 +6,9 @@ ...@@ -6,9 +6,9 @@
* to you under the Apache License, Version 2.0 (the * to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance * "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at * with the License. You may obtain a copy of the License at
* * <p>
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* * <p>
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
...@@ -21,24 +21,23 @@ package org.apache.atlas.model.instance; ...@@ -21,24 +21,23 @@ package org.apache.atlas.model.instance;
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.apache.atlas.model.PList;
import org.apache.atlas.model.SearchFilter.SortType;
import org.apache.atlas.model.glossary.relations.AtlasTermAssignmentHeader;
import org.apache.atlas.model.typedef.AtlasBaseTypeDef;
import org.apache.atlas.model.typedef.AtlasEntityDef;
import org.apache.commons.collections.CollectionUtils;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import org.apache.atlas.model.PList;
import org.apache.atlas.model.SearchFilter.SortType;
import org.apache.atlas.model.typedef.AtlasBaseTypeDef;
import org.apache.atlas.model.typedef.AtlasEntityDef;
import org.apache.commons.collections.CollectionUtils;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY;
...@@ -46,19 +45,21 @@ import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ ...@@ -46,19 +45,21 @@ import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_
/** /**
* An instance of an entity - like hive_table, hive_database. * An instance of an entity - like hive_table, hive_database.
*/ */
@JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true) @JsonIgnoreProperties(ignoreUnknown = true)
@XmlRootElement @XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY) @XmlAccessorType(XmlAccessType.PROPERTY)
public class AtlasEntityHeader extends AtlasStruct implements Serializable { public class AtlasEntityHeader extends AtlasStruct implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private String guid = null; private String guid = null;
private AtlasEntity.Status status = AtlasEntity.Status.ACTIVE; private AtlasEntity.Status status = AtlasEntity.Status.ACTIVE;
private String displayText = null; private String displayText = null;
private List<String> classificationNames = null; private List<String> classificationNames = null;
private List<AtlasClassification> classifications = null; private List<AtlasClassification> classifications = null;
private List<String> meaningNames = null;
private List<AtlasTermAssignmentHeader> meanings = null;
public AtlasEntityHeader() { public AtlasEntityHeader() {
this(null, null); this(null, null);
...@@ -80,7 +81,7 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable { ...@@ -80,7 +81,7 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable {
} }
public AtlasEntityHeader(String typeName, String guid, Map<String, Object> attributes) { public AtlasEntityHeader(String typeName, String guid, Map<String, Object> attributes) {
super(typeName, attributes); super(typeName, attributes);
setGuid(guid); setGuid(guid);
setClassificationNames(null); setClassificationNames(null);
...@@ -100,7 +101,7 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable { ...@@ -100,7 +101,7 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable {
} }
} }
public AtlasEntityHeader(AtlasEntity entity){ public AtlasEntityHeader(AtlasEntity entity) {
super(entity.getTypeName(), entity.getAttributes()); super(entity.getTypeName(), entity.getAttributes());
setGuid(entity.getGuid()); setGuid(entity.getGuid());
setClassifications(entity.getClassifications()); setClassifications(entity.getClassifications());
...@@ -138,7 +139,7 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable { ...@@ -138,7 +139,7 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable {
this.displayText = displayText; this.displayText = displayText;
} }
public List<String> getClassificationNames(){ public List<String> getClassificationNames() {
return classificationNames; return classificationNames;
} }
...@@ -146,9 +147,13 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable { ...@@ -146,9 +147,13 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable {
this.classificationNames = classificationNames; this.classificationNames = classificationNames;
} }
public List<AtlasClassification> getClassifications() { return classifications; } public List<AtlasClassification> getClassifications() {
return classifications;
}
public void setClassifications(List<AtlasClassification> classifications) { this.classifications = classifications; } public void setClassifications(List<AtlasClassification> classifications) {
this.classifications = classifications;
}
@Override @Override
public StringBuilder toString(StringBuilder sb) { public StringBuilder toString(StringBuilder sb) {
...@@ -179,15 +184,17 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable { ...@@ -179,15 +184,17 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable {
if (!super.equals(o)) return false; if (!super.equals(o)) return false;
AtlasEntityHeader that = (AtlasEntityHeader) o; AtlasEntityHeader that = (AtlasEntityHeader) o;
return Objects.equals(guid, that.guid) && return Objects.equals(guid, that.guid) &&
status == that.status && status == that.status &&
Objects.equals(displayText, that.displayText) && Objects.equals(displayText, that.displayText) &&
Objects.equals(classificationNames, that.classificationNames) && Objects.equals(classificationNames, that.classificationNames) &&
Objects.equals(classifications, that.classifications); Objects.equals(meaningNames, that.classificationNames) &&
Objects.equals(classifications, that.classifications) &&
Objects.equals(meanings, that.meanings);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(super.hashCode(), guid, status, displayText, classificationNames, classifications); return Objects.hash(super.hashCode(), guid, status, displayText, classificationNames, classifications, meaningNames, meanings);
} }
@Override @Override
...@@ -195,12 +202,28 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable { ...@@ -195,12 +202,28 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable {
return toString(new StringBuilder()).toString(); return toString(new StringBuilder()).toString();
} }
public List<String> getMeaningNames() {
return meaningNames;
}
public void setMeaningNames(final List<String> meaningNames) {
this.meaningNames = meaningNames;
}
public List<AtlasTermAssignmentHeader> getMeanings() {
return meanings;
}
public void setMeanings(final List<AtlasTermAssignmentHeader> meanings) {
this.meanings = meanings;
}
/** /**
* REST serialization friendly list. * REST serialization friendly list.
*/ */
@JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonAutoDetect(getterVisibility = PUBLIC_ONLY, setterVisibility = PUBLIC_ONLY, fieldVisibility = NONE)
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true) @JsonIgnoreProperties(ignoreUnknown = true)
@XmlRootElement @XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY) @XmlAccessorType(XmlAccessType.PROPERTY)
@XmlSeeAlso(AtlasEntity.class) @XmlSeeAlso(AtlasEntity.class)
...@@ -216,7 +239,7 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable { ...@@ -216,7 +239,7 @@ public class AtlasEntityHeader extends AtlasStruct implements Serializable {
} }
public AtlasEntityHeaders(List list, long startIndex, int pageSize, long totalCount, public AtlasEntityHeaders(List list, long startIndex, int pageSize, long totalCount,
SortType sortType, String sortBy) { SortType sortType, String sortBy) {
super(list, startIndex, pageSize, totalCount, sortType, sortBy); super(list, startIndex, pageSize, totalCount, sortType, sortBy);
} }
} }
......
...@@ -22,17 +22,14 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect; ...@@ -22,17 +22,14 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.apache.atlas.model.typedef.AtlasRelationshipDef; import org.apache.atlas.model.typedef.AtlasRelationshipDef;
import org.apache.atlas.model.typedef.AtlasRelationshipDef.PropagateTags; import org.apache.atlas.model.typedef.AtlasRelationshipDef.PropagateTags;
import org.apache.atlas.type.AtlasBuiltInTypes;
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.util.Date;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
......
...@@ -20,9 +20,7 @@ package org.apache.atlas.type; ...@@ -20,9 +20,7 @@ package org.apache.atlas.type;
import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasErrorCode;
import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.model.instance.AtlasObjectId;
import org.apache.atlas.model.instance.AtlasRelationship; import org.apache.atlas.model.instance.AtlasRelationship;
import org.apache.atlas.model.instance.AtlasStruct;
import org.apache.atlas.model.typedef.AtlasBaseTypeDef; import org.apache.atlas.model.typedef.AtlasBaseTypeDef;
import org.apache.atlas.model.typedef.AtlasRelationshipDef; import org.apache.atlas.model.typedef.AtlasRelationshipDef;
import org.apache.atlas.model.typedef.AtlasRelationshipDef.RelationshipCategory; import org.apache.atlas.model.typedef.AtlasRelationshipDef.RelationshipCategory;
......
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.glossary;
import org.apache.atlas.AtlasErrorCode;
import org.apache.atlas.SortOrder;
import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.model.glossary.AtlasGlossary;
import org.apache.atlas.model.glossary.AtlasGlossaryCategory;
import org.apache.atlas.model.glossary.AtlasGlossaryTerm;
import org.apache.atlas.model.glossary.relations.AtlasRelatedCategoryHeader;
import org.apache.atlas.model.glossary.relations.AtlasRelatedTermHeader;
import org.apache.atlas.model.glossary.relations.AtlasTermCategorizationHeader;
import org.apache.atlas.model.instance.AtlasEntityHeader;
import org.apache.atlas.model.instance.AtlasObjectId;
import org.apache.atlas.model.instance.AtlasRelationship;
import org.apache.atlas.repository.ogm.DataAccess;
import org.apache.atlas.repository.store.graph.AtlasRelationshipStore;
import org.apache.atlas.repository.store.graph.v1.AtlasGraphUtilsV1;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class GlossaryService {
private static final Logger LOG = LoggerFactory.getLogger(GlossaryService.class);
private static final boolean DEBUG_ENABLED = LOG.isDebugEnabled();
private static final String ATLAS_GLOSSARY_PREFIX = "__AtlasGlossary";
// Relation name constants
private static final String TERM_ANCHOR = ATLAS_GLOSSARY_PREFIX + "TermAnchor";
private static final String CATEGORY_ANCHOR = ATLAS_GLOSSARY_PREFIX + "CategoryAnchor";
private static final String CATEGORY_HIERARCHY = ATLAS_GLOSSARY_PREFIX + "CategoryHierarchyLink";
private static final String TERM_CATEGORIZATION = ATLAS_GLOSSARY_PREFIX + "TermCategorization";
private static final String TERM_ASSIGNMENT = ATLAS_GLOSSARY_PREFIX + "SemanticAssignment";
private final DataAccess dataAccess;
private final AtlasRelationshipStore relationshipStore;
@Inject
public GlossaryService(DataAccess dataAccess, final AtlasRelationshipStore relationshipStore) {
this.dataAccess = dataAccess;
this.relationshipStore = relationshipStore;
}
/**
* List all glossaries
*
* @param limit page size - no paging by default
* @param offset offset for pagination
* @param sortOrder ASC (default) or DESC
* @return List of all glossaries
* @throws AtlasBaseException
*/
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 = AtlasGraphUtilsV1.findEntityGUIDsByType(ATLAS_GLOSSARY_PREFIX, sortOrder);
PaginationHelper paginationHelper = new PaginationHelper<>(glossaryGuids, offset, limit);
List<AtlasGlossary> ret;
List<String> guidsToLoad = paginationHelper.getPaginatedList();
if (CollectionUtils.isNotEmpty(guidsToLoad)) {
ret = guidsToLoad.stream().map(GlossaryService::getGlossarySkeleton).collect(Collectors.toList());
Iterable<AtlasGlossary> glossaries = dataAccess.load(ret);
ret.clear();
glossaries.forEach(ret::add);
} else {
ret = Collections.emptyList();
}
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.getGlossaries() : {}", ret);
}
return ret;
}
/**
* Create a glossary
*
* @param atlasGlossary Glossary specification to be created
* @return Glossary definition
* @throws AtlasBaseException
*/
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 (Objects.isNull(atlasGlossary.getQualifiedName())) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "Glossary qualifiedName is mandatory");
}
AtlasGlossary saved = dataAccess.save(atlasGlossary);
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.createGlossary() : {}", saved);
}
return saved;
}
/**
* Get specific glossary
*
* @param glossaryGuid unique identifier
* @return Glossary corresponding to specified glossaryGuid
* @throws AtlasBaseException
*/
public AtlasGlossary getGlossary(String glossaryGuid) throws AtlasBaseException {
if (DEBUG_ENABLED) {
LOG.debug("==> GlossaryService.getGlossary({})", glossaryGuid);
}
if (Objects.isNull(glossaryGuid)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "glossaryGuid is null/empty");
}
AtlasGlossary atlasGlossary = getGlossarySkeleton(glossaryGuid);
AtlasGlossary ret = dataAccess.load(atlasGlossary);
setDisplayTextForRelations(ret);
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.getGlossary() : {}", ret);
}
return ret;
}
/**
* Get specific glossary
*
* @param glossaryGuid unique identifier
* @return Glossary corresponding to specified glossaryGuid
* @throws AtlasBaseException
*/
public AtlasGlossary.AtlasGlossaryExtInfo getDetailedGlossary(String glossaryGuid) throws AtlasBaseException {
if (DEBUG_ENABLED) {
LOG.debug("==> GlossaryService.getGlossary({})", glossaryGuid);
}
if (Objects.isNull(glossaryGuid)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "glossaryGuid is null/empty");
}
AtlasGlossary atlasGlossary = getGlossarySkeleton(glossaryGuid);
AtlasGlossary glossary = dataAccess.load(atlasGlossary);
AtlasGlossary.AtlasGlossaryExtInfo ret = new AtlasGlossary.AtlasGlossaryExtInfo(glossary);
// Load all linked terms
if (CollectionUtils.isNotEmpty(ret.getTerms())) {
List<AtlasGlossaryTerm> termsToLoad = ret.getTerms()
.stream()
.map(id -> getAtlasGlossaryTermSkeleton(id.getTermGuid()))
.collect(Collectors.toList());
Iterable<AtlasGlossaryTerm> glossaryTerms = dataAccess.load(termsToLoad);
glossaryTerms.forEach(ret::addTermInfo);
}
// Load all linked categories
if (CollectionUtils.isNotEmpty(ret.getCategories())) {
List<AtlasGlossaryCategory> categoriesToLoad = ret.getCategories()
.stream()
.map(id -> getAtlasGlossaryCategorySkeleton(id.getCategoryGuid()))
.collect(Collectors.toList());
Iterable<AtlasGlossaryCategory> glossaryCategories = dataAccess.load(categoriesToLoad);
glossaryCategories.forEach(ret::addCategoryInfo);
}
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.getGlossary() : {}", ret);
}
return ret;
}
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");
}
AtlasGlossary ret = dataAccess.load(atlasGlossary);
if (!ret.equals(atlasGlossary)) {
atlasGlossary.setGuid(ret.getGuid());
atlasGlossary.setQualifiedName(ret.getQualifiedName());
ret = dataAccess.save(atlasGlossary);
setDisplayTextForRelations(ret);
}
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.updateGlossary() : {}", ret);
}
return ret;
}
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");
}
// FIXME: When deleting all other related entities, the new edge label (r:<Relation>) is failing the delete calls
dataAccess.delete(glossaryGuid);
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.deleteGlossary()");
}
}
/*
* GlossaryTerms related operations
* */
public AtlasGlossaryTerm getTerm(String termGuid) throws AtlasBaseException {
if (DEBUG_ENABLED) {
LOG.debug("==> GlossaryService.getTerm({})", termGuid);
}
if (Objects.isNull(termGuid)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "termGuid is null/empty");
}
AtlasGlossaryTerm atlasGlossary = getAtlasGlossaryTermSkeleton(termGuid);
AtlasGlossaryTerm ret = dataAccess.load(atlasGlossary);
setDisplayTextForRelations(ret);
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.getTerm() : {}", ret);
}
return ret;
}
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.getQualifiedName())) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "GlossaryTerm qualifiedName is mandatory");
}
AtlasGlossaryTerm saved = dataAccess.save(glossaryTerm);
// TODO: Create all term relations
processTermAnchor(glossaryTerm, saved);
processRelatedTerms(glossaryTerm, saved);
processAssociatedCategories(glossaryTerm, saved);
saved = dataAccess.load(glossaryTerm);
setDisplayTextForRelations(saved);
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.create() : {}", saved);
}
return saved;
}
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;
}
public AtlasGlossaryTerm updateTerm(AtlasGlossaryTerm atlasGlossaryTerm) throws AtlasBaseException {
if (DEBUG_ENABLED) {
LOG.debug("==> GlossaryService.updateTerm({})", atlasGlossaryTerm);
}
if (Objects.isNull(atlasGlossaryTerm)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "atlasGlossaryTerm is null/empty");
}
AtlasGlossaryTerm existing = dataAccess.load(atlasGlossaryTerm);
AtlasGlossaryTerm updated = atlasGlossaryTerm;
if (!existing.equals(updated)) {
try {
updated.setGuid(existing.getGuid());
updated.setQualifiedName(existing.getQualifiedName());
atlasGlossaryTerm = dataAccess.save(updated);
} catch (AtlasBaseException e) {
LOG.debug("Glossary term had no immediate attr updates. Exception: {}", e.getMessage());
} finally {
// TODO: Manage remaining term relations
processRelations(atlasGlossaryTerm, existing);
}
}
updated = dataAccess.load(atlasGlossaryTerm);
setDisplayTextForRelations(updated);
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.updateTerm() : {}", updated);
}
return updated;
}
public void deleteTerm(String termGuid) throws AtlasBaseException {
if (DEBUG_ENABLED) {
LOG.debug("==> GlossaryService.deleteTerm({})", termGuid);
}
if (Objects.isNull(termGuid)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "termGuid is null/empty");
}
dataAccess.delete(termGuid);
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.deleteTerm()");
}
}
public void assignTermToEntities(String termGuid, Collection<AtlasEntityHeader> entityHeaders) throws AtlasBaseException {
AtlasGlossaryTerm glossaryTerm = dataAccess.load(getAtlasGlossaryTermSkeleton(termGuid));
if (Objects.nonNull(glossaryTerm)) {
Set<AtlasEntityHeader> assignedEntities = glossaryTerm.getAssignedEntities();
for (AtlasEntityHeader entityHeader : entityHeaders) {
if (CollectionUtils.isNotEmpty(assignedEntities) && assignedEntities.contains(entityHeader)) continue;
if (DEBUG_ENABLED) {
LOG.debug("Assigning term guid={}, to entity guid = {}", termGuid, entityHeader.getGuid());
}
createRelationship(defineTermAssignment(termGuid, entityHeader));
}
}
}
public void removeTermFromEntities(String termGuid, Collection<AtlasEntityHeader> entityHeaders) throws AtlasBaseException {
AtlasGlossaryTerm glossaryTerm = dataAccess.load(getAtlasGlossaryTermSkeleton(termGuid));
if (Objects.nonNull(glossaryTerm)) {
for (AtlasEntityHeader entityHeader : entityHeaders) {
if (DEBUG_ENABLED) {
LOG.debug("Removing term guid={}, from entity guid = {}", termGuid, entityHeader.getGuid());
}
Object relationGuid = entityHeader.getAttribute("relationGuid");
if (Objects.isNull(relationGuid)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "EntityHeader is missing mandatory attribute relation guid");
}
relationshipStore.deleteById((String) relationGuid);
}
}
}
/*
* GlossaryCategory related operations
* */
public AtlasGlossaryCategory getCategory(String categoryGuid) throws AtlasBaseException {
if (DEBUG_ENABLED) {
LOG.debug("==> GlossaryService.getCategory({})", categoryGuid);
}
if (Objects.isNull(categoryGuid)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "categoryGuid is null/empty");
}
AtlasGlossaryCategory atlasGlossary = getAtlasGlossaryCategorySkeleton(categoryGuid);
AtlasGlossaryCategory ret = dataAccess.load(atlasGlossary);
setDisplayTextForRelations(ret);
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.getCategory() : {}", ret);
}
return ret;
}
public AtlasGlossaryCategory createCategory(AtlasGlossaryCategory glossaryCategory) throws AtlasBaseException {
if (DEBUG_ENABLED) {
LOG.debug("==> GlossaryService.createCategory({})", glossaryCategory);
}
if (Objects.isNull(glossaryCategory)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "GlossaryCategory definition missing");
}
if (Objects.isNull(glossaryCategory.getQualifiedName())) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "GlossaryCategory qualifiedName is mandatory");
}
AtlasGlossaryCategory saved = dataAccess.save(glossaryCategory);
// Attempt relation creation
if (Objects.nonNull(glossaryCategory.getAnchor())) {
processCategoryAnchor(glossaryCategory, saved);
}
if (Objects.nonNull(glossaryCategory.getParentCategory())) {
processParentCategory(glossaryCategory, saved);
}
if (CollectionUtils.isNotEmpty(glossaryCategory.getChildrenCategories())) {
processCategoryChildren(glossaryCategory, saved);
}
saved = dataAccess.load(glossaryCategory);
setDisplayTextForRelations(glossaryCategory);
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.createCategory() : {}", saved);
}
return saved;
}
public List<AtlasGlossaryCategory> createCategories(List<AtlasGlossaryCategory> glossaryCategory) throws AtlasBaseException {
if (DEBUG_ENABLED) {
LOG.debug("==> GlossaryService.createCategories({})", glossaryCategory);
}
if (Objects.isNull(glossaryCategory)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "glossaryCategory is null/empty");
}
List<AtlasGlossaryCategory> ret = new ArrayList<>();
for (AtlasGlossaryCategory category : glossaryCategory) {
ret.add(createCategory(category));
}
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.createCategories() : {}", ret);
}
return ret;
}
public AtlasGlossaryCategory updateCategory(AtlasGlossaryCategory glossaryCategory) throws AtlasBaseException {
if (DEBUG_ENABLED) {
LOG.debug("==> GlossaryService.updateCategory({})", glossaryCategory);
}
if (Objects.isNull(glossaryCategory)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "GlossaryCategory is null/empty");
}
AtlasGlossaryCategory existing = dataAccess.load(glossaryCategory);
AtlasGlossaryCategory ret = glossaryCategory;
if (!existing.equals(glossaryCategory)) {
try {
glossaryCategory.setGuid(existing.getGuid());
glossaryCategory.setQualifiedName(existing.getQualifiedName());
ret = dataAccess.save(glossaryCategory);
} catch (AtlasBaseException e) {
LOG.debug("No immediate attribute update. Exception: {}", e.getMessage());
} finally {
processRelations(glossaryCategory, existing);
}
}
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.updateCategory() : {}", ret);
}
ret = dataAccess.load(glossaryCategory);
setDisplayTextForRelations(glossaryCategory);
return ret;
}
public void deleteCategory(String categoryGuid) throws AtlasBaseException {
if (DEBUG_ENABLED) {
LOG.debug("==> GlossaryService.deleteCategory({})", categoryGuid);
}
if (Objects.isNull(categoryGuid)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "Category guid is null/empty");
}
dataAccess.delete(categoryGuid);
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.deleteCategory()");
}
}
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);
}
AtlasGlossary glossary = getGlossary(glossaryGuid);
List<AtlasGlossaryTerm> ret;
if (CollectionUtils.isNotEmpty(glossary.getTerms())) {
List<AtlasGlossaryTerm> toLoad = glossary.getTerms().stream()
.map(t -> getAtlasGlossaryTermSkeleton(t.getTermGuid()))
.collect(Collectors.toList());
Iterable<AtlasGlossaryTerm> terms = dataAccess.load(toLoad);
toLoad.clear();
terms.forEach(toLoad::add);
if (sortOrder != null) {
toLoad.sort((o1, o2) -> sortOrder == SortOrder.ASCENDING ?
o1.getDisplayName().compareTo(o2.getDisplayName()) :
o2.getDisplayName().compareTo(o1.getDisplayName()));
}
ret = new PaginationHelper<>(toLoad, offset, limit).getPaginatedList();
} else {
ret = Collections.emptyList();
}
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.getGlossaryTerms() : {}", ret);
}
return ret;
}
public List<AtlasRelatedCategoryHeader> 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);
}
AtlasGlossary glossary = getGlossary(glossaryGuid);
List<AtlasRelatedCategoryHeader> ret;
List<AtlasRelatedCategoryHeader> categories = new ArrayList<>(glossary.getCategories());
if (CollectionUtils.isNotEmpty(categories)) {
if (sortOrder != null) {
categories.sort((o1, o2) -> sortOrder == SortOrder.ASCENDING ?
o1.getDisplayText().compareTo(o2.getDisplayText()) :
o2.getDisplayText().compareTo(o1.getDisplayText()));
}
ret = new PaginationHelper<>(categories, offset, limit).getPaginatedList();
} else {
ret = Collections.emptyList();
}
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.getGlossaryCategories() : {}", ret);
}
return ret;
}
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);
}
AtlasGlossaryCategory glossaryCategory = getCategory(categoryGuid);
List<AtlasRelatedTermHeader> ret;
List<AtlasRelatedTermHeader> terms = new ArrayList<>(glossaryCategory.getTerms());
if (CollectionUtils.isNotEmpty(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;
}
public Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(String termGuid, int offset, int limit, SortOrder sortOrder) throws AtlasBaseException {
if (Objects.isNull(termGuid)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "termGuid is null/empty");
}
if (DEBUG_ENABLED) {
LOG.debug("==> GlossaryService.getRelatedTerms({}, {}, {}, {})", termGuid, offset, limit, sortOrder);
}
AtlasGlossaryTerm glossaryTerm = getTerm(termGuid);
Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> ret;
if (glossaryTerm.hasTerms()) {
ret = glossaryTerm.getRelatedTerms();
} else {
ret = Collections.emptyMap();
}
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.getRelatedTerms() : {}", ret);
}
return ret;
}
public Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(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.getRelatedCategories({}, {}, {}, {})", categoryGuid, offset, limit, sortOrder);
}
AtlasGlossaryCategory glossaryCategory = getCategory(categoryGuid);
Map<String, List<AtlasRelatedCategoryHeader>> ret = new HashMap<>();
if (glossaryCategory.getParentCategory() != null) {
ret.put("parent", new ArrayList<AtlasRelatedCategoryHeader>() {{
add(glossaryCategory.getParentCategory());
}});
}
if (CollectionUtils.isNotEmpty(glossaryCategory.getChildrenCategories())) {
ret.put("children", new ArrayList<>(glossaryCategory.getChildrenCategories()));
}
if (DEBUG_ENABLED) {
LOG.debug("<== GlossaryService.getRelatedCategories() : {}", ret);
}
return ret;
}
public List<AtlasEntityHeader> getAssignedEntities(final String termGuid, int offset, int limit, SortOrder sortOrder) throws AtlasBaseException {
if (Objects.isNull(termGuid)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "termGuid is null/empty");
}
AtlasGlossaryTerm glossaryTerm = dataAccess.load(getAtlasGlossaryTermSkeleton(termGuid));
Set<AtlasEntityHeader> assignedEntities = glossaryTerm.getAssignedEntities();
List<AtlasEntityHeader> ret;
if (CollectionUtils.isNotEmpty(assignedEntities)) {
ret = new ArrayList<>(assignedEntities);
if (sortOrder != null) {
ret.sort((o1, o2) -> sortOrder == SortOrder.ASCENDING ?
o1.getDisplayText().compareTo(o2.getDisplayText()) :
o2.getDisplayText().compareTo(o1.getDisplayText()));
}
ret = new PaginationHelper<>(assignedEntities, offset, limit).getPaginatedList();
} else {
ret = Collections.emptyList();
}
return ret;
}
private static AtlasGlossary getGlossarySkeleton(String glossaryGuid) {
AtlasGlossary glossary = new AtlasGlossary();
glossary.setGuid(glossaryGuid);
return glossary;
}
private void processAssignedEntities(final AtlasGlossaryTerm newObj, final AtlasGlossaryTerm existing) throws AtlasBaseException {
if (newObj.equals(existing)) return;
if (CollectionUtils.isNotEmpty(newObj.getAssignedEntities())) {
for (AtlasEntityHeader entityHeader : newObj.getAssignedEntities()) {
createRelationship(defineTermAssignment(existing.getGuid(), entityHeader));
}
}
}
private void setDisplayTextForRelations(final AtlasGlossary ret) throws AtlasBaseException {
if (Objects.nonNull(ret.getTerms())) {
setDisplayNameForTerms(ret.getTerms());
}
if (Objects.nonNull(ret.getCategories())) {
setDisplayNameForRelatedCategories(ret.getCategories());
}
}
private void setDisplayTextForRelations(final AtlasGlossaryTerm ret) throws AtlasBaseException {
if (Objects.nonNull(ret.getCategories())) {
setDisplayNameForTermCategories(ret.getCategories());
}
if (Objects.nonNull(ret.getRelatedTerms())) {
for (Map.Entry<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> entry : ret.getRelatedTerms().entrySet()) {
setDisplayNameForTerms(entry.getValue());
}
}
}
private void setDisplayTextForRelations(final AtlasGlossaryCategory glossaryCategory) throws AtlasBaseException {
if (Objects.nonNull(glossaryCategory.getChildrenCategories())) {
setDisplayNameForRelatedCategories(glossaryCategory.getChildrenCategories());
}
if (Objects.nonNull(glossaryCategory.getTerms())) {
setDisplayNameForTerms(glossaryCategory.getTerms());
}
}
private void processRelations(final AtlasGlossaryTerm newObj, final AtlasGlossaryTerm existing) throws AtlasBaseException {
boolean hasRelatedTerms = newObj.hasTerms();
boolean hasTermAnchor = Objects.nonNull(newObj.getAnchor());
boolean hasCategories = Objects.nonNull(newObj.getCategories());
if (hasTermAnchor) {
processTermAnchor(newObj, existing);
}
if (hasRelatedTerms) {
processRelatedTerms(newObj, existing);
}
if (hasCategories) {
processAssociatedCategories(newObj, existing);
}
}
private void processRelations(final AtlasGlossaryCategory newObj, final AtlasGlossaryCategory existing) throws AtlasBaseException {
boolean hasParent = Objects.nonNull(newObj.getParentCategory());
boolean hasChildren = Objects.nonNull(newObj.getChildrenCategories());
boolean hasAnchor = Objects.nonNull(newObj.getAnchor());
boolean hasTerms = Objects.nonNull(newObj.getTerms());
if (hasAnchor) {
processCategoryAnchor(newObj, existing);
}
if (hasParent) {
processParentCategory(newObj, existing);
}
if (hasChildren) {
processCategoryChildren(newObj, existing);
}
if (hasTerms) {
processAssociatedTerms(newObj, existing);
}
}
private void setDisplayNameForTermCategories(final Set<AtlasTermCategorizationHeader> categorizationHeaders) throws AtlasBaseException {
List<AtlasGlossaryCategory> categories = categorizationHeaders
.stream()
.map(id -> getAtlasGlossaryCategorySkeleton(id.getCategoryGuid()))
.collect(Collectors.toList());
Map<String, AtlasGlossaryCategory> categoryMap = new HashMap<>();
dataAccess.load(categories).forEach(c -> categoryMap.put(c.getGuid(), c));
categorizationHeaders.forEach(c -> c.setDisplayText(categoryMap.get(c.getCategoryGuid()).getDisplayName()));
}
private void setDisplayNameForRelatedCategories(final Set<AtlasRelatedCategoryHeader> categoryHeaders) throws AtlasBaseException {
List<AtlasGlossaryCategory> categories = categoryHeaders
.stream()
.map(id -> getAtlasGlossaryCategorySkeleton(id.getCategoryGuid()))
.collect(Collectors.toList());
Map<String, AtlasGlossaryCategory> categoryMap = new HashMap<>();
dataAccess.load(categories).forEach(c -> categoryMap.put(c.getGuid(), c));
categoryHeaders.forEach(c -> c.setDisplayText(categoryMap.get(c.getCategoryGuid()).getDisplayName()));
}
private void setDisplayNameForTerms(final Set<AtlasRelatedTermHeader> termHeaders) throws AtlasBaseException {
List<AtlasGlossaryTerm> terms = termHeaders
.stream()
.map(id -> getAtlasGlossaryTermSkeleton(id.getTermGuid()))
.collect(Collectors.toList());
Map<String, AtlasGlossaryTerm> termMap = new HashMap<>();
dataAccess.load(terms).iterator().forEachRemaining(t -> termMap.put(t.getGuid(), t));
termHeaders.forEach(t -> t.setDisplayText(termMap.get(t.getTermGuid()).getDisplayName()));
}
private void processAssociatedCategories(final AtlasGlossaryTerm newObj, final AtlasGlossaryTerm existing) throws AtlasBaseException {
if (newObj.equals(existing)) return;
Set<AtlasTermCategorizationHeader> categories = newObj.getCategories();
if (Objects.nonNull(categories)) {
Set<AtlasTermCategorizationHeader> existingCategories = existing.getCategories();
for (AtlasTermCategorizationHeader category : categories) {
if (Objects.isNull(category.getCategoryGuid())) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "Linked category guid can't be empty");
} else {
if (Objects.nonNull(existingCategories) && existingCategories.contains(category)) {
if (DEBUG_ENABLED) {
LOG.debug("Skipping linked category {}", category.getCategoryGuid());
}
continue;
}
if (DEBUG_ENABLED) {
LOG.debug("Creating relation between term = {} and category = {}", existing.getGuid(), category.getCategoryGuid());
}
createRelationship(defineCategorizedTerm(category, existing.getGuid()));
}
}
}
}
private void processAssociatedTerms(final AtlasGlossaryCategory glossaryCategory, final AtlasGlossaryCategory existing) throws AtlasBaseException {
if (Objects.equals(glossaryCategory.getTerms(), existing.getTerms())) return;
for (AtlasRelatedTermHeader linkedTerm : glossaryCategory.getTerms()) {
if (Objects.isNull(linkedTerm.getTermGuid())) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "Linked term guid can't be empty");
} else {
// Don't process existing child relation
Set<AtlasRelatedTermHeader> existingTerms = existing.getTerms();
if (Objects.nonNull(existingTerms) && existingTerms.contains(linkedTerm)) {
if (DEBUG_ENABLED) {
LOG.debug("Skipping linked term {}", linkedTerm.getTermGuid());
}
continue;
}
if (DEBUG_ENABLED) {
LOG.debug("Creating relation between category = {} and term = {}", existing.getGuid(), linkedTerm.getTermGuid());
}
// TODO: Accept the relationship attributes as well
createRelationship(defineCategorizedTerm(existing.getGuid(), linkedTerm));
}
}
}
private void processTermAnchor(final AtlasGlossaryTerm glossaryTerm, final AtlasGlossaryTerm saved) throws AtlasBaseException {
if (Objects.isNull(glossaryTerm.getAnchor())) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "glossaryTerm anchor mandatory attribute");
}
if (Objects.equals(glossaryTerm.getAnchor(), saved.getAnchor())) return;
if (Objects.isNull(glossaryTerm.getAnchor().getGlossaryGuid())) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "Anchor guid can't be empty");
} else {
if (DEBUG_ENABLED) {
LOG.debug("Creating relation between glossary = {} and term = {}", glossaryTerm.getAnchor().getGlossaryGuid(), saved.getGuid());
}
createRelationship(defineTermAnchorRelation(glossaryTerm.getAnchor().getGlossaryGuid(), glossaryTerm.getGuid()));
}
}
private void processCategoryAnchor(final AtlasGlossaryCategory newObj, final AtlasGlossaryCategory existing) throws AtlasBaseException {
if (Objects.isNull(newObj.getAnchor())) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "glossaryCategory anchor mandatory attribute");
}
// Don't process anchor if no change
if (Objects.equals(newObj.getAnchor(), existing.getAnchor())) return;
if (Objects.isNull(newObj.getAnchor().getGlossaryGuid())) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "Category anchor guid can't be empty");
} else {
if (DEBUG_ENABLED) {
LOG.debug("Creating relation between glossary = {} and category = {}", newObj.getAnchor().getGlossaryGuid(), existing.getGuid());
}
createRelationship(defineCategoryAnchorRelation(newObj.getAnchor().getGlossaryGuid(), existing.getGuid()));
}
}
private void processRelatedTerms(final AtlasGlossaryTerm incomingObj, final AtlasGlossaryTerm savedObj) throws AtlasBaseException {
if (incomingObj.hasTerms()) {
for (Map.Entry<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> entry : incomingObj.getRelatedTerms().entrySet()) {
AtlasGlossaryTerm.Relation relation = entry.getKey();
Set<AtlasRelatedTermHeader> terms = entry.getValue();
if (DEBUG_ENABLED) {
LOG.debug("Creating relation {}", relation);
LOG.debug("Related Term count = {}", terms.size());
}
if (Objects.nonNull(terms)) {
for (AtlasRelatedTermHeader atlasGlossaryTerm : terms) {
createRelationship(defineTermRelation(relation.getRelationName(), savedObj.getGuid(), atlasGlossaryTerm));
}
}
}
}
// TODO: Process other term relations as well
}
private void processCategoryChildren(final AtlasGlossaryCategory newObj, final AtlasGlossaryCategory existing) throws AtlasBaseException {
for (AtlasRelatedCategoryHeader childCategory : newObj.getChildrenCategories()) {
if (Objects.isNull(childCategory.getCategoryGuid())) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "Child category guid can't be empty");
} else {
// Don't process existing child relation
Set<AtlasRelatedCategoryHeader> existingChildren = existing.getChildrenCategories();
if (Objects.nonNull(existingChildren) && existingChildren.contains(childCategory)) {
if (DEBUG_ENABLED) {
LOG.debug("Skipping category child {}", childCategory.getCategoryGuid());
}
continue;
}
if (DEBUG_ENABLED) {
LOG.debug("Creating relation between glossary = {} and term = {}", existing.getGuid(), childCategory.getCategoryGuid());
}
// TODO: Accept the relationship attributes as well
createRelationship(defineCategoryHierarchyLink(existing.getGuid(), childCategory));
}
}
}
private void processParentCategory(final AtlasGlossaryCategory newObj, final AtlasGlossaryCategory existing) throws AtlasBaseException {
// Don't process unchanged parent
if (Objects.equals(newObj.getParentCategory(), existing.getParentCategory())) return;
if (Objects.isNull(newObj.getParentCategory().getCategoryGuid())) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "Parent category guid can't be empty");
} else {
if (DEBUG_ENABLED) {
LOG.debug("Creating category hierarchy b/w parent = {} and child = {}", newObj.getParentCategory().getCategoryGuid(), existing.getGuid());
}
createRelationship(defineCategoryHierarchyLink(newObj.getParentCategory(), newObj.getGuid()));
}
}
private Map<String, List<AtlasGlossaryTerm>> loadTerms(final Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> relatedTerms,
final int offset,
final int limit,
final SortOrder sortOrder) throws AtlasBaseException {
Map<String, List<AtlasGlossaryTerm>> ret = new HashMap<>();
for (Map.Entry<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> entry : relatedTerms.entrySet()) {
ret.put(entry.getKey().getRelationAttrName(), loadTerms(entry.getValue(), offset, limit, sortOrder));
}
return ret;
}
private List<AtlasGlossaryTerm> loadTerms(final Set<AtlasRelatedTermHeader> terms,
final int offset,
final int limit,
final SortOrder sortOrder) throws AtlasBaseException {
return loadTerms(new ArrayList<>(terms), offset, limit, sortOrder);
}
private List<AtlasGlossaryTerm> loadTerms(final List<AtlasRelatedTermHeader> terms,
final int offset,
final int limit,
final SortOrder sortOrder) throws AtlasBaseException {
Objects.requireNonNull(terms);
List<AtlasGlossaryTerm> ret;
ret = terms.stream().map(id -> getAtlasGlossaryTermSkeleton(id.getTermGuid())).collect(Collectors.toList());
Iterable<AtlasGlossaryTerm> loadedTerms = dataAccess.load(ret);
ret.clear();
loadedTerms.forEach(ret::add);
// Sort only when needed
if (sortOrder != null) {
ret.sort((o1, o2) -> sortOrder == SortOrder.ASCENDING ?
o1.getDisplayName().compareTo(o2.getDisplayName()) :
o2.getDisplayName().compareTo(o1.getDisplayName()));
}
return new PaginationHelper<>(ret, offset, limit).getPaginatedList();
}
private List<AtlasGlossaryCategory> loadCategories(final Set<AtlasRelatedCategoryHeader> categories,
final int offset,
final int limit,
final SortOrder sortOrder) throws AtlasBaseException {
return loadCategories(new ArrayList<>(categories), offset, limit, sortOrder);
}
private List<AtlasGlossaryCategory> loadCategories(final List<AtlasRelatedCategoryHeader> categories,
final int offset,
final int limit,
final SortOrder sortOrder) throws AtlasBaseException {
Objects.requireNonNull(categories);
List<AtlasGlossaryCategory> ret = categories.stream()
.map(id -> getAtlasGlossaryCategorySkeleton(id.getCategoryGuid()))
.collect(Collectors.toList());
Iterable<AtlasGlossaryCategory> loadedCategories = dataAccess.load(ret);
ret.clear();
loadedCategories.forEach(ret::add);
// Sort only when needed
if (sortOrder != null) {
ret.sort((o1, o2) -> sortOrder == SortOrder.ASCENDING ?
o1.getDisplayName().compareTo(o2.getDisplayName()) :
o2.getDisplayName().compareTo(o1.getDisplayName()));
}
return new PaginationHelper<>(ret, offset, limit).getPaginatedList();
}
private AtlasGlossaryTerm getAtlasGlossaryTermSkeleton(final String termGuid) {
AtlasGlossaryTerm glossaryTerm = new AtlasGlossaryTerm();
glossaryTerm.setGuid(termGuid);
return glossaryTerm;
}
private AtlasGlossaryCategory getAtlasGlossaryCategorySkeleton(final String categoryGuid) {
AtlasGlossaryCategory glossaryCategory = new AtlasGlossaryCategory();
glossaryCategory.setGuid(categoryGuid);
return glossaryCategory;
}
private void createRelationship(AtlasRelationship relationship) throws AtlasBaseException {
try {
relationshipStore.create(relationship);
} catch (AtlasBaseException e) {
if (!e.getAtlasErrorCode().equals(AtlasErrorCode.RELATIONSHIP_ALREADY_EXISTS)) {
throw e;
}
}
}
private AtlasRelationship defineTermAnchorRelation(String glossaryGuid, String termGuid) {
return new AtlasRelationship(TERM_ANCHOR, new AtlasObjectId(glossaryGuid), new AtlasObjectId(termGuid));
}
private AtlasRelationship defineCategoryAnchorRelation(String glossaryGuid, String categoryGuid) {
return new AtlasRelationship(CATEGORY_ANCHOR, new AtlasObjectId(glossaryGuid), new AtlasObjectId(categoryGuid));
}
private AtlasRelationship defineCategoryHierarchyLink(String parentCategoryGuid, AtlasRelatedCategoryHeader childCategory) {
AtlasRelationship relationship = new AtlasRelationship(CATEGORY_HIERARCHY, new AtlasObjectId(parentCategoryGuid), new AtlasObjectId(childCategory.getCategoryGuid()));
relationship.setAttribute("description", childCategory.getDescription());
return relationship;
}
private AtlasRelationship defineCategoryHierarchyLink(final AtlasRelatedCategoryHeader parentCategory, final String childGuid) {
AtlasRelationship relationship = new AtlasRelationship(CATEGORY_HIERARCHY, new AtlasObjectId(parentCategory.getCategoryGuid()), new AtlasObjectId(childGuid));
relationship.setAttribute("description", parentCategory.getDescription());
return relationship;
}
private AtlasRelationship defineCategorizedTerm(String categoryGuid, AtlasRelatedTermHeader relatedTermId) {
AtlasRelationship relationship = new AtlasRelationship(TERM_CATEGORIZATION, new AtlasObjectId(categoryGuid), new AtlasObjectId(relatedTermId.getTermGuid()));
relationship.setAttribute("expression", relatedTermId.getExpression());
relationship.setAttribute("description", relatedTermId.getDescription());
relationship.setAttribute("steward", relatedTermId.getSteward());
relationship.setAttribute("source", relatedTermId.getSource());
if (Objects.nonNull(relatedTermId.getStatus())) {
relationship.setAttribute("status", relatedTermId.getStatus().name());
}
return relationship;
}
private AtlasRelationship defineCategorizedTerm(AtlasTermCategorizationHeader relatedCategoryId, String termId) {
AtlasRelationship relationship = new AtlasRelationship(TERM_CATEGORIZATION, new AtlasObjectId(relatedCategoryId.getCategoryGuid()), new AtlasObjectId(termId));
relationship.setAttribute("description", relatedCategoryId.getDescription());
if (Objects.nonNull(relatedCategoryId.getStatus())) {
relationship.setAttribute("status", relatedCategoryId.getStatus().name());
}
return relationship;
}
private AtlasRelationship defineTermRelation(String relation, String end1TermGuid, AtlasRelatedTermHeader end2RelatedTerm) {
AtlasRelationship relationship = new AtlasRelationship(relation, new AtlasObjectId(end1TermGuid), new AtlasObjectId(end2RelatedTerm.getTermGuid()));
relationship.setAttribute("expression", end2RelatedTerm.getExpression());
relationship.setAttribute("description", end2RelatedTerm.getDescription());
relationship.setAttribute("steward", end2RelatedTerm.getSteward());
relationship.setAttribute("source", end2RelatedTerm.getSource());
if (Objects.nonNull(end2RelatedTerm.getStatus())) {
relationship.setAttribute("status", end2RelatedTerm.getStatus().name());
}
return relationship;
}
private AtlasRelationship defineTermAssignment(String termGuid, AtlasEntityHeader entityHeader) {
return new AtlasRelationship(TERM_ASSIGNMENT, new AtlasObjectId(termGuid), new AtlasObjectId(entityHeader.getGuid()));
}
static class PaginationHelper<T> {
private int pageStart;
private int pageEnd;
private int maxSize;
private List<T> items;
PaginationHelper(Collection<T> items, int offset, int limit) {
Objects.requireNonNull(items, "items can't be empty/null");
this.items = new ArrayList<>(items);
this.maxSize = items.size();
// If limit is negative then limit is effectively the maxSize, else the smaller one out of limit and maxSize
int adjustedLimit = limit < 0 ? maxSize : Integer.min(maxSize, limit);
// Page starting can only be between zero and adjustedLimit
pageStart = Integer.max(0, offset);
// Page end can't exceed the maxSize
pageEnd = Integer.min(adjustedLimit + pageStart, maxSize);
}
List<T> getPaginatedList() {
List<T> ret;
if (isValidOffset()) {
if (isPagingNeeded()) {
ret = items.subList(pageStart, pageEnd);
} else {
ret = items;
}
} else {
ret = Collections.emptyList();
}
return ret;
}
private boolean isPagingNeeded() {
return !(pageStart == 0 && pageEnd == maxSize) && pageStart <= pageEnd;
}
private boolean isValidOffset() {
return pageStart <= maxSize;
}
}
}
...@@ -27,14 +27,24 @@ import org.apache.commons.lang3.StringUtils; ...@@ -27,14 +27,24 @@ import org.apache.commons.lang3.StringUtils;
public abstract class AbstractDataTransferObject<T extends AtlasBaseModelObject> implements DataTransferObject<T> { public abstract class AbstractDataTransferObject<T extends AtlasBaseModelObject> implements DataTransferObject<T> {
private static final String DEFAULT_PREFIX = "Atlas";
private final AtlasTypeRegistry typeRegistry; private final AtlasTypeRegistry typeRegistry;
private final Class<T> objectType; private final Class<T> objectType;
private final String entityTypeName; private final String entityTypeName;
private final String alternateEntityTypeName;
protected AbstractDataTransferObject(AtlasTypeRegistry typeRegistry, Class<T> tClass) { protected AbstractDataTransferObject(AtlasTypeRegistry typeRegistry, Class<T> tClass, boolean isInternal) {
this.typeRegistry = typeRegistry; this.typeRegistry = typeRegistry;
this.objectType = tClass; this.objectType = tClass;
this.entityTypeName = Constants.INTERNAL_PROPERTY_KEY_PREFIX + objectType.getSimpleName(); if (isInternal) {
this.entityTypeName = Constants.INTERNAL_PROPERTY_KEY_PREFIX + objectType.getSimpleName();
this.alternateEntityTypeName = null;
} else {
this.entityTypeName = objectType.getSimpleName();
this.alternateEntityTypeName = entityTypeName.startsWith(DEFAULT_PREFIX) ? entityTypeName.substring(DEFAULT_PREFIX.length()) : null;
}
} }
@Override @Override
...@@ -44,7 +54,11 @@ public abstract class AbstractDataTransferObject<T extends AtlasBaseModelObject> ...@@ -44,7 +54,11 @@ public abstract class AbstractDataTransferObject<T extends AtlasBaseModelObject>
@Override @Override
public AtlasEntityType getEntityType() { public AtlasEntityType getEntityType() {
return typeRegistry.getEntityTypeByName(entityTypeName); AtlasEntityType ret = typeRegistry.getEntityTypeByName(entityTypeName);
if (ret == null) {
ret = typeRegistry.getEntityTypeByName(alternateEntityTypeName);
}
return ret;
} }
......
...@@ -17,29 +17,30 @@ ...@@ -17,29 +17,30 @@
*/ */
package org.apache.atlas.repository.ogm; package org.apache.atlas.repository.ogm;
import org.apache.atlas.type.AtlasTypeRegistry; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.inject.Inject; import javax.inject.Inject;
import java.lang.reflect.Type;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set;
@Component @Component
public class DTORegistry { public class DTORegistry {
private final Map<Type, DataTransferObject> typeDTOMap = new HashMap<>(); private static final Logger LOG = LoggerFactory.getLogger(DTORegistry.class);
private final Map<Class, DataTransferObject> typeDTOMap = new HashMap<>();
@Inject @Inject
public DTORegistry(AtlasTypeRegistry typeRegistry) { public DTORegistry(Set<DataTransferObject> availableDTOs) {
AtlasSavedSearchDTO savedSearchDTO = new AtlasSavedSearchDTO(typeRegistry); for (DataTransferObject availableDTO : availableDTOs) {
AtlasUserProfileDTO userProfileDTO = new AtlasUserProfileDTO(typeRegistry, savedSearchDTO); LOG.info("Registering DTO: {}", availableDTO.getClass().getSimpleName());
registerDTO(availableDTO);
registerDTO(savedSearchDTO); }
registerDTO(userProfileDTO);
} }
public <T extends DataTransferObject> DataTransferObject get(Type t) { public <T extends DataTransferObject> DataTransferObject get(Class t) {
return typeDTOMap.get(t); return typeDTOMap.get(t);
} }
......
...@@ -20,18 +20,29 @@ package org.apache.atlas.repository.ogm; ...@@ -20,18 +20,29 @@ package org.apache.atlas.repository.ogm;
import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasErrorCode;
import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.model.AtlasBaseModelObject; import org.apache.atlas.model.AtlasBaseModelObject;
import org.apache.atlas.model.instance.AtlasEntity;
import org.apache.atlas.model.instance.AtlasEntity.AtlasEntityWithExtInfo; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntityWithExtInfo;
import org.apache.atlas.model.instance.EntityMutationResponse; import org.apache.atlas.model.instance.EntityMutationResponse;
import org.apache.atlas.repository.store.graph.AtlasEntityStore; import org.apache.atlas.repository.store.graph.AtlasEntityStore;
import org.apache.atlas.repository.store.graph.v1.AtlasEntityStream; import org.apache.atlas.repository.store.graph.v1.AtlasEntityStream;
import org.apache.atlas.utils.AtlasPerfTracer;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.inject.Inject; import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Component @Component
public class DataAccess { public class DataAccess {
private static final Logger LOG = LoggerFactory.getLogger(DataAccess.class);
private static final Logger PERF_LOG = AtlasPerfTracer.getPerfLogger("repository.DataAccess");
private final AtlasEntityStore entityStore; private final AtlasEntityStore entityStore;
private final DTORegistry dtoRegistry; private final DTORegistry dtoRegistry;
...@@ -42,49 +53,186 @@ public class DataAccess { ...@@ -42,49 +53,186 @@ public class DataAccess {
} }
public <T extends AtlasBaseModelObject> T save(T obj) throws AtlasBaseException { public <T extends AtlasBaseModelObject> T save(T obj) throws AtlasBaseException {
DataTransferObject<T> dto = (DataTransferObject<T>)dtoRegistry.get(obj.getClass()); Objects.requireNonNull(obj, "Can't save a null object");
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DataAccess.save()");
}
DataTransferObject<T> dto = (DataTransferObject<T>) dtoRegistry.get(obj.getClass());
AtlasEntityWithExtInfo entityWithExtInfo = dto.toEntityWithExtInfo(obj);
EntityMutationResponse entityMutationResponse = entityStore.createOrUpdate(new AtlasEntityStream(entityWithExtInfo), false);
if (noEntityMutation(entityMutationResponse)) {
throw new AtlasBaseException(AtlasErrorCode.DATA_ACCESS_SAVE_FAILED, obj.toString());
}
AtlasEntityWithExtInfo entityWithExtInfo = dto.toEntityWithExtInfo(obj); // Since mutation context has guid information, attempt to set the same.
EntityMutationResponse entityMutationResponse = entityStore.createOrUpdate(new AtlasEntityStream(entityWithExtInfo), false); if (entityMutationResponse.getFirstEntityCreated() != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Object created");
}
obj.setGuid(entityMutationResponse.getFirstEntityCreated().getGuid());
} else if (entityMutationResponse.getFirstEntityUpdated() != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Object updated");
}
obj.setGuid(entityMutationResponse.getFirstEntityUpdated().getGuid());
}
if (hasError(entityMutationResponse)) { return this.load(obj);
throw new AtlasBaseException(AtlasErrorCode.DATA_ACCESS_SAVE_FAILED, obj.toString());
} finally {
AtlasPerfTracer.log(perf);
} }
return this.load(obj); }
public <T extends AtlasBaseModelObject> Iterable<T> save(Iterable<T> obj) throws AtlasBaseException {
Objects.requireNonNull(obj, "Can't save a null object");
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DataAccess.multiSave()");
}
List<T> ret = new ArrayList<>();
for (T o : obj) {
ret.add(save(o));
}
return ret;
} finally {
AtlasPerfTracer.log(perf);
}
}
public <T extends AtlasBaseModelObject> Iterable<T> load(final Iterable<T> objects) throws AtlasBaseException {
Objects.requireNonNull(objects, "Objects to load");
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DataAccess.multiLoad()");
}
List<AtlasBaseModelObject> ret = new ArrayList<>();
for (T object : objects) {
ret.add(load(object));
}
return (Iterable<T>) ret;
} finally {
AtlasPerfTracer.log(perf);
}
} }
public <T extends AtlasBaseModelObject> T load(T obj) throws AtlasBaseException { public <T extends AtlasBaseModelObject> T load(T obj) throws AtlasBaseException {
DataTransferObject<T> dto = (DataTransferObject<T>)dtoRegistry.get(obj.getClass()); return load(obj, false);
}
public <T extends AtlasBaseModelObject> T load(T obj, boolean loadDeleted) throws AtlasBaseException {
Objects.requireNonNull(obj, "Can't load a null object");
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DataAccess.load()");
}
DataTransferObject<T> dto = (DataTransferObject<T>) dtoRegistry.get(obj.getClass());
AtlasEntityWithExtInfo entityWithExtInfo;
AtlasEntityWithExtInfo entityWithExtInfo; if (StringUtils.isNotEmpty(obj.getGuid())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Load using GUID");
}
entityWithExtInfo = entityStore.getById(obj.getGuid());
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Load using unique attributes");
}
entityWithExtInfo = entityStore.getByUniqueAttributes(dto.getEntityType(), dto.getUniqueAttributes(obj));
}
if (StringUtils.isNotEmpty(obj.getGuid())) { if (!loadDeleted && entityWithExtInfo.getEntity().getStatus() == AtlasEntity.Status.DELETED) {
entityWithExtInfo = entityStore.getById(obj.getGuid()); throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_DELETED, obj.getGuid());
} else { }
entityWithExtInfo = entityStore.getByUniqueAttributes(dto.getEntityType(), dto.getUniqueAttributes(obj));
return dto.from(entityWithExtInfo);
} finally {
AtlasPerfTracer.log(perf);
} }
return dto.from(entityWithExtInfo);
} }
public void delete(String guid) throws AtlasBaseException {
Objects.requireNonNull(guid, "guid");
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DataAccess.delete()");
}
entityStore.deleteById(guid);
} finally {
AtlasPerfTracer.log(perf);
}
}
public void delete(List<String> guids) throws AtlasBaseException {
Objects.requireNonNull(guids, "guids");
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DataAccess.multiDelete()");
}
entityStore.deleteByIds(guids);
public void deleteUsingGuid(String guid) throws AtlasBaseException { } finally {
entityStore.deleteById(guid); AtlasPerfTracer.log(perf);
}
} }
public <T extends AtlasBaseModelObject> void delete(T obj) throws AtlasBaseException { public <T extends AtlasBaseModelObject> void delete(T obj) throws AtlasBaseException {
T object = load(obj); Objects.requireNonNull(obj, "Can't delete a null object");
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "DataAccess.delete()");
}
T object = load(obj);
if (object != null) {
delete(object.getGuid());
}
if (object != null) { } finally {
deleteUsingGuid(object.getGuid()); AtlasPerfTracer.log(perf);
} }
} }
private boolean hasError(EntityMutationResponse er) { // Helper functions
return (er == null || private boolean noEntityMutation(EntityMutationResponse er) {
!((er.getCreatedEntities() != null && er.getCreatedEntities().size() > 0) return er == null || (CollectionUtils.isEmpty(er.getCreatedEntities()) && CollectionUtils.isEmpty(er.getUpdatedEntities()));
|| (er.getUpdatedEntities() != null && er.getUpdatedEntities().size() > 0)
)
);
} }
} }
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.repository.ogm.glossary;
import org.apache.atlas.model.AtlasBaseModelObject;
import org.apache.atlas.model.glossary.enums.AtlasTermRelationshipStatus;
import org.apache.atlas.model.glossary.relations.AtlasGlossaryHeader;
import org.apache.atlas.model.glossary.relations.AtlasRelatedCategoryHeader;
import org.apache.atlas.model.glossary.relations.AtlasRelatedTermHeader;
import org.apache.atlas.model.glossary.relations.AtlasTermCategorizationHeader;
import org.apache.atlas.model.instance.AtlasRelatedObjectId;
import org.apache.atlas.model.instance.AtlasRelationship;
import org.apache.atlas.model.instance.AtlasStruct;
import org.apache.atlas.repository.ogm.AbstractDataTransferObject;
import org.apache.atlas.type.AtlasTypeRegistry;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public abstract class AbstractGlossaryDTO<T extends AtlasBaseModelObject> extends AbstractDataTransferObject<T> {
protected AbstractGlossaryDTO(final AtlasTypeRegistry typeRegistry, final Class<T> tClass, final boolean isInternal) {
super(typeRegistry, tClass, isInternal);
}
protected AtlasRelatedTermHeader constructRelatedTermId(AtlasRelatedObjectId relatedObjectId) {
AtlasRelatedTermHeader ret = new AtlasRelatedTermHeader();
ret.setTermGuid(relatedObjectId.getGuid());
ret.setRelationGuid(relatedObjectId.getRelationshipGuid());
AtlasStruct relationshipAttributes = relatedObjectId.getRelationshipAttributes();
if (relationshipAttributes != null) {
ret.setDescription((String) relationshipAttributes.getAttribute("description"));
ret.setExpression((String) relationshipAttributes.getAttribute("expression"));
ret.setSource((String) relationshipAttributes.getAttribute("source"));
ret.setSteward((String) relationshipAttributes.getAttribute("steward"));
Object status = relationshipAttributes.getAttribute("status");
if (status instanceof String) {
ret.setStatus(AtlasTermRelationshipStatus.valueOf((String) status));
} else if (status instanceof AtlasTermRelationshipStatus) {
ret.setStatus((AtlasTermRelationshipStatus) status);
}
}
return ret;
}
protected AtlasRelatedObjectId termIdToRelatedObjectId(AtlasRelatedTermHeader relatedTermId) {
AtlasRelatedObjectId ret = new AtlasRelatedObjectId();
ret.setGuid(relatedTermId.getTermGuid());
ret.setRelationshipGuid(relatedTermId.getRelationGuid());
AtlasStruct relationshipAttributes = new AtlasStruct();
relationshipAttributes.setAttribute("description", relatedTermId.getDescription());
relationshipAttributes.setAttribute("expression", relatedTermId.getExpression());
relationshipAttributes.setAttribute("source", relatedTermId.getSource());
relationshipAttributes.setAttribute("steward", relatedTermId.getSteward());
relationshipAttributes.setAttribute("status", relatedTermId.getStatus().name());
ret.setRelationshipAttributes(relationshipAttributes);
return ret;
}
protected AtlasRelatedCategoryHeader constructRelatedCategoryId(AtlasRelatedObjectId relatedObjectId) {
AtlasRelatedCategoryHeader ret = new AtlasRelatedCategoryHeader();
ret.setCategoryGuid(relatedObjectId.getGuid());
ret.setRelationGuid(relatedObjectId.getRelationshipGuid());
AtlasStruct relationshipAttributes = relatedObjectId.getRelationshipAttributes();
if (relationshipAttributes != null) {
ret.setDescription((String) relationshipAttributes.getAttribute("description"));
}
return ret;
}
protected AtlasRelatedObjectId relatedCategoryIdToRelatedObjectId(AtlasRelatedCategoryHeader relatedCategoryId) {
AtlasRelatedObjectId ret = new AtlasRelatedObjectId();
ret.setGuid(relatedCategoryId.getCategoryGuid());
ret.setRelationshipGuid(relatedCategoryId.getRelationGuid());
AtlasStruct relationshipAttributes = new AtlasStruct();
relationshipAttributes.setAttribute("description", relatedCategoryId.getDescription());
ret.setRelationshipAttributes(relationshipAttributes);
return ret;
}
protected AtlasGlossaryHeader constructGlossaryId(AtlasRelatedObjectId relatedObjectId) {
AtlasGlossaryHeader ret = new AtlasGlossaryHeader();
ret.setGlossaryGuid(relatedObjectId.getGuid());
ret.setRelationGuid(relatedObjectId.getRelationshipGuid());
return ret;
}
protected AtlasRelatedObjectId glossaryIdToRelatedObjectId(AtlasGlossaryHeader glossaryId) {
AtlasRelatedObjectId ret = new AtlasRelatedObjectId();
ret.setGuid(glossaryId.getGlossaryGuid());
ret.setRelationshipGuid(glossaryId.getRelationGuid());
return ret;
}
protected AtlasTermCategorizationHeader constructTermCategorizationId(final AtlasRelatedObjectId category) {
AtlasTermCategorizationHeader ret = new AtlasTermCategorizationHeader();
ret.setCategoryGuid(category.getGuid());
ret.setRelationGuid(category.getRelationshipGuid());
AtlasStruct relationshipAttributes = category.getRelationshipAttributes();
if (relationshipAttributes != null) {
ret.setDescription((String) relationshipAttributes.getAttribute("description"));
Object status = relationshipAttributes.getAttribute("status");
if (status instanceof AtlasTermRelationshipStatus) {
ret.setStatus((AtlasTermRelationshipStatus) status);
} else if (status instanceof String) {
ret.setStatus(AtlasTermRelationshipStatus.valueOf((String) status));
}
}
return ret;
}
protected Set<AtlasRelatedTermHeader> toRelatedTermIdsSet(Object relatedObjectIds) {
Set<AtlasRelatedTermHeader> ret = null;
if (relatedObjectIds instanceof Collection) {
ret = new HashSet<>();
for (Object t : (Collection) relatedObjectIds) {
if (t instanceof AtlasRelatedObjectId) {
if (((AtlasRelatedObjectId) t).getRelationshipStatus() == AtlasRelationship.Status.ACTIVE) {
ret.add(constructRelatedTermId((AtlasRelatedObjectId) t));
}
}
}
}
return ret;
}
}
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.repository.ogm.glossary;
import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.model.glossary.AtlasGlossaryCategory;
import org.apache.atlas.model.instance.AtlasEntity;
import org.apache.atlas.model.instance.AtlasRelatedObjectId;
import org.apache.atlas.model.instance.AtlasRelationship;
import org.apache.atlas.type.AtlasTypeRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@Component
public class AtlasGlossaryCategoryDTO extends AbstractGlossaryDTO<AtlasGlossaryCategory> {
private static final Logger LOG = LoggerFactory.getLogger(AtlasGlossaryCategoryDTO.class);
@Inject
protected AtlasGlossaryCategoryDTO(final AtlasTypeRegistry typeRegistry) {
super(typeRegistry, AtlasGlossaryCategory.class, true);
}
@Override
public AtlasGlossaryCategory from(final AtlasEntity entity) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> AtlasGlossaryCategoryDTO.from()", entity);
}
Objects.requireNonNull(entity, "entity");
AtlasGlossaryCategory ret = new AtlasGlossaryCategory();
ret.setGuid(entity.getGuid());
ret.setQualifiedName((String) entity.getAttribute("qualifiedName"));
ret.setDisplayName((String) entity.getAttribute("displayName"));
ret.setShortDescription((String) entity.getAttribute("shortDescription"));
ret.setLongDescription((String) entity.getAttribute("longDescription"));
Object anchor = entity.getRelationshipAttribute("anchor");
if (anchor instanceof AtlasRelatedObjectId) {
LOG.debug("Processing anchor");
if (((AtlasRelatedObjectId) anchor).getRelationshipStatus() == AtlasRelationship.Status.ACTIVE) {
ret.setAnchor(constructGlossaryId((AtlasRelatedObjectId) anchor));
}
}
Object parentCategory = entity.getRelationshipAttribute("parentCategory");
if (parentCategory instanceof AtlasRelatedObjectId) {
LOG.debug("Processing parentCategory");
if (((AtlasRelatedObjectId) parentCategory).getRelationshipStatus() == AtlasRelationship.Status.ACTIVE) {
ret.setParentCategory(constructRelatedCategoryId((AtlasRelatedObjectId) parentCategory));
}
}
Object childrenCategories = entity.getRelationshipAttribute("childrenCategories");
if (childrenCategories instanceof Collection) {
LOG.debug("Processing childrenCategories");
for (Object child : (Collection) childrenCategories) {
if (child instanceof AtlasRelatedObjectId) {
if (((AtlasRelatedObjectId) child).getRelationshipStatus() == AtlasRelationship.Status.ACTIVE) {
ret.addChild(constructRelatedCategoryId((AtlasRelatedObjectId) child));
}
}
}
}
Object terms = entity.getRelationshipAttribute("terms");
if (terms instanceof Collection) {
LOG.debug("Processing terms");
for (Object term : (Collection) terms) {
if (term instanceof AtlasRelatedObjectId) {
if (((AtlasRelatedObjectId) term).getRelationshipStatus() == AtlasRelationship.Status.ACTIVE) {
ret.addTerm(constructRelatedTermId((AtlasRelatedObjectId) term));
}
}
}
}
return ret;
}
@Override
public AtlasGlossaryCategory from(final AtlasEntity.AtlasEntityWithExtInfo entityWithExtInfo) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> AtlasGlossaryCategoryDTO.from()", entityWithExtInfo);
}
Objects.requireNonNull(entityWithExtInfo, "entity");
AtlasGlossaryCategory ret = from(entityWithExtInfo.getEntity());
if (LOG.isDebugEnabled()) {
LOG.debug("<== AtlasGlossaryCategoryDTO.from() : {}", ret);
}
return ret;
}
@Override
public AtlasEntity toEntity(final AtlasGlossaryCategory obj) throws AtlasBaseException {
if (LOG.isDebugEnabled()) {
LOG.debug("==> AtlasGlossaryCategoryDTO.toEntity()", obj);
}
Objects.requireNonNull(obj, "atlasGlossaryCategory");
Objects.requireNonNull(obj.getQualifiedName(), "atlasGlossaryCategory qualifiedName must be specified");
Objects.requireNonNull(obj.getAnchor(), "atlasGlossaryCategory anchor must be specified");
AtlasEntity ret = getDefaultAtlasEntity(obj);
ret.setAttribute("qualifiedName", obj.getQualifiedName());
ret.setAttribute("displayName", obj.getDisplayName());
ret.setAttribute("shortDescription", obj.getShortDescription());
ret.setAttribute("longDescription", obj.getLongDescription());
if (LOG.isDebugEnabled()) {
LOG.debug("<== AtlasGlossaryCategoryDTO.toEntity() : {}", ret);
}
return ret;
}
@Override
public AtlasEntity.AtlasEntityWithExtInfo toEntityWithExtInfo(final AtlasGlossaryCategory obj) throws AtlasBaseException {
if (LOG.isDebugEnabled()) {
LOG.debug("==> AtlasGlossaryCategoryDTO.toEntityWithExtInfo()", obj);
}
Objects.requireNonNull(obj, "atlasGlossaryCategory");
AtlasEntity.AtlasEntityWithExtInfo ret = new AtlasEntity.AtlasEntityWithExtInfo(toEntity(obj));
if (LOG.isDebugEnabled()) {
LOG.debug("<== AtlasGlossaryCategoryDTO.toEntityWithExtInfo() : {}", ret);
}
return ret;
}
@Override
public Map<String, Object> getUniqueAttributes(final AtlasGlossaryCategory obj) {
Map<String, Object> ret = new HashMap<>();
ret.put("qualifiedName", obj.getQualifiedName());
return ret;
}
}
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.repository.ogm.glossary;
import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.model.glossary.AtlasGlossary;
import org.apache.atlas.model.instance.AtlasEntity;
import org.apache.atlas.model.instance.AtlasRelatedObjectId;
import org.apache.atlas.model.instance.AtlasRelationship;
import org.apache.atlas.type.AtlasTypeRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@Component
public class AtlasGlossaryDTO extends AbstractGlossaryDTO<AtlasGlossary> {
private static final Logger LOG = LoggerFactory.getLogger(AtlasGlossaryDTO.class);
@Inject
public AtlasGlossaryDTO(AtlasTypeRegistry typeRegistry) {
super(typeRegistry, AtlasGlossary.class, true);
}
@Override
public AtlasGlossary from(final AtlasEntity entity) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> AtlasGlossaryDTO.from()", entity);
}
Objects.requireNonNull(entity, "entity");
AtlasGlossary ret = new AtlasGlossary();
ret.setGuid(entity.getGuid());
ret.setQualifiedName((String) entity.getAttribute("qualifiedName"));
ret.setDisplayName((String) entity.getAttribute("displayName"));
ret.setShortDescription((String) entity.getAttribute("shortDescription"));
ret.setLongDescription((String) entity.getAttribute("longDescription"));
ret.setLanguage((String) entity.getAttribute("language"));
ret.setUsage((String) entity.getAttribute("usage"));
Object categoriesAttr = entity.getRelationshipAttribute("categories");
Object termsAttr = entity.getRelationshipAttribute("terms");
// Populate categories
if (Objects.nonNull(categoriesAttr)) {
LOG.debug("Processing categories");
if (categoriesAttr instanceof Collection) {
for (Object o : (Collection) categoriesAttr) {
if (o instanceof AtlasRelatedObjectId) {
if (((AtlasRelatedObjectId) o).getRelationshipStatus() == AtlasRelationship.Status.ACTIVE) {
ret.addCategory(constructRelatedCategoryId((AtlasRelatedObjectId) o));
}
}
}
}
}
// Populate terms
if (Objects.nonNull(termsAttr)) {
LOG.debug("Processing terms");
if (termsAttr instanceof Collection) {
for (Object o : (Collection) termsAttr) {
if (o instanceof AtlasRelatedObjectId) {
if (((AtlasRelatedObjectId) o).getRelationshipStatus() == AtlasRelationship.Status.ACTIVE) {
ret.addTerm(constructRelatedTermId((AtlasRelatedObjectId) o));
}
}
}
}
}
return ret;
}
@Override
public AtlasGlossary from(final AtlasEntity.AtlasEntityWithExtInfo entityWithExtInfo) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> AtlasGlossaryDTO.from()",entityWithExtInfo);
}
Objects.requireNonNull(entityWithExtInfo, "entity");
AtlasGlossary ret = from(entityWithExtInfo.getEntity());
if (LOG.isDebugEnabled()) {
LOG.debug("<== AtlasGlossaryDTO.from() : {}", ret);
}
return ret;
}
@Override
public AtlasEntity toEntity(final AtlasGlossary obj) throws AtlasBaseException {
if (LOG.isDebugEnabled()) {
LOG.debug("==> AtlasGlossaryDTO.toEntity()", obj);
}
Objects.requireNonNull(obj, "atlasGlossary");
Objects.requireNonNull(obj.getQualifiedName(), "atlasGlossary qualifiedName must be specified");
AtlasEntity ret = getDefaultAtlasEntity(obj);
ret.setAttribute("qualifiedName", obj.getQualifiedName());
ret.setAttribute("displayName", obj.getDisplayName());
ret.setAttribute("shortDescription", obj.getShortDescription());
ret.setAttribute("longDescription", obj.getLongDescription());
ret.setAttribute("language", obj.getLanguage());
ret.setAttribute("usage", obj.getUsage());
if (LOG.isDebugEnabled()) {
LOG.debug("<== AtlasGlossaryDTO.toEntity() : {}", ret);
}
return ret;
}
@Override
public AtlasEntity.AtlasEntityWithExtInfo toEntityWithExtInfo(final AtlasGlossary obj) throws AtlasBaseException {
if (LOG.isDebugEnabled()) {
LOG.debug("==> AtlasGlossaryDTO.toEntityWithExtInfo()", obj);
}
Objects.requireNonNull(obj, "atlasGlossary");
AtlasEntity entity = toEntity(obj);
AtlasEntity.AtlasEntityWithExtInfo ret = new AtlasEntity.AtlasEntityWithExtInfo(entity);
if (LOG.isDebugEnabled()) {
LOG.debug("<== AtlasGlossaryDTO.toEntityWithExtInfo() : {}", ret);
}
return ret;
}
@Override
public Map<String, Object> getUniqueAttributes(final AtlasGlossary obj) {
Map<String, Object> ret = new HashMap<>();
ret.put("qualifiedName", obj.getQualifiedName());
return ret;
}
}
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.repository.ogm.glossary;
import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.model.glossary.AtlasGlossaryTerm;
import org.apache.atlas.model.instance.AtlasEntity;
import org.apache.atlas.model.instance.AtlasEntityHeader;
import org.apache.atlas.model.instance.AtlasRelatedObjectId;
import org.apache.atlas.model.instance.AtlasRelationship;
import org.apache.atlas.type.AtlasTypeRegistry;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Component
public class AtlasGlossaryTermDTO extends AbstractGlossaryDTO<AtlasGlossaryTerm> {
private static final Logger LOG = LoggerFactory.getLogger(AtlasGlossaryTermDTO.class);
@Inject
protected AtlasGlossaryTermDTO(final AtlasTypeRegistry typeRegistry) {
super(typeRegistry, AtlasGlossaryTerm.class, true);
}
@Override
public AtlasGlossaryTerm from(final AtlasEntity entity) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> AtlasGlossaryTermDTO.from()", entity);
}
Objects.requireNonNull(entity, "entity");
AtlasGlossaryTerm ret = new AtlasGlossaryTerm();
ret.setGuid(entity.getGuid());
ret.setQualifiedName((String) entity.getAttribute("qualifiedName"));
ret.setDisplayName((String) entity.getAttribute("displayName"));
ret.setShortDescription((String) entity.getAttribute("shortDescription"));
ret.setLongDescription((String) entity.getAttribute("longDescription"));
ret.setExamples((List<String>) entity.getAttribute("examples"));
ret.setAbbreviation((String) entity.getAttribute("abbreviation"));
Object anchor = entity.getRelationshipAttribute("anchor");
if (anchor instanceof AtlasRelatedObjectId) {
LOG.debug("Processing anchor");
if (((AtlasRelatedObjectId) anchor).getRelationshipStatus() == AtlasRelationship.Status.ACTIVE) {
ret.setAnchor(constructGlossaryId((AtlasRelatedObjectId) anchor));
}
}
Object categories = entity.getRelationshipAttribute("categories");
if (categories instanceof Collection) {
LOG.debug("Processing categories");
for (Object category : (Collection) categories) {
if (category instanceof AtlasRelatedObjectId) {
if (((AtlasRelatedObjectId) category).getRelationshipStatus() == AtlasRelationship.Status.ACTIVE) {
ret.addCategory(constructTermCategorizationId((AtlasRelatedObjectId) category));
}
}
}
}
// ret.setContextRelevantTerms(toRelatedObjectIdsSet(entity.getRelationshipAttribute("contextRelevantTerms")));
// ret.setUsedInContexts(toRelatedObjectIdsSet(entity.getRelationshipAttribute("usedInContexts")));
Object assignedEntities = entity.getRelationshipAttribute("assignedEntities");
if (assignedEntities instanceof Collection) {
LOG.debug("Processing assigned entities");
for (Object assignedEntity : (Collection) assignedEntities) {
if (assignedEntity instanceof AtlasRelatedObjectId) {
AtlasRelatedObjectId id = (AtlasRelatedObjectId) assignedEntity;
if (id.getRelationshipStatus() == AtlasRelationship.Status.ACTIVE) {
AtlasEntityHeader entityHeader = new AtlasEntityHeader(id.getTypeName(), id.getGuid(), id.getUniqueAttributes());
if (entityHeader.getAttributes() == null) {
entityHeader.setAttributes(new HashMap<>());
}
entityHeader.getAttributes().put("relationGuid", id.getRelationshipGuid());
ret.addAssignedEntity(entityHeader);
}
}
}
}
Object seeAlso = entity.getRelationshipAttribute("seeAlso");
if (seeAlso instanceof Collection && CollectionUtils.isNotEmpty((Collection) seeAlso)) {
LOG.debug("Processing RelatedTerm(seeAlso)");
ret.setSeeAlso(toRelatedTermIdsSet(seeAlso));
}
Object synonyms = entity.getRelationshipAttribute("synonyms");
if (synonyms instanceof Collection && CollectionUtils.isNotEmpty((Collection) synonyms)) {
LOG.debug("Processing Synonym(synonyms)");
ret.setSynonyms(toRelatedTermIdsSet(synonyms));
}
Object antonyms = entity.getRelationshipAttribute("antonyms");
if (antonyms instanceof Collection && CollectionUtils.isNotEmpty((Collection) antonyms)) {
LOG.debug("Processing Antonym(antonyms)");
ret.setAntonyms(toRelatedTermIdsSet(antonyms));
}
Object preferredTerms = entity.getRelationshipAttribute("preferredTerms");
if (preferredTerms instanceof Collection && CollectionUtils.isNotEmpty((Collection) preferredTerms)) {
LOG.debug("Processing preferredTerm(preferredTerms)");
ret.setPreferredTerms(toRelatedTermIdsSet(preferredTerms));
}
Object preferredToTerms = entity.getRelationshipAttribute("preferredToTerms");
if (preferredToTerms instanceof Collection && CollectionUtils.isNotEmpty((Collection) preferredToTerms)) {
LOG.debug("Processing preferredTerm(preferredToTerms)");
ret.setPreferredToTerms(toRelatedTermIdsSet(preferredToTerms));
}
Object replacementTerms = entity.getRelationshipAttribute("replacementTerms");
if (replacementTerms instanceof Collection && CollectionUtils.isNotEmpty((Collection) replacementTerms)) {
LOG.debug("Processing ReplacementTerm(replacementTerms)");
ret.setReplacementTerms(toRelatedTermIdsSet(replacementTerms));
}
Object replacedBy = entity.getRelationshipAttribute("replacedBy");
if (replacedBy instanceof Collection && CollectionUtils.isNotEmpty((Collection) replacedBy)) {
LOG.debug("Processing ReplacementTerm(replacedBy)");
ret.setReplacedBy(toRelatedTermIdsSet(replacedBy));
}
Object translationTerms = entity.getRelationshipAttribute("translationTerms");
if (translationTerms instanceof Collection && CollectionUtils.isNotEmpty((Collection) translationTerms)) {
LOG.debug("Processing Translation(translationTerms)");
ret.setTranslationTerms(toRelatedTermIdsSet(translationTerms));
}
Object translatedTerms = entity.getRelationshipAttribute("translatedTerms");
if (translatedTerms instanceof Collection && CollectionUtils.isNotEmpty((Collection) translatedTerms)) {
LOG.debug("Processing Translation(translatedTerms)");
ret.setTranslatedTerms(toRelatedTermIdsSet(translatedTerms));
}
Object isA = entity.getRelationshipAttribute("isA");
if (isA instanceof Collection && CollectionUtils.isNotEmpty((Collection) isA)) {
LOG.debug("Processing Classifies(isA)");
ret.setIsA(toRelatedTermIdsSet(isA));
}
Object classifies = entity.getRelationshipAttribute("classifies");
if (classifies instanceof Collection && CollectionUtils.isNotEmpty((Collection) classifies)) {
LOG.debug("Processing Classifies(classifies)");
ret.setClassifies(toRelatedTermIdsSet(classifies));
}
Object validValues = entity.getRelationshipAttribute("validValues");
if (validValues instanceof Collection && CollectionUtils.isNotEmpty((Collection) validValues)) {
LOG.debug("Processing validValue(validValues)");
ret.setValidValues(toRelatedTermIdsSet(validValues));
}
Object validValuesFor = entity.getRelationshipAttribute("validValuesFor");
if (validValuesFor instanceof Collection && CollectionUtils.isNotEmpty((Collection) validValuesFor)) {
LOG.debug("Processing validValue(validValuesFor)");
ret.setValidValuesFor(toRelatedTermIdsSet(validValuesFor));
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== AtlasGlossaryTermDTO.from() : {}", ret);
}
return ret;
}
@Override
public AtlasGlossaryTerm from(final AtlasEntity.AtlasEntityWithExtInfo entityWithExtInfo) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> AtlasGlossaryTermDTO.from()", entityWithExtInfo);
}
Objects.requireNonNull(entityWithExtInfo, "entityWithExtInfo");
AtlasGlossaryTerm ret = from(entityWithExtInfo.getEntity());
if (LOG.isDebugEnabled()) {
LOG.debug("<== AtlasGlossaryTermDTO.from() : {}", ret);
}
return ret;
}
@Override
public AtlasEntity toEntity(final AtlasGlossaryTerm obj) throws AtlasBaseException {
if (LOG.isDebugEnabled()) {
LOG.debug("==> AtlasGlossaryTermDTO.toEntity()", obj);
}
Objects.requireNonNull(obj, "atlasGlossaryTerm");
Objects.requireNonNull(obj.getQualifiedName(), "atlasGlossaryTerm qualifiedName must be specified");
Objects.requireNonNull(obj.getAnchor(), "atlasGlossaryTerm anchor must be specified");
AtlasEntity ret = getDefaultAtlasEntity(obj);
ret.setAttribute("qualifiedName", obj.getQualifiedName());
ret.setAttribute("displayName", obj.getDisplayName());
ret.setAttribute("shortDescription", obj.getShortDescription());
ret.setAttribute("longDescription", obj.getLongDescription());
ret.setAttribute("examples", obj.getExamples());
ret.setAttribute("abbreviation", obj.getAbbreviation());
if (LOG.isDebugEnabled()) {
LOG.debug("<== AtlasGlossaryTermDTO.toEntity() : {}", ret);
}
return ret;
}
@Override
public AtlasEntity.AtlasEntityWithExtInfo toEntityWithExtInfo(final AtlasGlossaryTerm obj) throws AtlasBaseException {
if (LOG.isDebugEnabled()) {
LOG.debug("==> AtlasGlossaryTermDTO.toEntityWithExtInfo()", obj);
}
Objects.requireNonNull(obj, "atlasGlossaryTerm");
AtlasEntity entity = toEntity(obj);
AtlasEntity.AtlasEntityWithExtInfo ret = new AtlasEntity.AtlasEntityWithExtInfo(entity);
if (LOG.isDebugEnabled()) {
LOG.debug("<== AtlasGlossaryTermDTO.toEntityWithExtInfo() : {}", ret);
}
return ret;
}
@Override
public Map<String, Object> getUniqueAttributes(final AtlasGlossaryTerm obj) {
Map<String, Object> ret = new HashMap<>();
ret.put("qualifiedName", obj.getQualifiedName());
return ret;
}
}
...@@ -15,21 +15,25 @@ ...@@ -15,21 +15,25 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.atlas.repository.ogm; package org.apache.atlas.repository.ogm.profiles;
import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.model.discovery.SearchParameters; import org.apache.atlas.model.discovery.SearchParameters;
import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasEntity;
import org.apache.atlas.model.instance.AtlasEntity.AtlasEntityWithExtInfo; import org.apache.atlas.model.instance.AtlasEntity.AtlasEntityWithExtInfo;
import org.apache.atlas.model.profile.AtlasUserSavedSearch; import org.apache.atlas.model.profile.AtlasUserSavedSearch;
import org.apache.atlas.repository.ogm.AbstractDataTransferObject;
import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasType;
import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.type.AtlasTypeRegistry;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@Component
public class AtlasSavedSearchDTO extends AbstractDataTransferObject<AtlasUserSavedSearch> { public class AtlasSavedSearchDTO extends AbstractDataTransferObject<AtlasUserSavedSearch> {
private static final String PROPERTY_NAME = "name"; private static final String PROPERTY_NAME = "name";
private static final String PROPERTY_OWNER_NAME = "ownerName"; private static final String PROPERTY_OWNER_NAME = "ownerName";
...@@ -38,8 +42,9 @@ public class AtlasSavedSearchDTO extends AbstractDataTransferObject<AtlasUserSav ...@@ -38,8 +42,9 @@ public class AtlasSavedSearchDTO extends AbstractDataTransferObject<AtlasUserSav
private static final String PROPERTY_SEARCH_TYPE = "searchType"; private static final String PROPERTY_SEARCH_TYPE = "searchType";
private static final String PROPERTY_UI_PARAMETERS = "uiParameters"; private static final String PROPERTY_UI_PARAMETERS = "uiParameters";
@Inject
public AtlasSavedSearchDTO(AtlasTypeRegistry typeRegistry) { public AtlasSavedSearchDTO(AtlasTypeRegistry typeRegistry) {
super(typeRegistry, AtlasUserSavedSearch.class); super(typeRegistry, AtlasUserSavedSearch.class, true);
} }
@Override @Override
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.apache.atlas.repository.ogm; package org.apache.atlas.repository.ogm.profiles;
import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasEntity;
...@@ -23,10 +23,14 @@ import org.apache.atlas.model.instance.AtlasEntity.AtlasEntityWithExtInfo; ...@@ -23,10 +23,14 @@ import org.apache.atlas.model.instance.AtlasEntity.AtlasEntityWithExtInfo;
import org.apache.atlas.model.instance.AtlasObjectId; import org.apache.atlas.model.instance.AtlasObjectId;
import org.apache.atlas.model.profile.AtlasUserProfile; import org.apache.atlas.model.profile.AtlasUserProfile;
import org.apache.atlas.model.profile.AtlasUserSavedSearch; import org.apache.atlas.model.profile.AtlasUserSavedSearch;
import org.apache.atlas.repository.ogm.AbstractDataTransferObject;
import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.type.AtlasTypeRegistry;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.util.*; import java.util.*;
@Component
public class AtlasUserProfileDTO extends AbstractDataTransferObject<AtlasUserProfile> { public class AtlasUserProfileDTO extends AbstractDataTransferObject<AtlasUserProfile> {
private final String PROPERTY_USER_NAME = "name"; private final String PROPERTY_USER_NAME = "name";
private final String PROPERTY_FULL_NAME = "fullName"; private final String PROPERTY_FULL_NAME = "fullName";
...@@ -34,8 +38,9 @@ public class AtlasUserProfileDTO extends AbstractDataTransferObject<AtlasUserPro ...@@ -34,8 +38,9 @@ public class AtlasUserProfileDTO extends AbstractDataTransferObject<AtlasUserPro
private final AtlasSavedSearchDTO savedSearchDTO; private final AtlasSavedSearchDTO savedSearchDTO;
@Inject
public AtlasUserProfileDTO(AtlasTypeRegistry typeRegistry, AtlasSavedSearchDTO savedSearchDTO) { public AtlasUserProfileDTO(AtlasTypeRegistry typeRegistry, AtlasSavedSearchDTO savedSearchDTO) {
super(typeRegistry, AtlasUserProfile.class); super(typeRegistry, AtlasUserProfile.class, true);
this.savedSearchDTO = savedSearchDTO; this.savedSearchDTO = savedSearchDTO;
} }
......
...@@ -60,16 +60,16 @@ public class AtlasEntityChangeNotifier { ...@@ -60,16 +60,16 @@ public class AtlasEntityChangeNotifier {
private final Set<EntityChangeListener> entityChangeListeners; private final Set<EntityChangeListener> entityChangeListeners;
private final Set<EntityChangeListenerV2> entityChangeListenersV2; private final Set<EntityChangeListenerV2> entityChangeListenersV2;
private final AtlasInstanceConverter instanceConverter; private final AtlasInstanceConverter instanceConverter;
private final FullTextMapperV2 fullTextMapperV2;
@Inject
private FullTextMapperV2 fullTextMapperV2;
@Inject @Inject
public AtlasEntityChangeNotifier(Set<EntityChangeListener> entityChangeListeners, Set<EntityChangeListenerV2> entityChangeListenersV2, public AtlasEntityChangeNotifier(Set<EntityChangeListener> entityChangeListeners, Set<EntityChangeListenerV2> entityChangeListenersV2,
AtlasInstanceConverter instanceConverter) { AtlasInstanceConverter instanceConverter, final FullTextMapperV2 fullTextMapperV2) {
this.entityChangeListeners = entityChangeListeners; this.entityChangeListeners = entityChangeListeners;
this.entityChangeListenersV2 = entityChangeListenersV2; this.entityChangeListenersV2 = entityChangeListenersV2;
this.instanceConverter = instanceConverter; this.instanceConverter = instanceConverter;
this.fullTextMapperV2 = fullTextMapperV2;
} }
public void onEntitiesMutated(EntityMutationResponse entityMutationResponse, boolean isImport) throws AtlasBaseException { public void onEntitiesMutated(EntityMutationResponse entityMutationResponse, boolean isImport) throws AtlasBaseException {
......
...@@ -20,6 +20,7 @@ package org.apache.atlas.repository.store.graph.v1; ...@@ -20,6 +20,7 @@ package org.apache.atlas.repository.store.graph.v1;
import org.apache.atlas.ApplicationProperties; import org.apache.atlas.ApplicationProperties;
import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasErrorCode;
import org.apache.atlas.SortOrder;
import org.apache.atlas.discovery.SearchProcessor; import org.apache.atlas.discovery.SearchProcessor;
import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.model.TypeCategory; import org.apache.atlas.model.TypeCategory;
...@@ -54,6 +55,7 @@ import java.util.Set; ...@@ -54,6 +55,7 @@ import java.util.Set;
import static org.apache.atlas.repository.Constants.INDEX_SEARCH_VERTEX_PREFIX_DEFAULT; import static org.apache.atlas.repository.Constants.INDEX_SEARCH_VERTEX_PREFIX_DEFAULT;
import static org.apache.atlas.repository.Constants.INDEX_SEARCH_VERTEX_PREFIX_PROPERTY; import static org.apache.atlas.repository.Constants.INDEX_SEARCH_VERTEX_PREFIX_PROPERTY;
import static org.apache.atlas.repository.graphdb.AtlasGraphQuery.SortOrder.*;
/** /**
* Utility methods for Graph. * Utility methods for Graph.
...@@ -338,20 +340,30 @@ public class AtlasGraphUtilsV1 { ...@@ -338,20 +340,30 @@ public class AtlasGraphUtilsV1 {
return vertex; return vertex;
} }
public static List<String> findEntityGUIDsByType(String typename) { public static List<String> findEntityGUIDsByType(String typename, SortOrder sortOrder) {
AtlasGraphQuery query = AtlasGraphProvider.getGraphInstance().query() AtlasGraphQuery query = AtlasGraphProvider.getGraphInstance().query()
.has(Constants.ENTITY_TYPE_PROPERTY_KEY, typename); .has(Constants.ENTITY_TYPE_PROPERTY_KEY, typename);
if (sortOrder != null) {
AtlasGraphQuery.SortOrder qrySortOrder = sortOrder == SortOrder.ASCENDING ? ASC : DESC;
query.orderBy(Constants.QUALIFIED_NAME, qrySortOrder);
}
Iterator<AtlasVertex> results = query.vertices().iterator(); Iterator<AtlasVertex> results = query.vertices().iterator();
ArrayList<String> ret = new ArrayList<>();
if (!results.hasNext()) { if (!results.hasNext()) {
return Collections.emptyList(); return Collections.emptyList();
} }
ArrayList<String> entityList = new ArrayList<>();
while (results.hasNext()) { while (results.hasNext()) {
entityList.add(getIdFromVertex(results.next())); ret.add(getIdFromVertex(results.next()));
} }
return entityList; return ret;
}
public static List<String> findEntityGUIDsByType(String typename) {
return findEntityGUIDsByType(typename, null);
} }
public static boolean relationshipTypeHasInstanceEdges(String typeName) throws AtlasBaseException { public static boolean relationshipTypeHasInstanceEdges(String typeName) throws AtlasBaseException {
......
...@@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.type.TypeReference; ...@@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasErrorCode;
import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.model.TimeBoundary; import org.apache.atlas.model.TimeBoundary;
import org.apache.atlas.model.glossary.relations.AtlasTermAssignmentHeader;
import org.apache.atlas.model.instance.AtlasClassification; import org.apache.atlas.model.instance.AtlasClassification;
import org.apache.atlas.model.instance.AtlasClassification.PropagationState; import org.apache.atlas.model.instance.AtlasClassification.PropagationState;
import org.apache.atlas.model.instance.AtlasEntity; import org.apache.atlas.model.instance.AtlasEntity;
...@@ -68,6 +69,7 @@ import java.util.Iterator; ...@@ -68,6 +69,7 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
import static org.apache.atlas.model.instance.AtlasClassification.PropagationState.ACTIVE; import static org.apache.atlas.model.instance.AtlasClassification.PropagationState.ACTIVE;
import static org.apache.atlas.model.instance.AtlasClassification.PropagationState.DELETED; import static org.apache.atlas.model.instance.AtlasClassification.PropagationState.DELETED;
...@@ -220,6 +222,11 @@ public final class EntityGraphRetriever { ...@@ -220,6 +222,11 @@ public final class EntityGraphRetriever {
ret.setClassifications(classifications); ret.setClassifications(classifications);
ret.setClassificationNames(classificationNames); ret.setClassificationNames(classificationNames);
} }
if (CollectionUtils.isNotEmpty(entity.getMeanings())) {
ret.setMeanings(entity.getMeanings());
ret.setMeaningNames(entity.getMeanings().stream().map(AtlasTermAssignmentHeader::getDisplayText).collect(Collectors.toList()));
}
} }
return ret; return ret;
...@@ -359,6 +366,8 @@ public final class EntityGraphRetriever { ...@@ -359,6 +366,8 @@ public final class EntityGraphRetriever {
ret.setStatus(GraphHelper.getStatus(entityVertex)); ret.setStatus(GraphHelper.getStatus(entityVertex));
ret.setClassificationNames(getAllTraitNames(entityVertex)); ret.setClassificationNames(getAllTraitNames(entityVertex));
// TODO: Add the term mapping here
AtlasEntityType entityType = typeRegistry.getEntityTypeByName(typeName); AtlasEntityType entityType = typeRegistry.getEntityTypeByName(typeName);
if (entityType != null) { if (entityType != null) {
......
...@@ -144,11 +144,11 @@ public class UserProfileService { ...@@ -144,11 +144,11 @@ public class UserProfileService {
public void deleteUserProfile(String userName) throws AtlasBaseException { public void deleteUserProfile(String userName) throws AtlasBaseException {
AtlasUserProfile profile = getUserProfile(userName); AtlasUserProfile profile = getUserProfile(userName);
dataAccess.deleteUsingGuid(profile.getGuid()); dataAccess.delete(profile.getGuid());
} }
public void deleteSavedSearch(String guid) throws AtlasBaseException { public void deleteSavedSearch(String guid) throws AtlasBaseException {
dataAccess.deleteUsingGuid(guid); dataAccess.delete(guid);
} }
public void deleteSearchBySearchName(String userName, String searchName) throws AtlasBaseException { public void deleteSearchBySearchName(String userName, String searchName) throws AtlasBaseException {
......
...@@ -28,6 +28,7 @@ import org.apache.atlas.discovery.AtlasDiscoveryService; ...@@ -28,6 +28,7 @@ import org.apache.atlas.discovery.AtlasDiscoveryService;
import org.apache.atlas.discovery.AtlasLineageService; import org.apache.atlas.discovery.AtlasLineageService;
import org.apache.atlas.discovery.EntityDiscoveryService; import org.apache.atlas.discovery.EntityDiscoveryService;
import org.apache.atlas.discovery.EntityLineageService; import org.apache.atlas.discovery.EntityLineageService;
import org.apache.atlas.glossary.GlossaryService;
import org.apache.atlas.graph.GraphSandboxUtil; import org.apache.atlas.graph.GraphSandboxUtil;
import org.apache.atlas.listener.EntityChangeListener; import org.apache.atlas.listener.EntityChangeListener;
import org.apache.atlas.listener.EntityChangeListenerV2; import org.apache.atlas.listener.EntityChangeListenerV2;
...@@ -38,13 +39,21 @@ import org.apache.atlas.repository.audit.EntityAuditRepository; ...@@ -38,13 +39,21 @@ import org.apache.atlas.repository.audit.EntityAuditRepository;
import org.apache.atlas.repository.graph.GraphBackedSearchIndexer; import org.apache.atlas.repository.graph.GraphBackedSearchIndexer;
import org.apache.atlas.repository.graphdb.AtlasGraph; import org.apache.atlas.repository.graphdb.AtlasGraph;
import org.apache.atlas.repository.impexp.ExportService; import org.apache.atlas.repository.impexp.ExportService;
import org.apache.atlas.repository.ogm.profiles.AtlasSavedSearchDTO;
import org.apache.atlas.repository.ogm.profiles.AtlasUserProfileDTO;
import org.apache.atlas.repository.ogm.DTORegistry;
import org.apache.atlas.repository.ogm.DataAccess;
import org.apache.atlas.repository.ogm.DataTransferObject;
import org.apache.atlas.repository.ogm.glossary.AtlasGlossaryCategoryDTO;
import org.apache.atlas.repository.ogm.glossary.AtlasGlossaryDTO;
import org.apache.atlas.repository.ogm.glossary.AtlasGlossaryTermDTO;
import org.apache.atlas.repository.store.graph.AtlasEntityStore; import org.apache.atlas.repository.store.graph.AtlasEntityStore;
import org.apache.atlas.repository.store.graph.AtlasRelationshipStore; import org.apache.atlas.repository.store.graph.AtlasRelationshipStore;
import org.apache.atlas.repository.store.graph.BulkImporter; import org.apache.atlas.repository.store.graph.BulkImporter;
import org.apache.atlas.repository.store.graph.v1.AtlasEntityChangeNotifier; import org.apache.atlas.repository.store.graph.v1.AtlasEntityChangeNotifier;
import org.apache.atlas.repository.store.graph.v1.AtlasEntityStoreV1; import org.apache.atlas.repository.store.graph.v1.AtlasEntityStoreV1;
import org.apache.atlas.repository.store.graph.v1.AtlasTypeDefGraphStoreV1;
import org.apache.atlas.repository.store.graph.v1.AtlasRelationshipStoreV1; import org.apache.atlas.repository.store.graph.v1.AtlasRelationshipStoreV1;
import org.apache.atlas.repository.store.graph.v1.AtlasTypeDefGraphStoreV1;
import org.apache.atlas.repository.store.graph.v1.BulkImporterImpl; import org.apache.atlas.repository.store.graph.v1.BulkImporterImpl;
import org.apache.atlas.repository.store.graph.v1.DeleteHandlerV1; import org.apache.atlas.repository.store.graph.v1.DeleteHandlerV1;
import org.apache.atlas.repository.store.graph.v1.EntityGraphMapper; import org.apache.atlas.repository.store.graph.v1.EntityGraphMapper;
...@@ -151,6 +160,20 @@ public class TestModules { ...@@ -151,6 +160,20 @@ public class TestModules {
Multibinder.newSetBinder(binder(), EntityChangeListenerV2.class); Multibinder.newSetBinder(binder(), EntityChangeListenerV2.class);
entityChangeListenerV2Binder.addBinding().to(EntityAuditListenerV2.class); entityChangeListenerV2Binder.addBinding().to(EntityAuditListenerV2.class);
// OGM related mappings
Multibinder<DataTransferObject> availableDTOs = Multibinder.newSetBinder(binder(), DataTransferObject.class);
availableDTOs.addBinding().to(AtlasUserProfileDTO.class);
availableDTOs.addBinding().to(AtlasSavedSearchDTO.class);
availableDTOs.addBinding().to(AtlasGlossaryDTO.class);
availableDTOs.addBinding().to(AtlasGlossaryTermDTO.class);
availableDTOs.addBinding().to(AtlasGlossaryCategoryDTO.class);
bind(DTORegistry.class).asEagerSingleton();
bind(DataAccess.class).asEagerSingleton();
// Glossary related bindings
bind(GlossaryService.class).asEagerSingleton();
final GraphTransactionInterceptor graphTransactionInterceptor = new GraphTransactionInterceptor(new AtlasGraphProvider().get()); final GraphTransactionInterceptor graphTransactionInterceptor = new GraphTransactionInterceptor(new AtlasGraphProvider().get());
requestInjection(graphTransactionInterceptor); requestInjection(graphTransactionInterceptor);
bindInterceptor(Matchers.any(), Matchers.annotatedWith(GraphTransaction.class), graphTransactionInterceptor); bindInterceptor(Matchers.any(), Matchers.annotatedWith(GraphTransaction.class), graphTransactionInterceptor);
......
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.glossary;
import org.apache.atlas.AtlasErrorCode;
import org.apache.atlas.SortOrder;
import org.apache.atlas.TestModules;
import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.model.glossary.AtlasGlossary;
import org.apache.atlas.model.glossary.AtlasGlossaryCategory;
import org.apache.atlas.model.glossary.AtlasGlossaryTerm;
import org.apache.atlas.model.glossary.enums.AtlasTermRelationshipStatus;
import org.apache.atlas.model.glossary.relations.AtlasGlossaryHeader;
import org.apache.atlas.model.glossary.relations.AtlasRelatedCategoryHeader;
import org.apache.atlas.model.glossary.relations.AtlasRelatedTermHeader;
import org.apache.atlas.model.instance.AtlasEntity;
import org.apache.atlas.model.instance.AtlasEntityHeader;
import org.apache.atlas.model.instance.EntityMutationResponse;
import org.apache.atlas.repository.impexp.ZipFileResourceTestUtils;
import org.apache.atlas.repository.store.graph.AtlasEntityStore;
import org.apache.atlas.repository.store.graph.v1.AtlasEntityStream;
import org.apache.atlas.store.AtlasTypeDefStore;
import org.apache.atlas.type.AtlasTypeRegistry;
import org.apache.atlas.utils.AtlasJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.SkipException;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import javax.inject.Inject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import static org.testng.Assert.*;
@Guice(modules = TestModules.TestOnlyModule.class)
public class GlossaryServiceTest {
private static final Logger LOG = LoggerFactory.getLogger(GlossaryServiceTest.class);
@Inject
private GlossaryService glossaryService;
@Inject
private AtlasTypeDefStore typeDefStore;
@Inject
private AtlasTypeRegistry typeRegistry;
@Inject
private AtlasEntityStore entityStore;
private AtlasGlossary bankGlossary;
private AtlasGlossaryTerm checkingAccount, savingsAccount, fixedRateMortgage, adjustableRateMortgage;
private AtlasGlossaryCategory customerCategory, accountCategory, mortgageCategory;
private AtlasEntityHeader testEntityHeader;
@BeforeClass
public void setupSampleGlossary() {
try {
ZipFileResourceTestUtils.loadAllModels("0000-Area0", typeDefStore, typeRegistry);
} catch (AtlasBaseException | IOException e) {
throw new SkipException("SubjectArea model loading failed");
}
}
@Test(groups = "Glossary.CREATE")
public void testCreateGlossary() {
bankGlossary = new AtlasGlossary();
bankGlossary.setQualifiedName("testBankingGlossary");
bankGlossary.setDisplayName("Banking glossary");
bankGlossary.setShortDescription("Short description");
bankGlossary.setLongDescription("Long description");
bankGlossary.setUsage("N/A");
bankGlossary.setLanguage("en-US");
try {
AtlasGlossary created = glossaryService.createGlossary(bankGlossary);
bankGlossary.setGuid(created.getGuid());
} catch (AtlasBaseException e) {
fail("Glossary creation should've succeeded", e);
}
}
@Test(groups = "Glossary.CREATE", dependsOnMethods = {"testCreateGlossary"})
public void testCreateGlossaryTerms() {
AtlasGlossaryHeader glossaryId = new AtlasGlossaryHeader();
glossaryId.setGlossaryGuid(bankGlossary.getGuid());
checkingAccount = new AtlasGlossaryTerm();
checkingAccount.setQualifiedName("chk_acc@testBankingGlossary");
checkingAccount.setDisplayName("A checking account");
checkingAccount.setShortDescription("Short description");
checkingAccount.setLongDescription("Long description");
checkingAccount.setAbbreviation("CHK");
checkingAccount.setExamples(Arrays.asList("Personal", "Joint"));
checkingAccount.setUsage("N/A");
checkingAccount.setAnchor(glossaryId);
savingsAccount = new AtlasGlossaryTerm();
savingsAccount.setQualifiedName("sav_acc@testBankingGlossary");
savingsAccount.setDisplayName("A savings account");
savingsAccount.setShortDescription("Short description");
savingsAccount.setLongDescription("Long description");
savingsAccount.setAbbreviation("SAV");
savingsAccount.setExamples(Arrays.asList("Personal", "Joint"));
savingsAccount.setUsage("N/A");
savingsAccount.setAnchor(glossaryId);
fixedRateMortgage = new AtlasGlossaryTerm();
fixedRateMortgage.setQualifiedName("fixed_mtg@testBankingGlossary");
fixedRateMortgage.setDisplayName("15/30 yr mortgage");
fixedRateMortgage.setShortDescription("Short description");
fixedRateMortgage.setLongDescription("Long description");
fixedRateMortgage.setAbbreviation("FMTG");
fixedRateMortgage.setExamples(Arrays.asList("15-yr", "30-yr"));
fixedRateMortgage.setUsage("N/A");
fixedRateMortgage.setAnchor(glossaryId);
adjustableRateMortgage = new AtlasGlossaryTerm();
adjustableRateMortgage.setQualifiedName("arm_mtg@testBankingGlossary");
adjustableRateMortgage.setDisplayName("ARM loans");
adjustableRateMortgage.setShortDescription("Short description");
adjustableRateMortgage.setLongDescription("Long description");
adjustableRateMortgage.setAbbreviation("ARMTG");
adjustableRateMortgage.setExamples(Arrays.asList("5/1", "7/1", "10/1"));
adjustableRateMortgage.setUsage("N/A");
adjustableRateMortgage.setAnchor(glossaryId);
try {
List<AtlasGlossaryTerm> terms = glossaryService.createTerms(Arrays.asList(checkingAccount, savingsAccount, fixedRateMortgage, adjustableRateMortgage));
checkingAccount.setGuid(terms.get(0).getGuid());
savingsAccount.setGuid(terms.get(1).getGuid());
fixedRateMortgage.setGuid(terms.get(2).getGuid());
adjustableRateMortgage.setGuid(terms.get(3).getGuid());
} catch (AtlasBaseException e) {
fail("Term creation should've succeeded", e);
}
}
@Test(groups = "Glossary.CREATE", dependsOnMethods = {"testCreateGlossaryTerms"})
public void testCreateGlossaryCategory() {
AtlasGlossaryHeader glossaryId = new AtlasGlossaryHeader();
glossaryId.setGlossaryGuid(bankGlossary.getGuid());
customerCategory = new AtlasGlossaryCategory();
customerCategory.setQualifiedName("customer@testBankingGlossary");
customerCategory.setDisplayName("Customer category");
customerCategory.setShortDescription("Short description");
customerCategory.setLongDescription("Long description");
customerCategory.setAnchor(glossaryId);
accountCategory = new AtlasGlossaryCategory();
accountCategory.setQualifiedName("acc@testBankingGlossary");
accountCategory.setDisplayName("Account categorization");
accountCategory.setShortDescription("Short description");
accountCategory.setLongDescription("Long description");
accountCategory.setAnchor(glossaryId);
mortgageCategory = new AtlasGlossaryCategory();
mortgageCategory.setQualifiedName("mtg@testBankingGlossary");
mortgageCategory.setDisplayName("Mortgage categorization");
mortgageCategory.setShortDescription("Short description");
mortgageCategory.setLongDescription("Long description");
mortgageCategory.setAnchor(glossaryId);
try {
List<AtlasGlossaryCategory> categories = glossaryService.createCategories(Arrays.asList(customerCategory, accountCategory, mortgageCategory));
customerCategory.setGuid(categories.get(0).getGuid());
accountCategory.setGuid(categories.get(1).getGuid());
mortgageCategory.setGuid(categories.get(2).getGuid());
} catch (AtlasBaseException e) {
fail("Category creation should've succeeded", e);
}
}
@DataProvider
public Object[][] getAllGlossaryDataProvider() {
return new Object[][]{
// limit, offset, sortOrder, expected
{1, 0, SortOrder.ASCENDING, 1},
{5, 0, SortOrder.ASCENDING, 1},
{10, 0, SortOrder.ASCENDING, 1},
{1, 1, SortOrder.ASCENDING, 0},
{5, 1, SortOrder.ASCENDING, 0},
{10, 1, SortOrder.ASCENDING, 0},
{1, 2, SortOrder.ASCENDING, 0},
{5, 2, SortOrder.ASCENDING, 0},
{10, 2, SortOrder.ASCENDING, 0},
};
}
@Test(dataProvider = "getAllGlossaryDataProvider")
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);
}
}
@Test(groups = "Glossary.GET", dependsOnGroups = "Glossary.CREATE")
public void testGetGlossary() {
try {
AtlasGlossary glossary = glossaryService.getGlossary(bankGlossary.getGuid());
assertNotNull(glossary);
assertEquals(glossary.getGuid(), bankGlossary.getGuid());
} catch (AtlasBaseException e) {
fail("Glossary fetch should've succeeded", e);
}
}
@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());
assertEquals(updatedGlossary, bankGlossary);
bankGlossary = updatedGlossary;
} catch (AtlasBaseException e) {
fail("Glossary fetch/update should've succeeded", e);
}
}
@Test(dependsOnGroups = {"Glossary.GET", "Glossary.UPDATE", "Glossary.GET.postUpdate"}) // Should be the last test
public void testDeleteGlossary() {
try {
glossaryService.deleteGlossary(bankGlossary.getGuid());
try {
glossaryService.getGlossary(bankGlossary.getGuid());
} catch (AtlasBaseException e) {
assertEquals(e.getAtlasErrorCode(), AtlasErrorCode.INSTANCE_GUID_DELETED);
}
} catch (AtlasBaseException e) {
fail("Glossary delete should've succeeded", e);
}
}
@Test(groups = "Glossary.GET", dependsOnGroups = "Glossary.CREATE")
public void testGetGlossaryTerm() {
for (AtlasGlossaryTerm t : Arrays.asList(checkingAccount, savingsAccount, fixedRateMortgage, adjustableRateMortgage)) {
try {
AtlasGlossaryTerm glossaryTerm = glossaryService.getTerm(t.getGuid());
assertNotNull(glossaryTerm);
assertEquals(glossaryTerm.getGuid(), t.getGuid());
} catch (AtlasBaseException e) {
fail("Glossary term fetching should've succeeded", e);
}
}
}
@Test(groups = "Glossary.UPDATE", dependsOnGroups = "Glossary.CREATE")
public void testUpdateGlossaryTerm() {
List<AtlasGlossaryTerm> glossaryTerms = new ArrayList<>();
for (AtlasGlossaryTerm term : Arrays.asList(checkingAccount, savingsAccount, fixedRateMortgage, adjustableRateMortgage)) {
try {
glossaryTerms.add(glossaryService.getTerm(term.getGuid()));
} catch (AtlasBaseException e) {
fail("Fetch of GlossaryTerm should've succeeded", e);
}
}
for (AtlasGlossaryTerm t : glossaryTerms) {
try {
t.setShortDescription("Updated short description");
t.setLongDescription("Updated long description");
AtlasGlossaryTerm updatedTerm = glossaryService.updateTerm(t);
assertNotNull(updatedTerm);
assertEquals(updatedTerm.getGuid(), t.getGuid());
} catch (AtlasBaseException e) {
fail("Glossary term fetch/update should've succeeded", e);
}
}
}
@Test(groups = "Glossary.GET", dependsOnGroups = "Glossary.CREATE")
public void testGetGlossaryCategory() {
for (AtlasGlossaryCategory c : Arrays.asList(customerCategory, accountCategory, mortgageCategory)) {
try {
AtlasGlossaryCategory glossaryCategory = glossaryService.getCategory(c.getGuid());
assertNotNull(glossaryCategory);
assertEquals(glossaryCategory.getGuid(), c.getGuid());
} catch (AtlasBaseException e) {
fail("Glossary category fetching should've succeeded", e);
}
}
}
@Test(groups = "Glossary.UPDATE", dependsOnGroups = "Glossary.CREATE")
public void testUpdateGlossaryCategory() {
List<AtlasGlossaryCategory> glossaryCategories = new ArrayList<>();
for (AtlasGlossaryCategory glossaryCategory : Arrays.asList(customerCategory, accountCategory, mortgageCategory)) {
try {
glossaryCategories.add(glossaryService.getCategory(glossaryCategory.getGuid()));
} catch (AtlasBaseException e) {
fail("Category fetch should've succeeded", e);
}
}
for (AtlasGlossaryCategory c : glossaryCategories) {
try {
AtlasGlossaryCategory glossaryCategory = glossaryService.getCategory(c.getGuid());
glossaryCategory.setShortDescription("Updated short description");
glossaryCategory.setLongDescription("Updated long description");
AtlasGlossaryCategory updatedCategory = glossaryService.updateCategory(glossaryCategory);
assertNotNull(updatedCategory);
assertEquals(updatedCategory.getGuid(), c.getGuid());
} catch (AtlasBaseException e) {
fail("Glossary category fetching should've succeeded", e);
}
}
}
@Test(groups = "Glossary.UPDATE", dependsOnGroups = "Glossary.CREATE")
public void testAddTermsToCategory() {
assertNotNull(accountCategory);
try {
accountCategory = glossaryService.getCategory(accountCategory.getGuid());
} catch (AtlasBaseException e) {
fail("Fetch of accountCategory should've succeeded", e);
}
List<AtlasGlossaryTerm> terms = new ArrayList<>();
for (AtlasGlossaryTerm term : Arrays.asList(checkingAccount, savingsAccount)) {
try {
terms.add(glossaryService.getTerm(term.getGuid()));
} catch (AtlasBaseException e) {
fail("Term fetching should've succeeded", e);
}
}
for (AtlasGlossaryTerm termEntry : terms) {
AtlasRelatedTermHeader relatedTermId = new AtlasRelatedTermHeader();
relatedTermId.setTermGuid(termEntry.getGuid());
relatedTermId.setStatus(AtlasTermRelationshipStatus.ACTIVE);
relatedTermId.setSteward("UT");
relatedTermId.setSource("UT");
relatedTermId.setExpression("N/A");
relatedTermId.setDescription("Categorization under account category");
accountCategory.addTerm(relatedTermId);
}
try {
AtlasGlossaryCategory updated = glossaryService.updateCategory(accountCategory);
assertNotNull(updated.getTerms());
assertEquals(updated.getTerms().size(), 2);
accountCategory = updated;
} catch (AtlasBaseException e) {
fail("Glossary category update should've succeeded", e);
}
assertNotNull(accountCategory);
try {
accountCategory = glossaryService.getCategory(accountCategory.getGuid());
} catch (AtlasBaseException e) {
fail("Fetch of accountCategory should've succeeded", e);
}
terms.clear();
for (AtlasGlossaryTerm term : Arrays.asList(fixedRateMortgage, adjustableRateMortgage)) {
try {
terms.add(glossaryService.getTerm(term.getGuid()));
} catch (AtlasBaseException e) {
fail("Term fetching should've succeeded", e);
}
}
for (AtlasGlossaryTerm termEntry : terms) {
AtlasRelatedTermHeader relatedTermId = new AtlasRelatedTermHeader();
relatedTermId.setTermGuid(termEntry.getGuid());
relatedTermId.setStatus(AtlasTermRelationshipStatus.ACTIVE);
relatedTermId.setSteward("UT");
relatedTermId.setSource("UT");
relatedTermId.setExpression("N/A");
relatedTermId.setDescription("Categorization under mortgage category");
mortgageCategory.addTerm(relatedTermId);
}
try {
AtlasGlossaryCategory updated = glossaryService.updateCategory(mortgageCategory);
assertNotNull(updated.getTerms());
assertEquals(updated.getTerms().size(), 2);
mortgageCategory = updated;
} catch (AtlasBaseException e) {
fail("Glossary category update should've succeeded", e);
}
}
@Test(groups = "Glossary.UPDATE", dependsOnGroups = "Glossary.CREATE")
public void testAddGlossaryCategoryChildren() {
assertNotNull(customerCategory);
try {
customerCategory = glossaryService.getCategory(customerCategory.getGuid());
} catch (AtlasBaseException e) {
fail("Fetch of accountCategory should've succeeded", e);
}
List<AtlasGlossaryCategory> categories = new ArrayList<>();
for (AtlasGlossaryCategory category : Arrays.asList(accountCategory, mortgageCategory)) {
try {
categories.add(glossaryService.getCategory(category.getGuid()));
} catch (AtlasBaseException e) {
fail("Category fetch should've succeeded");
}
}
for (AtlasGlossaryCategory category : categories) {
AtlasRelatedCategoryHeader id = new AtlasRelatedCategoryHeader();
id.setCategoryGuid(category.getGuid());
id.setDescription("Sub-category of customer");
customerCategory.addChild(id);
}
try {
AtlasGlossaryCategory updateGlossaryCategory = glossaryService.updateCategory(customerCategory);
assertNull(updateGlossaryCategory.getParentCategory());
assertNotNull(updateGlossaryCategory.getChildrenCategories());
assertEquals(updateGlossaryCategory.getChildrenCategories().size(), 2);
customerCategory = updateGlossaryCategory;
LOG.debug(AtlasJson.toJson(updateGlossaryCategory));
} catch (AtlasBaseException e) {
fail("Sub category addition should've succeeded", e);
}
}
@Test(groups = "Glossary.GET.postUpdate", dependsOnGroups = "Glossary.UPDATE")
public void testCategoryRelation() {
AtlasGlossaryCategory parent = customerCategory;
Map<String, List<AtlasRelatedCategoryHeader>> relatedCategories;
try {
relatedCategories = glossaryService.getRelatedCategories(parent.getGuid(), 0, -1, SortOrder.ASCENDING);
assertNotNull(relatedCategories);
assertNotNull(relatedCategories.get("children"));
assertEquals(relatedCategories.get("children").size(), 2);
} catch (AtlasBaseException e) {
fail("Category fetch should've succeeded", e);
}
for (AtlasGlossaryCategory childCategory : Arrays.asList(accountCategory, mortgageCategory)) {
try {
relatedCategories = glossaryService.getRelatedCategories(childCategory.getGuid(), 0, -1, SortOrder.ASCENDING);
assertNotNull(relatedCategories.get("parent"));
assertEquals(relatedCategories.get("parent").size(), 1);
} catch (AtlasBaseException e) {
fail("Category fetch should've succeeded", e);
}
}
}
@Test(groups = "Glossary.UPDATE", dependsOnGroups = "Glossary.CREATE")
public void testTermAssignment() {
AtlasEntity assetEntity = new AtlasEntity("Asset");
assetEntity.setAttribute("qualifiedName", "testAsset");
assetEntity.setAttribute("name", "testAsset");
try {
EntityMutationResponse response = entityStore.createOrUpdate(new AtlasEntityStream(assetEntity), false);
testEntityHeader = response.getFirstEntityCreated();
assertNotNull(testEntityHeader);
} catch (AtlasBaseException e) {
fail("Entity creation should've succeeded", e);
}
try {
glossaryService.assignTermToEntities(fixedRateMortgage.getGuid(), Arrays.asList(testEntityHeader));
} catch (AtlasBaseException e) {
fail("Term assignment to asset should've succeeded", e);
}
try {
List<AtlasEntityHeader> assignedEntities = glossaryService.getAssignedEntities(fixedRateMortgage.getGuid(), 0, 1, SortOrder.ASCENDING);
assertNotNull(assignedEntities);
assertEquals(assignedEntities.size(), 1);
Object relationGuid = assignedEntities.get(0).getAttribute("relationGuid");
assertNotNull(relationGuid);
testEntityHeader.setAttribute("relationGuid", relationGuid);
} catch (AtlasBaseException e) {
fail("Term fetch should've succeeded",e);
}
}
// FIXME: The term dissociation is not working as intended.
@Test(groups = "Glossary.UPDATE", dependsOnGroups = "Glossary.CREATE", dependsOnMethods = "testTermAssignment")
public void testTermDissociation() {
try {
glossaryService.removeTermFromEntities(fixedRateMortgage.getGuid(), Arrays.asList(testEntityHeader));
AtlasGlossaryTerm term = glossaryService.getTerm(fixedRateMortgage.getGuid());
assertNotNull(term);
assertNull(term.getAssignedEntities());
} catch (AtlasBaseException e) {
fail("Term update should've succeeded", e);
}
}
@Test(groups = "Glossary.UPDATE", dependsOnGroups = "Glossary.CREATE")
public void testTermRelation() {
AtlasRelatedTermHeader relatedTerm = new AtlasRelatedTermHeader();
relatedTerm.setTermGuid(savingsAccount.getGuid());
relatedTerm.setStatus(AtlasTermRelationshipStatus.DRAFT);
relatedTerm.setSteward("UT");
relatedTerm.setSource("UT");
relatedTerm.setExpression("N/A");
relatedTerm.setDescription("Related term");
assertNotNull(checkingAccount);
try {
checkingAccount = glossaryService.getTerm(checkingAccount.getGuid());
} catch (AtlasBaseException e) {
fail("Glossary term fetch should've been a success", e);
}
checkingAccount.setSeeAlso(new HashSet<>(Arrays.asList(relatedTerm)));
try {
AtlasGlossaryTerm updatedTerm = glossaryService.updateTerm(checkingAccount);
assertNotNull(updatedTerm.getSeeAlso());
assertEquals(updatedTerm.getSeeAlso().size(), 1);
} catch (AtlasBaseException e) {
fail("RelatedTerm association should've succeeded", e);
}
relatedTerm.setTermGuid(fixedRateMortgage.getGuid());
assertNotNull(adjustableRateMortgage);
try {
adjustableRateMortgage = glossaryService.getTerm(adjustableRateMortgage.getGuid());
} catch (AtlasBaseException e) {
fail("Glossary term fetch should've been a success", e);
}
adjustableRateMortgage.setSeeAlso(new HashSet<>(Arrays.asList(relatedTerm)));
try {
AtlasGlossaryTerm updatedTerm = glossaryService.updateTerm(adjustableRateMortgage);
assertNotNull(updatedTerm.getSeeAlso());
assertEquals(updatedTerm.getSeeAlso().size(), 1);
} catch (AtlasBaseException e) {
fail("RelatedTerm association should've succeeded", e);
}
}
@DataProvider
public static Object[][] getGlossaryTermsProvider() {
return new Object[][]{
// offset, limit, expected
{0, -1, 4},
{0, 2, 2},
{2, 5, 2},
};
}
@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<AtlasGlossaryTerm> glossaryTerms = glossaryService.getGlossaryTerms(guid, offset, limit, sortOrder);
assertNotNull(glossaryTerms);
assertEquals(glossaryTerms.size(), expected);
} catch (AtlasBaseException e) {
fail("Glossary term fetching should've succeeded", e);
}
}
@DataProvider
public Object[][] getGlossaryCategoriesProvider() {
return new Object[][]{
// offset, limit, expected
{0, -1, 3},
{0, 2, 2},
{2, 5, 1},
};
}
@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.getGlossaryCategories(guid, offset, limit, sortOrder);
assertNotNull(glossaryCategories);
assertEquals(glossaryCategories.size(), expected);
} catch (AtlasBaseException e) {
fail("Glossary term fetching should've succeeded");
}
}
@DataProvider
public Object[][] getCategoryTermsProvider() {
return new Object[][]{
// offset, limit, expected
{0, -1, 2},
{0, 2, 2},
{1, 5, 1},
{2, 5, 0},
};
}
@Test(dataProvider = "getCategoryTermsProvider", groups = "Glossary.GET.postUpdate", dependsOnGroups = "Glossary.UPDATE")
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);
}
}
}
}
\ No newline at end of file
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.glossary;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.testng.Assert.assertEquals;
public class PaginationHelperTest {
@DataProvider
public Object[][] paginationProvider() {
return new Object[][] {
// maxSize, offset, limit, expected
{10, 0 , 5, 5},
{10, 0 , -1, 10},
{10, -1 , -1, 10},
{10, -1 , 5, 5},
{10, -1 , 11, 10},
{10, 5 , 11, 5},
{10, 2 , 11, 8},
{10, 8 , 11, 2},
{10, 5 , 1, 1},
{10, 9 , 1, 1},
{10, 10 , 5, 0},
{10, 11 , 5, 0},
{10, 20 , -1, 0},
{5, 6 , -1, 0},
{0, -1 , -1, 0},
{0, 5 , 10, 0},
{0, 0 , 10, 0},
{1, -1 , -1, 1},
{1, 5 , 10, 0},
{1, 0 , 10, 1},
};
}
@Test(dataProvider = "paginationProvider")
public void testPaginationHelper(int maxSize, int offset, int limit, int expectedSize) {
List<Integer> intList = IntStream.range(0, maxSize).boxed().collect(Collectors.toCollection(() -> new ArrayList<>(maxSize)));
GlossaryService.PaginationHelper helper = new GlossaryService.PaginationHelper<>(intList, offset, limit);
assertEquals(helper.getPaginatedList().size(), expectedSize);
}
}
...@@ -29,6 +29,7 @@ import org.apache.atlas.repository.store.bootstrap.AtlasTypeDefStoreInitializer; ...@@ -29,6 +29,7 @@ import org.apache.atlas.repository.store.bootstrap.AtlasTypeDefStoreInitializer;
import org.apache.atlas.store.AtlasTypeDefStore; import org.apache.atlas.store.AtlasTypeDefStore;
import org.apache.atlas.type.AtlasType; import org.apache.atlas.type.AtlasType;
import org.apache.atlas.type.AtlasTypeRegistry; import org.apache.atlas.type.AtlasTypeRegistry;
import org.apache.atlas.utils.AtlasJson;
import org.apache.atlas.utils.TestResourceFileUtils; import org.apache.atlas.utils.TestResourceFileUtils;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
...@@ -38,10 +39,12 @@ import org.slf4j.LoggerFactory; ...@@ -38,10 +39,12 @@ import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
...@@ -56,6 +59,36 @@ public class ZipFileResourceTestUtils { ...@@ -56,6 +59,36 @@ public class ZipFileResourceTestUtils {
return TestResourceFileUtils.getFileInputStream(fileName); return TestResourceFileUtils.getFileInputStream(fileName);
} }
public static List<String> getAllModels(String dirName) throws IOException {
List<String> ret = null;
File topModelsDir = new File(System.getProperty("user.dir") + "/../addons/models");
File[] topModelsDirContents = topModelsDir.exists() ? topModelsDir.listFiles() : null;
assertTrue(topModelsDirContents != null, topModelsDir.getAbsolutePath() + ": unable to find/read directory");
if(topModelsDirContents != null) {
Arrays.sort(topModelsDirContents);
for (File modelDir : topModelsDirContents) {
if (modelDir.exists() && modelDir.isDirectory() && modelDir.getAbsolutePath().contains(dirName)) {
File[] models = modelDir.listFiles();
Arrays.sort(models);
ret = new ArrayList<>();
for (File model : Objects.requireNonNull(models)) {
ret.add(getFileContents(modelDir, model.getName()));
}
}
if (ret != null && ret.size() > 0) {
break;
}
}
} else {
throw new IOException("Unable to retrieve model contents.");
}
return ret;
}
public static String getModelJson(String fileName) throws IOException { public static String getModelJson(String fileName) throws IOException {
String ret = null; String ret = null;
File topModelsDir = new File(System.getProperty("user.dir") + "/../addons/models"); File topModelsDir = new File(System.getProperty("user.dir") + "/../addons/models");
...@@ -145,12 +178,19 @@ public class ZipFileResourceTestUtils { ...@@ -145,12 +178,19 @@ public class ZipFileResourceTestUtils {
return r; return r;
} }
public static void loadModelFromJson(String fileName, AtlasTypeDefStore typeDefStore, AtlasTypeRegistry typeRegistry) throws IOException, AtlasBaseException { public static void loadModelFromJson(String fileName, AtlasTypeDefStore typeDefStore, AtlasTypeRegistry typeRegistry) throws IOException, AtlasBaseException {
AtlasTypesDef typesFromJson = getAtlasTypesDefFromFile(fileName); AtlasTypesDef typesFromJson = getAtlasTypesDefFromFile(fileName);
createTypesAsNeeded(typesFromJson, typeDefStore, typeRegistry); createTypesAsNeeded(typesFromJson, typeDefStore, typeRegistry);
} }
public static void loadAllModels(String dirName, AtlasTypeDefStore typeDefStore, AtlasTypeRegistry typeRegistry) throws IOException, AtlasBaseException {
List<String> allModels = getAllModels(dirName);
for (String model : allModels) {
AtlasTypesDef typesFromJson = AtlasJson.fromJson(model, AtlasTypesDef.class);
createTypesAsNeeded(typesFromJson, typeDefStore, typeRegistry);
}
}
public static void loadModelFromResourcesJson(String fileName, AtlasTypeDefStore typeDefStore, AtlasTypeRegistry typeRegistry) throws IOException, AtlasBaseException { public static void loadModelFromResourcesJson(String fileName, AtlasTypeDefStore typeDefStore, AtlasTypeRegistry typeRegistry) throws IOException, AtlasBaseException {
AtlasTypesDef typesFromJson = getAtlasTypesDefFromResourceFile(fileName); AtlasTypesDef typesFromJson = getAtlasTypesDefFromResourceFile(fileName);
createTypesAsNeeded(typesFromJson, typeDefStore, typeRegistry); createTypesAsNeeded(typesFromJson, typeDefStore, typeRegistry);
......
...@@ -24,6 +24,7 @@ import org.apache.atlas.model.SearchFilter; ...@@ -24,6 +24,7 @@ import org.apache.atlas.model.SearchFilter;
import org.apache.atlas.model.discovery.SearchParameters; import org.apache.atlas.model.discovery.SearchParameters;
import org.apache.atlas.model.profile.AtlasUserProfile; import org.apache.atlas.model.profile.AtlasUserProfile;
import org.apache.atlas.model.profile.AtlasUserSavedSearch; import org.apache.atlas.model.profile.AtlasUserSavedSearch;
import org.apache.atlas.model.typedef.AtlasEntityDef;
import org.apache.atlas.model.typedef.AtlasTypesDef; import org.apache.atlas.model.typedef.AtlasTypesDef;
import org.apache.atlas.repository.graph.AtlasGraphProvider; import org.apache.atlas.repository.graph.AtlasGraphProvider;
import org.apache.atlas.repository.util.FilterUtil; import org.apache.atlas.repository.util.FilterUtil;
...@@ -39,11 +40,15 @@ import javax.inject.Inject; ...@@ -39,11 +40,15 @@ import javax.inject.Inject;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional;
import static org.apache.atlas.graph.GraphSandboxUtil.useLocalSolr; import static org.apache.atlas.graph.GraphSandboxUtil.useLocalSolr;
import static org.apache.atlas.model.profile.AtlasUserSavedSearch.SavedSearchType.BASIC; import static org.apache.atlas.model.profile.AtlasUserSavedSearch.SavedSearchType.BASIC;
import static org.apache.atlas.repository.impexp.ZipFileResourceTestUtils.loadModelFromJson; import static org.apache.atlas.repository.impexp.ZipFileResourceTestUtils.loadModelFromJson;
import static org.testng.Assert.*; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
@Guice(modules = TestModules.TestOnlyModule.class) @Guice(modules = TestModules.TestOnlyModule.class)
public class UserProfileServiceTest { public class UserProfileServiceTest {
...@@ -80,7 +85,8 @@ public class UserProfileServiceTest { ...@@ -80,7 +85,8 @@ public class UserProfileServiceTest {
filteredTypeDefs = typeDefStore.searchTypesDef(searchFilter); filteredTypeDefs = typeDefStore.searchTypesDef(searchFilter);
assertNotNull(filteredTypeDefs); assertNotNull(filteredTypeDefs);
assertEquals(filteredTypeDefs.getEntityDefs().size(), maxTypeDefs - 3); Optional<AtlasEntityDef> anyInternal = filteredTypeDefs.getEntityDefs().stream().filter(e -> e.getSuperTypes().contains("__internal")).findAny();
assertFalse(anyInternal.isPresent());
} }
@Test @Test
......
...@@ -17,9 +17,7 @@ ...@@ -17,9 +17,7 @@
*/ */
package org.apache.atlas.notification; package org.apache.atlas.notification;
import org.apache.atlas.ApplicationProperties;
import org.apache.atlas.AtlasErrorCode; import org.apache.atlas.AtlasErrorCode;
import org.apache.atlas.AtlasException;
import org.apache.atlas.exception.AtlasBaseException; import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.listener.EntityChangeListenerV2; import org.apache.atlas.listener.EntityChangeListenerV2;
import org.apache.atlas.model.instance.AtlasClassification; import org.apache.atlas.model.instance.AtlasClassification;
...@@ -46,26 +44,23 @@ import java.util.Set; ...@@ -46,26 +44,23 @@ import java.util.Set;
import static org.apache.atlas.notification.NotificationEntityChangeListener.ATLAS_ENTITY_NOTIFICATION_PROPERTY; import static org.apache.atlas.notification.NotificationEntityChangeListener.ATLAS_ENTITY_NOTIFICATION_PROPERTY;
import static org.apache.atlas.notification.NotificationInterface.NotificationType.ENTITIES; import static org.apache.atlas.notification.NotificationInterface.NotificationType.ENTITIES;
import static org.apache.atlas.v1.model.notification.EntityNotificationV2.OperationType.CLASSIFICATION_ADD;
import static org.apache.atlas.v1.model.notification.EntityNotificationV2.OperationType.CLASSIFICATION_DELETE;
import static org.apache.atlas.v1.model.notification.EntityNotificationV2.OperationType.CLASSIFICATION_UPDATE;
import static org.apache.atlas.repository.graph.GraphHelper.isInternalType; import static org.apache.atlas.repository.graph.GraphHelper.isInternalType;
import static org.apache.atlas.v1.model.notification.EntityNotificationV2.OperationType.ENTITY_CREATE; import static org.apache.atlas.v1.model.notification.EntityNotificationV2.OperationType.*;
import static org.apache.atlas.v1.model.notification.EntityNotificationV2.OperationType.ENTITY_DELETE;
import static org.apache.atlas.v1.model.notification.EntityNotificationV2.OperationType.ENTITY_UPDATE;
@Component @Component
public class EntityNotificationListenerV2 implements EntityChangeListenerV2 { public class EntityNotificationListenerV2 implements EntityChangeListenerV2 {
private final AtlasTypeRegistry typeRegistry; private final AtlasTypeRegistry typeRegistry;
private final NotificationInterface notificationInterface; private final NotificationInterface notificationInterface;
private final Configuration configuration;
private final Map<String, List<String>> notificationAttributesCache = new HashMap<>(); private final Map<String, List<String>> notificationAttributesCache = new HashMap<>();
private static Configuration APPLICATION_PROPERTIES = null;
@Inject @Inject
public EntityNotificationListenerV2(AtlasTypeRegistry typeRegistry, NotificationInterface notificationInterface) { public EntityNotificationListenerV2(AtlasTypeRegistry typeRegistry,
NotificationInterface notificationInterface,
Configuration configuration) {
this.typeRegistry = typeRegistry; this.typeRegistry = typeRegistry;
this.notificationInterface = notificationInterface; this.notificationInterface = notificationInterface;
this.configuration = configuration;
} }
@Override @Override
...@@ -186,13 +181,11 @@ public class EntityNotificationListenerV2 implements EntityChangeListenerV2 { ...@@ -186,13 +181,11 @@ public class EntityNotificationListenerV2 implements EntityChangeListenerV2 {
private List<String> getNotificationAttributes(String entityType) { private List<String> getNotificationAttributes(String entityType) {
List<String> ret = null; List<String> ret = null;
initApplicationProperties();
if (notificationAttributesCache.containsKey(entityType)) { if (notificationAttributesCache.containsKey(entityType)) {
ret = notificationAttributesCache.get(entityType); ret = notificationAttributesCache.get(entityType);
} else if (APPLICATION_PROPERTIES != null) { } else if (configuration != null) {
String[] notificationAttributes = APPLICATION_PROPERTIES.getStringArray(ATLAS_ENTITY_NOTIFICATION_PROPERTY + "." + String attributesToIncludeKey = ATLAS_ENTITY_NOTIFICATION_PROPERTY + "." + entityType + "." + "attributes.include";
entityType + "." + "attributes.include"); String[] notificationAttributes = configuration.getStringArray(attributesToIncludeKey);
if (notificationAttributes != null) { if (notificationAttributes != null) {
ret = Arrays.asList(notificationAttributes); ret = Arrays.asList(notificationAttributes);
...@@ -203,14 +196,4 @@ public class EntityNotificationListenerV2 implements EntityChangeListenerV2 { ...@@ -203,14 +196,4 @@ public class EntityNotificationListenerV2 implements EntityChangeListenerV2 {
return ret; return ret;
} }
private void initApplicationProperties() {
if (APPLICATION_PROPERTIES == null) {
try {
APPLICATION_PROPERTIES = ApplicationProperties.get();
} catch (AtlasException ex) {
// ignore
}
}
}
} }
\ No newline at end of file
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.web.rest;
import org.apache.atlas.AtlasErrorCode;
import org.apache.atlas.SortOrder;
import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.glossary.GlossaryService;
import org.apache.atlas.model.glossary.AtlasGlossary;
import org.apache.atlas.model.glossary.AtlasGlossaryCategory;
import org.apache.atlas.model.glossary.AtlasGlossaryTerm;
import org.apache.atlas.model.glossary.relations.AtlasRelatedCategoryHeader;
import org.apache.atlas.model.glossary.relations.AtlasRelatedTermHeader;
import org.apache.atlas.model.instance.AtlasEntityHeader;
import org.apache.atlas.utils.AtlasPerfTracer;
import org.apache.atlas.web.util.Servlets;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import javax.ws.rs.*;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import static org.apache.atlas.web.util.Servlets.JSON_MEDIA_TYPE;
@Path("v2/glossary")
@Service
@Consumes(JSON_MEDIA_TYPE)
@Produces(JSON_MEDIA_TYPE)
public class GlossaryREST {
private static final Logger LOG = LoggerFactory.getLogger(GlossaryREST.class);
private static final Logger PERF_LOG = AtlasPerfTracer.getPerfLogger("rest.GlossaryREST");
private final GlossaryService glossaryService;
@Inject
public GlossaryREST(final GlossaryService glossaryService) {
this.glossaryService = glossaryService;
}
/**
* Retrieve all glossaries registered with Atlas
* @param limit page size - by default there is no paging
* @param offset offset for pagination purpose
* @param sort Sort order, ASC (default) or DESC
* @return List of glossary entities fitting the above criteria
* @HTTP 200 List of existing glossaries fitting the search criteria or empty list if nothing matches
* @throws AtlasBaseException
*/
@GET
public List<AtlasGlossary> getGlossaries(@DefaultValue("-1") @QueryParam("limit") final String limit,
@DefaultValue("0") @QueryParam("offset") final String offset,
@DefaultValue("ASC") @QueryParam("sort") final String sort) throws AtlasBaseException {
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.getGlossaries()");
}
return glossaryService.getGlossaries(Integer.parseInt(limit), Integer.parseInt(offset), toSortOrder(sort));
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Get a specific Glossary
* @param glossaryGuid unique glossary identifier
* @return Glossary
* @throws AtlasBaseException
* @HTTP 200 If glossary with given guid exists
* @HTTP 404 If glossary GUID is invalid
*/
@GET
@Path("/{glossaryGuid}")
public AtlasGlossary getGlossary(@PathParam("glossaryGuid") String glossaryGuid) throws AtlasBaseException {
Servlets.validateQueryParamLength("glossaryGuid", glossaryGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.getGlossary(" + glossaryGuid + ")");
}
AtlasGlossary ret = glossaryService.getGlossary(glossaryGuid);
if (ret == null) {
throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND);
}
return ret;
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Get a specific Glossary
* @param glossaryGuid unique glossary identifier
* @return Glossary
* @throws AtlasBaseException
* @HTTP 200 If glossary exists for given GUID
* @HTTP 404 If glossary GUID is invalid
*/
@GET
@Path("/{glossaryGuid}/detailed")
public AtlasGlossary.AtlasGlossaryExtInfo getDetailedGlossary(@PathParam("glossaryGuid") String glossaryGuid) throws AtlasBaseException {
Servlets.validateQueryParamLength("glossaryGuid", glossaryGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.getDetailedGlossary(" + glossaryGuid + ")");
}
AtlasGlossary.AtlasGlossaryExtInfo ret = glossaryService.getDetailedGlossary(glossaryGuid);
if (ret == null) {
throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND);
}
return ret;
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Get specific glossary term
* @param termGuid unique identifier for glossary term
* @return Glossary term
* @throws AtlasBaseException
* @HTTP 200 If glossary term exists for given GUID
* @HTTP 404 If glossary term GUID is invalid
*/
@GET
@Path("/term/{termGuid}")
public AtlasGlossaryTerm getGlossaryTerm(@PathParam("termGuid") String termGuid) throws AtlasBaseException {
Servlets.validateQueryParamLength("termGuid", termGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.getGlossaryTerm(" + termGuid + ")");
}
AtlasGlossaryTerm ret = glossaryService.getTerm(termGuid);
if (ret == null) {
throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND);
}
return ret;
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Get specific glossary category
* @param categoryGuid unique identifier for glossary category
* @return Glossary category
* @throws AtlasBaseException
* @HTTP 200 If glossary category exists for given GUID
* @HTTP 404 If glossary category GUID is invalid
*/
@GET
@Path("/category/{categoryGuid}")
public AtlasGlossaryCategory getGlossaryCategory(@PathParam("categoryGuid") String categoryGuid) throws AtlasBaseException {
Servlets.validateQueryParamLength("categoryGuid", categoryGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.getGlossaryCategory(" + categoryGuid + ")");
}
AtlasGlossaryCategory ret = glossaryService.getCategory(categoryGuid);
if (ret == null) {
throw new AtlasBaseException(AtlasErrorCode.INSTANCE_GUID_NOT_FOUND);
}
return ret;
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Create a glossary
* @param atlasGlossary Glossary definition, terms & categories can be anchored to a glossary
* using the anchor attribute when creating the Term/Category
* @return
* @throws AtlasBaseException
* @HTTP 200 If glossary creation was successful
* @HTTP 400 If Glossary definition has invalid or missing information
*/
@POST
public AtlasGlossary createGlossary(AtlasGlossary atlasGlossary) throws AtlasBaseException {
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.createGlossary()");
}
return glossaryService.createGlossary(atlasGlossary);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Create a glossary term
* @param glossaryTerm Glossary term definition, a term must be anchored to a Glossary at the time of creation
* optionally it can be categorized as well
* @return
* @throws AtlasBaseException
* @HTTP 200 If glossary term creation was successful
* @HTTP 400 If Glossary term definition has invalid or missing information
*/
@POST
@Path("/term")
public AtlasGlossaryTerm createGlossaryTerm(AtlasGlossaryTerm glossaryTerm) throws AtlasBaseException {
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.createGlossaryTerm()");
}
if (Objects.isNull(glossaryTerm.getAnchor())) {
throw new AtlasBaseException(AtlasErrorCode.MISSING_MANDATORY_ANCHOR);
}
return glossaryService.createTerm(glossaryTerm);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Create glossary terms in bulk
* @param glossaryTerm glossary term definitions
* @return
* @throws AtlasBaseException
* @HTTP 200 If Bulk glossary terms creation was successful
* @HTTP 400 If any glossary term definition has invalid or missing information
*/
@POST
@Path("/terms")
public List<AtlasGlossaryTerm> createGlossaryTerms(List<AtlasGlossaryTerm> glossaryTerm) throws AtlasBaseException {
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.createGlossaryTerms()");
}
for (AtlasGlossaryTerm term : glossaryTerm) {
if (Objects.isNull(term.getAnchor())) {
throw new AtlasBaseException(AtlasErrorCode.MISSING_MANDATORY_ANCHOR);
}
}
return glossaryService.createTerms(glossaryTerm);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Create glossary category
* @param glossaryCategory glossary category definition, a category must be anchored to a Glossary when creating
* Optionally, terms belonging to the category and the hierarchy can also be defined during creation
* @return
* @throws AtlasBaseException
* @HTTP 200 If glossary category creation was successful
* @HTTP 400 If Glossary category definition has invalid or missing information
*/
@POST
@Path("/category")
public AtlasGlossaryCategory createGlossaryCategory(AtlasGlossaryCategory glossaryCategory) throws AtlasBaseException {
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.createGlossaryCategory()");
}
if (Objects.isNull(glossaryCategory.getAnchor())) {
throw new AtlasBaseException(AtlasErrorCode.MISSING_MANDATORY_ANCHOR);
}
return glossaryService.createCategory(glossaryCategory);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Create glossary category in bulk
* @param glossaryCategory glossary category definitions
* @return
* @throws AtlasBaseException
* @HTTP 200 If BULK glossary category creation was successful
* @HTTP 400 If ANY Glossary category definition has invalid or missing information
*/
@POST
@Path("/categories")
public List<AtlasGlossaryCategory> createGlossaryCategories(List<AtlasGlossaryCategory> glossaryCategory) throws AtlasBaseException {
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.createGlossaryCategories()");
}
for (AtlasGlossaryCategory category : glossaryCategory) {
if (Objects.isNull(category.getAnchor())) {
throw new AtlasBaseException(AtlasErrorCode.MISSING_MANDATORY_ANCHOR);
}
}
return glossaryService.createCategories(glossaryCategory);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Update the given glossary
* @param glossaryGuid unique identifier for glossary
* @param updatedGlossary Updated glossary definition
* @return Glossary
* @throws AtlasBaseException
* @HTTP 200 If glossary update was successful
* @HTTP 404 If glossary guid in invalid
* @HTTP 400 If Glossary definition has invalid or missing information
*/
@PUT
@Path("/{glossaryGuid}")
public AtlasGlossary updateGlossary(@PathParam("glossaryGuid") String glossaryGuid, AtlasGlossary updatedGlossary) throws AtlasBaseException {
Servlets.validateQueryParamLength("glossaryGuid", glossaryGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.updateGlossary(" + glossaryGuid + ")");
}
updatedGlossary.setGuid(glossaryGuid);
return glossaryService.updateGlossary(updatedGlossary);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Partially update the glossary
* @param glossaryGuid unique identifier for glossary term
* @param partialUpdates Map containing keys as attribute names and values as corresponding attribute values
* @return Updated glossary
* @throws AtlasBaseException
* @HTTP 200 If glossary partial update was successful
* @HTTP 404 If glossary guid in invalid
* @HTTP 400 If partial update parameters are invalid
*/
@PUT
@Path("/{glossaryGuid}/partial")
public AtlasGlossary partialUpdateGlossary(@PathParam("glossaryGuid") String glossaryGuid, Map<String, String> partialUpdates) throws AtlasBaseException {
Servlets.validateQueryParamLength("glossaryGuid", glossaryGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.partialUpdateGlossary()");
}
if (MapUtils.isEmpty(partialUpdates)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "PartialUpdates missing or empty");
}
AtlasGlossary glossary = glossaryService.getGlossary(glossaryGuid);
for (Map.Entry<String, String> entry : partialUpdates.entrySet()) {
glossary.setAttribute(entry.getKey(), entry.getValue());
}
return glossaryService.updateGlossary(glossary);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Update the given glossary term
* @param termGuid unique identifier for glossary term
* @param glossaryTerm updated glossary term
* @return Updated glossary term
* @throws AtlasBaseException
* @HTTP 200 If glossary term update was successful
* @HTTP 404 If glossary term guid in invalid
* @HTTP 400 If Glossary temr definition has invalid or missing information
*/
@PUT
@Path("/term/{termGuid}")
public AtlasGlossaryTerm updateGlossaryTerm(@PathParam("termGuid") String termGuid, AtlasGlossaryTerm glossaryTerm) throws AtlasBaseException {
Servlets.validateQueryParamLength("termGuid", termGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.updateGlossaryTerm()");
}
glossaryTerm.setGuid(termGuid);
return glossaryService.updateTerm(glossaryTerm);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Partially update the glossary term
* @param termGuid unique identifier for glossary term
* @param partialUpdates Map containing keys as attribute names and values as corresponding attribute values
* @return Updated glossary term
* @throws AtlasBaseException
* @HTTP 200 If glossary partial update was successful
* @HTTP 404 If glossary term guid in invalid
* @HTTP 400 If partial attributes are invalid
*/
@PUT
@Path("/term/{termGuid}/partial")
public AtlasGlossaryTerm partialUpdateGlossaryTerm(@PathParam("termGuid") String termGuid, Map<String, String> partialUpdates) throws AtlasBaseException {
Servlets.validateQueryParamLength("termGuid", termGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.partialUpdateGlossaryTerm()");
}
if (MapUtils.isEmpty(partialUpdates)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "PartialUpdates missing or empty");
}
AtlasGlossaryTerm glossaryTerm = glossaryService.getTerm(termGuid);
for (Map.Entry<String, String> entry : partialUpdates.entrySet()) {
glossaryTerm.setAttribute(entry.getKey(), entry.getValue());
}
return glossaryService.updateTerm(glossaryTerm);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Update the given glossary category
* @param categoryGuid unique identifier for glossary category
* @param glossaryCategory updated glossary category
* @return glossary category
* @throws AtlasBaseException
* @HTTP 200 If glossary category partial update was successful
* @HTTP 404 If glossary category guid in invalid
* @HTTP 400 If Glossary category definition has invalid or missing information
*/
@PUT
@Path("/category/{categoryGuid}")
public AtlasGlossaryCategory updateGlossaryCategory(@PathParam("categoryGuid") String categoryGuid, AtlasGlossaryCategory glossaryCategory) throws AtlasBaseException {
Servlets.validateQueryParamLength("categoryGuid", categoryGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.updateGlossaryCategory()");
}
glossaryCategory.setGuid(categoryGuid);
return glossaryService.updateCategory(glossaryCategory);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Partially update the glossary category
* @param categoryGuid unique identifier for glossary term
* @param partialUpdates Map containing keys as attribute names and values as corresponding attribute values
* @return Updated glossary category
* @throws AtlasBaseException
* @HTTP 200 If glossary category partial update was successful
* @HTTP 404 If glossary category guid in invalid
* @HTTP 400 If category attributes are invalid
*/
@PUT
@Path("/category/{categoryGuid}/partial")
public AtlasGlossaryCategory partialUpdateGlossaryCategory(@PathParam("categoryGuid") String categoryGuid, Map<String, String> partialUpdates) throws AtlasBaseException {
Servlets.validateQueryParamLength("categoryGuid", categoryGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.partialUpdateGlossaryCategory()");
}
if (MapUtils.isEmpty(partialUpdates)) {
throw new AtlasBaseException(AtlasErrorCode.BAD_REQUEST, "PartialUpdates missing or empty");
}
AtlasGlossaryCategory glossaryCategory = glossaryService.getCategory(categoryGuid);
for (Map.Entry<String, String> entry : partialUpdates.entrySet()) {
glossaryCategory.setAttribute(entry.getKey(), entry.getValue());
}
return glossaryService.updateCategory(glossaryCategory);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Delete a glossary
* @param glossaryGuid unique identifier for glossary
* @throws AtlasBaseException
* @HTTP 204 If glossary delete was successful
* @HTTP 404 If glossary guid in invalid
*/
@DELETE
@Path("/{glossaryGuid}")
public void deleteGlossary(@PathParam("glossaryGuid") String glossaryGuid) throws AtlasBaseException {
Servlets.validateQueryParamLength("glossaryGuid", glossaryGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.deleteGlossary(" + glossaryGuid + ")");
}
glossaryService.deleteGlossary(glossaryGuid);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Delete a glossary term
* @param termGuid unique identifier for glossary term
* @throws AtlasBaseException
* @HTTP 204 If glossary term delete was successful
* @HTTP 404 If glossary term guid in invalid
*/
@DELETE
@Path("/term/{termGuid}")
public void deleteGlossaryTerm(@PathParam("termGuid") String termGuid) throws AtlasBaseException {
Servlets.validateQueryParamLength("termGuid", termGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.deleteGlossaryTerm(" + termGuid + ")");
}
glossaryService.deleteTerm(termGuid);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Delete a glossary category
* @param categoryGuid unique identifier for glossary category
* @throws AtlasBaseException
* @HTTP 204 If glossary category delete was successful
* @HTTP 404 If glossary category guid in invalid
*/
@DELETE
@Path("/category/{categoryGuid}")
public void deleteGlossaryCategory(@PathParam("categoryGuid") String categoryGuid) throws AtlasBaseException {
Servlets.validateQueryParamLength("categoryGuid", categoryGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.deleteGlossaryCategory(" + categoryGuid + ")");
}
glossaryService.deleteCategory(categoryGuid);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Get terms belonging to a specific glossary
* @param glossaryGuid unique identifier for glossary
* @param limit page size - by default there is no paging
* @param offset starting offset for loading terms
* @param sort ASC(default) or DESC
* @return List of terms associated with the glossary
* @throws AtlasBaseException
* @HTTP 200 List of glossary terms for the given glossary or an empty list
* @HTTP 404 If glossary guid in invalid
*/
@GET
@Path("/{glossaryGuid}/terms")
public List<AtlasGlossaryTerm> getGlossaryTerms(@PathParam("glossaryGuid") String glossaryGuid,
@DefaultValue("-1") @QueryParam("limit") String limit,
@DefaultValue("0") @QueryParam("offset") String offset,
@DefaultValue("ASC") @QueryParam("sort") final String sort) throws AtlasBaseException {
Servlets.validateQueryParamLength("glossaryGuid", glossaryGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.getGlossaryTerms(" + glossaryGuid + ")");
}
return glossaryService.getGlossaryTerms(glossaryGuid, Integer.parseInt(offset), Integer.parseInt(limit), toSortOrder(sort));
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Get the categories belonging to a specific glossary
* @param glossaryGuid unique identifier for glossary term
* @param limit page size - by default there is no paging
* @param offset offset for pagination purpose
* @param sort ASC (default) or DESC
* @return List of associated categories
* @throws AtlasBaseException
* @HTTP 200 List of glossary categories for the given glossary or an empty list
* @HTTP 404 If glossary guid in invalid
*/
@GET
@Path("/{glossaryGuid}/categories")
public List<AtlasRelatedCategoryHeader> getGlossaryCategories(@PathParam("glossaryGuid") String glossaryGuid,
@DefaultValue("-1") @QueryParam("limit") String limit,
@DefaultValue("0") @QueryParam("offset") String offset,
@DefaultValue("ASC") @QueryParam("sort") final String sort) throws AtlasBaseException {
Servlets.validateQueryParamLength("glossaryGuid", glossaryGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.getGlossaryCategories(" + glossaryGuid + ")");
}
return glossaryService.getGlossaryCategories(glossaryGuid, Integer.parseInt(offset), Integer.parseInt(limit), toSortOrder(sort));
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Get all terms associated with the specific category
* @param categoryGuid unique identifier for glossary category
* @param limit page size - by default there is no paging
* @param offset offset for pagination purpose
* @param sort ASC (default) or DESC
* @return List of associated terms
* @throws AtlasBaseException
* @HTTP 200 List of terms for the given category or an empty list
* @HTTP 404 If glossary category guid in invalid
*/
@GET
@Path("/category/{categoryGuid}/terms")
public List<AtlasRelatedTermHeader> getCategoryTerms(@PathParam("categoryGuid") String categoryGuid,
@DefaultValue("-1") @QueryParam("limit") String limit,
@DefaultValue("0") @QueryParam("offset") String offset,
@DefaultValue("ASC") @QueryParam("sort") final String sort) throws AtlasBaseException {
Servlets.validateQueryParamLength("categoryGuid", categoryGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.getCategoryTerms(" + categoryGuid + ")");
}
return glossaryService.getCategoryTerms(categoryGuid, Integer.parseInt(offset), Integer.parseInt(limit), toSortOrder(sort));
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Get all related terms for a specific term
* @param termGuid unique identifier for glossary term
* @param limit page size - by default there is no paging
* @param offset offset for pagination purpose
* @param sort ASC (default) or DESC
* @return List of all related terms
* @throws AtlasBaseException
* @HTTP 200 List of related glossary terms for the given glossary or an empty list
* @HTTP 404 If glossary term guid in invalid
*/
@GET
@Path("/terms/{termGuid}/related")
public Map<AtlasGlossaryTerm.Relation, Set<AtlasRelatedTermHeader>> getRelatedTerms(@PathParam("termGuid") String termGuid,
@DefaultValue("-1") @QueryParam("limit") String limit,
@DefaultValue("0") @QueryParam("offset") String offset,
@DefaultValue("ASC") @QueryParam("sort") final String sort) throws AtlasBaseException {
Servlets.validateQueryParamLength("termGuid", termGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.getRelatedTermsInfo(" + termGuid + ")");
}
return glossaryService.getRelatedTerms(termGuid, Integer.parseInt(offset), Integer.parseInt(limit), toSortOrder(sort));
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Get all entity headers assigned with the specified term
* @param termGuid GUID of the term
* @param limit page size - by default there is no paging
* @param offset offset for pagination purpose
* @param sort ASC (default) or DESC
* @return
* @throws AtlasBaseException
* @HTTP 200 List of entity headers (if any) for the given glossary or an empty list
* @HTTP 404 If glossary term guid in invalid
*/
@GET
@Path("/terms/{termGuid}/assignedEntities")
public List<AtlasEntityHeader> getEntitiesAssignedWithTerm(@PathParam("termGuid") String termGuid,
@DefaultValue("-1") @QueryParam("limit") String limit,
@DefaultValue("0") @QueryParam("offset") String offset,
@DefaultValue("ASC") @QueryParam("sort") final String sort) throws AtlasBaseException {
Servlets.validateQueryParamLength("termGuid", termGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.getEntitiesAssignedWithTerm(" + termGuid + ")");
}
return glossaryService.getAssignedEntities(termGuid, Integer.parseInt(offset), Integer.parseInt(limit), toSortOrder(sort));
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Assign the given term to the provided list of entity headers
* @param termGuid Glossary term GUID
* @param entityHeaders Entity headers for which the term has to be associated
* @throws AtlasBaseException
* @HTTP 204 If the term assignment was successful
* @HTTP 400 If ANY of the entity header is invalid
* @HTTP 404 If glossary guid in invalid
*/
@POST
@Path("/terms/{termGuid}/assignedEntities")
public void assignTermToEntities(@PathParam("termGuid") String termGuid, List<AtlasEntityHeader> entityHeaders) throws AtlasBaseException {
Servlets.validateQueryParamLength("termGuid", termGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.assignTermToEntities(" + termGuid + ")");
}
glossaryService.assignTermToEntities(termGuid, entityHeaders);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Remove the term assignment for the given list of entity headers
* @param termGuid Glossary term GUID
* @param entityHeaders List of entity headers from which the term has to be dissociated
* @throws AtlasBaseException
* @HTTP 204 If glossary term dissociation was successful
* @HTTP 400 If ANY of the entity header is invalid
* @HTTP 404 If glossary term guid in invalid
*/
@DELETE
@Path("/terms/{termGuid}/assignedEntities")
public void removeTermAssignmentFromEntities(@PathParam("termGuid") String termGuid, List<AtlasEntityHeader> entityHeaders) throws AtlasBaseException {
Servlets.validateQueryParamLength("termGuid", termGuid);
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.removeTermAssignmentFromEntities(" + termGuid + ")");
}
glossaryService.removeTermFromEntities(termGuid, entityHeaders);
} finally {
AtlasPerfTracer.log(perf);
}
}
/**
* Get all related categories (parent and children)
* @param categoryGuid unique identifier for glossary category
* @param limit page size - by default there is no paging
* @param offset offset for pagination purpose
* @param sort ASC (default) or DESC
* @return List of related categories
* @throws AtlasBaseException
*/
@GET
@Path("/category/{categoryGuid}/related")
public Map<String, List<AtlasRelatedCategoryHeader>> getRelatedCategories(@PathParam("categoryGuid") String categoryGuid,
@DefaultValue("-1") @QueryParam("limit") String limit,
@DefaultValue("0") @QueryParam("offset") String offset,
@DefaultValue("ASC") @QueryParam("sort") final String sort) throws AtlasBaseException {
AtlasPerfTracer perf = null;
try {
if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "GlossaryREST.getRelatedCategories()");
}
return glossaryService.getRelatedCategories(categoryGuid, Integer.parseInt(offset), Integer.parseInt(limit), toSortOrder(sort));
} finally {
AtlasPerfTracer.log(perf);
}
}
private SortOrder toSortOrder(final String sort) {
SortOrder ret = SortOrder.ASCENDING;
if (!"ASC".equals(sort)) {
if ("DESC".equals(sort)) {
ret = SortOrder.DESCENDING;
}
}
return ret;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment