diff options
author | Tal Gitelman <tg851x@intl.att.com> | 2018-05-30 15:25:07 +0300 |
---|---|---|
committer | Tal Gitelman <tg851x@intl.att.com> | 2018-05-30 13:17:08 +0000 |
commit | e7c6fa0d421e0e9df5c848ff2b6fc61c1b71871b (patch) | |
tree | bbbf77fcd067aad6cf20eac9aefcf1d49a81e216 | |
parent | bce898678176acd991d88bd5b6e1f5ebd2083184 (diff) |
new unit tests for sdc-dao
Change-Id: I00ac8b1bd58fd952b7c23d402ce71436658403b8
Issue-ID: SDC-1333
Signed-off-by: Tal Gitelman <tg851x@intl.att.com>
16 files changed, 2555 insertions, 1129 deletions
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelation.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelation.java index 4dfd1544d4..b2237332f2 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelation.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelation.java @@ -72,7 +72,9 @@ public class GraphRelation extends GraphElement { } public void addPropertis(Map<String, Object> props) { - properties.putAll(props); + if(props != null) { + properties.putAll(props); + } } public void overwritePropertis(Map<String, Object> props) { diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java index 27303613ea..d17a3d5b17 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/TitanDao.java @@ -64,964 +64,1057 @@ import fj.data.Either; @Component("titan-dao") public class TitanDao { - TitanGraphClient titanClient; - - private static Logger logger = LoggerFactory.getLogger(TitanDao.class.getName()); - - public TitanDao(@Qualifier("titan-client") TitanGraphClient titanClient) { - this.titanClient = titanClient; - logger.info("** TitanDao created"); - } - - public TitanOperationStatus commit() { - logger.debug("doing commit."); - return titanClient.commit(); - } - - public TitanOperationStatus rollback() { - return titanClient.rollback(); - } - - public Either<TitanGraph, TitanOperationStatus> getGraph() { - return titanClient.getGraph(); - } - - /** - * - * @param graphVertex - * @return - */ - public Either<GraphVertex, TitanOperationStatus> createVertex(GraphVertex graphVertex) { - logger.trace("try to create vertex for ID [{}]", graphVertex.getUniqueId()); - Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - TitanVertex vertex = tGraph.addVertex(); - - setVertexProperties(vertex, graphVertex); - - graphVertex.setVertex(vertex); - - return Either.left(graphVertex); - - } catch (Exception e) { - logger.debug("Failed to create Node for ID [{}]", graphVertex.getUniqueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - logger.debug("Failed to create vertex for ID [{}] {}", graphVertex.getUniqueId(), graph.right().value()); - return Either.right(graph.right().value()); - } - } - - /** - * - * @param name - * @param value - * @param label - * @return - */ - public Either<GraphVertex, TitanOperationStatus> getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label) { - return getVertexByPropertyAndLabel(name, value, label, JsonParseFlagEnum.ParseAll); - } - - public Either<GraphVertex, TitanOperationStatus> getVertexByLabel(VertexTypeEnum label) { - return titanClient.getGraph().left().map(graph -> graph.query().has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices()).left().bind(titanVertices -> getFirstFoundVertex(JsonParseFlagEnum.NoParse, titanVertices)); - } - - private Either<GraphVertex, TitanOperationStatus> getFirstFoundVertex(JsonParseFlagEnum parseFlag, Iterable<TitanVertex> vertices) { - Iterator<TitanVertex> iterator = vertices.iterator(); - if (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - return Either.left(graphVertex); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - /** - * - * @param name - * @param value - * @param label - * @param parseFlag - * @return - */ - public Either<GraphVertex, TitanOperationStatus> getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label, JsonParseFlagEnum parseFlag) { - - Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - @SuppressWarnings("unchecked") - Iterable<TitanVertex> vertecies = tGraph.query().has(name.getProperty(), value).has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices(); - - java.util.Iterator<TitanVertex> iterator = vertecies.iterator(); - if (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - return Either.left(graphVertex); - } - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for key = {} and value = {} label = {}" + name, value, label); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to get vertex in graph for key ={} and value = {} label = {}", name, value, label); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for key ={} and value = {} label = {} error :{}", name, value, label, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - /** - * - * @param id - * @return - */ - public Either<GraphVertex, TitanOperationStatus> getVertexById(String id) { - return getVertexById(id, JsonParseFlagEnum.ParseAll); - } - - /** - * - * @param id - * @param parseFlag - * @return - */ - public Either<GraphVertex, TitanOperationStatus> getVertexById(String id, JsonParseFlagEnum parseFlag) { - - Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph(); - if (id == null) { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for id = {} ", id); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - @SuppressWarnings("unchecked") - Iterable<TitanVertex> vertecies = tGraph.query().has(GraphPropertyEnum.UNIQUE_ID.getProperty(), id).vertices(); - - java.util.Iterator<TitanVertex> iterator = vertecies.iterator(); - if (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - return Either.left(graphVertex); - } else { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for id = {}", id); - } - return Either.right(TitanOperationStatus.NOT_FOUND); - } - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to get vertex in graph for id {} ", id); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("No vertex in graph for id {} error : {}", id, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - private void setVertexProperties(TitanVertex vertex, GraphVertex graphVertex) throws IOException { - - if (graphVertex.getMetadataProperties() != null) { - for (Map.Entry<GraphPropertyEnum, Object> entry : graphVertex.getMetadataProperties().entrySet()) { - if (entry.getValue() != null) { - vertex.property(entry.getKey().getProperty(), entry.getValue()); - } - } - } - vertex.property(GraphPropertyEnum.LABEL.getProperty(), graphVertex.getLabel().getName()); - - Map<String, ? extends ToscaDataDefinition> json = graphVertex.getJson(); - if (json != null) { - String jsonStr = JsonParserUtils.toJson(json); - vertex.property(GraphPropertyEnum.JSON.getProperty(), jsonStr); - - } - Map<String, Object> jsonMetadata = graphVertex.getMetadataJson(); - if (jsonMetadata != null) { - String jsonMetadataStr = JsonParserUtils.toJson(jsonMetadata); - vertex.property(GraphPropertyEnum.METADATA.getProperty(), jsonMetadataStr); - } - } - - public void setVertexProperties(Vertex vertex, Map<String, Object> properties) throws IOException { - for (Map.Entry<String, Object> entry : properties.entrySet()) { - if (entry.getValue() != null) { - vertex.property(entry.getKey(), entry.getValue()); - } - } - } - - private GraphVertex createAndFill(TitanVertex vertex, JsonParseFlagEnum parseFlag) { - GraphVertex graphVertex = new GraphVertex(); - graphVertex.setVertex(vertex); - parseVertexProperties(graphVertex, parseFlag); - return graphVertex; - } - - public void parseVertexProperties(GraphVertex graphVertex, JsonParseFlagEnum parseFlag) { - TitanVertex vertex = graphVertex.getVertex(); - Map<GraphPropertyEnum, Object> properties = getVertexProperties(vertex); - VertexTypeEnum label = VertexTypeEnum.getByName((String) (properties.get(GraphPropertyEnum.LABEL))); - for (Map.Entry<GraphPropertyEnum, Object> entry : properties.entrySet()) { - GraphPropertyEnum key = entry.getKey(); - switch (key) { - case UNIQUE_ID: - graphVertex.setUniqueId((String) entry.getValue()); - break; - case LABEL: - graphVertex.setLabel(VertexTypeEnum.getByName((String) entry.getValue())); - break; - case COMPONENT_TYPE: - String type = (String) entry.getValue(); - if (type != null) { - graphVertex.setType(ComponentTypeEnum.valueOf(type)); - } - break; - case JSON: - if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseJson) { - String json = (String) entry.getValue(); - Map<String, ? extends ToscaDataDefinition> jsonObj = JsonParserUtils.toMap(json, label.getClassOfJson()); - graphVertex.setJson(jsonObj); - } - break; - case METADATA: - if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseMetadata) { - String json = (String) entry.getValue(); - Map<String, Object> metadatObj = JsonParserUtils.toMap(json); - graphVertex.setMetadataJson(metadatObj); - } - break; - default: - graphVertex.addMetadataProperty(key, entry.getValue()); - break; - } - } - } - - public TitanOperationStatus createEdge(GraphVertex from, GraphVertex to, EdgeLabelEnum label, Map<EdgePropertyEnum, Object> properties) { - return createEdge(from.getVertex(), to.getVertex(), label, properties); - } - - public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Map<EdgePropertyEnum, Object> properties) { - if (logger.isTraceEnabled()) { - logger.trace("Try to connect {} with {} label {} properties {}", from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), to.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), label, properties); - } - if (from == null || to == null) { - logger.trace("No Titan vertex for id from {} or id to {}", from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), to.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); - return TitanOperationStatus.NOT_FOUND; - } - Edge edge = from.addEdge(label.name(), to); - setEdgeProperties(edge, properties); - return TitanOperationStatus.OK; - } - - public Map<GraphPropertyEnum, Object> getVertexProperties(Element element) { - - Map<GraphPropertyEnum, Object> result = new HashMap<GraphPropertyEnum, Object>(); - - if (element != null && element.keys() != null && element.keys().size() > 0) { - Map<String, Property> propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()])); - - for (Entry<String, Property> entry : propertyMap.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue().value(); - - GraphPropertyEnum valueOf = GraphPropertyEnum.getByProperty(key); - if (valueOf != null) { - result.put(valueOf, value); - } - } - } - return result; - } - - public Map<EdgePropertyEnum, Object> getEdgeProperties(Element element) { - - Map<EdgePropertyEnum, Object> result = new HashMap<EdgePropertyEnum, Object>(); - - if (element != null && element.keys() != null && element.keys().size() > 0) { - Map<String, Property> propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()])); - - for (Entry<String, Property> entry : propertyMap.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue().value(); - - EdgePropertyEnum valueOf = EdgePropertyEnum.getByProperty(key); - if (valueOf != null) { - result.put(valueOf, value); - } - } - } - return result; - } - - public void setEdgeProperties(Element element, Map<EdgePropertyEnum, Object> properties) { - - if (properties != null && !properties.isEmpty()) { - - Object[] propertyKeyValues = new Object[properties.size() * 2]; - int i = 0; - for (Entry<EdgePropertyEnum, Object> entry : properties.entrySet()) { - propertyKeyValues[i++] = entry.getKey().getProperty(); - propertyKeyValues[i++] = entry.getValue(); - } - - ElementHelper.attachProperties(element, propertyKeyValues); - - } - - } - - public Either<List<GraphVertex>, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map<GraphPropertyEnum, Object> props) { - return getByCriteria(type, props, JsonParseFlagEnum.ParseAll); - } - - public Either<List<GraphVertex>, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map<GraphPropertyEnum, Object> props, JsonParseFlagEnum parseFlag) { - Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query(); - if (type != null) { - query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName()); - } - - if (props != null && !props.isEmpty()) { - for (Map.Entry<GraphPropertyEnum, Object> entry : props.entrySet()) { - query = query.has(entry.getKey().getProperty(), entry.getValue()); - } - } - Iterable<TitanVertex> vertices = query.vertices(); - if (vertices == null) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - Iterator<TitanVertex> iterator = vertices.iterator(); - List<GraphVertex> result = new ArrayList<GraphVertex>(); - - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - - Map<GraphPropertyEnum, Object> newProp = getVertexProperties(vertex); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - result.add(graphVertex); - } - if (logger.isDebugEnabled()) { - logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size()); - } - if (result.size() == 0) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - return Either.left(result); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - public Either<List<GraphVertex>, TitanOperationStatus> getByCriteria(VertexTypeEnum type, Map<GraphPropertyEnum, Object> props, Map<GraphPropertyEnum, Object> hasNotProps, JsonParseFlagEnum parseFlag) { - Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query(); - if (type != null) { - query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName()); - } - - if (props != null && !props.isEmpty()) { - for (Map.Entry<GraphPropertyEnum, Object> entry : props.entrySet()) { - query = query.has(entry.getKey().getProperty(), entry.getValue()); - } - } - if (hasNotProps != null && !hasNotProps.isEmpty()) { - for (Map.Entry<GraphPropertyEnum, Object> entry : hasNotProps.entrySet()) { - if (entry.getValue() instanceof List) { - buildMultipleNegateQueryFromList(entry, query); - } else { - query = query.hasNot(entry.getKey().getProperty(), entry.getValue()); - } - } - } - Iterable<TitanVertex> vertices = query.vertices(); - if (vertices == null) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - Iterator<TitanVertex> iterator = vertices.iterator(); - List<GraphVertex> result = new ArrayList<GraphVertex>(); - - while (iterator.hasNext()) { - TitanVertex vertex = iterator.next(); - - Map<GraphPropertyEnum, Object> newProp = getVertexProperties(vertex); - GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - result.add(graphVertex); - } - if (logger.isDebugEnabled()) { - logger.debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size()); - } - if (result.size() == 0) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - - return Either.left(result); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - public Either<Iterator<Vertex>, TitanOperationStatus> getCatalogVerticies() { - Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph(); - if (graph.isLeft()) { - try { - TitanGraph tGraph = graph.left().value(); - - Iterable<TitanVertex> vCatalogIter = tGraph.query().has(GraphPropertyEnum.LABEL.getProperty(), VertexTypeEnum.CATALOG_ROOT.getName()).vertices(); - if (vCatalogIter == null) { - logger.debug("Failed to fetch catalog vertex"); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - TitanVertex catalogV = vCatalogIter.iterator().next(); - if (catalogV == null) { - logger.debug("Failed to fetch catalog vertex"); - return Either.right(TitanOperationStatus.GENERAL_ERROR); - } - Iterator<Vertex> vertices = catalogV.vertices(Direction.OUT, EdgeLabelEnum.CATALOG_ELEMENT.name()); - - return Either.left(vertices); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria: ", e); - } - return Either.right(TitanGraphClient.handleTitanException(e)); - } - - } else { - if (logger.isDebugEnabled()) { - logger.debug("Failed get by criteria : ", graph.right().value()); - } - return Either.right(graph.right().value()); - } - } - - private void buildMultipleNegateQueryFromList(Map.Entry<GraphPropertyEnum, Object> entry, TitanGraphQuery query) { - List<Object> negateList = (List<Object>) entry.getValue(); - for (Object listItem : negateList) { - query.hasNot(entry.getKey().getProperty(), listItem); - } - } - - /** - * - * @param parentVertex - * @param edgeLabel - * @param parseFlag - * @return - */ - public Either<GraphVertex, TitanOperationStatus> getChildVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, edgeLabel, parseFlag); - if (childrenVertecies.isRight()) { - return Either.right(childrenVertecies.right().value()); - } - return Either.left(childrenVertecies.left().value().get(0)); - } - - /** - * - * @param parentVertex - * @param edgeLabel - * @param parseFlag - * @return - */ - public Either<Vertex, TitanOperationStatus> getChildVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - Either<List<Vertex>, TitanOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, edgeLabel, parseFlag); - if (childrenVertecies.isRight()) { - return Either.right(childrenVertecies.right().value()); - } - return Either.left(childrenVertecies.left().value().get(0)); - } - - public Either<GraphVertex, TitanOperationStatus> getParentVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, parseFlag); - if (childrenVertecies.isRight()) { - return Either.right(childrenVertecies.right().value()); - } - return Either.left(childrenVertecies.left().value().get(0)); - } - - public Either<Vertex, TitanOperationStatus> getParentVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - Either<List<Vertex>, TitanOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, parseFlag); - if (childrenVertecies.isRight()) { - return Either.right(childrenVertecies.right().value()); - } - return Either.left(childrenVertecies.left().value().get(0)); - } - - /** - * - * @param parentVertex - * @param edgeLabel - * @param parseFlag - * @return - */ - public Either<List<GraphVertex>, TitanOperationStatus> getChildrenVertecies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT); - } - - public Either<List<GraphVertex>, TitanOperationStatus> getParentVertecies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN); - } - - public Either<List<Vertex>, TitanOperationStatus> getParentVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN); - } - - private Either<List<Vertex>, TitanOperationStatus> getAdjacentVerticies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) { - List<Vertex> list = new ArrayList<>(); - try { - Either<TitanGraph, TitanOperationStatus> graphRes = titanClient.getGraph(); - if (graphRes.isRight()) { - logger.error("Failed to retrieve graph. status is {}", graphRes); - return Either.right(graphRes.right().value()); - } - Iterator<Edge> edgesCreatorIterator = parentVertex.edges(direction, edgeLabel.name()); - if (edgesCreatorIterator != null) { - while (edgesCreatorIterator.hasNext()) { - Edge edge = edgesCreatorIterator.next(); - TitanVertex vertex; - if (direction == Direction.IN) { - vertex = (TitanVertex) edge.outVertex(); - } else { - vertex = (TitanVertex) edge.inVertex(); - } - // GraphVertex graphVertex = createAndFill(vertex, parseFlag); - - list.add(vertex); - } - } - if (true == list.isEmpty()) { - return Either.right(TitanOperationStatus.NOT_FOUND); - } - } catch (Exception e) { - logger.error("Failed to perform graph operation ", e); - Either.right(TitanGraphClient.handleTitanException(e)); - } - - return Either.left(list); - } - - /** - * - * @param parentVertex - * @param edgeLabel - * @param parseFlag - * @return - */ - public Either<List<Vertex>, TitanOperationStatus> getChildrenVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { - return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT); - } - - private Either<List<GraphVertex>, TitanOperationStatus> getAdjacentVerticies(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) { - List<GraphVertex> list = new ArrayList<GraphVertex>(); - - Either<List<Vertex>, TitanOperationStatus> adjacentVerticies = getAdjacentVerticies(parentVertex.getVertex(), edgeLabel, parseFlag, direction); - if (adjacentVerticies.isRight()) { - return Either.right(adjacentVerticies.right().value()); - } - adjacentVerticies.left().value().stream().forEach(vertex -> { - list.add(createAndFill((TitanVertex) vertex, parseFlag)); - }); - - return Either.left(list); - } - - /** - * Searches Edge by received label and criteria - * - * @param vertex - * @param label - * @param properties - * @return found edge or TitanOperationStatus - */ - public Either<Edge, TitanOperationStatus> getBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, Map<GraphPropertyEnum, Object> properties) { - - Either<Edge, TitanOperationStatus> result = null; - Edge matchingEdge = null; - String notFoundMsg = "No edges in graph for criteria"; - try { - TitanVertexQuery<?> query = vertex.getVertex().query().labels(label.name()); - - if (properties != null && !properties.isEmpty()) { - for (Map.Entry<GraphPropertyEnum, Object> entry : properties.entrySet()) { - query = query.has(entry.getKey().getProperty(), entry.getValue()); - } - } - - Iterable<TitanEdge> edges = query.edges(); - if (edges == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); - result = Either.right(TitanOperationStatus.NOT_FOUND); - } else { - Iterator<TitanEdge> eIter = edges.iterator(); - if (eIter.hasNext()) { - matchingEdge = eIter.next(); - } else { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); - result = Either.right(TitanOperationStatus.NOT_FOUND); - } - } - if (result == null) { - result = Either.left(matchingEdge); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during getting edge by criteria for component with id {}. {}", vertex.getUniqueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - return result; - } - - /** - * Deletes Edge by received label and criteria - * - * @param vertex - * @param label - * @param properties - * @return - */ - public Either<Edge, TitanOperationStatus> deleteBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, Map<GraphPropertyEnum, Object> properties) { - Either<Edge, TitanOperationStatus> result = null; - try { - result = getBelongingEdgeByCriteria(vertex, label, properties); - if (result.isLeft()) { - Edge edge = result.left().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} belonging to the vertex {} ", label.name(), vertex.getUniqueId()); - edge.remove(); - result = Either.left(edge); - } else { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find an edge with the label {} belonging to the vertex {} ", label.name(), vertex.getUniqueId()); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge by criteria for the component with id {}. {}", vertex.getUniqueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - return result; - } - - @SuppressWarnings("unchecked") - /** - * Deletes an edge between vertices fromVertex and toVertex according to received label - * - * @param fromVertex - * @param toVertex - * @param label - * @return - */ - - public Either<Edge, TitanOperationStatus> deleteEdge(GraphVertex fromVertex, GraphVertex toVertex, EdgeLabelEnum label) { - return deleteEdge(fromVertex.getVertex(), toVertex.getVertex(), label, fromVertex.getUniqueId(), toVertex.getUniqueId()); - } - - public Either<Edge, TitanOperationStatus> deleteEdge(TitanVertex fromVertex, TitanVertex toVertex, EdgeLabelEnum label, String uniqueIdFrom, String uniqueIdTo) { - Either<Edge, TitanOperationStatus> result = null; - try { - Iterable<TitanEdge> edges = fromVertex.query().labels(label.name()).edges(); - Iterator<TitanEdge> eIter = edges.iterator(); - while (eIter.hasNext()) { - Edge edge = eIter.next(); - String currVertexUniqueId = edge.inVertex().value(GraphPropertyEnum.UNIQUE_ID.getProperty()); - if (currVertexUniqueId != null && currVertexUniqueId.equals(uniqueIdTo)) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} between vertices {} and {}. ", label.name(), uniqueIdFrom, uniqueIdTo); - edge.remove(); - result = Either.left(edge); - break; - } - } - if (result == null) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete an edge with the label {} between vertices {} and {}. ", label.name(), uniqueIdFrom, uniqueIdTo); - result = Either.right(TitanOperationStatus.NOT_FOUND); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge with the label {} between vertices {} and {}. {}", label.name(), uniqueIdFrom, uniqueIdTo, e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - return result; - } - - public TitanOperationStatus deleteEdgeByDirection(GraphVertex fromVertex, Direction direction, EdgeLabelEnum label) { - try { - Iterator<Edge> edges = fromVertex.getVertex().edges(direction, label.name()); - - while (edges.hasNext()) { - Edge edge = edges.next(); - edge.remove(); - } - } catch (Exception e) { - logger.debug("Failed to remove from vertex {} edges {} by direction {} ", fromVertex.getUniqueId(), label, direction, e); - return TitanGraphClient.handleTitanException(e); - } - return TitanOperationStatus.OK; - } - - /** - * Updates vertex properties. Note that graphVertex argument should contain updated data - * - * @param graphVertex - * @return - */ - public Either<GraphVertex, TitanOperationStatus> updateVertex(GraphVertex graphVertex) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId()); - try { - graphVertex.updateMetadataJsonWithCurrentMetadataProperties(); - setVertexProperties(graphVertex.getVertex(), graphVertex); - - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId(), e); - return Either.right(TitanGraphClient.handleTitanException(e)); - } - return Either.left(graphVertex); - } - - /** - * Fetches vertices by uniqueId according to received parse flag - * - * @param verticesToGet - * @return - */ - public Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesByUniqueIdAndParseFlag(Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGet) { - - Either<Map<String, GraphVertex>, TitanOperationStatus> result = null; - Map<String, GraphVertex> vertices = new HashMap<>(); - TitanOperationStatus titatStatus; - Either<GraphVertex, TitanOperationStatus> getVertexRes = null; - for (Map.Entry<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> entry : verticesToGet.entrySet()) { - if (entry.getValue().getKey() == GraphPropertyEnum.UNIQUE_ID) { - getVertexRes = getVertexById(entry.getKey(), entry.getValue().getValue()); - } else if (entry.getValue().getKey() == GraphPropertyEnum.USERID) { - getVertexRes = getVertexByPropertyAndLabel(entry.getValue().getKey(), entry.getKey(), VertexTypeEnum.USER, entry.getValue().getValue()); - } - if (getVertexRes == null) { - titatStatus = TitanOperationStatus.ILLEGAL_ARGUMENT; - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Invalid vertex type label {} has been received. ", entry.getValue().getKey(), titatStatus); - result = Either.right(titatStatus); - } - if (getVertexRes.isRight()) { - titatStatus = getVertexRes.right().value(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get vertex by id {} . Status is {}. ", entry.getKey(), titatStatus); - result = Either.right(titatStatus); - break; - } else { - vertices.put(entry.getKey(), getVertexRes.left().value()); - } - } - if (result == null) { - result = Either.left(vertices); - } - return result; - } - - /** - * Creates edge between "from" and "to" vertices with specified label and properties extracted from received edge - * - * @param from - * @param to - * @param label - * @param edgeToCopy - * @return - */ - public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Edge edgeToCopy) { - return createEdge(from, to, label, getEdgeProperties(edgeToCopy)); - } - - public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, Edge prevEdge, EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) { - - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), - toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); - TitanOperationStatus result = createEdge(fromVertex, toVertex, newLabel, prevEdge); - if (result == TitanOperationStatus.OK) { - prevEdge.remove(); - } - return result; - } - - /** - * Replaces previous label of edge with new label - * - * @param fromVertex - * @param toVertex - * @param prevLabel - * @param newLabel - * @return - */ - public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) { - - TitanOperationStatus result = null; - Iterator<Edge> prevEdgeIter = toVertex.edges(Direction.IN, prevLabel.name()); - if (prevEdgeIter == null || !prevEdgeIter.hasNext()) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), - toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); - result = TitanOperationStatus.NOT_FOUND; - } - if (result == null) { - result = replaceEdgeLabel(fromVertex, toVertex, prevEdgeIter.next(), prevLabel, newLabel); - } - return result; - } - - /** - * Updates metadata properties of vertex on graph. Json metadata property of the vertex will be updated with received properties too. - * - * - * @param vertex - * @param properties - * @return - */ - public TitanOperationStatus updateVertexMetadataPropertiesWithJson(Vertex vertex, Map<GraphPropertyEnum, Object> properties) { - try { - if (!MapUtils.isEmpty(properties)) { - String jsonMetadataStr = (String) vertex.property(GraphPropertyEnum.METADATA.getProperty()).value(); - Map<String, Object> jsonMetadataMap = JsonParserUtils.toMap(jsonMetadataStr); - for (Map.Entry<GraphPropertyEnum, Object> property : properties.entrySet()) { - vertex.property(property.getKey().getProperty(), property.getValue()); - jsonMetadataMap.put(property.getKey().getProperty(), property.getValue()); - } - vertex.property(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.toJson(jsonMetadataMap)); - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occurred during update vertex metadata properties with json{}. {}", vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), e.getMessage()); - return TitanGraphClient.handleTitanException(e); - } - return TitanOperationStatus.OK; - } - - public TitanOperationStatus disassociateAndDeleteLast(GraphVertex vertex, Direction direction, EdgeLabelEnum label) { - try { - Iterator<Edge> edges = vertex.getVertex().edges(direction, label.name()); - - while (edges.hasNext()) { - Edge edge = edges.next(); - Vertex secondVertex; - Direction reverseDirection; - if (direction == Direction.IN) { - secondVertex = edge.outVertex(); - reverseDirection = Direction.OUT; - } else { - secondVertex = edge.inVertex(); - reverseDirection = Direction.IN; - } - edge.remove(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Edge {} with direction {} was removed from {}", label.name(), direction, vertex.getVertex()); - - Iterator<Edge> restOfEdges = secondVertex.edges(reverseDirection, label.name()); - if (restOfEdges.hasNext() == false) { - secondVertex.remove(); - CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "This was last edge . Vertex {} was removed ", vertex.getUniqueId()); - } - } - } catch (Exception e) { - CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge with the label {} direction {} from vertex {}. {}", label.name(), direction, vertex.getUniqueId(), e); - return TitanGraphClient.handleTitanException(e); - } - return TitanOperationStatus.OK; - } - - public Object getProperty(TitanVertex vertex, String key) { - PropertyKey propertyKey = titanClient.getGraph().left().value().getPropertyKey(key); - Object value = vertex.valueOrNull(propertyKey); - return value; - } - - public Object getProperty(Edge edge, EdgePropertyEnum key) { - Object value = null; - try { - Property<Object> property = edge.property(key.getProperty()); - if (property != null) { - return property.orElse(null); - } - } catch (Exception e) { - - } - return value; - } - - /** - * - * @param vertexA - * @param vertexB - * @param label - * @param direction - * @return - */ - public TitanOperationStatus moveEdge(GraphVertex vertexA, GraphVertex vertexB, EdgeLabelEnum label, Direction direction) { - TitanOperationStatus result = deleteEdgeByDirection(vertexA, direction, label); - if (result != TitanOperationStatus.OK) { - logger.error("Failed to diassociate {} from element {}. error {} ", label, vertexA.getUniqueId(), result); - return result; - } - TitanOperationStatus createRelation; - if (direction == Direction.IN) { - createRelation = createEdge(vertexB, vertexA, label, null); - } else { - createRelation = createEdge(vertexA, vertexB, label, null); - } - if (createRelation != TitanOperationStatus.OK) { - return createRelation; - } - return TitanOperationStatus.OK; - } - - public Either<Edge, TitanOperationStatus> getBelongingEdgeByCriteria(String parentId, EdgeLabelEnum label, Map<GraphPropertyEnum, Object> properties) { - Either<GraphVertex, TitanOperationStatus> getVertexRes = getVertexById(parentId, JsonParseFlagEnum.NoParse); - if (getVertexRes.isRight()) { - return Either.right(getVertexRes.right().value()); - } - return getBelongingEdgeByCriteria(getVertexRes.left().value(), label, properties); - } + TitanGraphClient titanClient; + + private static Logger logger = LoggerFactory.getLogger(TitanDao.class.getName()); + + public TitanDao(@Qualifier("titan-client") TitanGraphClient titanClient) { + this.titanClient = titanClient; + logger.info("** TitanDao created"); + } + + public TitanOperationStatus commit() { + logger.debug("doing commit."); + return titanClient.commit(); + } + + public TitanOperationStatus rollback() { + return titanClient.rollback(); + } + + public Either<TitanGraph, TitanOperationStatus> getGraph() { + return titanClient.getGraph(); + } + + /** + * + * @param graphVertex + * @return + */ + public Either<GraphVertex, TitanOperationStatus> createVertex(GraphVertex graphVertex) { + logger.trace("try to create vertex for ID [{}]", graphVertex.getUniqueId()); + Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph(); + if (graph.isLeft()) { + try { + TitanGraph tGraph = graph.left().value(); + + TitanVertex vertex = tGraph.addVertex(); + + setVertexProperties(vertex, graphVertex); + + graphVertex.setVertex(vertex); + + return Either.left(graphVertex); + + } catch (Exception e) { + logger.debug("Failed to create Node for ID [{}]", graphVertex.getUniqueId(), e); + return Either.right(TitanGraphClient.handleTitanException(e)); + } + } else { + logger.debug("Failed to create vertex for ID [{}] {}", graphVertex.getUniqueId(), graph.right().value()); + return Either.right(graph.right().value()); + } + } + + /** + * + * @param name + * @param value + * @param label + * @return + */ + public Either<GraphVertex, TitanOperationStatus> getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, + VertexTypeEnum label) { + return getVertexByPropertyAndLabel(name, value, label, JsonParseFlagEnum.ParseAll); + } + + public Either<GraphVertex, TitanOperationStatus> getVertexByLabel(VertexTypeEnum label) { + return titanClient.getGraph().left() + .map(graph -> graph.query().has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices()) + .left().bind(titanVertices -> getFirstFoundVertex(JsonParseFlagEnum.NoParse, titanVertices)); + } + + private Either<GraphVertex, TitanOperationStatus> getFirstFoundVertex(JsonParseFlagEnum parseFlag, + Iterable<TitanVertex> vertices) { + Iterator<TitanVertex> iterator = vertices.iterator(); + if (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + return Either.left(graphVertex); + } + return Either.right(TitanOperationStatus.NOT_FOUND); + } + + /** + * + * @param name + * @param value + * @param label + * @param parseFlag + * @return + */ + public Either<GraphVertex, TitanOperationStatus> getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, + VertexTypeEnum label, JsonParseFlagEnum parseFlag) { + + Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph(); + if (graph.isLeft()) { + try { + TitanGraph tGraph = graph.left().value(); + + @SuppressWarnings("unchecked") + Iterable<TitanVertex> vertecies = tGraph.query().has(name.getProperty(), value) + .has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices(); + + java.util.Iterator<TitanVertex> iterator = vertecies.iterator(); + if (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + return Either.left(graphVertex); + } + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for key = {} and value = {} label = {}" + name, value, label); + } + return Either.right(TitanOperationStatus.NOT_FOUND); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed to get vertex in graph for key ={} and value = {} label = {}", name, value, + label); + } + return Either.right(TitanGraphClient.handleTitanException(e)); + } + + } else { + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for key ={} and value = {} label = {} error :{}", name, value, label, + graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + /** + * + * @param id + * @return + */ + public Either<GraphVertex, TitanOperationStatus> getVertexById(String id) { + return getVertexById(id, JsonParseFlagEnum.ParseAll); + } + + /** + * + * @param id + * @param parseFlag + * @return + */ + public Either<GraphVertex, TitanOperationStatus> getVertexById(String id, JsonParseFlagEnum parseFlag) { + + Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph(); + if (id == null) { + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for id = {} ", id); + } + return Either.right(TitanOperationStatus.NOT_FOUND); + } + if (graph.isLeft()) { + try { + TitanGraph tGraph = graph.left().value(); + + @SuppressWarnings("unchecked") + Iterable<TitanVertex> vertecies = tGraph.query().has(GraphPropertyEnum.UNIQUE_ID.getProperty(), id) + .vertices(); + + java.util.Iterator<TitanVertex> iterator = vertecies.iterator(); + if (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + return Either.left(graphVertex); + } else { + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for id = {}", id); + } + return Either.right(TitanOperationStatus.NOT_FOUND); + } + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed to get vertex in graph for id {} ", id); + } + return Either.right(TitanGraphClient.handleTitanException(e)); + } + } else { + if (logger.isDebugEnabled()) { + logger.debug("No vertex in graph for id {} error : {}", id, graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + private void setVertexProperties(TitanVertex vertex, GraphVertex graphVertex) throws IOException { + + if (graphVertex.getMetadataProperties() != null) { + for (Map.Entry<GraphPropertyEnum, Object> entry : graphVertex.getMetadataProperties().entrySet()) { + if (entry.getValue() != null) { + vertex.property(entry.getKey().getProperty(), entry.getValue()); + } + } + } + vertex.property(GraphPropertyEnum.LABEL.getProperty(), graphVertex.getLabel().getName()); + + Map<String, ? extends ToscaDataDefinition> json = graphVertex.getJson(); + if (json != null) { + String jsonStr = JsonParserUtils.toJson(json); + vertex.property(GraphPropertyEnum.JSON.getProperty(), jsonStr); + + } + Map<String, Object> jsonMetadata = graphVertex.getMetadataJson(); + if (jsonMetadata != null) { + String jsonMetadataStr = JsonParserUtils.toJson(jsonMetadata); + vertex.property(GraphPropertyEnum.METADATA.getProperty(), jsonMetadataStr); + } + } + + public void setVertexProperties(Vertex vertex, Map<String, Object> properties) throws IOException { + for (Map.Entry<String, Object> entry : properties.entrySet()) { + if (entry.getValue() != null) { + vertex.property(entry.getKey(), entry.getValue()); + } + } + } + + private GraphVertex createAndFill(TitanVertex vertex, JsonParseFlagEnum parseFlag) { + GraphVertex graphVertex = new GraphVertex(); + graphVertex.setVertex(vertex); + parseVertexProperties(graphVertex, parseFlag); + return graphVertex; + } + + public void parseVertexProperties(GraphVertex graphVertex, JsonParseFlagEnum parseFlag) { + TitanVertex vertex = graphVertex.getVertex(); + Map<GraphPropertyEnum, Object> properties = getVertexProperties(vertex); + VertexTypeEnum label = VertexTypeEnum.getByName((String) (properties.get(GraphPropertyEnum.LABEL))); + for (Map.Entry<GraphPropertyEnum, Object> entry : properties.entrySet()) { + GraphPropertyEnum key = entry.getKey(); + switch (key) { + case UNIQUE_ID: + graphVertex.setUniqueId((String) entry.getValue()); + break; + case LABEL: + graphVertex.setLabel(VertexTypeEnum.getByName((String) entry.getValue())); + break; + case COMPONENT_TYPE: + String type = (String) entry.getValue(); + if (type != null) { + graphVertex.setType(ComponentTypeEnum.valueOf(type)); + } + break; + case JSON: + if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseJson) { + String json = (String) entry.getValue(); + Map<String, ? extends ToscaDataDefinition> jsonObj = JsonParserUtils.toMap(json, + label.getClassOfJson()); + graphVertex.setJson(jsonObj); + } + break; + case METADATA: + if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseMetadata) { + String json = (String) entry.getValue(); + Map<String, Object> metadatObj = JsonParserUtils.toMap(json); + graphVertex.setMetadataJson(metadatObj); + } + break; + default: + graphVertex.addMetadataProperty(key, entry.getValue()); + break; + } + } + } + + public TitanOperationStatus createEdge(GraphVertex from, GraphVertex to, EdgeLabelEnum label, + Map<EdgePropertyEnum, Object> properties) { + return createEdge(from.getVertex(), to.getVertex(), label, properties); + } + + public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, + Map<EdgePropertyEnum, Object> properties) { + logger.trace("Try to connect {} with {} label {} properties {}", + from == null ? "NULL" : from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), + to == null ? "NULL" : to.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), label, properties); + if (from == null || to == null) { + logger.trace("No Titan vertex for id from {} or id to {}", + from == null ? "NULL" : from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), + to == null ? "NULL" : to.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); + return TitanOperationStatus.NOT_FOUND; + } + Edge edge = from.addEdge(label.name(), to); + setEdgeProperties(edge, properties); + return TitanOperationStatus.OK; + } + + public Map<GraphPropertyEnum, Object> getVertexProperties(Element element) { + + Map<GraphPropertyEnum, Object> result = new HashMap<GraphPropertyEnum, Object>(); + + if (element != null && element.keys() != null && element.keys().size() > 0) { + Map<String, Property> propertyMap = ElementHelper.propertyMap(element, + element.keys().toArray(new String[element.keys().size()])); + + for (Entry<String, Property> entry : propertyMap.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue().value(); + + GraphPropertyEnum valueOf = GraphPropertyEnum.getByProperty(key); + if (valueOf != null) { + result.put(valueOf, value); + } + } + } + return result; + } + + public Map<EdgePropertyEnum, Object> getEdgeProperties(Element element) { + + Map<EdgePropertyEnum, Object> result = new HashMap<EdgePropertyEnum, Object>(); + + if (element != null && element.keys() != null && element.keys().size() > 0) { + Map<String, Property> propertyMap = ElementHelper.propertyMap(element, + element.keys().toArray(new String[element.keys().size()])); + + for (Entry<String, Property> entry : propertyMap.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue().value(); + + EdgePropertyEnum valueOf = EdgePropertyEnum.getByProperty(key); + if (valueOf != null) { + result.put(valueOf, value); + } + } + } + return result; + } + + public void setEdgeProperties(Element element, Map<EdgePropertyEnum, Object> properties) { + + if (properties != null && !properties.isEmpty()) { + + Object[] propertyKeyValues = new Object[properties.size() * 2]; + int i = 0; + for (Entry<EdgePropertyEnum, Object> entry : properties.entrySet()) { + propertyKeyValues[i++] = entry.getKey().getProperty(); + propertyKeyValues[i++] = entry.getValue(); + } + + ElementHelper.attachProperties(element, propertyKeyValues); + + } + + } + + public Either<List<GraphVertex>, TitanOperationStatus> getByCriteria(VertexTypeEnum type, + Map<GraphPropertyEnum, Object> props) { + return getByCriteria(type, props, JsonParseFlagEnum.ParseAll); + } + + public Either<List<GraphVertex>, TitanOperationStatus> getByCriteria(VertexTypeEnum type, + Map<GraphPropertyEnum, Object> props, JsonParseFlagEnum parseFlag) { + Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph(); + if (graph.isLeft()) { + try { + TitanGraph tGraph = graph.left().value(); + + TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query(); + if (type != null) { + query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName()); + } + + if (props != null && !props.isEmpty()) { + for (Map.Entry<GraphPropertyEnum, Object> entry : props.entrySet()) { + query = query.has(entry.getKey().getProperty(), entry.getValue()); + } + } + Iterable<TitanVertex> vertices = query.vertices(); + if (vertices == null) { + return Either.right(TitanOperationStatus.NOT_FOUND); + } + + Iterator<TitanVertex> iterator = vertices.iterator(); + List<GraphVertex> result = new ArrayList<GraphVertex>(); + + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + + Map<GraphPropertyEnum, Object> newProp = getVertexProperties(vertex); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + result.add(graphVertex); + } + if (logger.isDebugEnabled()) { + logger.debug( + "Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", + type, props, result.size()); + } + if (result.size() == 0) { + return Either.right(TitanOperationStatus.NOT_FOUND); + } + + return Either.left(result); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); + } + return Either.right(TitanGraphClient.handleTitanException(e)); + } + + } else { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, + graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + public Either<List<GraphVertex>, TitanOperationStatus> getByCriteria(VertexTypeEnum type, + Map<GraphPropertyEnum, Object> props, Map<GraphPropertyEnum, Object> hasNotProps, + JsonParseFlagEnum parseFlag) { + Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph(); + if (graph.isLeft()) { + try { + TitanGraph tGraph = graph.left().value(); + + TitanGraphQuery<? extends TitanGraphQuery> query = tGraph.query(); + if (type != null) { + query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName()); + } + + if (props != null && !props.isEmpty()) { + for (Map.Entry<GraphPropertyEnum, Object> entry : props.entrySet()) { + query = query.has(entry.getKey().getProperty(), entry.getValue()); + } + } + if (hasNotProps != null && !hasNotProps.isEmpty()) { + for (Map.Entry<GraphPropertyEnum, Object> entry : hasNotProps.entrySet()) { + if (entry.getValue() instanceof List) { + buildMultipleNegateQueryFromList(entry, query); + } else { + query = query.hasNot(entry.getKey().getProperty(), entry.getValue()); + } + } + } + Iterable<TitanVertex> vertices = query.vertices(); + if (vertices == null) { + return Either.right(TitanOperationStatus.NOT_FOUND); + } + + Iterator<TitanVertex> iterator = vertices.iterator(); + List<GraphVertex> result = new ArrayList<GraphVertex>(); + + while (iterator.hasNext()) { + TitanVertex vertex = iterator.next(); + + Map<GraphPropertyEnum, Object> newProp = getVertexProperties(vertex); + GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + result.add(graphVertex); + } + if (logger.isDebugEnabled()) { + logger.debug( + "Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", + type, props, result.size()); + } + if (result.size() == 0) { + return Either.right(TitanOperationStatus.NOT_FOUND); + } + + return Either.left(result); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e); + } + return Either.right(TitanGraphClient.handleTitanException(e)); + } + + } else { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, + graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + public Either<Iterator<Vertex>, TitanOperationStatus> getCatalogVerticies() { + Either<TitanGraph, TitanOperationStatus> graph = titanClient.getGraph(); + if (graph.isLeft()) { + try { + TitanGraph tGraph = graph.left().value(); + + Iterable<TitanVertex> vCatalogIter = tGraph.query() + .has(GraphPropertyEnum.LABEL.getProperty(), VertexTypeEnum.CATALOG_ROOT.getName()).vertices(); + if (vCatalogIter == null) { + logger.debug("Failed to fetch catalog vertex"); + return Either.right(TitanOperationStatus.GENERAL_ERROR); + } + TitanVertex catalogV = vCatalogIter.iterator().next(); + if (catalogV == null) { + logger.debug("Failed to fetch catalog vertex"); + return Either.right(TitanOperationStatus.GENERAL_ERROR); + } + Iterator<Vertex> vertices = catalogV.vertices(Direction.OUT, EdgeLabelEnum.CATALOG_ELEMENT.name()); + + return Either.left(vertices); + } catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria: ", e); + } + return Either.right(TitanGraphClient.handleTitanException(e)); + } + + } else { + if (logger.isDebugEnabled()) { + logger.debug("Failed get by criteria : ", graph.right().value()); + } + return Either.right(graph.right().value()); + } + } + + private void buildMultipleNegateQueryFromList(Map.Entry<GraphPropertyEnum, Object> entry, TitanGraphQuery query) { + List<Object> negateList = (List<Object>) entry.getValue(); + for (Object listItem : negateList) { + query.hasNot(entry.getKey().getProperty(), listItem); + } + } + + /** + * + * @param parentVertex + * @param edgeLabel + * @param parseFlag + * @return + */ + public Either<GraphVertex, TitanOperationStatus> getChildVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, + JsonParseFlagEnum parseFlag) { + Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, + edgeLabel, parseFlag); + if (childrenVertecies.isRight()) { + return Either.right(childrenVertecies.right().value()); + } + return Either.left(childrenVertecies.left().value().get(0)); + } + + /** + * + * @param parentVertex + * @param edgeLabel + * @param parseFlag + * @return + */ + public Either<Vertex, TitanOperationStatus> getChildVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, + JsonParseFlagEnum parseFlag) { + Either<List<Vertex>, TitanOperationStatus> childrenVertecies = getChildrenVertecies(parentVertex, edgeLabel, + parseFlag); + if (childrenVertecies.isRight()) { + return Either.right(childrenVertecies.right().value()); + } + return Either.left(childrenVertecies.left().value().get(0)); + } + + public Either<GraphVertex, TitanOperationStatus> getParentVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel, + JsonParseFlagEnum parseFlag) { + Either<List<GraphVertex>, TitanOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, + parseFlag); + if (childrenVertecies.isRight()) { + return Either.right(childrenVertecies.right().value()); + } + return Either.left(childrenVertecies.left().value().get(0)); + } + + public Either<Vertex, TitanOperationStatus> getParentVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, + JsonParseFlagEnum parseFlag) { + Either<List<Vertex>, TitanOperationStatus> childrenVertecies = getParentVertecies(parentVertex, edgeLabel, + parseFlag); + if (childrenVertecies.isRight()) { + return Either.right(childrenVertecies.right().value()); + } + List<Vertex> value = childrenVertecies.left().value(); + if (value.isEmpty()) { + return Either.right(TitanOperationStatus.NOT_FOUND); + } + return Either.left(value.get(0)); + } + + /** + * + * @param parentVertex + * @param edgeLabel + * @param parseFlag + * @return + */ + public Either<List<GraphVertex>, TitanOperationStatus> getChildrenVertecies(GraphVertex parentVertex, + EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT); + } + + public Either<List<GraphVertex>, TitanOperationStatus> getParentVertecies(GraphVertex parentVertex, + EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) { + return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN); + } + + public Either<List<Vertex>, TitanOperationStatus> getParentVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, + JsonParseFlagEnum parseFlag) { + return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.IN); + } + + private Either<List<Vertex>, TitanOperationStatus> getAdjacentVerticies(Vertex parentVertex, + EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) { + List<Vertex> list = new ArrayList<>(); + try { + Either<TitanGraph, TitanOperationStatus> graphRes = titanClient.getGraph(); + if (graphRes.isRight()) { + logger.error("Failed to retrieve graph. status is {}", graphRes); + return Either.right(graphRes.right().value()); + } + Iterator<Edge> edgesCreatorIterator = parentVertex.edges(direction, edgeLabel.name()); + if (edgesCreatorIterator != null) { + while (edgesCreatorIterator.hasNext()) { + Edge edge = edgesCreatorIterator.next(); + TitanVertex vertex; + if (direction == Direction.IN) { + vertex = (TitanVertex) edge.outVertex(); + } else { + vertex = (TitanVertex) edge.inVertex(); + } + // GraphVertex graphVertex = createAndFill(vertex, parseFlag); + + list.add(vertex); + } + } + if (true == list.isEmpty()) { + return Either.right(TitanOperationStatus.NOT_FOUND); + } + } catch (Exception e) { + logger.error("Failed to perform graph operation ", e); + Either.right(TitanGraphClient.handleTitanException(e)); + } + + return Either.left(list); + } + + /** + * + * @param parentVertex + * @param edgeLabel + * @param parseFlag + * @return + */ + public Either<List<Vertex>, TitanOperationStatus> getChildrenVertecies(Vertex parentVertex, EdgeLabelEnum edgeLabel, + JsonParseFlagEnum parseFlag) { + return getAdjacentVerticies(parentVertex, edgeLabel, parseFlag, Direction.OUT); + } + + private Either<List<GraphVertex>, TitanOperationStatus> getAdjacentVerticies(GraphVertex parentVertex, + EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag, Direction direction) { + List<GraphVertex> list = new ArrayList<GraphVertex>(); + + Either<List<Vertex>, TitanOperationStatus> adjacentVerticies = getAdjacentVerticies(parentVertex.getVertex(), + edgeLabel, parseFlag, direction); + if (adjacentVerticies.isRight()) { + return Either.right(adjacentVerticies.right().value()); + } + adjacentVerticies.left().value().stream().forEach(vertex -> { + list.add(createAndFill((TitanVertex) vertex, parseFlag)); + }); + + return Either.left(list); + } + + /** + * Searches Edge by received label and criteria + * + * @param vertex + * @param label + * @param properties + * @return found edge or TitanOperationStatus + */ + public Either<Edge, TitanOperationStatus> getBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, + Map<GraphPropertyEnum, Object> properties) { + + Either<Edge, TitanOperationStatus> result = null; + Edge matchingEdge = null; + String notFoundMsg = "No edges in graph for criteria"; + try { + TitanVertexQuery<?> query = vertex.getVertex().query().labels(label.name()); + + if (properties != null && !properties.isEmpty()) { + for (Map.Entry<GraphPropertyEnum, Object> entry : properties.entrySet()) { + query = query.has(entry.getKey().getProperty(), entry.getValue()); + } + } + + Iterable<TitanEdge> edges = query.edges(); + if (edges == null) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); + result = Either.right(TitanOperationStatus.NOT_FOUND); + } else { + Iterator<TitanEdge> eIter = edges.iterator(); + if (eIter.hasNext()) { + matchingEdge = eIter.next(); + } else { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg); + result = Either.right(TitanOperationStatus.NOT_FOUND); + } + } + if (result == null) { + result = Either.left(matchingEdge); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, + "Exception occured during getting edge by criteria for component with id {}. {}", + vertex.getUniqueId(), e); + return Either.right(TitanGraphClient.handleTitanException(e)); + } + return result; + } + + /** + * Deletes Edge by received label and criteria + * + * @param vertex + * @param label + * @param properties + * @return + */ + public Either<Edge, TitanOperationStatus> deleteBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label, + Map<GraphPropertyEnum, Object> properties) { + Either<Edge, TitanOperationStatus> result = null; + try { + result = getBelongingEdgeByCriteria(vertex, label, properties); + if (result.isLeft()) { + Edge edge = result.left().value(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, + "Going to delete an edge with the label {} belonging to the vertex {} ", label.name(), + vertex.getUniqueId()); + edge.remove(); + result = Either.left(edge); + } else { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, + "Failed to find an edge with the label {} belonging to the vertex {} ", label.name(), + vertex.getUniqueId()); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, + "Exception occured during deleting an edge by criteria for the component with id {}. {}", + vertex == null ? "NULL" : vertex.getUniqueId(), e); + return Either.right(TitanGraphClient.handleTitanException(e)); + } + return result; + } + + @SuppressWarnings("unchecked") + /** + * Deletes an edge between vertices fromVertex and toVertex according to + * received label + * + * @param fromVertex + * @param toVertex + * @param label + * @return + */ + + public Either<Edge, TitanOperationStatus> deleteEdge(GraphVertex fromVertex, GraphVertex toVertex, + EdgeLabelEnum label) { + return deleteEdge(fromVertex.getVertex(), toVertex.getVertex(), label, fromVertex.getUniqueId(), + toVertex.getUniqueId()); + } + + public Either<Edge, TitanOperationStatus> deleteEdge(TitanVertex fromVertex, TitanVertex toVertex, + EdgeLabelEnum label, String uniqueIdFrom, String uniqueIdTo) { + Either<Edge, TitanOperationStatus> result = null; + try { + Iterable<TitanEdge> edges = fromVertex.query().labels(label.name()).edges(); + Iterator<TitanEdge> eIter = edges.iterator(); + while (eIter.hasNext()) { + Edge edge = eIter.next(); + String currVertexUniqueId = edge.inVertex().value(GraphPropertyEnum.UNIQUE_ID.getProperty()); + if (currVertexUniqueId != null && currVertexUniqueId.equals(uniqueIdTo)) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, + "Going to delete an edge with the label {} between vertices {} and {}. ", label.name(), + uniqueIdFrom, uniqueIdTo); + edge.remove(); + result = Either.left(edge); + break; + } + } + if (result == null) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, + "Failed to delete an edge with the label {} between vertices {} and {}. ", label.name(), + uniqueIdFrom, uniqueIdTo); + result = Either.right(TitanOperationStatus.NOT_FOUND); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, + "Exception occured during deleting an edge with the label {} between vertices {} and {}. {}", + label.name(), uniqueIdFrom, uniqueIdTo, e); + return Either.right(TitanGraphClient.handleTitanException(e)); + } + return result; + } + + public TitanOperationStatus deleteEdgeByDirection(GraphVertex fromVertex, Direction direction, + EdgeLabelEnum label) { + try { + Iterator<Edge> edges = fromVertex.getVertex().edges(direction, label.name()); + + while (edges.hasNext()) { + Edge edge = edges.next(); + edge.remove(); + } + } catch (Exception e) { + logger.debug("Failed to remove from vertex {} edges {} by direction {} ", fromVertex.getUniqueId(), label, + direction, e); + return TitanGraphClient.handleTitanException(e); + } + return TitanOperationStatus.OK; + } + + /** + * Updates vertex properties. Note that graphVertex argument should contain + * updated data + * + * @param graphVertex + * @return + */ + public Either<GraphVertex, TitanOperationStatus> updateVertex(GraphVertex graphVertex) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, + "Going to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId()); + try { + graphVertex.updateMetadataJsonWithCurrentMetadataProperties(); + setVertexProperties(graphVertex.getVertex(), graphVertex); + + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, + "Failed to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId(), e); + return Either.right(TitanGraphClient.handleTitanException(e)); + } + return Either.left(graphVertex); + } + + /** + * Fetches vertices by uniqueId according to received parse flag + * + * @param verticesToGet + * @return + */ + public Either<Map<String, GraphVertex>, TitanOperationStatus> getVerticesByUniqueIdAndParseFlag( + Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGet) { + + Either<Map<String, GraphVertex>, TitanOperationStatus> result = null; + Map<String, GraphVertex> vertices = new HashMap<>(); + TitanOperationStatus titatStatus; + Either<GraphVertex, TitanOperationStatus> getVertexRes = null; + for (Map.Entry<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> entry : verticesToGet.entrySet()) { + if (entry.getValue().getKey() == GraphPropertyEnum.UNIQUE_ID) { + getVertexRes = getVertexById(entry.getKey(), entry.getValue().getValue()); + } else if (entry.getValue().getKey() == GraphPropertyEnum.USERID) { + getVertexRes = getVertexByPropertyAndLabel(entry.getValue().getKey(), entry.getKey(), + VertexTypeEnum.USER, entry.getValue().getValue()); + } + if (getVertexRes == null) { + titatStatus = TitanOperationStatus.ILLEGAL_ARGUMENT; + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, + "Invalid vertex type label {} has been received. ", entry.getValue().getKey(), titatStatus); + result = Either.right(titatStatus); + } + if (getVertexRes.isRight()) { + titatStatus = getVertexRes.right().value(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, + "Failed to get vertex by id {} . Status is {}. ", entry.getKey(), titatStatus); + result = Either.right(titatStatus); + break; + } else { + vertices.put(entry.getKey(), getVertexRes.left().value()); + } + } + if (result == null) { + result = Either.left(vertices); + } + return result; + } + + /** + * Creates edge between "from" and "to" vertices with specified label and + * properties extracted from received edge + * + * @param from + * @param to + * @param label + * @param edgeToCopy + * @return + */ + public TitanOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Edge edgeToCopy) { + return createEdge(from, to, label, getEdgeProperties(edgeToCopy)); + } + + public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, Edge prevEdge, + EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) { + + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, + "Going to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, + fromVertex == null ? "NULL" : fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), + toVertex == null ? "NULL" : toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); + TitanOperationStatus result = createEdge(fromVertex, toVertex, newLabel, prevEdge); + if (result == TitanOperationStatus.OK) { + prevEdge.remove(); + } + return result; + } + + /** + * Replaces previous label of edge with new label + * + * @param fromVertex + * @param toVertex + * @param prevLabel + * @param newLabel + * @return + */ + public TitanOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, EdgeLabelEnum prevLabel, + EdgeLabelEnum newLabel) { + + TitanOperationStatus result = null; + Iterator<Edge> prevEdgeIter = toVertex.edges(Direction.IN, prevLabel.name()); + if (prevEdgeIter == null || !prevEdgeIter.hasNext()) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, + "Failed to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel, + fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), + toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty())); + result = TitanOperationStatus.NOT_FOUND; + } + if (result == null) { + result = replaceEdgeLabel(fromVertex, toVertex, prevEdgeIter.next(), prevLabel, newLabel); + } + return result; + } + + /** + * Updates metadata properties of vertex on graph. Json metadata property of the + * vertex will be updated with received properties too. + * + * + * @param vertex + * @param properties + * @return + */ + public TitanOperationStatus updateVertexMetadataPropertiesWithJson(Vertex vertex, + Map<GraphPropertyEnum, Object> properties) { + try { + if (!MapUtils.isEmpty(properties)) { + String jsonMetadataStr = (String) vertex.property(GraphPropertyEnum.METADATA.getProperty()).value(); + Map<String, Object> jsonMetadataMap = JsonParserUtils.toMap(jsonMetadataStr); + for (Map.Entry<GraphPropertyEnum, Object> property : properties.entrySet()) { + vertex.property(property.getKey().getProperty(), property.getValue()); + jsonMetadataMap.put(property.getKey().getProperty(), property.getValue()); + } + vertex.property(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.toJson(jsonMetadataMap)); + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, + "Exception occurred during update vertex metadata properties with json{}. {}", + vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), e.getMessage()); + return TitanGraphClient.handleTitanException(e); + } + return TitanOperationStatus.OK; + } + + public TitanOperationStatus disassociateAndDeleteLast(GraphVertex vertex, Direction direction, + EdgeLabelEnum label) { + try { + Iterator<Edge> edges = vertex.getVertex().edges(direction, label.name()); + + while (edges.hasNext()) { + Edge edge = edges.next(); + Vertex secondVertex; + Direction reverseDirection; + if (direction == Direction.IN) { + secondVertex = edge.outVertex(); + reverseDirection = Direction.OUT; + } else { + secondVertex = edge.inVertex(); + reverseDirection = Direction.IN; + } + edge.remove(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, + "Edge {} with direction {} was removed from {}", label.name(), direction, vertex.getVertex()); + + Iterator<Edge> restOfEdges = secondVertex.edges(reverseDirection, label.name()); + if (restOfEdges.hasNext() == false) { + secondVertex.remove(); + CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, + "This was last edge . Vertex {} was removed ", vertex.getUniqueId()); + } + } + } catch (Exception e) { + CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, + "Exception occured during deleting an edge with the label {} direction {} from vertex {}. {}", + label.name(), direction, vertex.getUniqueId(), e); + return TitanGraphClient.handleTitanException(e); + } + return TitanOperationStatus.OK; + } + + public Object getProperty(TitanVertex vertex, String key) { + PropertyKey propertyKey = titanClient.getGraph().left().value().getPropertyKey(key); + Object value = vertex.valueOrNull(propertyKey); + return value; + } + + public Object getProperty(Edge edge, EdgePropertyEnum key) { + Object value = null; + try { + Property<Object> property = edge.property(key.getProperty()); + if (property != null) { + return property.orElse(null); + } + } catch (Exception e) { + + } + return value; + } + + /** + * + * @param vertexA + * @param vertexB + * @param label + * @param direction + * @return + */ + public TitanOperationStatus moveEdge(GraphVertex vertexA, GraphVertex vertexB, EdgeLabelEnum label, + Direction direction) { + TitanOperationStatus result = deleteEdgeByDirection(vertexA, direction, label); + if (result != TitanOperationStatus.OK) { + logger.error("Failed to diassociate {} from element {}. error {} ", label, vertexA.getUniqueId(), result); + return result; + } + TitanOperationStatus createRelation; + if (direction == Direction.IN) { + createRelation = createEdge(vertexB, vertexA, label, null); + } else { + createRelation = createEdge(vertexA, vertexB, label, null); + } + if (createRelation != TitanOperationStatus.OK) { + return createRelation; + } + return TitanOperationStatus.OK; + } + + public Either<Edge, TitanOperationStatus> getBelongingEdgeByCriteria(String parentId, EdgeLabelEnum label, + Map<GraphPropertyEnum, Object> properties) { + Either<GraphVertex, TitanOperationStatus> getVertexRes = getVertexById(parentId, JsonParseFlagEnum.NoParse); + if (getVertexRes.isRight()) { + return Either.right(getVertexRes.right().value()); + } + return getBelongingEdgeByCriteria(getVertexRes.left().value(), label, properties); + } } diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/es/ElasticSearchClientTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/es/ElasticSearchClientTest.java index b5c971496b..e9661e9605 100644 --- a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/es/ElasticSearchClientTest.java +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/es/ElasticSearchClientTest.java @@ -1,18 +1,30 @@ package org.openecomp.sdc.be.dao.es; -import javax.annotation.Generated; - import org.elasticsearch.client.Client; import org.junit.Test; +import org.openecomp.sdc.be.utils.DAOConfDependentTest; -@Generated(value = "org.junit-tools-1.0.6") -public class ElasticSearchClientTest { +public class ElasticSearchClientTest extends DAOConfDependentTest{ private ElasticSearchClient createTestSubject() { return new ElasticSearchClient(); } @Test + public void testInitialize() throws Exception { + ElasticSearchClient testSubject; + + // default test + testSubject = createTestSubject(); + testSubject.setTransportClient("true"); + testSubject.setLocal("true"); + testSubject.initialize(); + testSubject.setTransportClient("false"); + testSubject.setClusterName("false"); + testSubject.initialize(); + } + + @Test public void testClose() throws Exception { ElasticSearchClient testSubject; @@ -80,6 +92,9 @@ public class ElasticSearchClientTest { testSubject = createTestSubject(); strIsLocal = ""; testSubject.setLocal(strIsLocal); + + strIsLocal = "true"; + testSubject.setLocal(strIsLocal); } @@ -106,7 +121,7 @@ public class ElasticSearchClientTest { // test 2 testSubject = createTestSubject(); - strIsTransportclient = ""; + strIsTransportclient = "true"; testSubject.setTransportClient(strIsTransportclient); } }
\ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/graph/GraphElementFactoryTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/graph/GraphElementFactoryTest.java new file mode 100644 index 0000000000..588eb046a5 --- /dev/null +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/graph/GraphElementFactoryTest.java @@ -0,0 +1,76 @@ +package org.openecomp.sdc.be.dao.graph; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.tinkerpop.gremlin.structure.T; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; +import org.openecomp.sdc.be.dao.graph.datatype.GraphNode; +import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; + +import mockit.Deencapsulation; + +public class GraphElementFactoryTest { + + @Test + public void testCreateElement() throws Exception { + String label = "mock"; + Map<String, Object> properties = new HashMap<>(); + Class<GraphNode> clazz = (Class<GraphNode>) (Mockito.mock(GraphNode.class)).getClass(); + + // default test + GraphElementFactory.createElement(label, GraphElementTypeEnum.Node, properties, clazz); + } + + @Test + public void testCreateElement_1() throws Exception { + String label = "mock"; + GraphElementTypeEnum type = null; + Map<String, Object> properties = new HashMap<>(); + GraphNode result; + + // default test + result = GraphElementFactory.createElement(label, GraphElementTypeEnum.Node, properties); + } + + @Test + public void testCreateRelation() throws Exception { + String type = ""; + Map<String, Object> properties = new HashMap<>(); + GraphNode from = Mockito.mock(GraphNode.class); + GraphNode to = Mockito.mock(GraphNode.class); + ; + GraphRelation result; + + // default test + result = GraphElementFactory.createRelation(type, properties, from, to); + } + + @Test + public void testCreateNode() throws Exception { + Map<String, Object> properties = new HashMap<>(); + GraphNode result; + + result = Deencapsulation.invoke(GraphElementFactory.class, "createNode", NodeTypeEnum.User.getName(), + properties); + result = Deencapsulation.invoke(GraphElementFactory.class, "createNode", + NodeTypeEnum.ResourceCategory.getName(), properties); + result = Deencapsulation.invoke(GraphElementFactory.class, "createNode", NodeTypeEnum.ServiceCategory.getName(), + properties); + result = Deencapsulation.invoke(GraphElementFactory.class, "createNode", NodeTypeEnum.Tag.getName(), + properties); + result = Deencapsulation.invoke(GraphElementFactory.class, "createNode", NodeTypeEnum.Service.getName(), + properties); + // result = Deencapsulation.invoke(GraphElementFactory.class, "createNode", + // NodeTypeEnum.Resource.getName(), properties); + result = Deencapsulation.invoke(GraphElementFactory.class, "createNode", NodeTypeEnum.Property.getName(), + properties); + result = Deencapsulation.invoke(GraphElementFactory.class, "createNode", NodeTypeEnum.HeatParameter.getName(), + properties); + result = Deencapsulation.invoke(GraphElementFactory.class, "createNode", + NodeTypeEnum.HeatParameterValue.getName(), properties); + } +}
\ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/graph/datatype/GraphEdgeTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/graph/datatype/GraphEdgeTest.java new file mode 100644 index 0000000000..fba04bb55c --- /dev/null +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/graph/datatype/GraphEdgeTest.java @@ -0,0 +1,102 @@ +package org.openecomp.sdc.be.dao.graph.datatype; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels; + +public class GraphEdgeTest { + + private GraphEdge createTestSubject() { + return new GraphEdge(); + } + + @Test + public void testCtor() throws Exception { + new GraphEdge(GraphEdgeLabels.ADDITIONAL_INFORMATION, new HashMap<>()); + } + + @Test + public void testGetEdgeType() throws Exception { + GraphEdge testSubject; + GraphEdgeLabels result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getEdgeType(); + } + + @Test + public void testSetEdgeType() throws Exception { + GraphEdge testSubject; + GraphEdgeLabels edgeType = null; + + // default test + testSubject = createTestSubject(); + testSubject.setEdgeType(edgeType); + } + + @Test + public void testGetProperties() throws Exception { + GraphEdge testSubject; + Map<String, Object> result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getProperties(); + } + + @Test + public void testSetProperties() throws Exception { + GraphEdge testSubject; + Map<String, Object> properties = null; + + // default test + testSubject = createTestSubject(); + testSubject.setProperties(properties); + } + + @Test + public void testHashCode() throws Exception { + GraphEdge testSubject; + int result; + + // default test + testSubject = createTestSubject(); + result = testSubject.hashCode(); + } + + @Test + public void testEquals() throws Exception { + GraphEdge testSubject; + Object obj = null; + boolean result; + + // test 1 + testSubject = createTestSubject(); + obj = null; + result = testSubject.equals(obj); + Assert.assertEquals(false, result); + + result = testSubject.equals(testSubject); + Assert.assertEquals(true, result); + + result = testSubject.equals(createTestSubject()); + Assert.assertEquals(true, result); + + result = testSubject.equals(new Object()); + Assert.assertEquals(false, result); + } + + @Test + public void testToString() throws Exception { + GraphEdge testSubject; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.toString(); + } +}
\ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelationTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelationTest.java new file mode 100644 index 0000000000..5d47f5d735 --- /dev/null +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/graph/datatype/GraphRelationTest.java @@ -0,0 +1,171 @@ +package org.openecomp.sdc.be.dao.graph.datatype; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +public class GraphRelationTest { + + private GraphRelation createTestSubject() { + return new GraphRelation(); + } + + @Test + public void testCtor() throws Exception { + new GraphRelation("mock"); + } + + @Test + public void testGetFrom() throws Exception { + GraphRelation testSubject; + RelationEndPoint result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getFrom(); + } + + @Test + public void testSetFrom() throws Exception { + GraphRelation testSubject; + RelationEndPoint from = null; + + // default test + testSubject = createTestSubject(); + testSubject.setFrom(from); + } + + @Test + public void testGetTo() throws Exception { + GraphRelation testSubject; + RelationEndPoint result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getTo(); + } + + @Test + public void testSetTo() throws Exception { + GraphRelation testSubject; + RelationEndPoint to = null; + + // default test + testSubject = createTestSubject(); + testSubject.setTo(to); + } + + @Test + public void testGetType() throws Exception { + GraphRelation testSubject; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getType(); + } + + @Test + public void testSetType() throws Exception { + GraphRelation testSubject; + String type = ""; + + // default test + testSubject = createTestSubject(); + testSubject.setType(type); + } + + @Test + public void testAddProperty() throws Exception { + GraphRelation testSubject; + String property = ""; + Object value = null; + + // test 1 + testSubject = createTestSubject(); + property = null; + value = null; + testSubject.addProperty(property, value); + + // test 2 + testSubject = createTestSubject(); + property = ""; + value = null; + testSubject.addProperty(property, value); + + // test 3 + testSubject = createTestSubject(); + value = null; + property = null; + testSubject.addProperty(property, value); + + testSubject = createTestSubject(); + value = new Object(); + property = "mock"; + testSubject.addProperty(property, value); + } + + @Test + public void testAddPropertis() throws Exception { + GraphRelation testSubject; + Map<String, Object> props = null; + + // default test + testSubject = createTestSubject(); + testSubject.addPropertis(props); + props = new HashMap<>(); + testSubject.addPropertis(props); + } + + @Test + public void testOverwritePropertis() throws Exception { + GraphRelation testSubject; + Map<String, Object> props = null; + + // default test + testSubject = createTestSubject(); + testSubject.overwritePropertis(props); + } + + @Test + public void testGetProperty() throws Exception { + GraphRelation testSubject; + String property = ""; + Object result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getProperty(property); + } + + @Test + public void testToGraphMap() throws Exception { + GraphRelation testSubject; + Map<String, Object> result; + + // default test + testSubject = createTestSubject(); + result = testSubject.toGraphMap(); + } + + @Test + public void testToString() throws Exception { + GraphRelation testSubject; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.toString(); + } + + @Test + public void testHashCode() throws Exception { + GraphRelation testSubject; + int result; + + // default test + testSubject = createTestSubject(); + result = testSubject.hashCode(); + } +}
\ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/graph/datatype/RelationEndPointTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/graph/datatype/RelationEndPointTest.java new file mode 100644 index 0000000000..7e1a8358cf --- /dev/null +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/graph/datatype/RelationEndPointTest.java @@ -0,0 +1,114 @@ +package org.openecomp.sdc.be.dao.graph.datatype; + +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; + +public class RelationEndPointTest { + + private RelationEndPoint createTestSubject() { + return new RelationEndPoint(NodeTypeEnum.AdditionalInfoParameters, "", null); + } + + @Test + public void testGetLabel() throws Exception { + RelationEndPoint testSubject; + NodeTypeEnum result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getLabel(); + } + + @Test + public void testSetLabel() throws Exception { + RelationEndPoint testSubject; + NodeTypeEnum label = null; + + // default test + testSubject = createTestSubject(); + testSubject.setLabel(label); + } + + @Test + public void testGetIdName() throws Exception { + RelationEndPoint testSubject; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getIdName(); + } + + @Test + public void testSetIdName() throws Exception { + RelationEndPoint testSubject; + String idName = ""; + + // default test + testSubject = createTestSubject(); + testSubject.setIdName(idName); + } + + @Test + public void testGetIdValue() throws Exception { + RelationEndPoint testSubject; + Object result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getIdValue(); + } + + @Test + public void testSetIdValue() throws Exception { + RelationEndPoint testSubject; + Object idValue = null; + + // default test + testSubject = createTestSubject(); + testSubject.setIdValue(idValue); + } + + @Test + public void testToString() throws Exception { + RelationEndPoint testSubject; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.toString(); + } + + @Test + public void testHashCode() throws Exception { + RelationEndPoint testSubject; + int result; + + // default test + testSubject = createTestSubject(); + result = testSubject.hashCode(); + } + + @Test + public void testEquals() throws Exception { + RelationEndPoint testSubject; + Object obj = null; + boolean result; + + // test 1 + testSubject = createTestSubject(); + obj = null; + result = testSubject.equals(obj); + Assert.assertEquals(false, result); + + result = testSubject.equals(testSubject); + Assert.assertEquals(true, result); + + result = testSubject.equals(createTestSubject()); + Assert.assertEquals(true, result); + + result = testSubject.equals(new Object()); + Assert.assertEquals(false, result); + } +}
\ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertexTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertexTest.java index ae51f64d05..e09257d1f9 100644 --- a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertexTest.java +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/GraphVertexTest.java @@ -1,9 +1,11 @@ package org.openecomp.sdc.be.dao.jsongraph; +import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; @@ -16,7 +18,11 @@ public class GraphVertexTest { private GraphVertex createTestSubject() { return new GraphVertex(); } - + + @Test + public void testCtor() throws Exception { + new GraphVertex(VertexTypeEnum.ADDITIONAL_INFORMATION); + } @Test public void testGetUniqueId() throws Exception { @@ -181,12 +187,14 @@ public class GraphVertexTest { @Test public void testGetJsonMetadataField() throws Exception { GraphVertex testSubject; - JsonPresentationFields field = null; Object result; // default test testSubject = createTestSubject(); - result = testSubject.getJsonMetadataField(field); + result = testSubject.getJsonMetadataField(JsonPresentationFields.API_URL); + testSubject = createTestSubject(); + testSubject.setType(ComponentTypeEnum.RESOURCE); + result = testSubject.getJsonMetadataField(JsonPresentationFields.API_URL); } @@ -197,5 +205,38 @@ public class GraphVertexTest { // default test testSubject = createTestSubject(); testSubject.updateMetadataJsonWithCurrentMetadataProperties(); + Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(); + metadataProperties.put(GraphPropertyEnum.COMPONENT_TYPE, "mock"); + testSubject.setMetadataProperties(metadataProperties ); + testSubject.updateMetadataJsonWithCurrentMetadataProperties(); + } + + @Test + public void testGetType() throws Exception { + GraphVertex testSubject; + + // default test + testSubject = createTestSubject(); + testSubject.setType(ComponentTypeEnum.RESOURCE); + testSubject.getType(); + } + + @Test + public void testCloneData() throws Exception { + GraphVertex testSubject; + + // default test + testSubject = createTestSubject(); + testSubject.cloneData(new GraphVertex()); + } + + @Test + public void testSetJsonMetadataField() throws Exception { + GraphVertex testSubject; + + // default test + testSubject = createTestSubject(); + testSubject.setJsonMetadataField(JsonPresentationFields.API_URL, "mock"); } + }
\ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoMockTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoMockTest.java new file mode 100644 index 0000000000..f31e08e2fb --- /dev/null +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoMockTest.java @@ -0,0 +1,584 @@ +package org.openecomp.sdc.be.dao.jsongraph; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Element; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; +import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; +import org.openecomp.sdc.be.dao.titan.TitanGraphClient; +import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; + +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanVertex; + +import fj.data.Either; +import mockit.Deencapsulation; + +public class TitanDaoMockTest { + + @InjectMocks + TitanDao testSubject; + + @Mock + TitanGraphClient titanClient; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testCommit() throws Exception { + TitanOperationStatus result; + + // default test + result = testSubject.commit(); + } + + @Test + public void testRollback() throws Exception { + TitanOperationStatus result; + + // default test + result = testSubject.rollback(); + } + + @Test + public void testGetGraph() throws Exception { + + Either<TitanGraph, TitanOperationStatus> result; + + // default test + + result = testSubject.getGraph(); + } + + @Test + public void testCreateVertex() throws Exception { + + GraphVertex graphVertex = new GraphVertex(); + graphVertex.setLabel(VertexTypeEnum.ADDITIONAL_INFORMATION); + Either<GraphVertex, TitanOperationStatus> result; + + TitanGraph tg = Mockito.mock(TitanGraph.class); + Either<TitanGraph, TitanOperationStatus> value = Either.left(tg); + // default test + TitanVertex value2 = Mockito.mock(TitanVertex.class); + Mockito.when(tg.addVertex()).thenReturn(value2); + Mockito.when(titanClient.getGraph()).thenReturn(value); + result = testSubject.createVertex(graphVertex); + } + + @Test + public void testCreateVertexErrorGetGraph() throws Exception { + + GraphVertex graphVertex = new GraphVertex(); + graphVertex.setLabel(VertexTypeEnum.ADDITIONAL_INFORMATION); + Either<GraphVertex, TitanOperationStatus> result; + + Either<TitanGraph, TitanOperationStatus> value = Either.right(TitanOperationStatus.GENERAL_ERROR); + // default test + Mockito.when(titanClient.getGraph()).thenReturn(value); + result = testSubject.createVertex(graphVertex); + } + + @Test + public void testCreateVertexException() throws Exception { + + GraphVertex graphVertex = new GraphVertex(); + graphVertex.setLabel(VertexTypeEnum.ADDITIONAL_INFORMATION); + Either<GraphVertex, TitanOperationStatus> result; + + TitanGraph tg = Mockito.mock(TitanGraph.class); + Either<TitanGraph, TitanOperationStatus> value = Either.left(tg); + // default test + Mockito.when(tg.addVertex()).thenThrow(RuntimeException.class); + Mockito.when(titanClient.getGraph()).thenReturn(value); + result = testSubject.createVertex(graphVertex); + } + + @Test + public void testGetVertexByPropertyAndLabel() throws Exception { + Either<GraphVertex, TitanOperationStatus> result; + + // default test + Mockito.when(titanClient.getGraph()).thenReturn(Either.right(TitanOperationStatus.GENERAL_ERROR)); + result = testSubject.getVertexByPropertyAndLabel(GraphPropertyEnum.COMPONENT_TYPE, "mock", + VertexTypeEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testGetFirstFoundVertex() throws Exception { + Iterable<TitanVertex> vertices = Mockito.mock(Iterable.class); + Either<GraphVertex, TitanOperationStatus> result; + + Iterator<TitanVertex> value = Mockito.mock(Iterator.class); + Mockito.when(vertices.iterator()).thenReturn(value); + Mockito.when(value.hasNext()).thenReturn(true); + TitanVertex value2 = Mockito.mock(TitanVertex.class); + Mockito.when(value.next()).thenReturn(value2); + + // default test + result = Deencapsulation.invoke(testSubject, "getFirstFoundVertex", JsonParseFlagEnum.NoParse, vertices); + } + + @Test + public void testGetFirstFoundVertexNotFound() throws Exception { + Iterable<TitanVertex> vertices = Mockito.mock(Iterable.class); + Either<GraphVertex, TitanOperationStatus> result; + + Iterator<TitanVertex> value = Mockito.mock(Iterator.class); + Mockito.when(vertices.iterator()).thenReturn(value); + Mockito.when(value.hasNext()).thenReturn(false); + TitanVertex value2 = Mockito.mock(TitanVertex.class); + Mockito.when(value.next()).thenReturn(value2); + + // default test + result = Deencapsulation.invoke(testSubject, "getFirstFoundVertex", JsonParseFlagEnum.NoParse, vertices); + } + + @Test + public void testGetVertexById_1Exception() throws Exception { + + String id = "mock"; + Either<GraphVertex, TitanOperationStatus> result; + + TitanGraph tg = Mockito.mock(TitanGraph.class); + Either<TitanGraph, TitanOperationStatus> value = Either.left(tg); + // default test + TitanVertex value2 = Mockito.mock(TitanVertex.class); + Mockito.when(tg.addVertex()).thenReturn(value2); + Mockito.when(titanClient.getGraph()).thenReturn(value); + + // test 1 + result = testSubject.getVertexById(id, JsonParseFlagEnum.NoParse); + // Assert.assertEquals(null, result); + } + + @Test + public void testGetVertexById_1GraphClosed() throws Exception { + + String id = "mock"; + Either<GraphVertex, TitanOperationStatus> result; + + Object b; + Either<TitanGraph, TitanOperationStatus> value = Either.right(TitanOperationStatus.GENERAL_ERROR); + // default test + TitanVertex value2 = Mockito.mock(TitanVertex.class); + Mockito.when(titanClient.getGraph()).thenReturn(value); + + // test 1 + result = testSubject.getVertexById(id, JsonParseFlagEnum.NoParse); + // Assert.assertEquals(null, result); + } + + @Test + public void testSetVertexProperties_1() throws Exception { + Vertex vertex = Mockito.mock(Vertex.class); + Map<String, Object> properties = new HashMap<>(); + properties.put("mock", "mock"); + + // default test + testSubject.setVertexProperties(vertex, properties); + } + + @Test + public void testCreateAndFill() throws Exception { + + TitanVertex vertex = Mockito.mock(TitanVertex.class); + JsonParseFlagEnum parseFlag = null; + GraphVertex result; + + // default test + + result = Deencapsulation.invoke(testSubject, "createAndFill", vertex, JsonParseFlagEnum.NoParse); + } + + @Test + public void testParseVertexProperties() throws Exception { + + GraphVertex graphVertex = new GraphVertex(); + TitanVertex vertex = Mockito.mock(TitanVertex.class); + graphVertex.setVertex(vertex); + JsonParseFlagEnum parseFlag = null; + + // default test + + testSubject.parseVertexProperties(graphVertex, JsonParseFlagEnum.NoParse); + } + + @Test + public void testCreateEdge() throws Exception { + + GraphVertex from = Mockito.mock(GraphVertex.class); + GraphVertex to = Mockito.mock(GraphVertex.class); + + TitanVertex value = Mockito.mock(TitanVertex.class); + Mockito.when(from.getVertex()).thenReturn(value); + Mockito.when(to.getVertex()).thenReturn(value); + Map<EdgePropertyEnum, Object> properties = new HashMap<>(); + TitanOperationStatus result; + + // default test + + result = testSubject.createEdge(from, to, EdgeLabelEnum.ADDITIONAL_INFORMATION, properties); + from = new GraphVertex(); + to = new GraphVertex(); + result = testSubject.createEdge(from, to, EdgeLabelEnum.ADDITIONAL_INFORMATION, properties); + } + + @Test + public void testSetEdgeProperties() throws Exception { + + Element element = Mockito.mock(Element.class); + Map<EdgePropertyEnum, Object> properties = new HashMap<>(); + + // test 1 + + properties.put(EdgePropertyEnum.STATE, "mock"); + testSubject.setEdgeProperties(element, properties); + } + + @Test + public void testGetByCriteria() throws Exception { + Map<GraphPropertyEnum, Object> props = new HashMap<>(); + Either<List<GraphVertex>, TitanOperationStatus> result; + + TitanGraph tg = Mockito.mock(TitanGraph.class); + Either<TitanGraph, TitanOperationStatus> value = Either.left(tg); + TitanVertex value2 = Mockito.mock(TitanVertex.class); + Mockito.when(tg.addVertex()).thenReturn(value2); + Mockito.when(titanClient.getGraph()).thenReturn(value); + + // default test + result = testSubject.getByCriteria(VertexTypeEnum.ADDITIONAL_INFORMATION, props); + } + + @Test + public void testGetByCriteria_1() throws Exception { + + Map<GraphPropertyEnum, Object> props = new HashMap<>(); + Either<List<GraphVertex>, TitanOperationStatus> result; + + Either<TitanGraph, TitanOperationStatus> value = Either.right(TitanOperationStatus.GENERAL_ERROR); + TitanVertex value2 = Mockito.mock(TitanVertex.class); + Mockito.when(titanClient.getGraph()).thenReturn(value); + + // default test + result = testSubject.getByCriteria(VertexTypeEnum.ADDITIONAL_INFORMATION, props, JsonParseFlagEnum.NoParse); + } + + @Test + public void testGetCatalogVerticies() throws Exception { + Either<Iterator<Vertex>, TitanOperationStatus> result; + + Either<TitanGraph, TitanOperationStatus> value = Either.right(TitanOperationStatus.GENERAL_ERROR); + // default test + TitanVertex value2 = Mockito.mock(TitanVertex.class); + Mockito.when(titanClient.getGraph()).thenReturn(value); + + // default test + result = testSubject.getCatalogVerticies(); + } + + @Test + public void testGetChildVertex() throws Exception { + + GraphVertex parentVertex = new GraphVertex(); + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Either<GraphVertex, TitanOperationStatus> result; + + Either<TitanGraph, TitanOperationStatus> value = Either.right(TitanOperationStatus.GENERAL_ERROR); + TitanVertex value2 = Mockito.mock(TitanVertex.class); + Mockito.when(titanClient.getGraph()).thenReturn(value); + + // default test + result = testSubject.getChildVertex(parentVertex, EdgeLabelEnum.ADDITIONAL_INFORMATION, JsonParseFlagEnum.NoParse); + } + + @Test + public void testGetChildVertex_1() throws Exception { + + Vertex parentVertex = null; + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Either<Vertex, TitanOperationStatus> result; + + Either<TitanGraph, TitanOperationStatus> value = Either.right(TitanOperationStatus.GENERAL_ERROR); + TitanVertex value2 = Mockito.mock(TitanVertex.class); + Mockito.when(titanClient.getGraph()).thenReturn(value); + + // default test + result = testSubject.getChildVertex(parentVertex, edgeLabel, parseFlag); + } + + @Test + public void testGetParentVertex_1() throws Exception { + + Vertex parentVertex = null; + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Either<Vertex, TitanOperationStatus> result; + + // default test + + result = testSubject.getParentVertex(parentVertex, edgeLabel, parseFlag); + } + + @Test + public void testGetParentVertecies_1() throws Exception { + + Vertex parentVertex = null; + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Either<List<Vertex>, TitanOperationStatus> result; + + // default test + + result = testSubject.getParentVertecies(parentVertex, edgeLabel, parseFlag); + } + + @Test + public void testGetAdjacentVerticies() throws Exception { + + Vertex parentVertex = null; + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Direction direction = null; + Either<List<Vertex>, TitanOperationStatus> result; + + Either<TitanGraph, TitanOperationStatus> value = Either.right(TitanOperationStatus.GENERAL_ERROR); + TitanVertex value2 = Mockito.mock(TitanVertex.class); + Mockito.when(titanClient.getGraph()).thenReturn(value); + // default test + result = Deencapsulation.invoke(testSubject, "getAdjacentVerticies", + new Object[] { Vertex.class, EdgeLabelEnum.class, JsonParseFlagEnum.class, Direction.class }); + } + + @Test + public void testGetChildrenVertecies_1() throws Exception { + + Vertex parentVertex = null; + EdgeLabelEnum edgeLabel = null; + JsonParseFlagEnum parseFlag = null; + Either<List<Vertex>, TitanOperationStatus> result; + + // default test + + result = testSubject.getChildrenVertecies(parentVertex, edgeLabel, parseFlag); + } + + @Test + public void testDeleteBelongingEdgeByCriteria() throws Exception { + + GraphVertex vertex = null; + EdgeLabelEnum label = null; + Map<GraphPropertyEnum, Object> properties = null; + Either<Edge, TitanOperationStatus> result; + + // default test + + result = testSubject.deleteBelongingEdgeByCriteria(vertex, label, properties); + } + + @Test + public void testDeleteEdge() throws Exception { + + GraphVertex fromVertex = new GraphVertex(); + GraphVertex toVertex = new GraphVertex(); + Either<Edge, TitanOperationStatus> result; + + Either<TitanGraph, TitanOperationStatus> value = Either.right(TitanOperationStatus.GENERAL_ERROR); + TitanVertex value2 = Mockito.mock(TitanVertex.class); + Mockito.when(titanClient.getGraph()).thenReturn(value); + + // default test + result = testSubject.deleteEdge(fromVertex, toVertex, EdgeLabelEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testDeleteEdgeByDirection() throws Exception { + GraphVertex fromVertex = new GraphVertex(); + TitanOperationStatus result; + + // default test + result = testSubject.deleteEdgeByDirection(fromVertex, Direction.BOTH, EdgeLabelEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testDeleteEdgeByDirectionMock() throws Exception { + GraphVertex fromVertex = Mockito.mock(GraphVertex.class); + TitanOperationStatus result; + + TitanVertex value = Mockito.mock(TitanVertex.class);; + Mockito.when(fromVertex.getVertex()).thenReturn(value); + Iterator<Edge> value2 = Mockito.mock(Iterator.class);; + Mockito.when(value.edges(Mockito.any(), Mockito.any())).thenReturn(value2); + Mockito.when(value2.hasNext()).thenReturn(true, false); + Edge value3 = Mockito.mock(Edge.class);; + Mockito.when(value2.next()).thenReturn(value3); + // default test + result = testSubject.deleteEdgeByDirection(fromVertex, Direction.BOTH, EdgeLabelEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testUpdateVertex() throws Exception { + + GraphVertex graphVertex = new GraphVertex(); + Either<GraphVertex, TitanOperationStatus> result; + + // default test + + result = testSubject.updateVertex(graphVertex); + } + + @Test + public void testGetVerticesByUniqueIdAndParseFlag() throws Exception { + + Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGet = new HashMap<>(); + Either<Map<String, GraphVertex>, TitanOperationStatus> result; + + // default test + result = testSubject.getVerticesByUniqueIdAndParseFlag(verticesToGet); + ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum> value3 = ImmutablePair.of(GraphPropertyEnum.COMPONENT_TYPE, JsonParseFlagEnum.NoParse); + verticesToGet.put("mock", value3); + try { + result = testSubject.getVerticesByUniqueIdAndParseFlag(verticesToGet); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testCreateEdge_2() throws Exception { + + Vertex from = null; + Vertex to = null; + EdgeLabelEnum label = null; + Edge edgeToCopy = null; + TitanOperationStatus result; + + // default test + + result = testSubject.createEdge(from, to, label, edgeToCopy); + } + + @Test + public void testReplaceEdgeLabel() throws Exception { + + Vertex fromVertex = null; + Vertex toVertex = null; + Edge prevEdge = null; + EdgeLabelEnum prevLabel = null; + EdgeLabelEnum newLabel = null; + TitanOperationStatus result; + + // default test + + result = testSubject.replaceEdgeLabel(fromVertex, toVertex, prevEdge, prevLabel, newLabel); + } + + @Test + public void testUpdateVertexMetadataPropertiesWithJson() throws Exception { + + Vertex vertex = Mockito.mock(Vertex.class);; + Map<GraphPropertyEnum, Object> properties = new HashMap<>(); + properties.put(GraphPropertyEnum.COMPONENT_TYPE, "mock"); + TitanOperationStatus result; + + // default test + + result = testSubject.updateVertexMetadataPropertiesWithJson(vertex, properties); + } + + //TODO Last + @Test + public void testDisassociateAndDeleteLast() throws Exception { + + GraphVertex vertex = Mockito.mock(GraphVertex.class); + TitanOperationStatus result; + + TitanVertex value = Mockito.mock(TitanVertex.class); + Iterator<Edge> mockiter = Mockito.mock(Iterator.class); + Edge nextmock = Mockito.mock(Edge.class); + Mockito.when(vertex.getVertex()).thenReturn(value); + Mockito.when(value.edges(Mockito.any(), Mockito.any())).thenReturn(mockiter); + Mockito.when(mockiter.hasNext()).thenReturn(true, false); + Mockito.when(mockiter.next()).thenReturn(nextmock); + Vertex secondVertex = Mockito.mock(Vertex.class); + Mockito.when(nextmock.outVertex()).thenReturn(secondVertex); + Mockito.when(nextmock.inVertex()).thenReturn(secondVertex); + Iterator<Edge> restOfEdges = Mockito.mock(Iterator.class); + Mockito.when(secondVertex.edges(Mockito.any(), Mockito.any())).thenReturn(restOfEdges); + Mockito.when(restOfEdges.hasNext()).thenReturn(false); + + // default test + result = testSubject.disassociateAndDeleteLast(vertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testDisassociateAndDeleteLastOut() throws Exception { + + GraphVertex vertex = Mockito.mock(GraphVertex.class); + TitanOperationStatus result; + + TitanVertex value = Mockito.mock(TitanVertex.class); + Iterator<Edge> mockiter = Mockito.mock(Iterator.class); + Edge nextmock = Mockito.mock(Edge.class); + Mockito.when(vertex.getVertex()).thenReturn(value); + Mockito.when(value.edges(Mockito.any(), Mockito.any())).thenReturn(mockiter); + Mockito.when(mockiter.hasNext()).thenReturn(true, false); + Mockito.when(mockiter.next()).thenReturn(nextmock); + Vertex secondVertex = Mockito.mock(Vertex.class); + Mockito.when(nextmock.outVertex()).thenReturn(secondVertex); + Mockito.when(nextmock.inVertex()).thenReturn(secondVertex); + Iterator<Edge> restOfEdges = Mockito.mock(Iterator.class); + Mockito.when(secondVertex.edges(Mockito.any(), Mockito.any())).thenReturn(restOfEdges); + Mockito.when(restOfEdges.hasNext()).thenReturn(false); + + // default test + result = testSubject.disassociateAndDeleteLast(vertex, Direction.IN, EdgeLabelEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testDisassociateAndDeleteLastException() throws Exception { + + GraphVertex vertex = Mockito.mock(GraphVertex.class); + TitanOperationStatus result; + + Mockito.when(vertex.getVertex()).thenThrow(RuntimeException.class); + + // default test + result = testSubject.disassociateAndDeleteLast(vertex, Direction.OUT, EdgeLabelEnum.ADDITIONAL_INFORMATION); + } + + @Test + public void testMoveEdge() throws Exception { + + GraphVertex vertexA = new GraphVertex(); + GraphVertex vertexB = new GraphVertex(); + TitanOperationStatus result; + + // default test + + result = testSubject.moveEdge(vertexA, vertexB, EdgeLabelEnum.ADDITIONAL_INFORMATION, Direction.BOTH); + } +}
\ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoTest.java index cede79d7c8..4f962ba9b2 100644 --- a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoTest.java +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/jsongraph/TitanDaoTest.java @@ -6,11 +6,12 @@ import java.util.Map; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Element; +import org.apache.tinkerpop.gremlin.structure.Property; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.openecomp.sdc.be.config.ConfigurationManager; +import org.mockito.Mockito; import org.openecomp.sdc.be.dao.DAOTitanStrategy; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum; @@ -19,9 +20,7 @@ import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.titan.TitanGraphClient; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum; -import org.openecomp.sdc.common.api.ConfigurationSource; -import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.be.utils.DAOConfDependentTest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,18 +28,12 @@ import com.thinkaurelius.titan.core.TitanGraph; import fj.data.Either; -public class TitanDaoTest { +public class TitanDaoTest extends DAOConfDependentTest{ private static Logger logger = LoggerFactory.getLogger(TitanDaoTest.class); private TitanDao dao = new TitanDao(new TitanGraphClient(new DAOTitanStrategy())); - static { - String appConfigDir = "src/test/resources/config/catalog-dao"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - } - @Before public void init(){ dao.titanClient.createGraph(); @@ -51,6 +44,25 @@ public class TitanDaoTest { dao.titanClient.cleanupGraph(); } + @Test + public void testCreateVertex() throws Exception { + Either<GraphVertex, TitanOperationStatus> result; + + // default test + GraphVertex graphVertex = new GraphVertex(VertexTypeEnum.REQUIREMENTS); + result = dao.createVertex(graphVertex); + + graphVertex = new GraphVertex(); + result = dao.createVertex(graphVertex); + } + + @Test + public void testGetVertexByLabel() throws Exception { + Either<GraphVertex, TitanOperationStatus> result; + + // default test + result = dao.getVertexByLabel(VertexTypeEnum.ADDITIONAL_INFORMATION); + } @Test public void testCommit() throws Exception { @@ -72,7 +84,6 @@ public class TitanDaoTest { result = dao.rollback(); } - @Test public void testGetGraph() throws Exception { @@ -83,10 +94,6 @@ public class TitanDaoTest { result = dao.getGraph(); } - - - - @Test public void testGetVertexByPropertyAndLabel() throws Exception { @@ -98,13 +105,10 @@ public class TitanDaoTest { // default test result = dao.getVertexByPropertyAndLabel(name, value, label); + + result = dao.getVertexByPropertyAndLabel(GraphPropertyEnum.COMPONENT_TYPE, new Object(), VertexTypeEnum.ADDITIONAL_INFORMATION); } - - - - - @Test public void testGetVertexByPropertyAndLabel_1() throws Exception { @@ -131,7 +135,6 @@ public class TitanDaoTest { result = dao.getVertexById(id); } - @Test public void testGetVertexById_1() throws Exception { @@ -150,19 +153,6 @@ public class TitanDaoTest { result = dao.getVertexById(id, parseFlag); } - - - - - - - - - - - - - @Test public void testGetVertexProperties() throws Exception { @@ -188,10 +178,6 @@ public class TitanDaoTest { result = dao.getEdgeProperties(element); } - - - - @Test public void testGetByCriteria() throws Exception { @@ -204,7 +190,6 @@ public class TitanDaoTest { result = dao.getByCriteria(type, props); } - @Test public void testGetByCriteria_1() throws Exception { @@ -233,7 +218,6 @@ public class TitanDaoTest { result = dao.getByCriteria(type, props, hasNotProps, parseFlag); } - @Test public void testGetCatalogVerticies() throws Exception { @@ -243,21 +227,6 @@ public class TitanDaoTest { result = dao.getCatalogVerticies(); } - - - - - - - - - - - - - - - @Test public void testGetParentVertecies_1() throws Exception { @@ -272,9 +241,6 @@ public class TitanDaoTest { result = dao.getParentVertecies(parentVertex, edgeLabel, parseFlag); } - - - @Test public void testGetChildrenVertecies_1() throws Exception { @@ -288,34 +254,6 @@ public class TitanDaoTest { result = dao.getChildrenVertecies(parentVertex, edgeLabel, parseFlag); } - - - - - - - - - - - - - - - - - - - - - - - - - - - - @Test public void testUpdateVertexMetadataPropertiesWithJson() throws Exception { @@ -328,26 +266,38 @@ public class TitanDaoTest { result = dao.updateVertexMetadataPropertiesWithJson(vertex, properties); } - - - - + @Test + public void testGetProperty() throws Exception { + Edge edge = Mockito.mock(Edge.class);; + Object result; + + Property<Object> value = Mockito.mock(Property.class); + Mockito.when(edge.property(Mockito.any())).thenReturn(value); + + // default test + result = dao.getProperty(edge, EdgePropertyEnum.STATE); + } @Test public void testGetProperty_1() throws Exception { - - Edge edge = null; - EdgePropertyEnum key = null; + Edge edge = Mockito.mock(Edge.class);; Object result; // default test - - result = dao.getProperty(edge, key); + result = dao.getProperty(edge, EdgePropertyEnum.STATE); } - - - + @Test + public void testGetPropertyexception() throws Exception { + Edge edge = Mockito.mock(Edge.class);; + Object result; + + Property<Object> value = Mockito.mock(Property.class); + Mockito.when(edge.property(Mockito.any())).thenThrow(RuntimeException.class); + + // default test + result = dao.getProperty(edge, EdgePropertyEnum.STATE); + } @Test public void testGetBelongingEdgeByCriteria_1() throws Exception { diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/model/GetMultipleDataResultTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/model/GetMultipleDataResultTest.java new file mode 100644 index 0000000000..a3304517f6 --- /dev/null +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/model/GetMultipleDataResultTest.java @@ -0,0 +1,137 @@ +package org.openecomp.sdc.be.dao.model; + +import org.apache.tinkerpop.gremlin.structure.T; +import org.junit.Test; + +public class GetMultipleDataResultTest { + + private GetMultipleDataResult createTestSubject() { + return new GetMultipleDataResult<>(); + } + + @Test + public void testCtor() throws Exception { + new GetMultipleDataResult<>(new String [1], new Object[1]); + new GetMultipleDataResult<>(new String [1], new String [1], 0L, 0L, 1, 1); + } + + @Test + public void testGetTypes() throws Exception { + GetMultipleDataResult testSubject; + String[] result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getTypes(); + } + + @Test + public void testGetData() throws Exception { + GetMultipleDataResult testSubject; + Object[] result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getData(); + } + + @Test + public void testSetTypes() throws Exception { + GetMultipleDataResult testSubject; + String[] types = new String[] { "" }; + + // default test + testSubject = createTestSubject(); + testSubject.setTypes(types); + } + + @Test + public void testSetData() throws Exception { + GetMultipleDataResult testSubject; + T[] data = new T[] { null }; + + // default test + testSubject = createTestSubject(); + testSubject.setData(data); + } + + @Test + public void testSetQueryDuration() throws Exception { + GetMultipleDataResult testSubject; + long queryDuration = 0L; + + // default test + testSubject = createTestSubject(); + testSubject.setQueryDuration(queryDuration); + } + + @Test + public void testSetTotalResults() throws Exception { + GetMultipleDataResult testSubject; + long totalResults = 0L; + + // default test + testSubject = createTestSubject(); + testSubject.setTotalResults(totalResults); + } + + @Test + public void testSetFrom() throws Exception { + GetMultipleDataResult testSubject; + int from = 0; + + // default test + testSubject = createTestSubject(); + testSubject.setFrom(from); + } + + @Test + public void testSetTo() throws Exception { + GetMultipleDataResult testSubject; + int to = 0; + + // default test + testSubject = createTestSubject(); + testSubject.setTo(to); + } + + @Test + public void testGetQueryDuration() throws Exception { + GetMultipleDataResult testSubject; + long result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getQueryDuration(); + } + + @Test + public void testGetTotalResults() throws Exception { + GetMultipleDataResult testSubject; + long result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getTotalResults(); + } + + @Test + public void testGetFrom() throws Exception { + GetMultipleDataResult testSubject; + int result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getFrom(); + } + + @Test + public void testGetTo() throws Exception { + GetMultipleDataResult testSubject; + int result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getTo(); + } +}
\ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabelsTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabelsTest.java new file mode 100644 index 0000000000..40800f70e2 --- /dev/null +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgeLabelsTest.java @@ -0,0 +1,50 @@ +package org.openecomp.sdc.be.dao.neo4j; + +import java.util.List; + +import org.junit.Test; + +public class GraphEdgeLabelsTest { + + private GraphEdgeLabels createTestSubject() { + return GraphEdgeLabels.ADDITIONAL_INFORMATION; + } + + @Test + public void testGetProperty() throws Exception { + GraphEdgeLabels testSubject; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getProperty(); + } + + @Test + public void testSetProperty() throws Exception { + GraphEdgeLabels testSubject; + String property = ""; + + // default test + testSubject = createTestSubject(); + testSubject.setProperty(property); + } + + @Test + public void testGetAllProperties() throws Exception { + List<String> result; + + // default test + result = GraphEdgeLabels.getAllProperties(); + } + + @Test + public void testGetByName() throws Exception { + String property = ""; + GraphEdgeLabels result; + + // default test + result = GraphEdgeLabels.getByName(property); + result = GraphEdgeLabels.getByName("mock"); + } +}
\ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionaryTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionaryTest.java new file mode 100644 index 0000000000..9a1514ec4f --- /dev/null +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/dao/neo4j/GraphEdgePropertiesDictionaryTest.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.be.dao.neo4j; + +import java.util.List; + +import org.junit.Test; + +public class GraphEdgePropertiesDictionaryTest { + + private GraphEdgePropertiesDictionary createTestSubject() { + return GraphEdgePropertiesDictionary.GET_INPUT_INDEX; + } + + @Test + public void testGetProperty() throws Exception { + GraphEdgePropertiesDictionary testSubject; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getProperty(); + } + + @Test + public void testSetProperty() throws Exception { + GraphEdgePropertiesDictionary testSubject; + String property = ""; + + // default test + testSubject = createTestSubject(); + testSubject.setProperty(property); + } + + @Test + public void testGetClazz() throws Exception { + GraphEdgePropertiesDictionary testSubject; + Class result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getClazz(); + } + + @Test + public void testSetClazz() throws Exception { + GraphEdgePropertiesDictionary testSubject; + Class clazz = null; + + // default test + testSubject = createTestSubject(); + testSubject.setClazz(clazz); + } + + @Test + public void testGetAllProperties() throws Exception { + List<String> result; + + // default test + result = GraphEdgePropertiesDictionary.getAllProperties(); + } + + @Test + public void testGetByName() throws Exception { + String property = ""; + GraphEdgePropertiesDictionary result; + + // default test + result = GraphEdgePropertiesDictionary.getByName(property); + result = GraphEdgePropertiesDictionary.getByName("mock"); + } +}
\ No newline at end of file diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ArtifactDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ArtifactDaoTest.java index 292ae08f0a..29d5d60870 100644 --- a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ArtifactDaoTest.java +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/ArtifactDaoTest.java @@ -29,7 +29,6 @@ import javax.annotation.Resource; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -38,9 +37,7 @@ import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; import org.openecomp.sdc.be.dao.es.ElasticSearchClient; import org.openecomp.sdc.be.resources.api.IResourceUploader; import org.openecomp.sdc.be.resources.data.ESArtifactData; -import org.openecomp.sdc.common.api.ConfigurationSource; -import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.openecomp.sdc.common.impl.FSConfigurationSource; +import org.openecomp.sdc.be.utils.DAOConfDependentTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -56,7 +53,7 @@ import fj.data.Either; DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class }) // , // CassandraUnitTestExecutionListener.class}) // @EmbeddedCassandra(host ="localhost", port=9042) -public class ArtifactDaoTest { +public class ArtifactDaoTest extends DAOConfDependentTest { private static final String TEST_IMAGES_DIRECTORY = "src/test/resources/images"; @Resource @@ -73,23 +70,8 @@ public class ArtifactDaoTest { @Resource(name = "resource-dao") private IGenericSearchDAO resourceDAO; - private String nodeType = "NodeType1"; private String nodeTypeVersion = "1.0.0"; - private String nodeType2 = "NodeType2"; - private String nodeTypeVersion2 = "1.0.1"; - - private String nodeType3 = "NodeType3"; - private String nodeNypeVersion3 = "1.1.1"; - - private String topologyId = "topology"; - private String topologyTemplateName = "topologyTemplate"; - private String topologyTemplateVersion = "1.1.1"; - - private String nodeTypeTemplate1 = "NodeTypeTemplate1"; - private String nodeTypeTemplate2 = "NodeTypeTemplate2"; - private String nodeTypeTemplate3 = "NodeTypeTemplate3"; - private static ConfigurationManager configurationManager; @Before @@ -103,14 +85,14 @@ public class ArtifactDaoTest { } - @BeforeClass + /*@BeforeClass public static void setupBeforeClass() { ExternalConfiguration.setAppName("catalog-dao"); String appConfigDir = "src/test/resources/config/catalog-dao"; ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); configurationManager = new ConfigurationManager(configurationSource); - } + }*/ // @Before // public void createSchema(){ diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/AuditingDaoTest.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/AuditingDaoTest.java index 1d0c9e0a89..10e2c9ea86 100644 --- a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/AuditingDaoTest.java +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/AuditingDaoTest.java @@ -42,6 +42,7 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mockito; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.Configuration.ElasticSearchConfig.IndicesTimeFrequencyEntry; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -231,6 +232,22 @@ public class AuditingDaoTest { testCreationPeriodScenario(params, creationPeriod, expectedIndexName, ResourceAdminEvent.class); } + @Test + public void testGetFilteredResourceAdminAuditingEvents() { + Map<AuditingFieldsKeysEnum, Object> filterMap = new HashMap<>(); + filterMap.put(AuditingFieldsKeysEnum.AUDIT_ACTION, new Object()); + Either<List<ESTimeBasedEvent>, ActionStatus> filteredResourceAdminAuditingEvents = auditingDao + .getFilteredResourceAdminAuditingEvents(filterMap); + } + + @Test + public void testGetListOfDistributionByAction() { + Either<List<ESTimeBasedEvent>, ActionStatus> filteredResourceAdminAuditingEvents = auditingDao + .getListOfDistributionByAction("mock", "mock", "mock", AuditingGenericEvent.class); + filteredResourceAdminAuditingEvents = auditingDao + .getListOfDistributionByAction("mock", "mock", null, AuditingGenericEvent.class); + } + private SearchResponse testCreationPeriodScenario(Map<AuditingFieldsKeysEnum, Object> params, String creationPeriod, String expectedIndexName, Class<? extends AuditingGenericEvent> clazz) { diff --git a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JsonParserUtilsTests.java b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JsonParserUtilsTests.java index 508fb0c2cc..d92d8dee16 100644 --- a/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JsonParserUtilsTests.java +++ b/catalog-dao/src/test/java/org/openecomp/sdc/be/resources/JsonParserUtilsTests.java @@ -25,6 +25,7 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.openecomp.sdc.be.utils.FixtureHelpers.fixture; import static org.openecomp.sdc.be.utils.JsonTester.testJsonMap; +import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -33,6 +34,7 @@ import org.junit.Test; import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; @@ -41,49 +43,69 @@ import com.google.common.collect.ImmutableList; public class JsonParserUtilsTests { - private static final String FIXTURE_PATH = "fixtures/ListCapabilityDataDefinition.json"; + private static final String FIXTURE_PATH = "fixtures/ListCapabilityDataDefinition.json"; - @Test - public void testToMap() { - String json = fixture(FIXTURE_PATH); - Map<String, ListCapabilityDataDefinition> actual = JsonParserUtils.toMap(json, ListCapabilityDataDefinition.class); - Map<String, ListCapabilityDataDefinition> expected = buildMap(); - assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected); - } + @Test + public void testToMap() { + String json = fixture(FIXTURE_PATH); + Map<String, ListCapabilityDataDefinition> actual = JsonParserUtils.toMap(json, + ListCapabilityDataDefinition.class); + Map<String, ListCapabilityDataDefinition> expected = buildMap(); + assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected); + } - @Test - public void testJacksonFasterXml() { - ObjectMapper mapper = new ObjectMapper() - .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); - assertThatCode(() -> testJsonMap(buildMap(), ListCapabilityDataDefinition.class, FIXTURE_PATH, mapper)) - .doesNotThrowAnyException(); - } + @Test + public void testJacksonFasterXml() { + ObjectMapper mapper = new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); + assertThatCode(() -> testJsonMap(buildMap(), ListCapabilityDataDefinition.class, FIXTURE_PATH, mapper)) + .doesNotThrowAnyException(); + } - private Map<String, ListCapabilityDataDefinition> buildMap() { - Map<String, ListCapabilityDataDefinition> map = new HashMap<>(); - map.put("org.openecomp.capabilities.Forwarder", buildListCapabilityDataDefinition()); - return map; - } + @Test + public void testToJson() { + try { + JsonParserUtils.toJson(new Object()); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - private ListCapabilityDataDefinition buildListCapabilityDataDefinition() { - CapabilityDataDefinition dataDefinition = new CapabilityDataDefinition(); - dataDefinition.setName("forwarder"); - dataDefinition.setType("org.openecomp.capabilities.Forwarder"); - dataDefinition.setUniqueId("capability.deb142fd-95eb-48f7-99ae-81ab09466b1e.forwarder"); - dataDefinition.setOwnerId("deb142fd-95eb-48f7-99ae-81ab09466b1e"); - dataDefinition.setMinOccurrences("1"); - dataDefinition.setLeftOccurrences("UNBOUNDED"); - dataDefinition.setMaxOccurrences("UNBOUNDED"); - dataDefinition.setCapabilitySources(buildCapabilitySources()); + @Test + public void testMap() { + JsonParserUtils.toMap("{}"); + JsonParserUtils.toMap(""); + JsonParserUtils.toMap("****"); + + JsonParserUtils.toMap("{}", ToscaDataDefinition.class); + JsonParserUtils.toMap("", ToscaDataDefinition.class); + JsonParserUtils.toMap("****", ToscaDataDefinition.class); + + } - return new ListCapabilityDataDefinition(ImmutableList.of(dataDefinition)); - } + private Map<String, ListCapabilityDataDefinition> buildMap() { + Map<String, ListCapabilityDataDefinition> map = new HashMap<>(); + map.put("org.openecomp.capabilities.Forwarder", buildListCapabilityDataDefinition()); + return map; + } - private List<String> buildCapabilitySources() { - return ImmutableList.of( - "org.openecomp.resource.cp.nodes.network.Port", - "org.openecomp.resource.cp.v2.extCP", - "org.openecomp.resource.cp.v2.extContrailCP"); - } + private ListCapabilityDataDefinition buildListCapabilityDataDefinition() { + CapabilityDataDefinition dataDefinition = new CapabilityDataDefinition(); + dataDefinition.setName("forwarder"); + dataDefinition.setType("org.openecomp.capabilities.Forwarder"); + dataDefinition.setUniqueId("capability.deb142fd-95eb-48f7-99ae-81ab09466b1e.forwarder"); + dataDefinition.setOwnerId("deb142fd-95eb-48f7-99ae-81ab09466b1e"); + dataDefinition.setMinOccurrences("1"); + dataDefinition.setLeftOccurrences("UNBOUNDED"); + dataDefinition.setMaxOccurrences("UNBOUNDED"); + dataDefinition.setCapabilitySources(buildCapabilitySources()); + + return new ListCapabilityDataDefinition(ImmutableList.of(dataDefinition)); + } + + private List<String> buildCapabilitySources() { + return ImmutableList.of("org.openecomp.resource.cp.nodes.network.Port", "org.openecomp.resource.cp.v2.extCP", + "org.openecomp.resource.cp.v2.extContrailCP"); + } } |