2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
20 package org.openecomp.sdc.be.dao.jsongraph;
22 import static org.apache.commons.collections.CollectionUtils.isEmpty;
24 import fj.data.Either;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.List;
31 import java.util.Map.Entry;
32 import java.util.function.Predicate;
33 import java.util.stream.Collectors;
34 import java.util.stream.StreamSupport;
35 import java.util.Optional;
36 import org.apache.commons.collections.MapUtils;
37 import org.apache.commons.lang.StringUtils;
38 import org.apache.commons.lang3.tuple.ImmutablePair;
39 import org.apache.tinkerpop.gremlin.structure.Direction;
40 import org.apache.tinkerpop.gremlin.structure.Edge;
41 import org.apache.tinkerpop.gremlin.structure.Element;
42 import org.apache.tinkerpop.gremlin.structure.Property;
43 import org.apache.tinkerpop.gremlin.structure.Vertex;
44 import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
45 import org.janusgraph.core.JanusGraph;
46 import org.janusgraph.core.JanusGraphEdge;
47 import org.janusgraph.core.JanusGraphQuery;
48 import org.janusgraph.core.JanusGraphVertex;
49 import org.janusgraph.core.JanusGraphVertexQuery;
50 import org.janusgraph.core.PropertyKey;
51 import org.janusgraph.graphdb.query.JanusGraphPredicate;
52 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphClient;
53 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
54 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
55 import org.openecomp.sdc.be.dao.jsongraph.types.EdgePropertyEnum;
56 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
57 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
58 import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
59 import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
60 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
61 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
62 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
63 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
64 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
65 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
66 import org.openecomp.sdc.common.log.wrappers.Logger;
67 import org.springframework.beans.factory.annotation.Qualifier;
69 public class JanusGraphDao {
71 private static Logger logger = Logger.getLogger(JanusGraphDao.class.getName());
72 JanusGraphClient janusGraphClient;
74 public JanusGraphDao(@Qualifier("janusgraph-client") JanusGraphClient janusGraphClient) {
75 this.janusGraphClient = janusGraphClient;
76 logger.info("** JanusGraphDao created");
79 public JanusGraphOperationStatus commit() {
80 logger.debug("#commit - The operation succeeded. Doing commit...");
81 return janusGraphClient.commit();
84 public JanusGraphOperationStatus rollback() {
85 logger.debug("#rollback - The operation failed. Doing rollback...");
86 return janusGraphClient.rollback();
89 public Either<JanusGraph, JanusGraphOperationStatus> getGraph() {
90 return janusGraphClient.getGraph();
97 public Either<GraphVertex, JanusGraphOperationStatus> createVertex(GraphVertex graphVertex) {
98 logger.trace("try to create vertex for ID [{}]", graphVertex.getUniqueId());
99 Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphClient.getGraph();
100 if (graph.isLeft()) {
102 JanusGraph tGraph = graph.left().value();
103 JanusGraphVertex vertex = tGraph.addVertex();
104 setVertexProperties(vertex, graphVertex);
105 graphVertex.setVertex(vertex);
106 return Either.left(graphVertex);
107 } catch (Exception e) {
109 .error(EcompLoggerErrorCode.DATA_ERROR, "JanusGraphDao", "Failed to create Node for ID '{}'", (Object) graphVertex.getUniqueId(),
111 return Either.right(JanusGraphClient.handleJanusGraphException(e));
114 logger.debug("Failed to create vertex for ID '{}' {}", graphVertex.getUniqueId(), graph.right().value());
115 return Either.right(graph.right().value());
125 public Either<GraphVertex, JanusGraphOperationStatus> getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label) {
126 return getVertexByPropertyAndLabel(name, value, label, JsonParseFlagEnum.ParseAll);
129 public Either<GraphVertex, JanusGraphOperationStatus> getVertexByLabel(VertexTypeEnum label) {
130 return janusGraphClient.getGraph().left().map(graph -> graph.query().has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices())
131 .left().bind(janusGraphVertices -> getFirstFoundVertex(JsonParseFlagEnum.NoParse, janusGraphVertices));
134 private Either<GraphVertex, JanusGraphOperationStatus> getFirstFoundVertex(JsonParseFlagEnum parseFlag, Iterable<JanusGraphVertex> vertices) {
135 Iterator<JanusGraphVertex> iterator = vertices.iterator();
136 if (iterator.hasNext()) {
137 JanusGraphVertex vertex = iterator.next();
138 GraphVertex graphVertex = createAndFill(vertex, parseFlag);
139 return Either.left(graphVertex);
141 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
151 public Either<GraphVertex, JanusGraphOperationStatus> getVertexByPropertyAndLabel(GraphPropertyEnum name, Object value, VertexTypeEnum label,
152 JsonParseFlagEnum parseFlag) {
153 Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphClient.getGraph();
154 if (graph.isLeft()) {
156 JanusGraph tGraph = graph.left().value();
157 @SuppressWarnings("unchecked") Iterable<JanusGraphVertex> vertecies = tGraph.query().has(name.getProperty(), value)
158 .has(GraphPropertyEnum.LABEL.getProperty(), label.getName()).vertices();
159 java.util.Iterator<JanusGraphVertex> iterator = vertecies.iterator();
160 if (iterator.hasNext()) {
161 JanusGraphVertex vertex = iterator.next();
162 GraphVertex graphVertex = createAndFill(vertex, parseFlag);
163 return Either.left(graphVertex);
165 if (logger.isDebugEnabled()) {
166 logger.debug("No vertex in graph for key = {} and value = {} label = {}", name, value, label);
168 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
169 } catch (Exception e) {
170 if (logger.isDebugEnabled()) {
171 logger.debug("Failed to get vertex in graph for key ={} and value = {} label = {}", name, value, label);
173 return Either.right(JanusGraphClient.handleJanusGraphException(e));
176 if (logger.isDebugEnabled()) {
177 logger.debug("No vertex in graph for key ={} and value = {} label = {} error :{}", name, value, label, graph.right().value());
179 return Either.right(graph.right().value());
187 public Either<GraphVertex, JanusGraphOperationStatus> getVertexById(String id) {
188 return getVertexById(id, JsonParseFlagEnum.ParseAll);
196 public Either<GraphVertex, JanusGraphOperationStatus> getVertexById(String id, JsonParseFlagEnum parseFlag) {
197 Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphClient.getGraph();
199 if (logger.isDebugEnabled()) {
200 logger.debug("No vertex in graph for id = {} ", id);
202 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
204 if (graph.isLeft()) {
206 JanusGraph tGraph = graph.left().value();
207 @SuppressWarnings("unchecked") Iterable<JanusGraphVertex> vertecies = tGraph.query()
208 .has(GraphPropertyEnum.UNIQUE_ID.getProperty(), id).vertices();
209 java.util.Iterator<JanusGraphVertex> iterator = vertecies.iterator();
210 if (iterator.hasNext()) {
211 JanusGraphVertex vertex = iterator.next();
212 GraphVertex graphVertex = createAndFill(vertex, parseFlag);
213 return Either.left(graphVertex);
215 if (logger.isDebugEnabled()) {
216 logger.debug("No vertex in graph for id = {}", id);
218 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
220 } catch (Exception e) {
221 if (logger.isDebugEnabled()) {
222 logger.debug("Failed to get vertex in graph for id {} ", id);
224 return Either.right(JanusGraphClient.handleJanusGraphException(e));
227 if (logger.isDebugEnabled()) {
228 logger.debug("No vertex in graph for id {} error : {}", id, graph.right().value());
230 return Either.right(graph.right().value());
234 private void setVertexProperties(JanusGraphVertex vertex, GraphVertex graphVertex) throws IOException {
235 if (graphVertex.getMetadataProperties() != null) {
236 for (Map.Entry<GraphPropertyEnum, Object> entry : graphVertex.getMetadataProperties().entrySet()) {
237 if (entry.getValue() != null) {
238 vertex.property(entry.getKey().getProperty(), entry.getValue());
242 vertex.property(GraphPropertyEnum.LABEL.getProperty(), graphVertex.getLabel().getName());
243 Map<String, ? extends ToscaDataDefinition> json = graphVertex.getJson();
245 String jsonStr = JsonParserUtils.toJson(json);
246 vertex.property(GraphPropertyEnum.JSON.getProperty(), jsonStr);
248 Map<String, Object> jsonMetadata = graphVertex.getMetadataJson();
249 if (jsonMetadata != null) {
250 String jsonMetadataStr = JsonParserUtils.toJson(jsonMetadata);
251 vertex.property(GraphPropertyEnum.METADATA.getProperty(), jsonMetadataStr);
255 public void setVertexProperties(Vertex vertex, Map<String, Object> properties) throws IOException {
256 for (Map.Entry<String, Object> entry : properties.entrySet()) {
257 if (entry.getValue() != null) {
258 vertex.property(entry.getKey(), entry.getValue());
263 private GraphVertex createAndFill(JanusGraphVertex vertex, JsonParseFlagEnum parseFlag) {
264 GraphVertex graphVertex = new GraphVertex();
265 graphVertex.setVertex(vertex);
266 parseVertexProperties(graphVertex, parseFlag);
270 public void parseVertexProperties(GraphVertex graphVertex, JsonParseFlagEnum parseFlag) {
271 JanusGraphVertex vertex = graphVertex.getVertex();
272 Map<GraphPropertyEnum, Object> properties = getVertexProperties(vertex);
273 VertexTypeEnum label = VertexTypeEnum.getByName((String) (properties.get(GraphPropertyEnum.LABEL)));
274 for (Map.Entry<GraphPropertyEnum, Object> entry : properties.entrySet()) {
275 GraphPropertyEnum key = entry.getKey();
278 graphVertex.setUniqueId((String) entry.getValue());
281 graphVertex.setLabel(VertexTypeEnum.getByName((String) entry.getValue()));
284 String type = (String) entry.getValue();
286 graphVertex.setType(ComponentTypeEnum.valueOf(type));
290 if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseJson) {
291 String json = (String) entry.getValue();
292 Map<String, ? extends ToscaDataDefinition> jsonObj = JsonParserUtils.toMap(json, label.getClassOfJson());
293 graphVertex.setJson(jsonObj);
297 if (parseFlag == JsonParseFlagEnum.ParseAll || parseFlag == JsonParseFlagEnum.ParseMetadata) {
298 String json = (String) entry.getValue();
299 Map<String, Object> metadatObj = JsonParserUtils.toMap(json);
300 graphVertex.setMetadataJson(metadatObj);
304 graphVertex.addMetadataProperty(key, entry.getValue());
310 public JanusGraphOperationStatus createEdge(GraphVertex from, GraphVertex to, EdgeLabelEnum label, Map<EdgePropertyEnum, Object> properties) {
311 return createEdge(from.getVertex(), to.getVertex(), label, properties);
314 public JanusGraphOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Map<EdgePropertyEnum, Object> properties) {
315 if (logger.isTraceEnabled()) {
316 logger.trace("Try to connect {} with {} label {} properties {}",
317 from == null ? "NULL" : from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()),
318 to == null ? "NULL" : to.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), label, properties);
320 if (from == null || to == null) {
321 logger.trace("No JanusGraph vertex for id from {} or id to {}",
322 from == null ? "NULL" : from.property(GraphPropertyEnum.UNIQUE_ID.getProperty()),
323 to == null ? "NULL" : to.property(GraphPropertyEnum.UNIQUE_ID.getProperty()));
324 return JanusGraphOperationStatus.NOT_FOUND;
326 Edge edge = from.addEdge(label.name(), to);
327 JanusGraphOperationStatus status;
329 setEdgeProperties(edge, properties);
330 status = JanusGraphOperationStatus.OK;
331 } catch (IOException e) {
332 logger.error(EcompLoggerErrorCode.DATA_ERROR, "JanusGraphDao", "Failed to set properties on edge properties [{}]", properties, e);
333 status = JanusGraphOperationStatus.GENERAL_ERROR;
338 public Map<GraphPropertyEnum, Object> getVertexProperties(Element element) {
339 Map<GraphPropertyEnum, Object> result = new HashMap<>();
340 if (element != null && element.keys() != null && element.keys().size() > 0) {
341 Map<String, Property> propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()]));
342 for (Entry<String, Property> entry : propertyMap.entrySet()) {
343 String key = entry.getKey();
344 Object value = entry.getValue().value();
345 GraphPropertyEnum valueOf = GraphPropertyEnum.getByProperty(key);
346 if (valueOf != null) {
347 result.put(valueOf, value);
350 // add print to properties that can't be converted by enum
355 public Map<EdgePropertyEnum, Object> getEdgeProperties(Element element) {
356 Map<EdgePropertyEnum, Object> result = new HashMap<>();
357 if (element != null && element.keys() != null && element.keys().size() > 0) {
358 Map<String, Property> propertyMap = ElementHelper.propertyMap(element, element.keys().toArray(new String[element.keys().size()]));
359 for (Entry<String, Property> entry : propertyMap.entrySet()) {
360 String key = entry.getKey();
361 Object value = entry.getValue().value();
362 EdgePropertyEnum valueOf = EdgePropertyEnum.getByProperty(key);
363 if (valueOf != null) {
364 if (valueOf == EdgePropertyEnum.INSTANCES) {
365 List<String> list = JsonParserUtils.toList((String) value, String.class);
366 result.put(valueOf, list);
368 result.put(valueOf, value);
376 public void setEdgeProperties(Element element, Map<EdgePropertyEnum, Object> properties) throws IOException {
377 if (properties != null && !properties.isEmpty()) {
378 Object[] propertyKeyValues = new Object[properties.size() * 2];
380 for (Entry<EdgePropertyEnum, Object> entry : properties.entrySet()) {
381 propertyKeyValues[i++] = entry.getKey().getProperty();
382 Object value = entry.getValue();
383 if (entry.getKey() == EdgePropertyEnum.INSTANCES) {
384 String jsonStr = JsonParserUtils.toJson(value);
385 propertyKeyValues[i++] = jsonStr;
387 propertyKeyValues[i++] = entry.getValue();
390 ElementHelper.attachProperties(element, propertyKeyValues);
394 public Either<List<GraphVertex>, JanusGraphOperationStatus> getByCriteria(VertexTypeEnum type, Map<GraphPropertyEnum, Object> props) {
395 return getByCriteria(type, props, JsonParseFlagEnum.ParseAll);
398 public Either<List<GraphVertex>, JanusGraphOperationStatus> getByCriteria(VertexTypeEnum type, Map<GraphPropertyEnum, Object> props,
399 JsonParseFlagEnum parseFlag) {
400 Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphClient.getGraph();
401 if (graph.isLeft()) {
403 JanusGraph tGraph = graph.left().value();
404 JanusGraphQuery<? extends JanusGraphQuery> query = tGraph.query();
406 query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName());
408 if (props != null && !props.isEmpty()) {
409 for (Map.Entry<GraphPropertyEnum, Object> entry : props.entrySet()) {
410 query = query.has(entry.getKey().getProperty(), entry.getValue());
413 Iterable<JanusGraphVertex> vertices = query.vertices();
414 if (vertices == null) {
415 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
417 Iterator<JanusGraphVertex> iterator = vertices.iterator();
418 List<GraphVertex> result = new ArrayList<>();
419 while (iterator.hasNext()) {
420 JanusGraphVertex vertex = iterator.next();
421 Map<GraphPropertyEnum, Object> newProp = getVertexProperties(vertex);
422 GraphVertex graphVertex = createAndFill(vertex, parseFlag);
423 result.add(graphVertex);
425 if (logger.isDebugEnabled()) {
427 .debug("Number of fetced nodes in graph for criteria : from type = {} and properties = {} is {}", type, props, result.size());
429 if (result.size() == 0) {
430 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
432 return Either.left(result);
433 } catch (Exception e) {
434 if (logger.isDebugEnabled()) {
435 logger.debug("Failed get by criteria for type = {} and properties = {}", type, props, e);
437 return Either.right(JanusGraphClient.handleJanusGraphException(e));
440 if (logger.isDebugEnabled()) {
441 logger.debug("Failed get by criteria for type ={} and properties = {} error : {}", type, props, graph.right().value());
443 return Either.right(graph.right().value());
447 public Either<List<GraphVertex>, JanusGraphOperationStatus> getByCriteria(VertexTypeEnum type, Map<GraphPropertyEnum, Object> props,
448 Map<GraphPropertyEnum, Object> hasNotProps,
449 JsonParseFlagEnum parseFlag,
451 return getByCriteria(type, props, hasNotProps, null, parseFlag, model);
454 public Either<List<GraphVertex>, JanusGraphOperationStatus> getByCriteria(final VertexTypeEnum type,
455 final Map<GraphPropertyEnum, Object> hasProps,
456 final Map<GraphPropertyEnum, Object> hasNotProps,
457 final Map<String, Entry<JanusGraphPredicate, Object>> predicates,
458 final JsonParseFlagEnum parseFlag,
459 final String model) {
460 Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphClient.getGraph();
461 if (graph.isLeft()) {
463 JanusGraph tGraph = graph.left().value();
464 JanusGraphQuery<? extends JanusGraphQuery> query = tGraph.query();
467 query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName());
469 if (hasProps != null && !hasProps.isEmpty()) {
470 for (Map.Entry<GraphPropertyEnum, Object> entry : hasProps.entrySet()) {
471 query = query.has(entry.getKey().getProperty(), entry.getValue());
474 if (hasNotProps != null && !hasNotProps.isEmpty()) {
475 for (Map.Entry<GraphPropertyEnum, Object> entry : hasNotProps.entrySet()) {
476 if (entry.getValue() instanceof List) {
477 buildMultipleNegateQueryFromList(entry, query);
479 query = query.hasNot(entry.getKey().getProperty(), entry.getValue());
483 if (predicates != null && !predicates.isEmpty()) {
484 for (Map.Entry<String, Entry<JanusGraphPredicate, Object>> entry : predicates.entrySet()) {
485 JanusGraphPredicate predicate = entry.getValue().getKey();
486 Object object = entry.getValue().getValue();
487 query = query.has(entry.getKey(), predicate, object);
490 Iterable<JanusGraphVertex> vertices = query.vertices();
491 if (vertices == null || !vertices.iterator().hasNext()) {
492 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
494 List<GraphVertex> result = new ArrayList<>();
496 final Predicate<? super JanusGraphVertex> filterPredicate = StringUtils.isEmpty(model) ? this::vertexNotConnectedToAnyModel : vertex -> vertexValidForModel(vertex, model);
497 final List<JanusGraphVertex> verticesForModel = StreamSupport.stream(vertices.spliterator(), false).filter(filterPredicate).collect(Collectors.toList());
498 if (verticesForModel == null || verticesForModel.size() == 0) {
499 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
502 verticesForModel.forEach(vertex -> result.add(createAndFill(vertex, parseFlag)));
503 if (logger.isDebugEnabled()) {
504 logger.debug("Number of fetched nodes in graph for criteria : from type '{}' and properties '{}' is '{}'", type, hasProps,
507 return Either.left(result);
508 } catch (Exception e) {
509 if (logger.isDebugEnabled()) {
510 logger.debug("Failed to get by criteria for type '{}' and properties '{}'", type, hasProps, e);
512 return Either.right(JanusGraphClient.handleJanusGraphException(e));
515 if (logger.isDebugEnabled()) {
516 logger.debug("Failed to get by criteria for type '{}' and properties '{}'. Error : '{}'", type, hasProps, graph.right().value());
518 return Either.right(graph.right().value());
522 public Either<List<GraphVertex>, JanusGraphOperationStatus> getByCriteria(VertexTypeEnum type,
523 Map<GraphPropertyEnum, Object> props, Map<GraphPropertyEnum, Object> hasNotProps,
524 JsonParseFlagEnum parseFlag) {
525 return getByCriteria(type, props, hasNotProps, null, parseFlag);
528 public Either<List<GraphVertex>, JanusGraphOperationStatus> getByCriteria(final VertexTypeEnum type,
529 final Map<GraphPropertyEnum, Object> hasProps, final Map<GraphPropertyEnum, Object> hasNotProps,
530 final Map<String, Entry<JanusGraphPredicate, Object>> predicates, final JsonParseFlagEnum parseFlag) {
531 Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphClient.getGraph();
532 if (graph.isLeft()) {
534 JanusGraph tGraph = graph.left().value();
535 JanusGraphQuery<? extends JanusGraphQuery> query = tGraph.query();
538 query = query.has(GraphPropertyEnum.LABEL.getProperty(), type.getName());
540 if (hasProps != null && !hasProps.isEmpty()) {
541 for (Map.Entry<GraphPropertyEnum, Object> entry : hasProps.entrySet()) {
542 query = query.has(entry.getKey().getProperty(), entry.getValue());
545 if (hasNotProps != null && !hasNotProps.isEmpty()) {
546 for (Map.Entry<GraphPropertyEnum, Object> entry : hasNotProps.entrySet()) {
547 if (entry.getValue() instanceof List) {
548 buildMultipleNegateQueryFromList(entry, query);
550 query = query.hasNot(entry.getKey().getProperty(), entry.getValue());
554 if (predicates != null && !predicates.isEmpty()) {
555 for (Map.Entry<String, Entry<JanusGraphPredicate, Object>> entry : predicates.entrySet()) {
556 JanusGraphPredicate predicate = entry.getValue().getKey();
557 Object object = entry.getValue().getValue();
558 query = query.has(entry.getKey(), predicate, object);
561 Iterable<JanusGraphVertex> vertices = query.vertices();
562 if (vertices == null || !vertices.iterator().hasNext()) {
563 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
565 List<GraphVertex> result = new ArrayList<>();
567 vertices.forEach(vertex -> result.add(createAndFill(vertex, parseFlag)));
568 if (logger.isDebugEnabled()) {
570 "Number of fetched nodes in graph for criteria : from type '{}' and properties '{}' is '{}'",
571 type, hasProps, result.size());
573 return Either.left(result);
574 } catch (Exception e) {
575 if (logger.isDebugEnabled()) {
576 logger.debug("Failed to get by criteria for type '{}' and properties '{}'", type, hasProps, e);
578 return Either.right(JanusGraphClient.handleJanusGraphException(e));
581 if (logger.isDebugEnabled()) {
582 logger.debug("Failed to get by criteria for type '{}' and properties '{}'. Error : '{}'", type,
583 hasProps, graph.right().value());
585 return Either.right(graph.right().value());
589 private boolean vertexValidForModel(final JanusGraphVertex vertex, final String model) {
590 final Either<List<ImmutablePair<JanusGraphVertex, Edge>>, JanusGraphOperationStatus> modelVertices = getParentVerticies(vertex, GraphEdgeLabels.MODEL_ELEMENT);
592 if (modelVertices.isLeft()) {
593 for (ImmutablePair<JanusGraphVertex, Edge> vertexPair : modelVertices.left().value()) {
594 if (model.equals((String)vertexPair.getLeft().property("name").value())) {
602 private Either<List<ImmutablePair<JanusGraphVertex, Edge>>, JanusGraphOperationStatus> getParentVerticies(
603 final JanusGraphVertex rootVertex, final GraphEdgeLabels edgeType) {
604 return getEdgeVerticies(rootVertex, Direction.IN, edgeType);
607 private Either<List<ImmutablePair<JanusGraphVertex, Edge>>, JanusGraphOperationStatus> getEdgeVerticies(
608 final JanusGraphVertex rootVertex, final Direction direction, final GraphEdgeLabels edgeType) {
609 final List<ImmutablePair<JanusGraphVertex, Edge>> immutablePairs = new ArrayList<>();
610 final Iterator<Edge> edgesCreatorIterator = rootVertex.edges(direction, edgeType.getProperty());
611 if (edgesCreatorIterator != null) {
612 while (edgesCreatorIterator.hasNext()) {
613 Edge edge = edgesCreatorIterator.next();
614 JanusGraphVertex vertex = Direction.OUT.equals(direction)? (JanusGraphVertex) edge.inVertex() : (JanusGraphVertex) edge.outVertex();
615 ImmutablePair<JanusGraphVertex, Edge> immutablePair = new ImmutablePair<>(vertex, edge);
616 immutablePairs.add(immutablePair);
619 if (immutablePairs.isEmpty()) {
620 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
622 return Either.left(immutablePairs);
625 private boolean vertexNotConnectedToAnyModel(final JanusGraphVertex vertex) {
626 String vt = (String)vertex.property(GraphPropertyEnum.LABEL.getProperty()).value();
627 VertexTypeEnum vertexType = VertexTypeEnum.getByName(vt);
628 EdgeLabelEnum edgeLabel = vertexType.equals(VertexTypeEnum.TOPOLOGY_TEMPLATE) ? EdgeLabelEnum.MODEL : EdgeLabelEnum.MODEL_ELEMENT;
629 return !vertex.edges(Direction.IN, edgeLabel.name()).hasNext();
632 public Either<Iterator<Vertex>, JanusGraphOperationStatus> getCatalogOrArchiveVerticies(boolean isCatalog) {
633 Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphClient.getGraph();
634 if (graph.isLeft()) {
636 JanusGraph tGraph = graph.left().value();
637 String name = isCatalog ? VertexTypeEnum.CATALOG_ROOT.getName() : VertexTypeEnum.ARCHIVE_ROOT.getName();
638 Iterable<JanusGraphVertex> vCatalogIter = tGraph.query().has(GraphPropertyEnum.LABEL.getProperty(), name).vertices();
639 if (vCatalogIter == null) {
640 logger.debug("Failed to fetch catalog vertex");
641 return Either.right(JanusGraphOperationStatus.GENERAL_ERROR);
643 JanusGraphVertex catalogV = vCatalogIter.iterator().next();
644 if (catalogV == null) {
645 logger.debug("Failed to fetch catalog vertex");
646 return Either.right(JanusGraphOperationStatus.GENERAL_ERROR);
648 String edgeLabel = isCatalog ? EdgeLabelEnum.CATALOG_ELEMENT.name() : EdgeLabelEnum.ARCHIVE_ELEMENT.name();
649 Iterator<Vertex> vertices = catalogV.vertices(Direction.OUT, edgeLabel);
650 return Either.left(vertices);
651 } catch (Exception e) {
652 if (logger.isDebugEnabled()) {
653 logger.debug("Failed get by criteria: ", e);
655 return Either.right(JanusGraphClient.handleJanusGraphException(e));
658 if (logger.isDebugEnabled()) {
659 logger.debug("Failed get by criteria : ", graph.right().value());
661 return Either.right(graph.right().value());
665 private void buildMultipleNegateQueryFromList(Map.Entry<GraphPropertyEnum, Object> entry, JanusGraphQuery query) {
666 List<Object> negateList = (List<Object>) entry.getValue();
667 for (Object listItem : negateList) {
668 query.hasNot(entry.getKey().getProperty(), listItem);
673 * @param parentVertex
678 public Either<GraphVertex, JanusGraphOperationStatus> getChildVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel,
679 JsonParseFlagEnum parseFlag) {
680 Either<List<GraphVertex>, JanusGraphOperationStatus> childrenVertecies = getChildrenVertices(parentVertex, edgeLabel, parseFlag);
681 if (childrenVertecies.isRight()) {
682 return Either.right(childrenVertecies.right().value());
684 return Either.left(childrenVertecies.left().value().get(0));
688 * @param parentVertex
693 public Either<Vertex, JanusGraphOperationStatus> getChildVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
694 Either<List<Vertex>, JanusGraphOperationStatus> childrenVertecies = getChildrenVertices(parentVertex, edgeLabel, parseFlag);
695 if (childrenVertecies.isRight()) {
696 return Either.right(childrenVertecies.right().value());
698 return Either.left(childrenVertecies.left().value().get(0));
701 public Either<GraphVertex, JanusGraphOperationStatus> getParentVertex(GraphVertex parentVertex, EdgeLabelEnum edgeLabel,
702 JsonParseFlagEnum parseFlag) {
703 Either<List<GraphVertex>, JanusGraphOperationStatus> childrenVertecies = getParentVertices(parentVertex, edgeLabel, parseFlag);
704 if (childrenVertecies.isRight()) {
705 return Either.right(childrenVertecies.right().value());
707 if (isEmpty(childrenVertecies.left().value())) {
708 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
710 return Either.left(childrenVertecies.left().value().get(0));
713 public Either<Vertex, JanusGraphOperationStatus> getParentVertex(Vertex parentVertex, EdgeLabelEnum edgeLabel, JsonParseFlagEnum parseFlag) {
714 Either<List<Vertex>, JanusGraphOperationStatus> childrenVertecies = getParentVertices(parentVertex, edgeLabel, parseFlag);
715 if (childrenVertecies.isRight()) {
716 return Either.right(childrenVertecies.right().value());
718 if (isEmpty(childrenVertecies.left().value())) {
719 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
721 return Either.left(childrenVertecies.left().value().get(0));
725 * @param parentVertex
730 public Either<List<GraphVertex>, JanusGraphOperationStatus> getChildrenVertices(GraphVertex parentVertex, EdgeLabelEnum edgeLabel,
731 JsonParseFlagEnum parseFlag) {
732 return getAdjacentVertices(parentVertex, edgeLabel, parseFlag, Direction.OUT);
735 public Either<List<GraphVertex>, JanusGraphOperationStatus> getParentVertices(GraphVertex parentVertex, EdgeLabelEnum edgeLabel,
736 JsonParseFlagEnum parseFlag) {
737 return getAdjacentVertices(parentVertex, edgeLabel, parseFlag, Direction.IN);
740 public Either<List<Vertex>, JanusGraphOperationStatus> getParentVertices(Vertex parentVertex, EdgeLabelEnum edgeLabel,
741 JsonParseFlagEnum parseFlag) {
742 return getAdjacentVertices(parentVertex, edgeLabel, parseFlag, Direction.IN);
745 private Either<List<Vertex>, JanusGraphOperationStatus> getAdjacentVertices(Vertex parentVertex, EdgeLabelEnum edgeLabel,
746 JsonParseFlagEnum parseFlag, Direction direction) {
747 List<Vertex> list = new ArrayList<>();
749 Either<JanusGraph, JanusGraphOperationStatus> graphRes = janusGraphClient.getGraph();
750 if (graphRes.isRight()) {
751 logger.error("Failed to retrieve graph. status is {}", graphRes);
752 return Either.right(graphRes.right().value());
754 Iterator<Edge> edgesCreatorIterator = parentVertex.edges(direction, edgeLabel.name());
755 if (edgesCreatorIterator != null) {
756 while (edgesCreatorIterator.hasNext()) {
757 Edge edge = edgesCreatorIterator.next();
758 JanusGraphVertex vertex;
759 if (direction == Direction.IN) {
760 vertex = (JanusGraphVertex) edge.outVertex();
762 vertex = (JanusGraphVertex) edge.inVertex();
764 // GraphVertex graphVertex = createAndFill(vertex, parseFlag);
768 if (list.isEmpty()) {
769 return Either.right(JanusGraphOperationStatus.NOT_FOUND);
771 } catch (Exception e) {
772 logger.error("Failed to perform graph operation ", e);
773 Either.right(JanusGraphClient.handleJanusGraphException(e));
775 return Either.left(list);
779 * @param parentVertex
784 public Either<List<Vertex>, JanusGraphOperationStatus> getChildrenVertices(Vertex parentVertex, EdgeLabelEnum edgeLabel,
785 JsonParseFlagEnum parseFlag) {
786 return getAdjacentVertices(parentVertex, edgeLabel, parseFlag, Direction.OUT);
789 private Either<List<GraphVertex>, JanusGraphOperationStatus> getAdjacentVertices(GraphVertex parentVertex, EdgeLabelEnum edgeLabel,
790 JsonParseFlagEnum parseFlag, Direction direction) {
791 List<GraphVertex> list = new ArrayList<>();
792 Either<List<Vertex>, JanusGraphOperationStatus> adjacentVerticies = getAdjacentVertices(parentVertex.getVertex(), edgeLabel, parseFlag,
794 if (adjacentVerticies.isRight()) {
795 return Either.right(adjacentVerticies.right().value());
797 adjacentVerticies.left().value().stream().forEach(vertex -> {
798 list.add(createAndFill((JanusGraphVertex) vertex, parseFlag));
800 return Either.left(list);
804 * Searches Edge by received label and criteria
809 * @return found edge or JanusGraphOperationStatus
811 public Either<Edge, JanusGraphOperationStatus> getBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label,
812 Map<GraphPropertyEnum, Object> properties) {
813 Either<Edge, JanusGraphOperationStatus> result = null;
814 Edge matchingEdge = null;
815 String notFoundMsg = "No edges in graph for criteria";
817 JanusGraphVertexQuery<?> query = vertex.getVertex().query().labels(label.name());
818 if (properties != null && !properties.isEmpty()) {
819 for (Map.Entry<GraphPropertyEnum, Object> entry : properties.entrySet()) {
820 query = query.has(entry.getKey().getProperty(), entry.getValue());
823 Iterable<JanusGraphEdge> edges = query.edges();
825 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg);
826 result = Either.right(JanusGraphOperationStatus.NOT_FOUND);
828 Iterator<JanusGraphEdge> eIter = edges.iterator();
829 if (eIter.hasNext()) {
830 matchingEdge = eIter.next();
832 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg);
833 result = Either.right(JanusGraphOperationStatus.NOT_FOUND);
836 if (result == null) {
837 result = Either.left(matchingEdge);
839 } catch (Exception e) {
840 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during getting edge by criteria for component with id {}. {}",
841 vertex.getUniqueId(), e);
842 return Either.right(JanusGraphClient.handleJanusGraphException(e));
847 public Either<Edge, JanusGraphOperationStatus> getEdgeByChildrenVertexProperties(GraphVertex vertex, EdgeLabelEnum label,
848 Map<GraphPropertyEnum, Object> properties) {
849 Either<Edge, JanusGraphOperationStatus> result = null;
850 Edge matchingEdge = null;
851 String notFoundMsg = "No edges in graph for criteria";
853 Iterator<Edge> edges = vertex.getVertex().edges(Direction.OUT, label.name());
854 while (edges.hasNext()) {
855 matchingEdge = edges.next();
856 Vertex childV = matchingEdge.inVertex();
857 Map<GraphPropertyEnum, Object> vertexProperties = getVertexProperties(childV);
858 Optional<Entry<GraphPropertyEnum, Object>> findNotMatch = properties.entrySet().stream()
859 .filter(e -> vertexProperties.get(e.getKey()) == null || !vertexProperties.get(e.getKey()).equals(e.getValue())).findFirst();
860 if (!findNotMatch.isPresent()) {
861 result = Either.left(matchingEdge);
864 if (result == null) {
866 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, notFoundMsg);
867 result = Either.right(JanusGraphOperationStatus.NOT_FOUND);
869 } catch (Exception e) {
870 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during getting edge by criteria for component with id {}. {}",
871 vertex.getUniqueId(), e);
872 return Either.right(JanusGraphClient.handleJanusGraphException(e));
878 * Deletes Edge by received label and criteria
885 public Either<Edge, JanusGraphOperationStatus> deleteBelongingEdgeByCriteria(GraphVertex vertex, EdgeLabelEnum label,
886 Map<GraphPropertyEnum, Object> properties) {
887 Either<Edge, JanusGraphOperationStatus> result = null;
889 result = getBelongingEdgeByCriteria(vertex, label, properties);
890 if (result.isLeft()) {
891 Edge edge = result.left().value();
893 .addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} belonging to the vertex {} ", label.name(),
894 vertex.getUniqueId());
896 result = Either.left(edge);
899 .addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find an edge with the label {} belonging to the vertex {} ", label.name(),
900 vertex.getUniqueId());
902 } catch (Exception e) {
904 .addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during deleting an edge by criteria for the component with id {}. {}",
905 vertex == null ? "NULL" : vertex.getUniqueId(), e);
906 return Either.right(JanusGraphClient.handleJanusGraphException(e));
911 @SuppressWarnings("unchecked")
913 * Deletes an edge between vertices fromVertex and toVertex according to received label
920 public Either<Edge, JanusGraphOperationStatus> deleteEdge(GraphVertex fromVertex, GraphVertex toVertex, EdgeLabelEnum label) {
921 return deleteEdge(fromVertex.getVertex(), toVertex.getVertex(), label, fromVertex.getUniqueId(), toVertex.getUniqueId(), false);
924 public Either<Edge, JanusGraphOperationStatus> deleteAllEdges(GraphVertex fromVertex, GraphVertex toVertex, EdgeLabelEnum label) {
925 return deleteEdge(fromVertex.getVertex(), toVertex.getVertex(), label, fromVertex.getUniqueId(), toVertex.getUniqueId(), true);
928 public Either<Edge, JanusGraphOperationStatus> deleteEdge(JanusGraphVertex fromVertex, JanusGraphVertex toVertex, EdgeLabelEnum label,
929 String uniqueIdFrom, String uniqueIdTo, boolean deleteAll) {
930 Either<Edge, JanusGraphOperationStatus> result = null;
931 Vertex problemV = null;
933 Iterable<JanusGraphEdge> edges = fromVertex.query().labels(label.name()).edges();
934 Iterator<JanusGraphEdge> eIter = edges.iterator();
935 while (eIter.hasNext()) {
936 Edge edge = eIter.next();
937 problemV = edge.inVertex();
938 String currVertexUniqueId = null;
940 currVertexUniqueId = edge.inVertex().value(GraphPropertyEnum.UNIQUE_ID.getProperty());
941 } catch (Exception e) {
942 // AutoHealing procedure
943 logger.info("Corrupted vertex and edge were found and deleted {}", e);
944 if (problemV != null) {
945 Map<GraphPropertyEnum, Object> props = getVertexProperties(problemV);
946 logger.debug("problematic Vertex properties:");
947 logger.debug("props size: {}", props.size());
948 for (Map.Entry<GraphPropertyEnum, Object> entry : props.entrySet()) {
949 logger.debug("{}{}", entry.getKey() + ":" + entry.getValue());
951 Either<List<Vertex>, JanusGraphOperationStatus> childrenVertices = getChildrenVertices(problemV, EdgeLabelEnum.VERSION,
952 JsonParseFlagEnum.NoParse);
953 if (childrenVertices.isLeft()) {
954 childrenVertices.left().value().size();
955 logger.debug("number of children that problematic Vertex has: {}", props.size());
959 } catch (Exception e1) {
960 logger.debug("failed to remove problematic edge. {}", e1);
964 } catch (Exception e2) {
965 logger.debug("failed to remove problematic vertex . {}", e2);
970 if (currVertexUniqueId != null && currVertexUniqueId.equals(uniqueIdTo)) {
971 CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to delete an edge with the label {} between vertices {} and {}. ",
972 label.name(), uniqueIdFrom, uniqueIdTo);
974 result = Either.left(edge);
980 if (result == null) {
981 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete an edge with the label {} between vertices {} and {}. ",
982 label.name(), uniqueIdFrom, uniqueIdTo);
983 result = Either.right(JanusGraphOperationStatus.NOT_FOUND);
985 } catch (Exception e) {
986 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,
987 "Exception occured during deleting an edge with the label {} between vertices {} and {}. {}", label.name(), uniqueIdFrom, uniqueIdTo,
989 return Either.right(JanusGraphClient.handleJanusGraphException(e));
994 public JanusGraphOperationStatus deleteEdgeByDirection(GraphVertex fromVertex, Direction direction, EdgeLabelEnum label) {
996 Iterator<Edge> edges = fromVertex.getVertex().edges(direction, label.name());
997 while (edges.hasNext()) {
998 Edge edge = edges.next();
1001 } catch (Exception e) {
1002 logger.debug("Failed to remove from vertex {} edges {} by direction {} ", fromVertex.getUniqueId(), label, direction, e);
1003 return JanusGraphClient.handleJanusGraphException(e);
1005 return JanusGraphOperationStatus.OK;
1009 * Updates vertex properties. Note that graphVertex argument should contain updated data
1011 * @param graphVertex
1014 public Either<GraphVertex, JanusGraphOperationStatus> updateVertex(GraphVertex graphVertex) {
1015 CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId());
1017 graphVertex.updateMetadataJsonWithCurrentMetadataProperties();
1018 setVertexProperties(graphVertex.getVertex(), graphVertex);
1019 } catch (Exception e) {
1021 .addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update metadata of vertex with uniqueId {}. ", graphVertex.getUniqueId(), e);
1022 return Either.right(JanusGraphClient.handleJanusGraphException(e));
1024 return Either.left(graphVertex);
1028 * Fetches vertices by uniqueId according to received parse flag
1030 * @param verticesToGet
1033 public Either<Map<String, GraphVertex>, JanusGraphOperationStatus> getVerticesByUniqueIdAndParseFlag(
1034 Map<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> verticesToGet) {
1035 Either<Map<String, GraphVertex>, JanusGraphOperationStatus> result = null;
1036 Map<String, GraphVertex> vertices = new HashMap<>();
1037 JanusGraphOperationStatus titatStatus;
1038 Either<GraphVertex, JanusGraphOperationStatus> getVertexRes = null;
1039 for (Map.Entry<String, ImmutablePair<GraphPropertyEnum, JsonParseFlagEnum>> entry : verticesToGet.entrySet()) {
1040 if (entry.getValue().getKey() == GraphPropertyEnum.UNIQUE_ID) {
1041 getVertexRes = getVertexById(entry.getKey(), entry.getValue().getValue());
1042 } else if (entry.getValue().getKey() == GraphPropertyEnum.USERID) {
1043 getVertexRes = getVertexByPropertyAndLabel(entry.getValue().getKey(), entry.getKey(), VertexTypeEnum.USER,
1044 entry.getValue().getValue());
1046 if (getVertexRes == null) {
1047 titatStatus = JanusGraphOperationStatus.ILLEGAL_ARGUMENT;
1049 .addRecordToLog(logger, LogLevelEnum.DEBUG, "Invalid vertex type label {} has been received. ", entry.getValue().getKey(),
1051 return Either.right(titatStatus);
1053 if (getVertexRes.isRight()) {
1054 titatStatus = getVertexRes.right().value();
1056 .addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to get vertex by id {} . Status is {}. ", entry.getKey(), titatStatus);
1057 result = Either.right(titatStatus);
1060 vertices.put(entry.getKey(), getVertexRes.left().value());
1063 if (result == null) {
1064 result = Either.left(vertices);
1070 * Creates edge between "from" and "to" vertices with specified label and properties extracted from received edge
1078 public JanusGraphOperationStatus createEdge(Vertex from, Vertex to, EdgeLabelEnum label, Edge edgeToCopy) {
1079 return createEdge(from, to, label, getEdgeProperties(edgeToCopy));
1082 public JanusGraphOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, Edge prevEdge, EdgeLabelEnum prevLabel,
1083 EdgeLabelEnum newLabel) {
1085 .addRecordToLog(logger, LogLevelEnum.TRACE, "Going to replace edge with label {} to {} between vertices {} and {}", prevLabel, newLabel,
1086 fromVertex != null ? fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()) : "NULL",
1087 toVertex != null ? toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()) : "NULL");
1088 JanusGraphOperationStatus result = createEdge(fromVertex, toVertex, newLabel, prevEdge);
1089 if (result == JanusGraphOperationStatus.OK) {
1096 * Replaces previous label of edge with new label
1104 public JanusGraphOperationStatus replaceEdgeLabel(Vertex fromVertex, Vertex toVertex, EdgeLabelEnum prevLabel, EdgeLabelEnum newLabel) {
1105 Iterator<Edge> prevEdgeIter = toVertex.edges(Direction.IN, prevLabel.name());
1106 if (prevEdgeIter == null || !prevEdgeIter.hasNext()) {
1108 .addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to replace edge with label {} to {} between vertices {} and {}", prevLabel,
1109 newLabel, fromVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()),
1110 toVertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()));
1111 return JanusGraphOperationStatus.NOT_FOUND;
1113 return replaceEdgeLabel(fromVertex, toVertex, prevEdgeIter.next(), prevLabel, newLabel);
1118 * Updates metadata properties of vertex on graph. Json metadata property of the vertex will be updated with received properties too.
1124 public JanusGraphOperationStatus updateVertexMetadataPropertiesWithJson(Vertex vertex, Map<GraphPropertyEnum, Object> properties) {
1126 if (!MapUtils.isEmpty(properties)) {
1127 String jsonMetadataStr = (String) vertex.property(GraphPropertyEnum.METADATA.getProperty()).value();
1128 Map<String, Object> jsonMetadataMap = JsonParserUtils.toMap(jsonMetadataStr);
1129 for (Map.Entry<GraphPropertyEnum, Object> property : properties.entrySet()) {
1130 vertex.property(property.getKey().getProperty(), property.getValue());
1131 jsonMetadataMap.put(property.getKey().getProperty(), property.getValue());
1133 vertex.property(GraphPropertyEnum.METADATA.getProperty(), JsonParserUtils.toJson(jsonMetadataMap));
1135 } catch (Exception e) {
1136 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occurred during update vertex metadata properties with json{}. {}",
1137 vertex.property(GraphPropertyEnum.UNIQUE_ID.getProperty()), e.getMessage());
1138 return JanusGraphClient.handleJanusGraphException(e);
1140 return JanusGraphOperationStatus.OK;
1143 public JanusGraphOperationStatus disassociateAndDeleteLast(GraphVertex vertex, Direction direction, EdgeLabelEnum label) {
1145 Iterator<Edge> edges = vertex.getVertex().edges(direction, label.name());
1146 while (edges.hasNext()) {
1147 Edge edge = edges.next();
1148 Vertex secondVertex;
1149 Direction reverseDirection;
1150 if (direction == Direction.IN) {
1151 secondVertex = edge.outVertex();
1152 reverseDirection = Direction.OUT;
1154 secondVertex = edge.inVertex();
1155 reverseDirection = Direction.IN;
1158 CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Edge {} with direction {} was removed from {}", label.name(), direction,
1159 vertex.getVertex());
1160 Iterator<Edge> restOfEdges = secondVertex.edges(reverseDirection, label.name());
1161 if (!restOfEdges.hasNext()) {
1162 secondVertex.remove();
1163 CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "This was last edge . Vertex {} was removed ", vertex.getUniqueId());
1166 } catch (Exception e) {
1167 CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG,
1168 "Exception occured during deleting an edge with the label {} direction {} from vertex {}. {}", label.name(), direction,
1169 vertex.getUniqueId(), e);
1170 return JanusGraphClient.handleJanusGraphException(e);
1172 return JanusGraphOperationStatus.OK;
1175 public Object getProperty(JanusGraphVertex vertex, String key) {
1176 PropertyKey propertyKey = janusGraphClient.getGraph().left().value().getPropertyKey(key);
1177 return vertex.valueOrNull(propertyKey);
1180 public Object getProperty(Edge edge, EdgePropertyEnum key) {
1181 Object value = null;
1183 Property<Object> property = edge.property(key.getProperty());
1184 if (property != null) {
1185 value = property.orElse(null);
1186 if (value != null && key == EdgePropertyEnum.INSTANCES) {
1187 return JsonParserUtils.toList((String) value, String.class);
1191 } catch (Exception e) {
1203 public JanusGraphOperationStatus moveEdge(GraphVertex vertexA, GraphVertex vertexB, EdgeLabelEnum label, Direction direction) {
1204 JanusGraphOperationStatus result = deleteEdgeByDirection(vertexA, direction, label);
1205 if (result != JanusGraphOperationStatus.OK) {
1206 logger.error("Failed to diassociate {} from element {}. error {} ", label, vertexA.getUniqueId(), result);
1209 JanusGraphOperationStatus createRelation;
1210 if (direction == Direction.IN) {
1211 createRelation = createEdge(vertexB, vertexA, label, null);
1213 createRelation = createEdge(vertexA, vertexB, label, null);
1215 if (createRelation != JanusGraphOperationStatus.OK) {
1216 return createRelation;
1218 return JanusGraphOperationStatus.OK;
1221 public Either<Edge, JanusGraphOperationStatus> getBelongingEdgeByCriteria(String parentId, EdgeLabelEnum label,
1222 Map<GraphPropertyEnum, Object> properties) {
1223 Either<GraphVertex, JanusGraphOperationStatus> getVertexRes = getVertexById(parentId, JsonParseFlagEnum.NoParse);
1224 if (getVertexRes.isRight()) {
1225 return Either.right(getVertexRes.right().value());
1227 return getBelongingEdgeByCriteria(getVertexRes.left().value(), label, properties);