2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2019 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.onap.aai.serialization.db;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24 import com.google.common.base.CaseFormat;
25 import org.apache.commons.lang.StringUtils;
26 import org.apache.tinkerpop.gremlin.process.traversal.Path;
27 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
28 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
29 import org.apache.tinkerpop.gremlin.structure.Direction;
30 import org.apache.tinkerpop.gremlin.structure.Edge;
31 import org.apache.tinkerpop.gremlin.structure.Vertex;
32 import org.apache.tinkerpop.gremlin.structure.VertexProperty;
33 import org.janusgraph.core.SchemaViolationException;
34 import org.javatuples.Pair;
35 import org.onap.aai.concurrent.AaiCallable;
36 import org.onap.aai.config.SpringContextAware;
37 import org.onap.aai.db.props.AAIProperties;
38 import org.onap.aai.edges.EdgeIngestor;
39 import org.onap.aai.edges.EdgeRule;
40 import org.onap.aai.edges.EdgeRuleQuery;
41 import org.onap.aai.edges.enums.AAIDirection;
42 import org.onap.aai.edges.enums.EdgeField;
43 import org.onap.aai.edges.enums.EdgeProperty;
44 import org.onap.aai.edges.enums.EdgeType;
45 import org.onap.aai.edges.exceptions.AmbiguousRuleChoiceException;
46 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
47 import org.onap.aai.exceptions.AAIException;
48 import org.onap.aai.introspection.*;
49 import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
50 import org.onap.aai.introspection.sideeffect.*;
51 import org.onap.aai.logging.ErrorLogHelper;
52 import org.onap.aai.logging.LogFormatTools;
53 import org.onap.aai.logging.StopWatch;
54 import org.onap.aai.parsers.query.QueryParser;
55 import org.onap.aai.parsers.relationship.RelationshipToURI;
56 import org.onap.aai.parsers.uri.URIParser;
57 import org.onap.aai.parsers.uri.URIToObject;
58 import org.onap.aai.parsers.uri.URIToRelationshipObject;
59 import org.onap.aai.query.builder.QueryBuilder;
60 import org.onap.aai.schema.enums.ObjectMetadata;
61 import org.onap.aai.schema.enums.PropertyMetadata;
62 import org.onap.aai.serialization.db.exceptions.MultipleEdgeRuleFoundException;
63 import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
64 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
65 import org.onap.aai.serialization.engines.query.QueryEngine;
66 import org.onap.aai.setup.SchemaVersion;
67 import org.onap.aai.setup.SchemaVersions;
68 import org.onap.aai.util.AAIConfig;
69 import org.onap.aai.util.AAIConstants;
70 import org.onap.aai.util.delta.*;
71 import org.onap.aai.workarounds.NamingExceptions;
72 import org.springframework.context.ApplicationContext;
74 import javax.ws.rs.core.UriBuilder;
75 import java.io.UnsupportedEncodingException;
76 import java.lang.reflect.Array;
77 import java.lang.reflect.InvocationTargetException;
78 import java.net.MalformedURLException;
80 import java.net.URISyntaxException;
82 import java.util.concurrent.ExecutionException;
83 import java.util.concurrent.ExecutorService;
84 import java.util.concurrent.Future;
85 import java.util.regex.Matcher;
86 import java.util.regex.Pattern;
88 public class DBSerializer {
90 private static final Logger LOGGER = LoggerFactory.getLogger(DBSerializer.class);
91 private static final String RELATIONSHIP_LABEL = "relationship-label";
92 private static final String RELATIONSHIP = "relationship";
93 public static final String FALSE = "false";
94 public static final String AAI_6145 = "AAI_6145";
95 public static final String AAI_6129 = "AAI_6129";
97 private final TransactionalGraphEngine engine;
98 private final String sourceOfTruth;
99 private final Set<String> groups;
100 private final ModelType introspectionType;
101 private final SchemaVersion version;
102 private final Loader latestLoader;
103 private EdgeSerializer edgeSer;
104 private EdgeIngestor edgeRules;
105 private final Loader loader;
106 private final String baseURL;
107 private double dbTimeMsecs = 0;
108 private long currentTimeMillis;
110 private SchemaVersions schemaVersions;
111 private Set<String> namedPropNodes;
112 private Map<String, ObjectDelta> objectDeltas = new LinkedHashMap<>();
113 private Map<Vertex, Boolean> updatedVertexes = new LinkedHashMap<>();
114 private Set<Vertex> edgeVertexes = new LinkedHashSet<>();
115 private Map<String, Pair<Introspector, LinkedHashMap<String, Introspector>>> impliedDeleteUriObjectPair = new LinkedHashMap<>();
116 private int notificationDepth;
117 private boolean isDeltaEventsEnabled;
120 * Instantiates a new DB serializer.
122 * @param version the version
123 * @param engine the engine
124 * @param introspectionType the introspection type
125 * @param sourceOfTruth the source of truth
126 * @throws AAIException
128 public DBSerializer(SchemaVersion version, TransactionalGraphEngine engine, ModelType introspectionType,
129 String sourceOfTruth) throws AAIException {
130 this.engine = engine;
131 this.sourceOfTruth = sourceOfTruth;
132 this.groups = Collections.EMPTY_SET;
133 this.introspectionType = introspectionType;
134 this.schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
135 SchemaVersion latestVersion = schemaVersions.getDefaultVersion();
137 SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, latestVersion);
138 this.version = version;
140 SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, version);
141 this.namedPropNodes = this.latestLoader.getNamedPropNodes();
142 this.baseURL = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE);
143 this.currentTimeMillis = System.currentTimeMillis();
144 // If creating the DBSerializer the old way then set the notification depth to maximum
145 this.notificationDepth = AAIProperties.MAXIMUM_DEPTH;
149 public DBSerializer(SchemaVersion version, TransactionalGraphEngine engine, ModelType introspectionType,
150 String sourceOfTruth, Set<String> groups) throws AAIException {
151 this.engine = engine;
152 this.sourceOfTruth = sourceOfTruth;
153 this.groups = groups;
154 this.introspectionType = introspectionType;
155 this.schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
156 SchemaVersion latestVersion = schemaVersions.getDefaultVersion();
158 SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, latestVersion);
159 this.version = version;
161 SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, version);
162 this.namedPropNodes = this.latestLoader.getNamedPropNodes();
163 this.baseURL = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE);
164 this.currentTimeMillis = System.currentTimeMillis();
165 // If creating the DBSerializer the old way then set the notification depth to maximum
166 this.notificationDepth = AAIProperties.MAXIMUM_DEPTH;
170 public DBSerializer(SchemaVersion version,
171 TransactionalGraphEngine engine,
172 ModelType introspectionType,
173 String sourceOfTruth,
174 int notificationDepth) throws AAIException {
175 this.engine = engine;
176 this.sourceOfTruth = sourceOfTruth;
177 this.groups = Collections.EMPTY_SET;
178 this.introspectionType = introspectionType;
179 this.schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
180 SchemaVersion latestVersion = schemaVersions.getDefaultVersion();
182 SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, latestVersion);
183 this.version = version;
185 SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, version);
186 this.namedPropNodes = this.latestLoader.getNamedPropNodes();
187 this.baseURL = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE);
188 this.currentTimeMillis = System.currentTimeMillis();
189 this.notificationDepth = notificationDepth;
193 public DBSerializer(SchemaVersion version,
194 TransactionalGraphEngine engine,
195 ModelType introspectionType,
196 String sourceOfTruth,
198 int notificationDepth) throws AAIException {
199 this.engine = engine;
200 this.sourceOfTruth = sourceOfTruth;
201 this.groups = groups;
202 this.introspectionType = introspectionType;
203 this.schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
204 SchemaVersion latestVersion = schemaVersions.getDefaultVersion();
206 SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, latestVersion);
207 this.version = version;
209 SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, version);
210 this.namedPropNodes = this.latestLoader.getNamedPropNodes();
211 this.baseURL = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE);
212 this.currentTimeMillis = System.currentTimeMillis();
213 this.notificationDepth = notificationDepth;
217 public DBSerializer(SchemaVersion version,
218 TransactionalGraphEngine engine,
219 ModelType introspectionType,
220 String sourceOfTruth,
221 int notificationDepth,
222 String serverBase) throws AAIException {
223 this.engine = engine;
224 this.sourceOfTruth = sourceOfTruth;
225 this.groups = Collections.EMPTY_SET;
226 this.introspectionType = introspectionType;
227 this.schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
228 SchemaVersion latestVersion = schemaVersions.getDefaultVersion();
230 SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, latestVersion);
231 this.version = version;
233 SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, version);
234 this.namedPropNodes = this.latestLoader.getNamedPropNodes();
235 this.baseURL = serverBase;
236 this.currentTimeMillis = System.currentTimeMillis();
237 this.notificationDepth = notificationDepth;
241 public DBSerializer(SchemaVersion version,
242 TransactionalGraphEngine engine,
243 ModelType introspectionType,
244 String sourceOfTruth,
246 int notificationDepth,
247 String serverBase) throws AAIException {
248 this.engine = engine;
249 this.sourceOfTruth = sourceOfTruth;
250 this.groups = groups;
251 this.introspectionType = introspectionType;
252 this.schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
253 SchemaVersion latestVersion = schemaVersions.getDefaultVersion();
255 SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, latestVersion);
256 this.version = version;
258 SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, version);
259 this.namedPropNodes = this.latestLoader.getNamedPropNodes();
260 this.baseURL = serverBase;
261 this.currentTimeMillis = System.currentTimeMillis();
262 this.notificationDepth = notificationDepth;
266 private void initBeans() {
267 // TODO proper spring wiring, but that requires a lot of refactoring so for now we have this
268 ApplicationContext ctx = SpringContextAware.getApplicationContext();
269 EdgeIngestor ei = ctx.getBean(EdgeIngestor.class);
271 EdgeSerializer es = ctx.getBean(EdgeSerializer.class);
272 setEdgeSerializer(es);
273 isDeltaEventsEnabled = Boolean.parseBoolean(SpringContextAware.getApplicationContext().getEnvironment().getProperty("delta.events.enabled", FALSE));
276 public void setEdgeSerializer(EdgeSerializer edgeSer) {
277 this.edgeSer = edgeSer;
280 public EdgeSerializer getEdgeSeriailizer() {
284 public void setEdgeIngestor(EdgeIngestor ei) {
288 public EdgeIngestor getEdgeIngestor() {
289 return this.edgeRules;
292 public Map<Vertex, Boolean> getUpdatedVertexes() {
293 return updatedVertexes;
296 public Map<String, Pair<Introspector, LinkedHashMap<String, Introspector>>> getImpliedDeleteUriObjectPair(){
297 return impliedDeleteUriObjectPair;
300 public Set<String> getGroups() {
305 * Touch standard vertex properties.
307 * @param isNewVertex the is new vertex
309 public void touchStandardVertexProperties(Vertex v, boolean isNewVertex) {
310 String timeNowInSec = Long.toString(currentTimeMillis);
312 String uuid = UUID.randomUUID().toString();
313 v.property(AAIProperties.SOURCE_OF_TRUTH, this.sourceOfTruth);
314 v.property(AAIProperties.CREATED_TS, currentTimeMillis);
315 v.property(AAIProperties.AAI_UUID, uuid);
316 v.property(AAIProperties.RESOURCE_VERSION, timeNowInSec);
317 v.property(AAIProperties.LAST_MOD_TS, currentTimeMillis);
318 v.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, this.sourceOfTruth);
320 if(isDeltaEventsEnabled) {
321 standardVertexPropsDeltas(v, timeNowInSec);
323 v.property(AAIProperties.RESOURCE_VERSION, timeNowInSec);
324 v.property(AAIProperties.LAST_MOD_TS, currentTimeMillis);
325 v.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, this.sourceOfTruth);
329 private void standardVertexPropsDeltas(Vertex v, String timeNowInSec) {
330 String uri = v.property(AAIProperties.AAI_URI).value().toString();
331 long createdTs = (Long) v.property(AAIProperties.CREATED_TS).value();
332 DeltaAction objDeltaAction = createdTs == currentTimeMillis ? DeltaAction.CREATE : DeltaAction.UPDATE;
333 if (getObjectDeltas().containsKey(uri)) {
334 getObjectDeltas().get(uri).setAction(objDeltaAction);
337 addPropDelta(uri, AAIProperties.AAI_UUID, PropertyDeltaFactory.getDelta(DeltaAction.STATIC, v.property(AAIProperties.AAI_UUID).value()), objDeltaAction);
338 addPropDelta(uri, AAIProperties.NODE_TYPE, PropertyDeltaFactory.getDelta(DeltaAction.STATIC, v.property(AAIProperties.NODE_TYPE).value()), objDeltaAction);
339 addPropDelta(uri, AAIProperties.SOURCE_OF_TRUTH, PropertyDeltaFactory.getDelta(DeltaAction.STATIC, v.property(AAIProperties.SOURCE_OF_TRUTH).value()), objDeltaAction);
340 addPropDelta(uri, AAIProperties.CREATED_TS, PropertyDeltaFactory.getDelta(DeltaAction.STATIC, v.property(AAIProperties.CREATED_TS).value()), objDeltaAction);
342 if (objDeltaAction.equals(DeltaAction.UPDATE)) {
345 AAIProperties.RESOURCE_VERSION,
346 PropertyDeltaFactory.getDelta(objDeltaAction, timeNowInSec, v.property(AAIProperties.RESOURCE_VERSION).value()),
351 AAIProperties.LAST_MOD_TS,
352 PropertyDeltaFactory.getDelta(objDeltaAction, currentTimeMillis, v.property(AAIProperties.LAST_MOD_TS).value()),
357 AAIProperties.LAST_MOD_SOURCE_OF_TRUTH,
358 PropertyDeltaFactory.getDelta(objDeltaAction, this.sourceOfTruth, v.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value()),
362 addPropDelta(uri, AAIProperties.RESOURCE_VERSION, PropertyDeltaFactory.getDelta(objDeltaAction, v.property(AAIProperties.RESOURCE_VERSION).value()), objDeltaAction);
363 addPropDelta(uri, AAIProperties.LAST_MOD_TS, PropertyDeltaFactory.getDelta(objDeltaAction, v.property(AAIProperties.LAST_MOD_TS).value()), objDeltaAction);
364 addPropDelta(uri, AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, PropertyDeltaFactory.getDelta(objDeltaAction, v.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value()), objDeltaAction);
368 public Map<String, ObjectDelta> getObjectDeltas() {return objectDeltas;}
370 private void addPropDelta(String uri, String prop, PropertyDelta delta, DeltaAction objDeltaAction) {
371 ObjectDelta objectDelta = this.objectDeltas.getOrDefault(uri, new ObjectDelta(uri, objDeltaAction, this.sourceOfTruth, this.currentTimeMillis));
372 objectDelta.addPropertyDelta(prop, delta);
373 objectDeltas.put(uri, objectDelta);
376 private void addRelationshipDelta(String uri, RelationshipDelta delta, DeltaAction objDeltaAction) {
377 ObjectDelta objectDelta = this.objectDeltas.getOrDefault(uri, new ObjectDelta(uri, objDeltaAction, this.sourceOfTruth, this.currentTimeMillis));
378 objectDelta.addRelationshipDelta(delta);
379 objectDeltas.put(uri, objectDelta);
382 private void touchStandardVertexProperties(String nodeType, Vertex v, boolean isNewVertex) {
383 v.property(AAIProperties.NODE_TYPE, nodeType);
384 touchStandardVertexProperties(v, isNewVertex);
388 * Creates the new vertex.
390 * @param wrappedObject the wrapped object
393 public Vertex createNewVertex(Introspector wrappedObject) {
396 StopWatch.conditionalStart();
397 v = this.engine.tx().addVertex(wrappedObject.getDbName());
398 touchStandardVertexProperties(wrappedObject.getDbName(), v, true);
400 dbTimeMsecs += StopWatch.stopIfStarted();
408 * @param className the class name
412 * Removes the classpath from a class name
414 public String trimClassName(String className) {
415 String returnValue = "";
417 if (className.lastIndexOf('.') == -1) {
420 returnValue = className.substring(className.lastIndexOf('.') + 1);
430 * @param uriQuery the uri query
431 * @param identifier the identifier
432 * @throws SecurityException the security exception
433 * @throws IllegalArgumentException the illegal argument exception
434 * @throws AAIException the AAI exception
435 * @throws UnsupportedEncodingException the unsupported encoding exception
437 public void serializeToDb(Introspector obj, Vertex v, QueryParser uriQuery, String identifier,
438 String requestContext) throws AAIException, UnsupportedEncodingException {
439 StopWatch.conditionalStart();
441 if (uriQuery.isDependent()) {
442 // try to find the parent
443 List<Vertex> vertices = uriQuery.getQueryBuilder().getParentQuery().toList();
444 if (!vertices.isEmpty()) {
445 Vertex parent = vertices.get(0);
446 this.reflectDependentVertex(parent, v, obj, requestContext);
448 dbTimeMsecs += StopWatch.stopIfStarted();
449 throw new AAIException("AAI_6114",
450 "No parent Node of type " + uriQuery.getParentResultType() + " for " + identifier);
453 serializeSingleVertex(v, obj, requestContext);
456 } catch (SchemaViolationException e) {
457 dbTimeMsecs += StopWatch.stopIfStarted();
458 throw new AAIException("AAI_6117", e);
460 dbTimeMsecs += StopWatch.stopIfStarted();
463 public void serializeSingleVertex(Vertex v, Introspector obj, String requestContext)
464 throws UnsupportedEncodingException, AAIException {
465 StopWatch.conditionalStart();
467 boolean isTopLevel = obj.isTopLevel();
469 addUriIfNeeded(v, obj.getURI());
472 URI uri = this.getURIForVertex(v);
473 URIParser parser = new URIParser(this.loader, uri);
474 if (parser.validate()) {
475 addUriIfNeeded(v, uri.toString());
478 processObject(obj, v, requestContext);
479 } catch (SchemaViolationException e) {
480 throw new AAIException("AAI_6117", e);
482 dbTimeMsecs += StopWatch.stopIfStarted();
486 private void addUriIfNeeded(Vertex v, String uri) {
487 VertexProperty<String> uriProp = v.property(AAIProperties.AAI_URI);
488 if (!uriProp.isPresent() || !uriProp.value().equals(uri)) {
489 v.property(AAIProperties.AAI_URI, uri);
499 * @throws IllegalArgumentException the illegal argument exception
500 * @throws SecurityException the security exception
501 * @throws AAIException the AAI exception
502 * @throws UnsupportedEncodingException the unsupported encoding exception
505 * Helper method for reflectToDb
506 * Handles all the property setting
508 private List<Vertex> processObject(Introspector obj, Vertex v, String requestContext)
509 throws UnsupportedEncodingException, AAIException {
510 Set<String> properties = new LinkedHashSet<>(obj.getProperties());
511 properties.remove(AAIProperties.RESOURCE_VERSION);
512 List<Vertex> dependentVertexes = new ArrayList<>();
513 List<Vertex> processedVertexes = new ArrayList<>();
515 boolean isComplexType ;
518 // If the notification depth is set to maximum
519 // this is the behavior of the expected clients
520 if(notificationDepth == AAIProperties.MAXIMUM_DEPTH) {
521 if (!obj.isContainer()) {
522 this.touchStandardVertexProperties(v, false);
525 this.executePreSideEffects(obj, v);
526 for (String property : properties) {
527 final String propertyType;
528 propertyType = obj.getType(property);
529 isComplexType = obj.isComplexType(property);
530 isListType = obj.isListType(property);
531 Object value = obj.getValue(property);
533 if (!(isComplexType || isListType)) {
534 boolean canModify = this.canModify(obj, property, requestContext);
537 final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(property);
538 String dbProperty = property;
539 if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) {
540 dbProperty = metadata.get(PropertyMetadata.DB_ALIAS);
542 if (metadata.containsKey(PropertyMetadata.DATA_LINK)) {
543 // data linked properties are ephemeral
544 // they are populated dynamically on GETs
547 Object oldValue = v.property(dbProperty).orElse(null);
548 String uri = getURIForVertex(v).toString();
550 if (!value.equals(oldValue)) {
551 if (propertyType.toLowerCase().contains(".long")) {
552 v.property(dbProperty, new Integer(((Long) value).toString()));
554 v.property(dbProperty, value);
556 if (isDeltaEventsEnabled) {
557 createDeltaProperty(uri, value, dbProperty, oldValue);
559 this.updatedVertexes.putIfAbsent(v, false);
562 if (oldValue != null) {
563 v.property(dbProperty).remove();
564 if (isDeltaEventsEnabled) {
565 addPropDelta(uri, dbProperty, PropertyDeltaFactory.getDelta(DeltaAction.DELETE, oldValue), DeltaAction.UPDATE);
567 this.updatedVertexes.putIfAbsent(v, false);
571 } else if (isListType) {
572 List<Object> list = (List<Object>) value;
573 if (obj.isComplexGenericType(property)) {
575 for (Object o : list) {
576 Introspector child = IntrospectorFactory.newInstance(this.introspectionType, o);
577 child.setURIChain(obj.getURI());
578 processedVertexes.add(reflectDependentVertex(v, child, requestContext));
583 if (isDeltaEventsEnabled) {
584 String uri = getURIForVertex(v).toString();
585 List<Object> oldVal = engine.getListProperty(v, property);
586 engine.setListProperty(v, property, list);
587 if (list == null || list.isEmpty()) { // property delete scenario, there is no new value
588 if (oldVal != null && !oldVal.isEmpty()) { // and there is an old value
589 addPropDelta(uri, property, PropertyDeltaFactory.getDelta(DeltaAction.DELETE, oldVal), DeltaAction.UPDATE);
591 } else { // is either a create or update and is handled by the called method
592 createDeltaProperty(uri, list, property, oldVal);
595 engine.setListProperty(v, property, list);
597 this.updatedVertexes.putIfAbsent(v, false);
600 // method.getReturnType() is not 'simple' then create a vertex and edge recursively returning an edge
601 // back to this method
602 if (value != null) { // effectively ignore complex properties not included in the object we're
604 if (value.getClass().isArray()) {
606 int length = Array.getLength(value);
607 for (int i = 0; i < length; i++) {
608 Object arrayElement = Array.get(value, i);
609 Introspector child = IntrospectorFactory.newInstance(this.introspectionType, arrayElement);
610 child.setURIChain(obj.getURI());
611 processedVertexes.add(reflectDependentVertex(v, child, requestContext));
614 } else if (!property.equals("relationship-list")) {
616 Introspector introspector = IntrospectorFactory.newInstance(this.introspectionType, value);
617 if (introspector.isContainer()) {
618 dependentVertexes.addAll(
619 this.engine.getQueryEngine().findChildrenOfType(v, introspector.getChildDBName()));
620 introspector.setURIChain(obj.getURI());
622 processedVertexes.addAll(processObject(introspector, v, requestContext));
625 dependentVertexes.addAll(
626 this.engine.getQueryEngine().findChildrenOfType(v, introspector.getDbName()));
627 processedVertexes.add(reflectDependentVertex(v, introspector, requestContext));
630 } else if (property.equals("relationship-list")) {
631 handleRelationships(obj, v);
636 this.writeThroughDefaults(v, obj);
637 /* handle those vertexes not touched */
638 for (Vertex toBeKept : processedVertexes) {
639 dependentVertexes.remove(toBeKept);
642 ImpliedDelete impliedDelete = new ImpliedDelete(engine, this);
643 List<Vertex> impliedDeleteVertices = impliedDelete.execute(v.id(), sourceOfTruth, obj.getName(), dependentVertexes);
645 if(notificationDepth == AAIProperties.MINIMUM_DEPTH){
646 for(Vertex curVertex : impliedDeleteVertices){
647 if(!curVertex.property("aai-uri").isPresent()){
648 LOGGER.debug("Encountered an vertex {} with missing aai-uri", curVertex.id());
651 String curAaiUri = curVertex.<String>property(AAIProperties.AAI_URI).value();
652 Introspector curObj = this.getLatestVersionView(curVertex, notificationDepth);
654 LinkedHashMap<String, Introspector> curObjRelated = new LinkedHashMap<>();
656 if(!curObj.isTopLevel()){
657 curObjRelated.putAll(this.getRelatedObjects(engine.getQueryEngine(), curVertex, curObj, this.loader));
660 if(!impliedDeleteUriObjectPair.containsKey(curAaiUri)){
661 impliedDeleteUriObjectPair.put(curAaiUri, new Pair<>(curObj, curObjRelated));
666 impliedDelete.delete(impliedDeleteVertices);
668 // touch svp using vertex list for what changed
669 // if the notification depth is zero
670 if(notificationDepth == AAIProperties.MINIMUM_DEPTH){
671 this.updatedVertexes.entrySet().stream()
672 .filter(e -> !e.getValue())
673 .filter(e -> !edgeVertexes.contains(e.getKey()))
675 this.touchStandardVertexProperties(e.getKey(), false);
679 this.executePostSideEffects(obj, v);
680 return processedVertexes;
683 private void createDeltaProperty(String uri, Object value, String dbProperty, Object oldValue) {
684 if (oldValue == null) {
685 addPropDelta(uri, dbProperty, PropertyDeltaFactory.getDelta(DeltaAction.CREATE, value), DeltaAction.UPDATE);
687 addPropDelta(uri, dbProperty, PropertyDeltaFactory.getDelta(DeltaAction.UPDATE, value, oldValue), DeltaAction.UPDATE);
691 public HashMap<String, Introspector> getRelatedObjects(QueryEngine queryEngine, Vertex v,
692 Introspector obj, Loader loader) throws IllegalArgumentException, SecurityException, UnsupportedEncodingException, AAIException {
694 HashMap<String, Introspector> relatedVertices = new HashMap<>();
695 VertexProperty aaiUriProperty = v.property(AAIProperties.AAI_URI);
697 if (!aaiUriProperty.isPresent()) {
698 if (LOGGER.isDebugEnabled()) {
699 LOGGER.debug("For the given vertex {}, it seems aai-uri is not present so not getting related objects",
703 "It seems aai-uri is not present in vertex, so not getting related objects, for more info enable debug log");
705 return relatedVertices;
708 String aaiUri = aaiUriProperty.value().toString();
710 if (!obj.isTopLevel()) {
711 String[] uriList = convertIntrospectorToUriList(aaiUri, obj, loader);
712 List<Vertex> vertexChain;
713 // If the uriList is null then there is something wrong with converting the uri
714 // into a list of aai-uris so falling back to the old mechanism for finding parents
715 if (uriList == null) {
717 "Falling back to the old mechanism due to unable to convert aai-uri to list of uris but this is not optimal");
718 vertexChain = queryEngine.findParents(v);
719 } else if (uriList.length == 1) {
720 // If the uri list is size 1 the only uri in the list is the one represented by v thus no need to query
721 vertexChain = Collections.singletonList(v);
723 // the uriList at element 0 is the node in question and should not be included in the vertex chain lookup.
724 vertexChain = queryEngine.findParents(Arrays.copyOfRange(uriList, 1, uriList.length));
725 // inject v into start of vertexChain
726 vertexChain.add(0, v);
728 for (Vertex vertex : vertexChain) {
730 final Introspector vertexObj = this.getVertexProperties(vertex);
731 relatedVertices.put(vertexObj.getObjectId(), vertexObj);
732 } catch (AAIUnknownObjectException e) {
733 LOGGER.warn("Unable to get vertex properties, partial list of related vertices returned");
738 final Introspector vertexObj = this.getVertexProperties(v);
739 relatedVertices.put(vertexObj.getObjectId(), vertexObj);
740 } catch (AAIUnknownObjectException e) {
741 LOGGER.warn("Unable to get vertex properties, partial list of related vertices returned");
745 return relatedVertices;
749 * Given an uri, introspector object and loader object
750 * it will check if the obj is top level object if it is,
751 * it will return immediately returning the uri passed in
752 * If it isn't, it will go through, get the uriTemplate
753 * from the introspector object and get the count of "/"s
754 * and remove that part of the uri using substring
755 * and keep doing that until the current object is top level
756 * Also added the max depth just so worst case scenario
757 * Then keep adding aai-uri to the list include the aai-uri passed in
758 * Convert that list into an array and return it
765 * /cloud-infrastructure/cloud-regions/cloud-region/cloud-owner/cloud-region-id/tenants/tenant/tenant1/vservers/vserver/v1
767 * Given the uriTemplate vserver -> /vservers/vserver/{vserver-id}
768 * it converts to /vservers/vserver
770 * lastIndexOf /vservers/vserver in
771 * /cloud-infrastructure/cloud-regions/cloud-region/cloud-owner/cloud-region-id/tenants/tenant/tenant1/vservers/vserver/v1
776 * Use substring to get the string from 0 to that lastIndexOf
777 * aai-uri -> /cloud-infrastructure/cloud-regions/cloud-region/cloud-owner/cloud-region-id/tenants/tenant/tenant1
779 * From this new aai-uri, generate a introspector from the URITOObject class
780 * and keep doing this until you
784 * @param aaiUri - aai-uri of the vertex representating the unique id of a given vertex
785 * @param obj - introspector object of the given starting vertex
786 * @param loader - Type of loader which will always be MoxyLoader to support model driven
787 * @return an array of strings which can be used to get the vertexes of parent and grand parents from a given vertex
788 * @throws UnsupportedEncodingException
789 * @throws AAIException
791 String[] convertIntrospectorToUriList(String aaiUri, Introspector obj, Loader loader)
792 throws UnsupportedEncodingException, AAIException {
794 List<String> uriList = new ArrayList<>();
796 String truncatedUri = aaiUri;
797 int depth = AAIProperties.MAXIMUM_DEPTH;
798 uriList.add(truncatedUri);
800 while (depth >= 0 && !obj.isTopLevel()) {
801 template = obj.getMetadata(ObjectMetadata.URI_TEMPLATE);
803 if (template == null) {
804 LOGGER.warn("Unable to find the uriTemplate for the object {}", obj.getDbName());
808 int templateCount = StringUtils.countMatches(template, "/");
809 int truncatedUriCount = StringUtils.countMatches(truncatedUri, "/");
811 if (templateCount > truncatedUriCount) {
812 LOGGER.warn("Template uri {} contains more slashes than truncatedUri {}", template, truncatedUri);
816 int cutIndex = StringUtils.ordinalIndexOf(truncatedUri, "/", truncatedUriCount - templateCount + 1);
817 truncatedUri = StringUtils.substring(truncatedUri, 0, cutIndex);
818 uriList.add(truncatedUri);
819 obj = new URIToObject(loader, UriBuilder.fromPath(truncatedUri).build()).getEntity();
823 return uriList.toArray(new String[0]);
827 * Handle relationships.
830 * @param vertex the vertex
831 * @throws SecurityException the security exception
832 * @throws IllegalArgumentException the illegal argument exception
833 * @throws UnsupportedEncodingException the unsupported encoding exception
834 * @throws AAIException the AAI exception
837 * Handles the explicit relationships defined for an obj
839 private void handleRelationships(Introspector obj, Vertex vertex)
840 throws UnsupportedEncodingException, AAIException {
842 Introspector wrappedRl = obj.getWrappedValue("relationship-list");
843 processRelationshipList(wrappedRl, vertex);
848 * Process relationship list.
850 * @param wrapped the wrapped
852 * @throws UnsupportedEncodingException the unsupported encoding exception
853 * @throws AAIException the AAI exception
855 private void processRelationshipList(Introspector wrapped, Vertex v)
856 throws UnsupportedEncodingException, AAIException {
858 List<Object> relationships = wrapped.getValue("relationship");
859 String mainUri = getURIForVertex(v).toString();
860 String aNodeType = v.property(AAIProperties.NODE_TYPE).value().toString();
861 EdgeRuleQuery.Builder cousinQueryBuilder = new EdgeRuleQuery.Builder(aNodeType)
862 .edgeType(EdgeType.COUSIN)
863 .version(wrapped.getVersion());
864 EdgeRuleQuery.Builder treeQueryBuilder = new EdgeRuleQuery.Builder(aNodeType)
865 .edgeType(EdgeType.TREE)
866 .version(wrapped.getVersion());
868 EdgeIngestor edgeIngestor = SpringContextAware.getBean(EdgeIngestor.class);
870 Set<Pair<String, String>> cousinUriAndLabels = new LinkedHashSet<>();
871 for (Object relationship : relationships) {
874 Introspector wrappedRel = IntrospectorFactory.newInstance(this.introspectionType, relationship);
875 String relUri = urlToUri(new RelationshipToURI(loader, wrappedRel).getUri().toString());
877 if (relUri.startsWith("/vnf/")) {
878 QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(wrappedRel);
879 List<Vertex> results = parser.getQueryBuilder().toList();
880 if (results.isEmpty()) {
881 final AAIException ex = new AAIException(AAI_6129,
882 String.format("Node of type %s. Could not find object at: %s", parser.getResultType(), parser.getUri()));
883 ex.getTemplateVars().add(parser.getResultType());
884 ex.getTemplateVars().add(parser.getUri().toString());
887 // still an issue if there's more than one
888 if (results.get(0).property(AAIProperties.AAI_URI).isPresent()) {
889 relUri = results.get(0).value(AAIProperties.AAI_URI);
891 LOGGER.warn("Not processing the vertex {} because its missing required property aai-uri", results.get(0).id());
897 if (wrappedRel.getValue(RELATIONSHIP_LABEL) != null) {
898 label = wrappedRel.getValue(RELATIONSHIP_LABEL);
900 URIToObject uriToObject = new URIToObject(loader, URI.create(relUri));
901 String bNodeType = uriToObject.getEntityName();
902 EdgeRuleQuery ruleQuery = cousinQueryBuilder.to(bNodeType).build();
903 if (!edgeIngestor.hasRule(ruleQuery)) {
904 EdgeRuleQuery treeQuery = treeQueryBuilder.to(bNodeType).build();
905 if (edgeIngestor.hasRule(treeQuery)) {
906 throw new AAIException(AAI_6145); //attempted to create cousin edge for a parent-child edge rule
908 throw new AAIException("AAI_6120", String.format(
909 "No EdgeRule found for passed nodeTypes: %s, %s.",
910 aNodeType, bNodeType));
913 final List<EdgeRule> rules = new ArrayList<>(edgeIngestor.getRules(ruleQuery).values());
914 if (rules.size() == 1) {
915 label = rules.get(0).getLabel();
917 Optional<EdgeRule> defaultRule = rules.stream().filter(EdgeRule::isDefault).findFirst();
918 if (defaultRule.isPresent()) {
919 label = defaultRule.get().getLabel();
921 throw new AAIException(AAI_6145);
924 } catch (EdgeRuleNotFoundException ea) {
925 throw new AAIException(AAI_6145, ea);
929 cousinUriAndLabels.add(Pair.with(relUri, label));
932 List<Path> paths = this.engine.getQueryEngine().findCousinsAsPath(v);
933 Set<Path> toRemove = new HashSet<>();
936 // for each path 3 things can happen:
937 // 1. The edge rule that created it is not in this version no action is to be taken on that edge
938 // 2. The edge rule exits in this version it's included in the request the edge is left alone
939 // 3. The edge rule exits in this version and is not included in the request it is marked for removal
940 for (Path path : paths) {
941 if (path.size() < 3) {
946 // v ----related-to--> otherV
947 // In the above case,
948 // path objects get(0) returns vertex v
949 // path objects.get(1) returns edge related-to
950 // path objects.get(2) returns vertex otherV
951 Vertex otherV = path.get(2);
954 if (otherV.property(AAIProperties.AAI_URI).isPresent()) {
955 bUri = otherV.value(AAIProperties.AAI_URI);
959 String edgeLabel = path.<Edge>get(1).label();
961 Pair<String, String> key = Pair.with(bUri, edgeLabel);
962 if (cousinUriAndLabels.contains(key)) {
963 cousinUriAndLabels.remove(key);
966 if (otherV.property(AAIProperties.NODE_TYPE).isPresent()) {
967 bNodeType = otherV.property(AAIProperties.NODE_TYPE).value().toString();
971 EdgeRuleQuery ruleQuery = cousinQueryBuilder.to(bNodeType).label(edgeLabel).build();
972 if (edgeIngestor.hasRule(ruleQuery)) {
979 Set<Pair<Vertex, String>> toBeCreated = new HashSet<>();
980 for (Pair<String, String> cousinUriAndLabel : cousinUriAndLabels) {
983 String label = cousinUriAndLabel.getValue1();
984 String cousinUri = cousinUriAndLabel.getValue0();
985 QueryParser parser = engine.getQueryBuilder().createQueryFromURI(URI.create(cousinUri));
987 List<Vertex> results = parser.getQueryBuilder().toList();
988 if (results.isEmpty()) {
989 final AAIException ex = new AAIException(AAI_6129,
990 "Node of type " + parser.getResultType() + ". Could not find object at: " + parser.getUri());
991 ex.getTemplateVars().add(parser.getResultType());
992 ex.getTemplateVars().add(parser.getUri().toString());
995 // still an issue if there's more than one
996 cousinVertex = results.get(0);
999 if (cousinVertex != null) {
1000 String vType = (String) v.property(AAIProperties.NODE_TYPE).value();
1001 String cousinType = (String) cousinVertex.property(AAIProperties.NODE_TYPE).value();
1002 EdgeRuleQuery.Builder baseQ = new EdgeRuleQuery.Builder(vType, cousinType).label(label);
1004 if (!edgeRules.hasRule(baseQ.build())) {
1005 throw new AAIException("AAI_6120", String.format(
1006 "No EdgeRule found for passed nodeTypes: %s, %s%s.",
1007 aNodeType, cousinType, label != null ? (" with label " + label) : ""));
1008 } else if (edgeRules.hasRule(baseQ.edgeType(EdgeType.TREE).build())
1009 && !edgeRules.hasRule(baseQ.edgeType(EdgeType.COUSIN).build())) {
1010 throw new AAIException(AAI_6145);
1013 e = this.getEdgeBetween(EdgeType.COUSIN, v, cousinVertex, label);
1016 toBeCreated.add(Pair.with(cousinVertex, label));
1021 for (Path path : toRemove) {
1022 if(isDeltaEventsEnabled) {
1023 deltaForEdge(mainUri, path.get(1), DeltaAction.DELETE_REL, DeltaAction.UPDATE);
1025 this.updatedVertexes.putIfAbsent(v, false);
1026 this.edgeVertexes.add(path.get(2));
1027 path.<Edge>get(1).remove();
1030 for (Pair<Vertex, String> create : toBeCreated) {
1032 Edge e = edgeSer.addEdge(this.engine.asAdmin().getTraversalSource(), v, create.getValue0(), create.getValue1());
1033 if (isDeltaEventsEnabled) {
1034 deltaForEdge(mainUri, e, DeltaAction.CREATE_REL, DeltaAction.UPDATE);
1036 this.updatedVertexes.putIfAbsent(v, false);
1037 this.edgeVertexes.add(create.getValue0());
1038 } catch (NoEdgeRuleFoundException ex) {
1039 throw new AAIException(AAI_6129, ex);
1045 private void deltaForEdge(String mainUri, Edge edge, DeltaAction edgeAction, DeltaAction mainAction) {
1046 RelationshipDelta relationshipDelta = new RelationshipDelta(
1048 edge.inVertex().property(AAIProperties.AAI_UUID).value().toString(),
1049 edge.outVertex().property(AAIProperties.AAI_UUID).value().toString(),
1050 edge.inVertex().property(AAIProperties.AAI_URI).value().toString(),
1051 edge.outVertex().property(AAIProperties.AAI_URI).value().toString(),
1053 edge.properties().forEachRemaining(p -> relationshipDelta.addProp(p.key(), p.value().toString()));
1054 addRelationshipDelta(mainUri, relationshipDelta, mainAction);
1058 * Write through defaults.
1061 * @param obj the obj
1062 * @throws AAIUnknownObjectException
1064 private void writeThroughDefaults(Vertex v, Introspector obj) throws AAIUnknownObjectException {
1065 Introspector latest = this.latestLoader.introspectorFromName(obj.getName());
1066 if (latest != null) {
1067 Set<String> required = latest.getRequiredProperties();
1069 for (String field : required) {
1070 String defaultValue = latest.getPropertyMetadata(field).get(PropertyMetadata.DEFAULT_VALUE);
1071 if (defaultValue != null) {
1072 Object vertexProp = v.property(field).orElse(null);
1073 if (vertexProp == null) {
1074 v.property(field, defaultValue);
1083 * Reflect dependent vertex.
1086 * @param dependentObj the dependent obj
1087 * @return the vertex
1088 * @throws IllegalArgumentException the illegal argument exception
1089 * @throws SecurityException the security exception
1090 * @throws AAIException the AAI exception
1091 * @throws UnsupportedEncodingException the unsupported encoding exception
1092 * @throws AAIUnknownObjectException
1094 private Vertex reflectDependentVertex(Vertex v, Introspector dependentObj, String requestContext)
1095 throws AAIException, UnsupportedEncodingException {
1097 QueryBuilder<Vertex> query = this.engine.getQueryBuilder(v);
1098 query.createEdgeTraversal(EdgeType.TREE, v, dependentObj);
1099 query.createKeyQuery(dependentObj);
1101 List<Vertex> items = query.toList();
1103 Vertex dependentVertex;
1104 if (items.size() == 1) {
1105 dependentVertex = items.get(0);
1106 this.verifyResourceVersion("update", dependentObj.getDbName(),
1107 dependentVertex.<String>property(AAIProperties.RESOURCE_VERSION).orElse(null),
1108 dependentObj.getValue(AAIProperties.RESOURCE_VERSION), dependentObj.getURI());
1110 this.verifyResourceVersion("create", dependentObj.getDbName(), "",
1111 dependentObj.getValue(AAIProperties.RESOURCE_VERSION), dependentObj.getURI());
1112 dependentVertex = createNewVertex(dependentObj);
1115 return reflectDependentVertex(v, dependentVertex, dependentObj, requestContext);
1120 * Reflect dependent vertex.
1122 * @param parent the parent
1123 * @param child the child
1124 * @param obj the obj
1125 * @return the vertex
1126 * @throws IllegalArgumentException the illegal argument exception
1127 * @throws SecurityException the security exception
1128 * @throws AAIException the AAI exception
1129 * @throws UnsupportedEncodingException the unsupported encoding exception
1130 * @throws AAIUnknownObjectException
1132 private Vertex reflectDependentVertex(Vertex parent, Vertex child, Introspector obj, String requestContext)
1133 throws AAIException, UnsupportedEncodingException {
1135 String parentUri = parent.<String>property(AAIProperties.AAI_URI).orElse(null);
1136 if (parentUri != null) {
1139 addUriIfNeeded(child, parentUri + uri);
1141 processObject(obj, child, requestContext);
1144 e = this.getEdgeBetween(EdgeType.TREE, parent, child, null);
1147 String canBeLinked = obj.getMetadata(ObjectMetadata.CAN_BE_LINKED);
1148 if (canBeLinked != null && canBeLinked.equals("true")) {
1149 Loader ldrForCntxt = SpringContextAware.getBean(LoaderFactory.class)
1150 .createLoaderForVersion(introspectionType, getVerForContext(requestContext));
1151 boolean isFirst = !this.engine.getQueryBuilder(ldrForCntxt, parent)
1152 .createEdgeTraversal(EdgeType.TREE, parent, obj).hasNext();
1154 child.property(AAIProperties.LINKED, true);
1157 e = edgeSer.addTreeEdge(this.engine.asAdmin().getTraversalSource(), parent, child);
1158 if(isDeltaEventsEnabled) {
1159 deltaForEdge(child.property(AAIProperties.AAI_URI).value().toString(), e, DeltaAction.CREATE_REL, DeltaAction.CREATE);
1166 private SchemaVersion getVerForContext(String requestContext) {
1167 Pattern pattern = Pattern.compile("v[0-9]+");
1168 Matcher m = pattern.matcher(requestContext);
1170 return this.version;
1172 return new SchemaVersion(requestContext);
1179 * @param vertices the vertices
1180 * @param obj the obj
1181 * @param depth the depth
1182 * @param cleanUp the clean up
1183 * @return the introspector
1184 * @throws AAIException the AAI exception
1185 * @throws IllegalArgumentException the illegal argument exception
1186 * @throws SecurityException the security exception
1187 * @throws UnsupportedEncodingException the unsupported encoding exception
1188 * @throws AAIUnknownObjectException
1189 * @throws URISyntaxException
1191 public Introspector dbToObject(List<Vertex> vertices, final Introspector obj, int depth, boolean nodeOnly,
1192 String cleanUp, boolean isSkipRelatedTo) throws UnsupportedEncodingException, AAIException {
1193 final int internalDepth;
1194 if (depth == Integer.MAX_VALUE) {
1195 internalDepth = depth--;
1197 internalDepth = depth;
1199 StopWatch.conditionalStart();
1200 if (vertices.size() > 1 && !obj.isContainer()) {
1201 dbTimeMsecs += StopWatch.stopIfStarted();
1202 throw new AAIException("AAI_6136",
1203 "query object mismatch: this object cannot hold multiple items." + obj.getDbName());
1204 } else if (obj.isContainer()) {
1206 String listProperty = null;
1207 for (String property : obj.getProperties()) {
1208 if (obj.isListType(property) && obj.isComplexGenericType(property)) {
1209 listProperty = property;
1213 final String propertyName = listProperty;
1214 getList = obj.getValue(listProperty);
1217 * This is an experimental multithreading experiment
1220 ExecutorService pool = GetAllPool.getInstance().getPool();
1222 List<Future<Object>> futures = new ArrayList<>();
1224 for (Vertex v : vertices) {
1225 AaiCallable<Object> task = new AaiCallable<Object>() {
1227 public Object process() throws UnsupportedEncodingException, AAIException {
1228 Set<Vertex> seen = new HashSet<>();
1229 Introspector childObject;
1230 childObject = obj.newIntrospectorInstanceOfNestedProperty(propertyName);
1231 dbToObject(childObject, v, seen, internalDepth, nodeOnly, cleanUp, isSkipRelatedTo);
1232 return childObject.getUnderlyingObject();
1235 futures.add(pool.submit(task));
1238 for (Future<Object> future : futures) {
1240 getList.add(future.get());
1241 } catch (ExecutionException | InterruptedException e) {
1242 dbTimeMsecs += StopWatch.stopIfStarted();
1243 throw new AAIException("AAI_4000", e);
1246 } else if (vertices.size() == 1) {
1247 Set<Vertex> seen = new HashSet<>();
1248 dbToObject(obj, vertices.get(0), seen, depth, nodeOnly, cleanUp, isSkipRelatedTo);
1253 dbTimeMsecs += StopWatch.stopIfStarted();
1260 * @param vertices the vertices
1261 * @param obj the obj
1262 * @param depth the depth
1263 * @param cleanUp the clean up
1264 * @return the introspector
1265 * @throws AAIException the AAI exception
1266 * @throws IllegalArgumentException the illegal argument exception
1267 * @throws SecurityException the security exception
1268 * @throws UnsupportedEncodingException the unsupported encoding exception
1269 * @throws AAIUnknownObjectException
1270 * @throws URISyntaxException
1272 public Introspector dbToObject(List<Vertex> vertices, final Introspector obj, int depth, boolean nodeOnly,
1273 String cleanUp) throws UnsupportedEncodingException, AAIException {
1274 return dbToObject(vertices, obj, depth, nodeOnly, cleanUp, false);
1280 * @param obj the obj
1282 * @param seen the seen
1283 * @param depth the depth
1284 * @param cleanUp the clean up
1285 * @return the introspector
1286 * @throws IllegalArgumentException the illegal argument exception
1287 * @throws SecurityException the security exception
1288 * @throws UnsupportedEncodingException the unsupported encoding exception
1289 * @throws AAIException the AAI exception
1290 * @throws AAIUnknownObjectException
1291 * @throws URISyntaxException
1293 private Introspector dbToObject(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly,
1294 String cleanUp) throws AAIException, UnsupportedEncodingException {
1295 return dbToObject(obj, v, seen, depth, nodeOnly, cleanUp, false);
1301 * @param obj the obj
1303 * @param seen the seen
1304 * @param depth the depth
1305 * @param cleanUp the clean up
1306 * @return the introspector
1307 * @throws IllegalArgumentException the illegal argument exception
1308 * @throws SecurityException the security exception
1309 * @throws UnsupportedEncodingException the unsupported encoding exception
1310 * @throws AAIException the AAI exception
1311 * @throws AAIUnknownObjectException
1312 * @throws URISyntaxException
1314 private Introspector dbToObject(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly,
1315 String cleanUp, boolean isSkipRelatedTo) throws AAIException, UnsupportedEncodingException {
1323 boolean modified = false;
1324 for (String property : obj.getProperties(PropertyPredicates.isVisible())) {
1325 List<Object> getList = null;
1327 if (!(obj.isComplexType(property) || obj.isListType(property))) {
1328 this.copySimpleProperty(property, obj, v);
1331 if (obj.isComplexType(property)) {
1332 /* container case */
1334 if (!property.equals("relationship-list") && depth >= 0) {
1335 Introspector argumentObject = obj.newIntrospectorInstanceOfProperty(property);
1336 Object result = dbToObject(argumentObject, v, seen, depth + 1, nodeOnly, cleanUp);
1337 if (result != null) {
1338 obj.setValue(property, argumentObject.getUnderlyingObject());
1341 } else if (property.equals("relationship-list") && !nodeOnly) {
1342 /* relationships need to be handled correctly */
1343 Introspector relationshipList = obj.newIntrospectorInstanceOfProperty(property);
1344 relationshipList = createRelationshipList(v, relationshipList, cleanUp, isSkipRelatedTo);
1345 if (relationshipList != null) {
1346 obj.setValue(property, relationshipList.getUnderlyingObject());
1351 } else if (obj.isListType(property)) {
1353 if (property.equals("any")) {
1356 String genericType = obj.getGenericTypeClass(property).getSimpleName();
1357 if (obj.isComplexGenericType(property) && depth >= 0) {
1358 final String childDbName = convertFromCamelCase(genericType);
1359 String vType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null);
1363 rule = edgeRules.getRule(
1364 new EdgeRuleQuery.Builder(vType, childDbName).edgeType(EdgeType.TREE).build());
1365 } catch (EdgeRuleNotFoundException e) {
1366 throw new NoEdgeRuleFoundException(e);
1367 } catch (AmbiguousRuleChoiceException e) {
1368 throw new MultipleEdgeRuleFoundException(e);
1370 if (!rule.getContains().equals(AAIDirection.NONE.toString())) {
1372 Direction ruleDirection = rule.getDirection();
1373 List<Vertex> verticesList = new ArrayList<>();
1374 v.vertices(ruleDirection, rule.getLabel()).forEachRemaining(vertex -> {
1375 if (vertex.property(AAIProperties.NODE_TYPE).orElse("").equals(childDbName)) {
1376 verticesList.add(vertex);
1379 if (!verticesList.isEmpty()) {
1380 getList = obj.getValue(property);
1383 for (Vertex childVertex : verticesList) {
1384 if (!seen.contains(childVertex)) {
1385 Introspector argumentObject = obj.newIntrospectorInstanceOfNestedProperty(property);
1388 dbToObject(argumentObject, childVertex, seen, depth, nodeOnly, cleanUp, isSkipRelatedTo);
1389 if (result != null) {
1390 getList.add(argumentObject.getUnderlyingObject());
1395 LOGGER.warn("Cycle found while serializing vertex id={}",
1396 childVertex.id().toString());
1399 if (processed == 0) {
1400 // vertices were all seen, reset the list
1403 if (processed > 0) {
1407 } else if (obj.isSimpleGenericType(property)) {
1408 List<Object> temp = this.engine.getListProperty(v, property);
1410 getList = (List<Object>) obj.getValue(property);
1411 getList.addAll(temp);
1419 // no changes were made to this obj, discard the instance
1423 this.enrichData(obj, v);
1428 public Introspector getVertexProperties(Vertex v) throws AAIException, UnsupportedEncodingException {
1429 String nodeType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null);
1430 if (nodeType == null) {
1431 throw new AAIException("AAI_6143");
1434 Introspector obj = this.latestLoader.introspectorFromName(nodeType);
1435 Set<Vertex> seen = new HashSet<>();
1437 StopWatch.conditionalStart();
1438 this.dbToObject(obj, v, seen, depth, true, FALSE);
1439 dbTimeMsecs += StopWatch.stopIfStarted();
1444 public Introspector getLatestVersionView(Vertex v) throws AAIException, UnsupportedEncodingException {
1445 return getLatestVersionView(v, AAIProperties.MAXIMUM_DEPTH);
1448 public Introspector getLatestVersionView(Vertex v, int depth) throws AAIException, UnsupportedEncodingException {
1449 String nodeType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null);
1450 if (nodeType == null) {
1451 throw new AAIException("AAI_6143");
1453 Introspector obj = this.latestLoader.introspectorFromName(nodeType);
1454 Set<Vertex> seen = new HashSet<>();
1455 StopWatch.conditionalStart();
1456 this.dbToObject(obj, v, seen, depth, false, FALSE);
1457 dbTimeMsecs += StopWatch.stopIfStarted();
1462 * Copy simple property.
1464 * @param property the property
1465 * @param obj the obj
1467 * @throws IllegalArgumentException the illegal argument exception
1468 * @throws SecurityException the security exception
1470 private void copySimpleProperty(String property, Introspector obj, Vertex v) {
1471 final Object temp = getProperty(obj, property, v);
1473 obj.setValue(property, temp);
1477 public Map<String, Object> convertVertexToHashMap(Introspector obj, Vertex v) {
1479 Set<String> simpleProperties = obj.getSimpleProperties(PropertyPredicates.isVisible());
1480 String[] simplePropsArray = new String[simpleProperties.size()];
1481 simplePropsArray = simpleProperties.toArray(simplePropsArray);
1483 Map<String, Object> simplePropsHashMap = new HashMap<>(simplePropsArray.length * 2);
1485 v.properties(simplePropsArray).forEachRemaining(vp -> simplePropsHashMap.put(vp.key(), vp.value()));
1487 return simplePropsHashMap;
1490 public Introspector dbToRelationshipObject(Vertex v, boolean isSkipRelatedTo) throws UnsupportedEncodingException, AAIException {
1491 Introspector relationshipList = this.latestLoader.introspectorFromName("relationship-list");
1492 relationshipList = createRelationshipList(v, relationshipList, FALSE, isSkipRelatedTo);
1493 return relationshipList;
1497 * Creates the relationship list.
1500 * @param obj the obj
1501 * @param cleanUp the clean up
1502 * @return the object
1503 * @throws IllegalArgumentException the illegal argument exception
1504 * @throws SecurityException the security exception
1505 * @throws UnsupportedEncodingException the unsupported encoding exception
1506 * @throws AAIException the AAI exception
1507 * @throws URISyntaxException
1509 private Introspector createRelationshipList(Vertex v, Introspector obj, String cleanUp)
1510 throws UnsupportedEncodingException, AAIException {
1511 // default boolean value for isSkipRelatedTo is false
1512 return createRelationshipList(v, obj, cleanUp, false);
1516 * Creates the relationship list.
1519 * @param obj the obj
1520 * @param cleanUp the clean up
1521 * @param isSkipRelatedTo to determine adding related-to-property in response
1522 * @return the object
1523 * @throws IllegalArgumentException the illegal argument exception
1524 * @throws SecurityException the security exception
1525 * @throws UnsupportedEncodingException the unsupported encoding exception
1526 * @throws AAIException the AAI exception
1527 * @throws URISyntaxException
1529 private Introspector createRelationshipList(Vertex v, Introspector obj, String cleanUp, boolean isSkipRelatedTo)
1530 throws UnsupportedEncodingException, AAIException {
1532 List<Object> relationshipObjList = obj.getValue(RELATIONSHIP);
1533 VertexProperty nodeTypeProperty = v.property(AAIProperties.NODE_TYPE);
1535 if (!nodeTypeProperty.isPresent()) {
1536 LOGGER.warn("Not processing the vertex {} because its missing required property aai-node-type", v.id());
1540 List<Path> paths = this.engine.getQueryEngine().findCousinsAsPath(v);
1542 String aNodeType = v.property(AAIProperties.NODE_TYPE).value().toString();
1544 EdgeIngestor edgeIngestor = SpringContextAware.getBean(EdgeIngestor.class);
1546 EdgeRuleQuery.Builder queryBuilder = new EdgeRuleQuery.Builder(aNodeType)
1547 .edgeType(EdgeType.COUSIN)
1548 .version(obj.getVersion());
1550 for (Path path : paths){
1551 if(path.size() < 3){
1556 // v ----related-to--> otherV
1557 // In the above case,
1558 // path objects get(0) returns vertex v
1559 // path objects.get(1) returns edge related-to
1560 // path objects.get(2) returns vertex otherV
1561 Edge edge = path.get(1);
1562 Vertex otherV= path.get(2);
1564 // TODO: Come back and revisit this code
1565 // Create a query based on the a nodetype and b nodetype
1566 // which is also a cousin edge and ensure the version
1567 // is used properly so for example in order to be backwards
1568 // compatible if we had allowed a edge between a and b
1569 // in a previous release and we decided to remove it from
1570 // the edge rules in the future we can display the edge
1571 // only for the older apis and the new apis if the edge rule
1572 // is removed will not be seen in the newer version of the API
1575 if (otherV.property(AAIProperties.NODE_TYPE).isPresent()) {
1576 bNodeType = otherV.value(AAIProperties.NODE_TYPE);
1581 String edgeLabel = edge.label();
1582 EdgeRuleQuery ruleQuery = queryBuilder.to(bNodeType).label(edgeLabel).build();
1584 if(!edgeIngestor.hasRule(ruleQuery)){
1585 LOGGER.debug( "Caught an edge rule not found for query {}", ruleQuery);
1589 Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty(RELATIONSHIP);
1590 Object result = processEdgeRelationship(relationshipObj, otherV, cleanUp, edgeLabel, isSkipRelatedTo);
1591 if (result != null) {
1592 relationshipObjList.add(result);
1597 if (relationshipObjList.isEmpty()) {
1605 * Process edge relationship.
1607 * @param relationshipObj the relationship obj
1608 * @param edgeLabel the edge's label
1609 * @param cleanUp the clean up
1610 * @return the object
1611 * @throws IllegalArgumentException the illegal argument exception
1612 * @throws SecurityException the security exception
1613 * @throws UnsupportedEncodingException the unsupported encoding exception
1614 * @throws AAIUnknownObjectException
1615 * @throws URISyntaxException
1617 private Object processEdgeRelationship(Introspector relationshipObj, Vertex cousin, String cleanUp,
1618 String edgeLabel, boolean isSkipRelatedTo) throws UnsupportedEncodingException, AAIUnknownObjectException {
1620 VertexProperty aaiUriProperty = cousin.property("aai-uri");
1622 if (!aaiUriProperty.isPresent()) {
1626 URI uri = UriBuilder.fromUri(aaiUriProperty.value().toString()).build();
1628 URIToRelationshipObject uriParser;
1629 Introspector result;
1631 uriParser = new URIToRelationshipObject(relationshipObj.getLoader(), uri, this.baseURL);
1632 result = uriParser.getResult();
1633 } catch (AAIException | URISyntaxException e) {
1634 LOGGER.error("Error while processing edge relationship in version " + relationshipObj.getVersion()
1635 + " (bad vertex ID=" + ": " + e.getMessage() + " " + LogFormatTools.getStackTop(e));
1639 VertexProperty cousinVertexNodeType = cousin.property(AAIProperties.NODE_TYPE);
1641 if (cousinVertexNodeType.isPresent()) {
1642 String cousinType = cousinVertexNodeType.value().toString();
1643 if (namedPropNodes.contains(cousinType) && !isSkipRelatedTo) {
1644 this.addRelatedToProperty(result, cousin, cousinType);
1648 if (edgeLabel != null && result.hasProperty(RELATIONSHIP_LABEL)) {
1649 result.setValue(RELATIONSHIP_LABEL, edgeLabel);
1652 return result.getUnderlyingObject();
1656 * Gets the URI for vertex.
1659 * @return the URI for vertex
1660 * @throws IllegalArgumentException the illegal argument exception
1661 * @throws SecurityException the security exception
1662 * @throws UnsupportedEncodingException the unsupported encoding exception
1663 * @throws AAIUnknownObjectException
1665 public URI getURIForVertex(Vertex v) throws UnsupportedEncodingException {
1667 return getURIForVertex(v, false);
1670 public URI getURIForVertex(Vertex v, boolean overwrite) {
1671 URI uri = UriBuilder.fromPath("/unknown-uri").build();
1673 String aaiUri = v.<String>property(AAIProperties.AAI_URI).orElse(null);
1675 if (aaiUri != null && !overwrite) {
1676 uri = UriBuilder.fromPath(aaiUri).build();
1683 public void addRelatedToProperty(Introspector relationship, Vertex cousinVertex, String cousinType)
1684 throws AAIUnknownObjectException {
1689 obj = this.loader.introspectorFromName(cousinType);
1690 } catch (AAIUnknownObjectException ex) {
1691 if (LOGGER.isTraceEnabled()) {
1692 LOGGER.trace("Encountered unknown object exception when trying to load nodetype of {} for vertex id {}",
1693 cousinType, cousinVertex.id());
1698 String nameProps = obj.getMetadata(ObjectMetadata.NAME_PROPS);
1699 List<Introspector> relatedToProperties = new ArrayList<>();
1701 if (nameProps != null) {
1702 String[] props = nameProps.split(",");
1703 for (String prop : props) {
1704 final Object temp = getProperty(obj, prop, cousinVertex);
1705 Introspector relatedTo = relationship.newIntrospectorInstanceOfNestedProperty("related-to-property");
1706 relatedTo.setValue("property-key", cousinType + "." + prop);
1707 relatedTo.setValue("property-value", temp);
1708 relatedToProperties.add(relatedTo);
1712 if (!relatedToProperties.isEmpty()) {
1713 List<Object> relatedToList = relationship.getValue("related-to-property");
1714 for (Introspector introspector : relatedToProperties) {
1715 relatedToList.add(introspector.getUnderlyingObject());
1721 private Object getProperty(Introspector obj, String prop, Vertex vertex) {
1723 final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(prop);
1724 String dbPropertyName = prop;
1726 if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) {
1727 dbPropertyName = metadata.get(PropertyMetadata.DB_ALIAS);
1730 return vertex.<Object>property(dbPropertyName).orElse(null);
1736 * @param relationship the relationship
1737 * @param inputVertex the input vertex
1738 * @return true, if successful
1739 * @throws UnsupportedEncodingException the unsupported encoding exception
1740 * @throws AAIException the AAI exception
1742 public Vertex createEdge(Introspector relationship, Vertex inputVertex)
1743 throws UnsupportedEncodingException, AAIException {
1745 Vertex relatedVertex;
1746 StopWatch.conditionalStart();
1747 QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(relationship);
1749 String label = null;
1750 if (relationship.hasProperty(RELATIONSHIP_LABEL)) {
1751 label = relationship.getValue(RELATIONSHIP_LABEL);
1754 List<Vertex> results = parser.getQueryBuilder().toList();
1755 if (results.isEmpty()) {
1756 dbTimeMsecs += StopWatch.stopIfStarted();
1757 AAIException e = new AAIException(AAI_6129,
1758 "Node of type " + parser.getResultType() + ". Could not find object at: " + parser.getUri());
1759 e.getTemplateVars().add(parser.getResultType());
1760 e.getTemplateVars().add(parser.getUri().toString());
1763 // still an issue if there's more than one
1764 relatedVertex = results.get(0);
1767 if (relatedVertex != null) {
1771 e = this.getEdgeBetween(EdgeType.COUSIN, inputVertex, relatedVertex, label);
1773 e = edgeSer.addEdge(this.engine.asAdmin().getTraversalSource(), inputVertex, relatedVertex, label);
1774 if(isDeltaEventsEnabled) {
1775 deltaForEdge(inputVertex.property(AAIProperties.AAI_URI).value().toString(), e, DeltaAction.CREATE_REL, DeltaAction.UPDATE);
1778 // attempted to link two vertexes already linked
1781 dbTimeMsecs += StopWatch.stopIfStarted();
1785 dbTimeMsecs += StopWatch.stopIfStarted();
1786 return relatedVertex;
1790 * Gets all the edges between of the type with the specified label.
1792 * @param aVertex the out vertex
1793 * @param bVertex the in vertex
1794 * @return the edges between
1796 private Edge getEdgeBetweenWithLabel(EdgeType type, Vertex aVertex, Vertex bVertex, EdgeRule edgeRule) {
1800 if (bVertex != null) {
1801 GraphTraversal<Vertex, Edge> findEdgesBetween = null;
1802 if (EdgeType.TREE.equals(type)) {
1803 GraphTraversal<Vertex, Vertex> findVertex = this.engine.asAdmin().getTraversalSource().V(bVertex);
1804 if (edgeRule.getDirection().equals(Direction.IN)) {
1805 findEdgesBetween = findVertex.outE(edgeRule.getLabel())
1806 .has(EdgeProperty.CONTAINS.toString(), edgeRule.getContains())
1807 .not(__.has(EdgeField.PRIVATE.toString(), true));
1809 findEdgesBetween = findVertex.inE(edgeRule.getLabel())
1810 .has(EdgeProperty.CONTAINS.toString(), edgeRule.getContains())
1811 .not(__.has(EdgeField.PRIVATE.toString(), true));
1813 findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(aVertex.id())).limit(1);
1815 findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE(edgeRule.getLabel());
1816 findEdgesBetween = findEdgesBetween.has(EdgeProperty.CONTAINS.toString(), "NONE")
1817 .not(__.has(EdgeField.PRIVATE.toString(), true));
1818 findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id())).limit(1);
1820 List<Edge> list = findEdgesBetween.toList();
1821 if (!list.isEmpty()) {
1822 result = list.get(0);
1830 * Gets all the edges string between of the type.
1832 * @param aVertex the out vertex
1833 * @param bVertex the in vertex
1834 * @return the edges between
1835 * @throws NoEdgeRuleFoundException
1837 private List<String> getEdgeLabelsBetween(EdgeType type, Vertex aVertex, Vertex bVertex) {
1839 List<String> result = new ArrayList<>();
1841 if (bVertex != null) {
1842 GraphTraversal<Vertex, Edge> findEdgesBetween = null;
1843 findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE();
1844 if (EdgeType.TREE.equals(type)) {
1845 findEdgesBetween = findEdgesBetween.not(__.or(__.has(EdgeProperty.CONTAINS.toString(), "NONE"),
1846 __.has(EdgeField.PRIVATE.toString(), true)));
1848 findEdgesBetween = findEdgesBetween.has(EdgeProperty.CONTAINS.toString(), "NONE")
1849 .not(__.has(EdgeField.PRIVATE.toString(), true));
1851 findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id()));
1852 result = findEdgesBetween.label().toList();
1858 * Gets all the edges between the vertexes with the label and type.
1860 * @param aVertex the out vertex
1861 * @param bVertex the in vertex
1863 * @return the edges between
1864 * @throws AAIException the AAI exception
1866 private Edge getEdgesBetween(EdgeType type, Vertex aVertex, Vertex bVertex, String label) throws AAIException {
1870 if (bVertex != null) {
1871 String aType = aVertex.<String>property(AAIProperties.NODE_TYPE).value();
1872 String bType = bVertex.<String>property(AAIProperties.NODE_TYPE).value();
1873 EdgeRuleQuery q = new EdgeRuleQuery.Builder(aType, bType).edgeType(type).label(label).build();
1876 rule = edgeRules.getRule(q);
1877 } catch (EdgeRuleNotFoundException e) {
1878 throw new NoEdgeRuleFoundException(e);
1879 } catch (AmbiguousRuleChoiceException e) {
1880 throw new MultipleEdgeRuleFoundException(e);
1882 edge = this.getEdgeBetweenWithLabel(type, aVertex, bVertex, rule);
1889 * Gets the edge between with the label and edge type.
1891 * @param aVertex the out vertex
1892 * @param bVertex the in vertex
1894 * @return the edge between
1895 * @throws AAIException the AAI exception
1896 * @throws NoEdgeRuleFoundException
1898 public Edge getEdgeBetween(EdgeType type, Vertex aVertex, Vertex bVertex, String label) throws AAIException {
1900 StopWatch.conditionalStart();
1901 if (bVertex != null) {
1903 Edge edge = this.getEdgesBetween(type, aVertex, bVertex, label);
1905 dbTimeMsecs += StopWatch.stopIfStarted();
1910 dbTimeMsecs += StopWatch.stopIfStarted();
1914 public Edge getEdgeBetween(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException {
1915 return this.getEdgeBetween(type, aVertex, bVertex, null);
1921 * @param relationship the relationship
1922 * @param inputVertex the input vertex
1923 * @return true, if successful
1924 * @throws UnsupportedEncodingException the unsupported encoding exception
1925 * @throws AAIException the AAI exception
1927 public Optional<Vertex> deleteEdge(Introspector relationship, Vertex inputVertex)
1928 throws UnsupportedEncodingException, AAIException {
1930 Vertex relatedVertex;
1931 StopWatch.conditionalStart();
1932 QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(relationship);
1934 List<Vertex> results = parser.getQueryBuilder().toList();
1936 String label = null;
1937 if (relationship.hasProperty(RELATIONSHIP_LABEL)) {
1938 label = relationship.getValue(RELATIONSHIP_LABEL);
1941 if (results.isEmpty()) {
1942 dbTimeMsecs += StopWatch.stopIfStarted();
1943 return Optional.empty();
1946 relatedVertex = results.get(0);
1949 edge = this.getEdgeBetween(EdgeType.COUSIN, inputVertex, relatedVertex, label);
1950 } catch (NoEdgeRuleFoundException e) {
1951 dbTimeMsecs += StopWatch.stopIfStarted();
1952 throw new AAIException(AAI_6129, e);
1955 if(isDeltaEventsEnabled) {
1956 String mainUri = inputVertex.property(AAIProperties.AAI_URI).value().toString();
1957 deltaForEdge(mainUri, edge, DeltaAction.DELETE_REL, DeltaAction.UPDATE);
1960 dbTimeMsecs += StopWatch.stopIfStarted();
1961 return Optional.of(relatedVertex);
1963 dbTimeMsecs += StopWatch.stopIfStarted();
1964 return Optional.empty();
1970 * Delete with traversal.
1972 * @param startVertex the start vertex
1974 public void deleteWithTraversal(Vertex startVertex) {
1975 StopWatch.conditionalStart();
1976 List<Vertex> results = this.engine.getQueryEngine().findDeletable(startVertex);
1977 this.delete(results);
1981 * Removes the list of vertexes from the graph
1983 * Current the vertex label will just be vertex but
1984 * in the future the aai-node-type property will be replaced
1985 * by using the vertex label as when retrieving an vertex
1986 * and retrieving an single property on an vertex will pre-fetch
1987 * all the properties of that vertex and this is due to the following property
1990 * query.fast-property=true
1993 * JanusGraph doesn't provide the capability to override that
1994 * at a transaction level and there is a plan to move to vertex label
1995 * so it is best to utilize this for now and when the change is applied
1997 * @param vertices - list of vertices to delete from the graph
1999 void delete(List<Vertex> vertices) {
2000 StopWatch.conditionalStart();
2002 for (Vertex v : vertices) {
2003 LOGGER.debug("Removing vertex {} with label {}", v.id(), v.label());
2004 if(isDeltaEventsEnabled) {
2005 deltaForVertexDelete(v);
2007 //add the cousin vertexes of v to have their resource-version updated and notified on.
2008 v.edges(Direction.BOTH)
2009 .forEachRemaining(e -> {
2010 if (e.property(EdgeProperty.CONTAINS.toString()).isPresent()
2011 && AAIDirection.NONE.toString().equals(e.<String>value(EdgeProperty.CONTAINS.toString()))) {
2012 e.bothVertices().forEachRemaining(cousinV -> {
2013 if (!v.equals(cousinV)) {
2014 edgeVertexes.add(cousinV);
2020 //if somewhere along the way v was added to the sets tracking the what is to be updated/notified on
2021 // it should be removed from them as v is to be deleted
2022 edgeVertexes.remove(v);
2023 updatedVertexes.remove(v);
2027 dbTimeMsecs += StopWatch.stopIfStarted();
2030 private void deltaForVertexDelete(Vertex v) {
2031 String aaiUri = v.property(AAIProperties.AAI_URI).value().toString();
2032 v.keys().forEach(k -> {
2033 List<Object> list = new ArrayList<>();
2034 v.properties(k).forEachRemaining(vp -> list.add(vp.value()));
2035 if (list.size() == 1) {
2036 addPropDelta(aaiUri, k, PropertyDeltaFactory.getDelta(DeltaAction.DELETE, list.get(0)), DeltaAction.DELETE);
2038 addPropDelta(aaiUri, k, PropertyDeltaFactory.getDelta(DeltaAction.DELETE, list), DeltaAction.DELETE);
2042 v.edges(Direction.BOTH).forEachRemaining(e -> deltaForEdge(aaiUri, e, DeltaAction.DELETE, DeltaAction.DELETE));
2049 * @param resourceVersion the resource version
2050 * @throws IllegalArgumentException the illegal argument exception
2051 * @throws AAIException the AAI exception
2052 * @throws InterruptedException the interrupted exception
2054 public void delete(Vertex v, List<Vertex> deletableVertices, String resourceVersion, boolean enableResourceVersion)
2055 throws IllegalArgumentException, AAIException {
2057 boolean result = verifyDeleteSemantics(v, resourceVersion, enableResourceVersion);
2059 * The reason why I want to call PreventDeleteSemantics second time is to catch the prevent-deletes in a chain
2060 * These are far-fewer than seeing a prevent-delete on the vertex to be deleted
2061 * So its better to make these in 2 steps
2063 if (result && !deletableVertices.isEmpty()) {
2064 result = verifyPreventDeleteSemantics(deletableVertices);
2069 deleteWithTraversal(v);
2070 } catch (IllegalStateException e) {
2071 throw new AAIException("AAI_6110", e);
2081 * @param resourceVersion the resource version
2082 * @throws IllegalArgumentException the illegal argument exception
2083 * @throws AAIException the AAI exception
2084 * @throws InterruptedException the interrupted exception
2086 public void delete(Vertex v, String resourceVersion, boolean enableResourceVersion)
2087 throws IllegalArgumentException, AAIException {
2089 boolean result = verifyDeleteSemantics(v, resourceVersion, enableResourceVersion);
2094 deleteWithTraversal(v);
2095 } catch (IllegalStateException e) {
2096 throw new AAIException("AAI_6110", e);
2103 * Verify delete semantics.
2105 * @param vertex the vertex
2106 * @param resourceVersion the resource version
2107 * @return true, if successful
2108 * @throws AAIException the AAI exception
2110 private boolean verifyDeleteSemantics(Vertex vertex, String resourceVersion, boolean enableResourceVersion)
2111 throws AAIException {
2114 nodeType = vertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
2115 if (enableResourceVersion) {
2116 this.verifyResourceVersion("delete", nodeType,
2117 vertex.<String>property(AAIProperties.RESOURCE_VERSION).orElse(null), resourceVersion, nodeType);
2119 List<Vertex> vertices = new ArrayList<>();
2120 vertices.add(vertex);
2121 result = verifyPreventDeleteSemantics(vertices);
2127 * Verify Prevent delete semantics.
2129 * @param vertices the list of vertices
2130 * @return true, if successful
2131 * @throws AAIException the AAI exception
2133 private boolean verifyPreventDeleteSemantics(List<Vertex> vertices) throws AAIException {
2134 boolean result = true;
2135 String errorDetail = " unknown delete semantic found";
2136 String aaiExceptionCode = "";
2138 StopWatch.conditionalStart();
2140 * This takes in all the vertices in a cascade-delete-chain and checks if there is any edge with a
2141 * "prevent-delete" condition
2142 * If yes - that should prevent the deletion of the vertex
2143 * Dedup makes sure we dont capture the prevent-delete vertices twice
2144 * The prevent-delete vertices are stored so that the error message displays what prevents the delete
2147 List<Object> preventDeleteVertices = this.engine.asAdmin().getReadOnlyTraversalSource().V(vertices)
2148 .union(__.inE().has(EdgeProperty.PREVENT_DELETE.toString(), AAIDirection.IN.toString()).outV()
2149 .values(AAIProperties.NODE_TYPE),
2150 __.outE().has(EdgeProperty.PREVENT_DELETE.toString(), AAIDirection.OUT.toString()).inV()
2151 .values(AAIProperties.NODE_TYPE))
2154 dbTimeMsecs += StopWatch.stopIfStarted();
2155 if (!preventDeleteVertices.isEmpty()) {
2156 aaiExceptionCode = "AAI_6110";
2157 errorDetail = String.format(
2158 "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types %s",
2159 preventDeleteVertices);
2163 throw new AAIException(aaiExceptionCode, errorDetail);
2169 * Verify resource version.
2171 * @param action the action
2172 * @param nodeType the node type
2173 * @param currentResourceVersion the current resource version
2174 * @param resourceVersion the resource version
2175 * @param uri the uri
2176 * @return true, if successful
2177 * @throws AAIException the AAI exception
2179 public boolean verifyResourceVersion(String action, String nodeType, String currentResourceVersion,
2180 String resourceVersion, String uri) throws AAIException {
2181 String enabled = "";
2182 String errorDetail = "";
2183 String aaiExceptionCode = "";
2184 boolean isDeleteResourceVersionOk = true;
2185 if (currentResourceVersion == null) {
2186 currentResourceVersion = "";
2189 if (resourceVersion == null) {
2190 resourceVersion = "";
2193 enabled = AAIConfig.get(AAIConstants.AAI_RESVERSION_ENABLEFLAG);
2195 } catch (AAIException e) {
2196 ErrorLogHelper.logException(e);
2198 if (enabled.equals("true")) {
2199 if ("delete".equals(action)) {
2200 isDeleteResourceVersionOk = verifyResourceVersionForDelete(currentResourceVersion, resourceVersion);
2202 if ((!isDeleteResourceVersionOk)
2203 || ((!"delete".equals(action)) && (!currentResourceVersion.equals(resourceVersion)))) {
2204 if ("create".equals(action) && !resourceVersion.equals("")) {
2205 errorDetail = "resource-version passed for " + action + " of " + uri;
2206 aaiExceptionCode = "AAI_6135";
2207 } else if (resourceVersion.equals("")) {
2208 errorDetail = "resource-version not passed for " + action + " of " + uri;
2209 aaiExceptionCode = "AAI_6130";
2211 errorDetail = "resource-version MISMATCH for " + action + " of " + uri;
2212 aaiExceptionCode = "AAI_6131";
2215 throw new AAIException(aaiExceptionCode, errorDetail);
2223 * Verify resource version for delete.
2225 * @param currentResourceVersion the current resource version
2226 * @param resourceVersion the resource version
2227 * @return true, if successful or false if there is a mismatch
2229 private boolean verifyResourceVersionForDelete(String currentResourceVersion, String resourceVersion) {
2231 boolean isDeleteResourceVersionOk = true;
2232 String resourceVersionDisabledUuid = AAIConfig.get(AAIConstants.AAI_RESVERSION_DISABLED_UUID,
2233 AAIConstants.AAI_RESVERSION_DISABLED_UUID_DEFAULT);
2235 if ((!currentResourceVersion.equals(resourceVersion))
2236 && (!resourceVersion.equals(resourceVersionDisabledUuid))) {
2237 isDeleteResourceVersionOk = false;
2239 return isDeleteResourceVersionOk;
2243 * Convert from camel case.
2245 * @param name the name
2246 * @return the string
2248 private String convertFromCamelCase(String name) {
2250 result = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, name);
2252 NamingExceptions exceptions = NamingExceptions.getInstance();
2253 result = exceptions.getDBName(result);
2258 private boolean canModify(Introspector obj, String propName, String requestContext) {
2259 final String readOnly = obj.getPropertyMetadata(propName).get(PropertyMetadata.READ_ONLY);
2260 if (readOnly != null) {
2261 final String[] items = readOnly.split(",");
2262 for (String item : items) {
2263 if (requestContext.equals(item)) {
2271 private void executePreSideEffects(Introspector obj, Vertex self) throws AAIException {
2273 SideEffectRunner runner = new SideEffectRunner.Builder(this.engine, this).addSideEffect(DataCopy.class)
2274 .addSideEffect(PrivateEdge.class).addSideEffect(OwnerCheck.class).build();
2276 runner.execute(obj, self);
2279 private void executePostSideEffects(Introspector obj, Vertex self) throws AAIException {
2281 SideEffectRunner runner =
2282 new SideEffectRunner.Builder(this.engine, this).addSideEffect(DataLinkWriter.class).build();
2284 runner.execute(obj, self);
2287 private void enrichData(Introspector obj, Vertex self) throws AAIException {
2289 SideEffectRunner runner =
2290 new SideEffectRunner.Builder(this.engine, this).addSideEffect(DataLinkReader.class)
2291 .addSideEffect(OwnerCheck.class).build();
2293 runner.execute(obj, self);
2296 public double getDBTimeMsecs() {
2297 return (dbTimeMsecs);
2301 * Db to object With Filters
2302 * This is for a one-time run with Tenant Isloation to only filter relationships
2304 * @param obj the obj
2305 * @param v the vertex from the graph
2306 * @param depth the depth
2307 * @param nodeOnly specify if to exclude relationships or not
2308 * @param filterCousinNodes
2309 * @return the introspector
2310 * @throws AAIException the AAI exception
2311 * @throws IllegalAccessException the illegal access exception
2312 * @throws IllegalArgumentException the illegal argument exception
2313 * @throws InvocationTargetException the invocation target exception
2314 * @throws SecurityException the security exception
2315 * @throws InstantiationException the instantiation exception
2316 * @throws NoSuchMethodException the no such method exception
2317 * @throws UnsupportedEncodingException the unsupported encoding exception
2318 * @throws MalformedURLException the malformed URL exception
2319 * @throws AAIUnknownObjectException
2320 * @throws URISyntaxException
2322 public Introspector dbToObjectWithFilters(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly,
2323 List<String> filterCousinNodes, List<String> filterParentNodes)
2324 throws AAIException, UnsupportedEncodingException {
2325 return dbToObjectWithFilters(obj, v, seen, depth, nodeOnly,
2326 filterCousinNodes, filterParentNodes, false);
2330 * Db to object With Filters
2331 * This is for a one-time run with Tenant Isloation to only filter relationships
2332 * TODO: Chnage the original dbToObject to take filter parent/cousins
2334 * @param obj the obj
2335 * @param v the vertex from the graph
2336 * @param depth the depth
2337 * @param nodeOnly specify if to exclude relationships or not
2338 * @param filterCousinNodes
2339 * @param isSkipRelatedTo determine to incorporated related-to-property data
2340 * @return the introspector
2341 * @throws AAIException the AAI exception
2342 * @throws IllegalAccessException the illegal access exception
2343 * @throws IllegalArgumentException the illegal argument exception
2344 * @throws InvocationTargetException the invocation target exception
2345 * @throws SecurityException the security exception
2346 * @throws InstantiationException the instantiation exception
2347 * @throws NoSuchMethodException the no such method exception
2348 * @throws UnsupportedEncodingException the unsupported encoding exception
2349 * @throws MalformedURLException the malformed URL exception
2350 * @throws AAIUnknownObjectException
2351 * @throws URISyntaxException
2353 // TODO - See if you can merge the 2 dbToObjectWithFilters
2354 public Introspector dbToObjectWithFilters(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly,
2355 List<String> filterCousinNodes, List<String> filterParentNodes, boolean isSkipRelatedTo)
2356 throws AAIException, UnsupportedEncodingException {
2357 String cleanUp = FALSE;
2363 boolean modified = false;
2364 for (String property : obj.getProperties(PropertyPredicates.isVisible())) {
2365 List<Object> getList = null;
2367 if (!(obj.isComplexType(property) || obj.isListType(property))) {
2368 this.copySimpleProperty(property, obj, v);
2371 if (obj.isComplexType(property)) {
2372 /* container case */
2374 if (!property.equals("relationship-list") && depth >= 0) {
2375 Introspector argumentObject = obj.newIntrospectorInstanceOfProperty(property);
2376 Object result = dbToObjectWithFilters(argumentObject, v, seen, depth + 1, nodeOnly,
2377 filterCousinNodes, filterParentNodes, isSkipRelatedTo);
2378 if (result != null) {
2379 obj.setValue(property, argumentObject.getUnderlyingObject());
2382 } else if (property.equals("relationship-list") && !nodeOnly) {
2383 /* relationships need to be handled correctly */
2384 Introspector relationshipList = obj.newIntrospectorInstanceOfProperty(property);
2386 createFilteredRelationshipList(v, relationshipList, cleanUp, filterCousinNodes, isSkipRelatedTo);
2387 if (relationshipList != null) {
2388 obj.setValue(property, relationshipList.getUnderlyingObject());
2393 } else if (obj.isListType(property)) {
2395 if (property.equals("any")) {
2398 String genericType = obj.getGenericTypeClass(property).getSimpleName();
2399 if (obj.isComplexGenericType(property) && depth >= 0) {
2400 final String childDbName = convertFromCamelCase(genericType);
2401 String vType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null);
2404 boolean isThisParentRequired =
2405 filterParentNodes.parallelStream().anyMatch(childDbName::contains);
2407 EdgeRuleQuery q = new EdgeRuleQuery.Builder(vType, childDbName).edgeType(EdgeType.TREE).build();
2410 rule = edgeRules.getRule(q);
2411 } catch (EdgeRuleNotFoundException e) {
2412 throw new NoEdgeRuleFoundException(e);
2413 } catch (AmbiguousRuleChoiceException e) {
2414 throw new MultipleEdgeRuleFoundException(e);
2416 if (!rule.getContains().equals(AAIDirection.NONE.toString()) && isThisParentRequired) {
2417 Direction ruleDirection = rule.getDirection();
2418 List<Vertex> verticesList = new ArrayList<>();
2419 v.vertices(ruleDirection, rule.getLabel()).forEachRemaining(vertex -> {
2420 if (vertex.property(AAIProperties.NODE_TYPE).orElse("").equals(childDbName)) {
2421 verticesList.add(vertex);
2424 if (!verticesList.isEmpty()) {
2425 getList = obj.getValue(property);
2428 for (Vertex childVertex : verticesList) {
2429 if (!seen.contains(childVertex)) {
2430 Introspector argumentObject = obj.newIntrospectorInstanceOfNestedProperty(property);
2432 Object result = dbToObjectWithFilters(argumentObject, childVertex, seen, depth,
2433 nodeOnly, filterCousinNodes, filterParentNodes, isSkipRelatedTo);
2434 if (result != null) {
2435 getList.add(argumentObject.getUnderlyingObject());
2440 LOGGER.warn("Cycle found while serializing vertex id={}",
2441 childVertex.id().toString());
2444 if (processed == 0) {
2445 // vertices were all seen, reset the list
2448 if (processed > 0) {
2452 } else if (obj.isSimpleGenericType(property)) {
2453 List<Object> temp = this.engine.getListProperty(v, property);
2455 getList = obj.getValue(property);
2456 getList.addAll(temp);
2467 // no changes were made to this obj, discard the instance
2471 this.enrichData(obj, v);
2477 * Creates the relationship list with the filtered node types.
2480 * @param obj the obj
2481 * @param cleanUp the clean up
2482 * @return the object
2483 * @throws IllegalArgumentException the illegal argument exception
2484 * @throws SecurityException the security exception
2485 * @throws UnsupportedEncodingException the unsupported encoding exception
2486 * @throws AAIException the AAI exception
2488 private Introspector createFilteredRelationshipList(Vertex v, Introspector obj, String cleanUp,
2489 List<String> filterNodes, boolean isSkipRelatedTo) throws UnsupportedEncodingException, AAIException {
2490 List<Vertex> allCousins = this.engine.getQueryEngine().findCousinVertices(v);
2492 Iterator<Vertex> cousinVertices = allCousins.stream().filter(item -> {
2493 String node = (String) item.property(AAIProperties.NODE_TYPE).orElse("");
2494 return filterNodes.parallelStream().anyMatch(node::contains);
2497 List<Object> relationshipObjList = obj.getValue(RELATIONSHIP);
2499 List<Vertex> cousins = new ArrayList<>();
2500 cousinVertices.forEachRemaining(cousins::add);
2501 for (Vertex cousin : cousins) {
2503 Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty(RELATIONSHIP);
2504 Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp, null, isSkipRelatedTo);
2505 if (result != null) {
2506 relationshipObjList.add(result);
2511 if (relationshipObjList.isEmpty()) {
2518 public Set<Vertex> touchStandardVertexPropertiesForEdges() {
2519 this.edgeVertexes.forEach(v -> this.touchStandardVertexProperties(v, false));
2520 return this.edgeVertexes;
2523 public void addVertexToEdgeVertexes(Vertex vertex){
2524 this.edgeVertexes.add(vertex);
2527 private String urlToUri(String url) {
2528 if (url.startsWith("/")) {
2529 url = url.substring(1);
2532 if (url.endsWith("/")) {
2533 url = url.substring(0, url.length() - 1);
2536 // TODO - Check if this makes to do for model driven for base uri path
2537 url = url.replaceFirst("[a-z][a-z]*/v\\d+/", "");
2538 if (url.charAt(0) != '/') {