Update DBSerializer for relationships retrieving
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / serialization / db / DBSerializer.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 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
10  *
11  *    http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20 package org.onap.aai.serialization.db;
21
22
23 import com.att.eelf.configuration.EELFLogger;
24 import com.att.eelf.configuration.EELFManager;
25 import com.google.common.base.CaseFormat;
26 import com.google.common.collect.Multimap;
27 import org.apache.commons.collections.IteratorUtils;
28 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
29 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
30 import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
31 import org.apache.tinkerpop.gremlin.structure.*;
32 import org.janusgraph.core.SchemaViolationException;
33 import org.javatuples.Triplet;
34 import org.onap.aai.concurrent.AaiCallable;
35 import org.onap.aai.config.SpringContextAware;
36 import org.onap.aai.db.props.AAIProperties;
37 import org.onap.aai.edges.EdgeIngestor;
38 import org.onap.aai.edges.EdgeRule;
39 import org.onap.aai.edges.EdgeRuleQuery;
40 import org.onap.aai.edges.TypeAlphabetizer;
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.uri.URIParser;
56 import org.onap.aai.parsers.uri.URIToRelationshipObject;
57 import org.onap.aai.query.builder.QueryBuilder;
58 import org.onap.aai.schema.enums.ObjectMetadata;
59 import org.onap.aai.schema.enums.PropertyMetadata;
60 import org.onap.aai.serialization.db.exceptions.MultipleEdgeRuleFoundException;
61 import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
62 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
63 import org.onap.aai.serialization.engines.query.QueryEngine;
64 import org.onap.aai.serialization.tinkerpop.TreeBackedVertex;
65 import org.onap.aai.setup.SchemaVersion;
66 import org.onap.aai.setup.SchemaVersions;
67 import org.onap.aai.util.AAIConfig;
68 import org.onap.aai.util.AAIConstants;
69 import org.onap.aai.workarounds.NamingExceptions;
70 import org.springframework.context.ApplicationContext;
71
72 import javax.ws.rs.core.UriBuilder;
73 import java.io.UnsupportedEncodingException;
74 import java.lang.reflect.Array;
75 import java.lang.reflect.InvocationTargetException;
76 import java.net.MalformedURLException;
77 import java.net.URI;
78 import java.net.URISyntaxException;
79 import java.util.*;
80 import java.util.concurrent.ExecutionException;
81 import java.util.concurrent.ExecutorService;
82 import java.util.concurrent.Future;
83 import java.util.function.Function;
84 import java.util.regex.Matcher;
85 import java.util.regex.Pattern;
86 import java.util.stream.Collectors;
87
88 public class DBSerializer {
89
90     private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(DBSerializer.class);
91
92     private final TransactionalGraphEngine engine;
93     private final String sourceOfTruth;
94     private final ModelType introspectionType;
95     private final SchemaVersion version;
96     private final Loader latestLoader;
97     private EdgeSerializer edgeSer;
98     private EdgeIngestor edgeRules;
99     private final Loader loader;
100     private final String baseURL;
101     private double dbTimeMsecs = 0;
102     private long currentTimeMillis;
103
104     private SchemaVersions schemaVersions;
105     private Set<String> namedPropNodes;
106     /**
107      * Instantiates a new DB serializer.
108      *
109      * @param version the version
110      * @param engine the engine
111      * @param introspectionType the introspection type
112      * @param sourceOfTruth the source of truth
113      * @throws AAIException
114      */
115     public DBSerializer(SchemaVersion version, TransactionalGraphEngine engine, ModelType introspectionType, String sourceOfTruth) throws AAIException {
116         this.engine = engine;
117         this.sourceOfTruth = sourceOfTruth;
118         this.introspectionType = introspectionType;
119         this.schemaVersions = SpringContextAware.getBean(SchemaVersions.class);
120         SchemaVersion LATEST = schemaVersions.getDefaultVersion();
121         this.latestLoader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, LATEST);
122         this.version = version;
123         this.loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, version);
124         this.namedPropNodes = this.latestLoader.getNamedPropNodes();
125         this.baseURL = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE);
126         this.currentTimeMillis = System.currentTimeMillis();
127         initBeans();
128     }
129
130     private void initBeans() {
131         //TODO proper spring wiring, but that requires a lot of refactoring so for now we have this
132         ApplicationContext ctx = SpringContextAware.getApplicationContext();
133         EdgeIngestor ei = ctx.getBean(EdgeIngestor.class);
134         setEdgeIngestor(ei);
135         EdgeSerializer es = ctx.getBean(EdgeSerializer.class);
136         setEdgeSerializer(es);
137     }
138
139     private void backupESInit() {
140         setEdgeSerializer(new EdgeSerializer(this.edgeRules));
141     }
142
143     public void setEdgeSerializer(EdgeSerializer edgeSer) {
144         this.edgeSer = edgeSer;
145     }
146
147     public EdgeSerializer getEdgeSeriailizer() {
148         return this.edgeSer;
149     }
150
151     public void setEdgeIngestor(EdgeIngestor ei) {
152         this.edgeRules = ei;
153     }
154
155     public EdgeIngestor getEdgeIngestor() {
156         return this.edgeRules;
157     }
158
159     /**
160      * Touch standard vertex properties.
161      *
162      * @param v the v
163      * @param isNewVertex the is new vertex
164      */
165     public void touchStandardVertexProperties(Vertex v, boolean isNewVertex) {
166         String timeNowInSec = Long.toString(currentTimeMillis);
167
168         if (isNewVertex) {
169             v.property(AAIProperties.SOURCE_OF_TRUTH, this.sourceOfTruth);
170             v.property(AAIProperties.CREATED_TS, timeNowInSec);
171             v.property(AAIProperties.AAI_UUID, UUID.randomUUID().toString());
172         }
173         v.property(AAIProperties.RESOURCE_VERSION, timeNowInSec);
174         v.property(AAIProperties.LAST_MOD_TS, timeNowInSec);
175         v.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, this.sourceOfTruth);
176
177     }
178
179     private void touchStandardVertexProperties(String nodeType, Vertex v, boolean isNewVertex) {
180
181         v.property(AAIProperties.NODE_TYPE, nodeType);
182         touchStandardVertexProperties(v, isNewVertex);
183
184     }
185
186
187     /**
188      * Creates the new vertex.
189      *
190      * @param wrappedObject the wrapped object
191      * @return the vertex
192      * @throws UnsupportedEncodingException the unsupported encoding exception
193      * @throws AAIException                 the AAI exception
194      */
195     public Vertex createNewVertex(Introspector wrappedObject) {
196         Vertex v;
197         try {
198             StopWatch.conditionalStart();
199             v = this.engine.tx().addVertex();
200             touchStandardVertexProperties(wrappedObject.getDbName(), v, true);
201         } finally {
202             dbTimeMsecs += StopWatch.stopIfStarted();
203         }
204         return v;
205     }
206
207     /**
208      * Trim class name.
209      *
210      * @param className the class name
211      * @return the string
212      */
213     /*
214      * Removes the classpath from a class name
215      */
216     public String trimClassName(String className) {
217         String returnValue = "";
218
219         if (className.lastIndexOf('.') == -1) {
220             return className;
221         }
222         returnValue = className.substring(className.lastIndexOf('.') + 1, className.length());
223
224         return returnValue;
225     }
226
227     /**
228      * Serialize to db.
229      *
230      * @param obj        the obj
231      * @param v          the v
232      * @param uriQuery   the uri query
233      * @param identifier the identifier
234      * @throws SecurityException            the security exception
235      * @throws IllegalAccessException       the illegal access exception
236      * @throws IllegalArgumentException     the illegal argument exception
237      * @throws InvocationTargetException    the invocation target exception
238      * @throws InstantiationException       the instantiation exception
239      * @throws InterruptedException         the interrupted exception
240      * @throws NoSuchMethodException        the no such method exception
241      * @throws AAIException                 the AAI exception
242      * @throws UnsupportedEncodingException the unsupported encoding exception
243      * @throws AAIUnknownObjectException
244      */
245     public void serializeToDb(Introspector obj, Vertex v, QueryParser uriQuery, String identifier, String requestContext) throws AAIException, UnsupportedEncodingException {
246         StopWatch.conditionalStart();
247         try {
248             if (uriQuery.isDependent()) {
249                 //try to find the parent
250                 List<Vertex> vertices = uriQuery.getQueryBuilder().getParentQuery().toList();
251                 if (!vertices.isEmpty()) {
252                     Vertex parent = vertices.get(0);
253                     this.reflectDependentVertex(parent, v, obj, requestContext);
254                 } else {
255                     dbTimeMsecs += StopWatch.stopIfStarted();
256                     throw new AAIException("AAI_6114", "No parent Node of type " + uriQuery.getParentResultType() + " for " + identifier);
257                 }
258             } else {
259                 serializeSingleVertex(v, obj, requestContext);
260             }
261
262         } catch (SchemaViolationException e) {
263             dbTimeMsecs += StopWatch.stopIfStarted();
264             throw new AAIException("AAI_6117", e);
265         }
266         dbTimeMsecs += StopWatch.stopIfStarted();
267     }
268
269     public void serializeSingleVertex(Vertex v, Introspector obj, String requestContext) throws UnsupportedEncodingException, AAIException {
270         StopWatch.conditionalStart();
271         try {
272             boolean isTopLevel = obj.isTopLevel();
273             if (isTopLevel) {
274                 addUriIfNeeded(v, obj.getURI());
275             }
276
277             processObject(obj, v, requestContext);
278             if (!isTopLevel) {
279                 URI uri = this.getURIForVertex(v);
280                 URIParser parser = new URIParser(this.loader, uri);
281                 if (parser.validate()) {
282                     addUriIfNeeded(v, uri.toString());
283                 }
284             }
285         } catch (SchemaViolationException e) {
286             throw new AAIException("AAI_6117", e);
287         } finally {
288             dbTimeMsecs += StopWatch.stopIfStarted();
289         }
290     }
291
292     private void addUriIfNeeded(Vertex v, String uri) {
293         VertexProperty<String> uriProp = v.property(AAIProperties.AAI_URI);
294         if (!uriProp.isPresent() || (uriProp.isPresent() && !uriProp.value().equals(uri))) {
295             v.property(AAIProperties.AAI_URI, uri);
296         }
297     }
298
299     /**
300      * Process object.
301      *
302      * @param <T> the generic type
303      * @param obj the obj
304      * @param v   the v
305      * @return the list
306      * @throws IllegalAccessException       the illegal access exception
307      * @throws IllegalArgumentException     the illegal argument exception
308      * @throws InvocationTargetException    the invocation target exception
309      * @throws InstantiationException       the instantiation exception
310      * @throws NoSuchMethodException        the no such method exception
311      * @throws SecurityException            the security exception
312      * @throws AAIException                 the AAI exception
313      * @throws UnsupportedEncodingException the unsupported encoding exception
314      * @throws AAIUnknownObjectException
315      */
316     /*
317      * Helper method for reflectToDb
318      * Handles all the property setting
319      */
320     private <T> List<Vertex> processObject(Introspector obj, Vertex v, String requestContext) throws UnsupportedEncodingException, AAIException {
321         Set<String> properties = new LinkedHashSet<>(obj.getProperties());
322         properties.remove(AAIProperties.RESOURCE_VERSION);
323         List<Vertex> dependentVertexes = new ArrayList<>();
324         List<Vertex> processedVertexes = new ArrayList<>();
325         boolean isComplexType = false;
326         boolean isListType = false;
327         if (!obj.isContainer()) {
328             this.touchStandardVertexProperties(obj.getDbName(), v, false);
329         }
330         this.executePreSideEffects(obj, v);
331         for (String property : properties) {
332             Object value = null;
333             final String propertyType;
334             propertyType = obj.getType(property);
335             isComplexType = obj.isComplexType(property);
336             isListType = obj.isListType(property);
337             value = obj.getValue(property);
338
339             if (!(isComplexType || isListType)) {
340                 boolean canModify = this.canModify(obj, property, requestContext);
341
342                 if (canModify) {
343                     final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(property);
344                     String dbProperty = property;
345                     if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) {
346                         dbProperty = metadata.get(PropertyMetadata.DB_ALIAS);
347                     }
348                     if (metadata.containsKey(PropertyMetadata.DATA_LINK)) {
349                         //data linked properties are ephemeral
350                         //they are populated dynamically on GETs
351                         continue;
352                     }
353                     if (value != null) {
354                         if (!value.equals(v.property(dbProperty).orElse(null))) {
355                             if (propertyType.toLowerCase().contains(".long")) {
356                                 v.property(dbProperty, new Integer(((Long) value).toString()));
357                             } else {
358                                 v.property(dbProperty, value);
359                             }
360                         }
361                     } else {
362                         v.property(dbProperty).remove();
363                     }
364                 }
365             } else if (isListType) {
366                 List<Object> list = (List<Object>) value;
367                 if (obj.isComplexGenericType(property)) {
368                     if (list != null) {
369                         for (Object o : list) {
370                             Introspector child = IntrospectorFactory.newInstance(this.introspectionType, o);
371                             child.setURIChain(obj.getURI());
372                             processedVertexes.add(reflectDependentVertex(v, child, requestContext));
373                         }
374                     }
375                 } else {
376                     //simple list case
377                     engine.setListProperty(v, property, list);
378                 }
379             } else {
380                 //method.getReturnType() is not 'simple' then create a vertex and edge recursively returning an edge back to this method
381                 if (value != null) { //effectively ignore complex properties not included in the object we're processing
382                     if (value.getClass().isArray()) {
383
384                         int length = Array.getLength(value);
385                         for (int i = 0; i < length; i++) {
386                             Object arrayElement = Array.get(value, i);
387                             Introspector child = IntrospectorFactory.newInstance(this.introspectionType, arrayElement);
388                             child.setURIChain(obj.getURI());
389                             processedVertexes.add(reflectDependentVertex(v, child, requestContext));
390
391                         }
392                     } else if (!property.equals("relationship-list")) {
393                         // container case
394                         Introspector introspector = IntrospectorFactory.newInstance(this.introspectionType, value);
395                         if (introspector.isContainer()) {
396                             dependentVertexes.addAll(this.engine.getQueryEngine().findChildrenOfType(v, introspector.getChildDBName()));
397                             introspector.setURIChain(obj.getURI());
398
399                             processedVertexes.addAll(processObject(introspector, v, requestContext));
400
401                         } else {
402                             dependentVertexes.addAll(this.engine.getQueryEngine().findChildrenOfType(v, introspector.getDbName()));
403                             processedVertexes.add(reflectDependentVertex(v, introspector, requestContext));
404
405                         }
406                     } else if (property.equals("relationship-list")) {
407                         handleRelationships(obj, v);
408                     }
409                 }
410             }
411         }
412         this.writeThroughDefaults(v, obj);
413         /* handle those vertexes not touched */
414         for (Vertex toBeRemoved : processedVertexes) {
415             dependentVertexes.remove(toBeRemoved);
416         }
417         this.deleteItemsWithTraversal(dependentVertexes);
418
419         this.executePostSideEffects(obj, v);
420         return processedVertexes;
421     }
422
423     /**
424      * Handle relationships.
425      *
426      * @param obj    the obj
427      * @param vertex the vertex
428      * @throws SecurityException            the security exception
429      * @throws IllegalAccessException       the illegal access exception
430      * @throws IllegalArgumentException     the illegal argument exception
431      * @throws InvocationTargetException    the invocation target exception
432      * @throws UnsupportedEncodingException the unsupported encoding exception
433      * @throws AAIException                 the AAI exception
434      */
435     /*
436      * Handles the explicit relationships defined for an obj
437      */
438     private void handleRelationships(Introspector obj, Vertex vertex) throws UnsupportedEncodingException, AAIException {
439
440
441         Introspector wrappedRl = obj.getWrappedValue("relationship-list");
442         processRelationshipList(wrappedRl, vertex);
443
444
445     }
446
447
448     /**
449      * Process relationship list.
450      *
451      * @param wrapped the wrapped
452      * @param v       the v
453      * @throws UnsupportedEncodingException the unsupported encoding exception
454      * @throws AAIException                 the AAI exception
455      */
456     private void processRelationshipList(Introspector wrapped, Vertex v) throws UnsupportedEncodingException, AAIException {
457
458         List<Object> relationships = (List<Object>) wrapped.getValue("relationship");
459
460         List<Triplet<Vertex, Vertex, String>> addEdges = new ArrayList<>();
461         List<Edge> existingEdges = this.engine.getQueryEngine().findEdgesForVersion(v, wrapped.getLoader());
462
463         for (Object relationship : relationships) {
464             Edge e = null;
465             Vertex cousinVertex = null;
466             String label = null;
467             Introspector wrappedRel = IntrospectorFactory.newInstance(this.introspectionType, relationship);
468             QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(wrappedRel);
469
470             if (wrappedRel.hasProperty("relationship-label")) {
471                 label = wrappedRel.getValue("relationship-label");
472             }
473
474             List<Vertex> results = parser.getQueryBuilder().toList();
475             if (results.isEmpty()) {
476                 final AAIException ex = new AAIException("AAI_6129", "Node of type " + parser.getResultType() + ". Could not find object at: " + parser.getUri());
477                 ex.getTemplateVars().add(parser.getResultType());
478                 ex.getTemplateVars().add(parser.getUri().toString());
479                 throw ex;
480             } else {
481                 //still an issue if there's more than one
482                 cousinVertex = results.get(0);
483             }
484
485             if (cousinVertex != null) {
486                 String vType = (String) v.property(AAIProperties.NODE_TYPE).value();
487                 String cousinType = (String) cousinVertex.property(AAIProperties.NODE_TYPE).value();
488                 EdgeRuleQuery.Builder baseQ = new EdgeRuleQuery.Builder(vType, cousinType).label(label);
489
490
491                 if (!edgeRules.hasRule(baseQ.build())) {
492                     throw new AAIException("AAI_6120", "No EdgeRule found for passed nodeTypes: " + v.property(AAIProperties.NODE_TYPE).value().toString() + ", "
493                         + cousinVertex.property(AAIProperties.NODE_TYPE).value().toString() + (label != null ? (" with label " + label) : "") + ".");
494                 } else if (edgeRules.hasRule(baseQ.edgeType(EdgeType.TREE).build()) && !edgeRules.hasRule(baseQ.edgeType(EdgeType.COUSIN).build())) {
495                     throw new AAIException("AAI_6145");
496                 }
497
498                 e = this.getEdgeBetween(EdgeType.COUSIN, v, cousinVertex, label);
499
500                 if (e == null) {
501                     addEdges.add(new Triplet<>(v, cousinVertex, label));
502                 } else {
503                     existingEdges.remove(e);
504                 }
505             }
506         }
507
508         for (Edge edge : existingEdges) {
509             edge.remove();
510         }
511         for (Triplet<Vertex, Vertex, String> triplet : addEdges) {
512             try {
513                 edgeSer.addEdge(this.engine.asAdmin().getTraversalSource(), triplet.getValue0(), triplet.getValue1(), triplet.getValue2());
514             } catch (NoEdgeRuleFoundException e) {
515                 throw new AAIException("AAI_6129", e);
516             }
517         }
518
519     }
520
521     /**
522      * Write through defaults.
523      *
524      * @param v   the v
525      * @param obj the obj
526      * @throws AAIUnknownObjectException
527      */
528     private void writeThroughDefaults(Vertex v, Introspector obj) throws AAIUnknownObjectException {
529         Introspector latest = this.latestLoader.introspectorFromName(obj.getName());
530         if (latest != null) {
531             Set<String> required = latest.getRequiredProperties();
532
533             for (String field : required) {
534                 String defaultValue = null;
535                 Object vertexProp = null;
536                 defaultValue = latest.getPropertyMetadata(field).get(PropertyMetadata.DEFAULT_VALUE);
537                 if (defaultValue != null) {
538                     vertexProp = v.<Object>property(field).orElse(null);
539                     if (vertexProp == null) {
540                         v.property(field, defaultValue);
541                     }
542                 }
543             }
544         }
545
546     }
547
548
549     /**
550      * Reflect dependent vertex.
551      *
552      * @param v            the v
553      * @param dependentObj the dependent obj
554      * @return the vertex
555      * @throws IllegalAccessException       the illegal access exception
556      * @throws IllegalArgumentException     the illegal argument exception
557      * @throws InvocationTargetException    the invocation target exception
558      * @throws InstantiationException       the instantiation exception
559      * @throws NoSuchMethodException        the no such method exception
560      * @throws SecurityException            the security exception
561      * @throws AAIException                 the AAI exception
562      * @throws UnsupportedEncodingException the unsupported encoding exception
563      * @throws AAIUnknownObjectException
564      */
565     private Vertex reflectDependentVertex(Vertex v, Introspector dependentObj, String requestContext) throws AAIException, UnsupportedEncodingException {
566
567         //QueryParser p = this.engine.getQueryBuilder().createQueryFromURI(obj.getURI());
568         //List<Vertex> items = p.getQuery().toList();
569         QueryBuilder<Vertex> query = this.engine.getQueryBuilder(v);
570         query.createEdgeTraversal(EdgeType.TREE, v, dependentObj);
571         query.createKeyQuery(dependentObj);
572
573         List<Vertex> items = query.toList();
574
575         Vertex dependentVertex = null;
576         if (items.size() == 1) {
577             dependentVertex = items.get(0);
578             this.verifyResourceVersion("update", dependentObj.getDbName(), dependentVertex.<String>property(AAIProperties.RESOURCE_VERSION).orElse(null), (String) dependentObj.getValue(AAIProperties.RESOURCE_VERSION), (String) dependentObj.getURI());
579         } else {
580             this.verifyResourceVersion("create", dependentObj.getDbName(), "", (String) dependentObj.getValue(AAIProperties.RESOURCE_VERSION), (String) dependentObj.getURI());
581             dependentVertex = createNewVertex(dependentObj);
582         }
583
584         return reflectDependentVertex(v, dependentVertex, dependentObj, requestContext);
585
586     }
587
588     /**
589      * Reflect dependent vertex.
590      *
591      * @param parent the parent
592      * @param child  the child
593      * @param obj    the obj
594      * @return the vertex
595      * @throws IllegalAccessException       the illegal access exception
596      * @throws IllegalArgumentException     the illegal argument exception
597      * @throws InvocationTargetException    the invocation target exception
598      * @throws InstantiationException       the instantiation exception
599      * @throws NoSuchMethodException        the no such method exception
600      * @throws SecurityException            the security exception
601      * @throws AAIException                 the AAI exception
602      * @throws UnsupportedEncodingException the unsupported encoding exception
603      * @throws AAIUnknownObjectException
604      */
605     private Vertex reflectDependentVertex(Vertex parent, Vertex child, Introspector obj, String requestContext) throws AAIException, UnsupportedEncodingException {
606
607         String parentUri = parent.<String>property(AAIProperties.AAI_URI).orElse(null);
608         if (parentUri != null) {
609             String uri;
610             uri = obj.getURI();
611             addUriIfNeeded(child, parentUri + uri);
612         }
613         processObject(obj, child, requestContext);
614
615         Edge e;
616         e = this.getEdgeBetween(EdgeType.TREE, parent, child, null);
617
618         if (e == null) {
619             String canBeLinked = obj.getMetadata(ObjectMetadata.CAN_BE_LINKED);
620             if (canBeLinked != null && canBeLinked.equals("true")) {
621                 Loader ldrForCntxt = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectionType, getVerForContext(requestContext));
622                 boolean isFirst = !this.engine.getQueryBuilder(ldrForCntxt, parent).createEdgeTraversal(EdgeType.TREE, parent, obj).hasNext();
623                 if (isFirst) {
624                     child.property(AAIProperties.LINKED, true);
625                 }
626             }
627             edgeSer.addTreeEdge(this.engine.asAdmin().getTraversalSource(), parent, child);
628         }
629         return child;
630
631     }
632
633     private SchemaVersion getVerForContext(String requestContext) {
634         Pattern pattern = Pattern.compile("v[0-9]+");
635         Matcher m = pattern.matcher(requestContext);
636         if (!m.find()) {
637             return this.version;
638         } else {
639             return new SchemaVersion(requestContext);
640         }
641     }
642
643     /**
644      * Db to object.
645      *
646      * @param vertices the vertices
647      * @param obj      the obj
648      * @param depth    the depth
649      * @param cleanUp  the clean up
650      * @return the introspector
651      * @throws AAIException                 the AAI exception
652      * @throws IllegalAccessException       the illegal access exception
653      * @throws IllegalArgumentException     the illegal argument exception
654      * @throws InvocationTargetException    the invocation target exception
655      * @throws SecurityException            the security exception
656      * @throws InstantiationException       the instantiation exception
657      * @throws NoSuchMethodException        the no such method exception
658      * @throws UnsupportedEncodingException the unsupported encoding exception
659      * @throws MalformedURLException        the malformed URL exception
660      * @throws AAIUnknownObjectException
661      * @throws URISyntaxException
662      */
663     public Introspector dbToObject(List<Vertex> vertices, final Introspector obj, int depth, boolean nodeOnly, String cleanUp) throws UnsupportedEncodingException, AAIException {
664         final int internalDepth;
665         if (depth == Integer.MAX_VALUE) {
666             internalDepth = depth--;
667         } else {
668             internalDepth = depth;
669         }
670         StopWatch.conditionalStart();
671         if (vertices.size() > 1 && !obj.isContainer()) {
672             dbTimeMsecs += StopWatch.stopIfStarted();
673             throw new AAIException("AAI_6136", "query object mismatch: this object cannot hold multiple items." + obj.getDbName());
674         } else if (obj.isContainer()) {
675             final List getList;
676             String listProperty = null;
677             for (String property : obj.getProperties()) {
678                 if (obj.isListType(property) && obj.isComplexGenericType(property)) {
679                     listProperty = property;
680                     break;
681                 }
682             }
683             final String propertyName = listProperty;
684             getList = (List) obj.getValue(listProperty);
685
686             /* This is an experimental multithreading experiment
687              * on get alls.
688              */
689             ExecutorService pool = GetAllPool.getInstance().getPool();
690
691             List<Future<Object>> futures = new ArrayList<>();
692
693             QueryEngine tgEngine = this.engine.getQueryEngine();
694             for (Vertex v : vertices) {
695
696                 AaiCallable<Object> task = new AaiCallable<Object>() {
697                     @Override
698                     public Object process() throws UnsupportedEncodingException, AAIException {
699                         Set<Vertex> seen = new HashSet<>();
700                         Introspector childObject;
701                         try {
702                             childObject = obj.newIntrospectorInstanceOfNestedProperty(propertyName);
703                         } catch (AAIUnknownObjectException e) {
704                             throw e;
705                         }
706                         try {
707                             dbToObject(childObject, v, seen, internalDepth, nodeOnly, cleanUp);
708                         } catch (UnsupportedEncodingException e) {
709                             throw e;
710                         } catch (AAIException e) {
711                             throw e;
712                         }
713                         return childObject.getUnderlyingObject();
714                         //getList.add(childObject.getUnderlyingObject());
715                     }
716                 };
717                 futures.add(pool.submit(task));
718             }
719
720             for (Future<Object> future : futures) {
721                 try {
722                     getList.add(future.get());
723                 } catch (ExecutionException e) {
724                     dbTimeMsecs += StopWatch.stopIfStarted();
725                     throw new AAIException("AAI_4000", e);
726                 } catch (InterruptedException e) {
727                     dbTimeMsecs += StopWatch.stopIfStarted();
728                     throw new AAIException("AAI_4000", e);
729                 }
730             }
731         } else if (vertices.size() == 1) {
732             Set<Vertex> seen = new HashSet<>();
733             dbToObject(obj, vertices.get(0), seen, depth, nodeOnly, cleanUp);
734         } else {
735             //obj = null;
736         }
737
738         dbTimeMsecs += StopWatch.stopIfStarted();
739         return obj;
740     }
741
742     /**
743      * Db to object.
744      *
745      * @param obj     the obj
746      * @param v       the v
747      * @param seen    the seen
748      * @param depth   the depth
749      * @param cleanUp the clean up
750      * @return the introspector
751      * @throws IllegalAccessException       the illegal access exception
752      * @throws IllegalArgumentException     the illegal argument exception
753      * @throws InvocationTargetException    the invocation target exception
754      * @throws SecurityException            the security exception
755      * @throws InstantiationException       the instantiation exception
756      * @throws NoSuchMethodException        the no such method exception
757      * @throws UnsupportedEncodingException the unsupported encoding exception
758      * @throws AAIException                 the AAI exception
759      * @throws MalformedURLException        the malformed URL exception
760      * @throws AAIUnknownObjectException
761      * @throws URISyntaxException
762      */
763     private Introspector dbToObject(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly, String cleanUp) throws AAIException, UnsupportedEncodingException {
764
765         if (depth < 0) {
766             return null;
767         }
768         depth--;
769         seen.add(v);
770
771         boolean modified = false;
772         for (String property : obj.getProperties(PropertyPredicates.isVisible())) {
773             List<Object> getList = null;
774             Vertex[] vertices = null;
775
776             if (!(obj.isComplexType(property) || obj.isListType(property))) {
777                 this.copySimpleProperty(property, obj, v);
778                 modified = true;
779             } else {
780                 if (obj.isComplexType(property)) {
781                     /* container case */
782
783                     if (!property.equals("relationship-list") && depth >= 0) {
784                         Introspector argumentObject = obj.newIntrospectorInstanceOfProperty(property);
785                         Object result = dbToObject(argumentObject, v, seen, depth + 1, nodeOnly, cleanUp);
786                         if (result != null) {
787                             obj.setValue(property, argumentObject.getUnderlyingObject());
788                             modified = true;
789                         }
790                     } else if (property.equals("relationship-list") && !nodeOnly) {
791                         /* relationships need to be handled correctly */
792                         Introspector relationshipList = obj.newIntrospectorInstanceOfProperty(property);
793                         relationshipList = createRelationshipList(v, relationshipList, cleanUp);
794                         if (relationshipList != null) {
795                             modified = true;
796                             obj.setValue(property, relationshipList.getUnderlyingObject());
797                             modified = true;
798                         }
799
800                     }
801                 } else if (obj.isListType(property)) {
802
803                     if (property.equals("any")) {
804                         continue;
805                     }
806                     String genericType = obj.getGenericTypeClass(property).getSimpleName();
807                     if (obj.isComplexGenericType(property) && depth >= 0) {
808                         final String childDbName = convertFromCamelCase(genericType);
809                         String vType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null);
810                         EdgeRule rule;
811
812                         try {
813                             rule = edgeRules.getRule(new EdgeRuleQuery.Builder(vType, childDbName).edgeType(EdgeType.TREE).build());
814                         } catch (EdgeRuleNotFoundException e) {
815                             throw new NoEdgeRuleFoundException(e);
816                         } catch (AmbiguousRuleChoiceException e) {
817                             throw new MultipleEdgeRuleFoundException(e);
818                         }
819                         if (!rule.getContains().equals(AAIDirection.NONE.toString())) {
820                             //vertices = this.queryEngine.findRelatedVertices(v, Direction.OUT, rule.getLabel(), childDbName);
821                             Direction ruleDirection = rule.getDirection();
822                             Iterator<Vertex> itr = v.vertices(ruleDirection, rule.getLabel());
823                             List<Vertex> verticesList = (List<Vertex>) IteratorUtils.toList(itr);
824                             itr = verticesList.stream().filter(item -> {
825                                 return item.property(AAIProperties.NODE_TYPE).orElse("").equals(childDbName);
826                             }).iterator();
827                             if (itr.hasNext()) {
828                                 getList = (List<Object>) obj.getValue(property);
829                             }
830                             int processed = 0;
831                             int removed = 0;
832                             while (itr.hasNext()) {
833                                 Vertex childVertex = itr.next();
834                                 if (!seen.contains(childVertex)) {
835                                     Introspector argumentObject = obj.newIntrospectorInstanceOfNestedProperty(property);
836
837                                     Object result = dbToObject(argumentObject, childVertex, seen, depth, nodeOnly, cleanUp);
838                                     if (result != null) {
839                                         getList.add(argumentObject.getUnderlyingObject());
840                                     }
841
842                                     processed++;
843                                 } else {
844                                     removed++;
845                                     LOGGER.warn("Cycle found while serializing vertex id={}", childVertex.id().toString());
846                                 }
847                             }
848                             if (processed == 0) {
849                                 //vertices were all seen, reset the list
850                                 getList = null;
851                             }
852                             if (processed > 0) {
853                                 modified = true;
854                             }
855                         }
856                     } else if (obj.isSimpleGenericType(property)) {
857                         List<Object> temp = this.engine.getListProperty(v, property);
858                         if (temp != null) {
859                             getList = (List<Object>) obj.getValue(property);
860                             getList.addAll(temp);
861                             modified = true;
862                         }
863
864                     }
865
866                 }
867
868             }
869         }
870
871         //no changes were made to this obj, discard the instance
872         if (!modified) {
873             return null;
874         }
875         this.enrichData(obj, v);
876         return obj;
877
878     }
879
880
881     public Introspector getVertexProperties(Vertex v) throws AAIException, UnsupportedEncodingException {
882         String nodeType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null);
883         if (nodeType == null) {
884             throw new AAIException("AAI_6143");
885         }
886
887         Introspector obj = this.latestLoader.introspectorFromName(nodeType);
888         Set<Vertex> seen = new HashSet<>();
889         int depth = 0;
890         String cleanUp = "false";
891         boolean nodeOnly = true;
892         StopWatch.conditionalStart();
893         this.dbToObject(obj, v, seen, depth, nodeOnly, cleanUp);
894         dbTimeMsecs += StopWatch.stopIfStarted();
895         return obj;
896
897     }
898
899     public Introspector getLatestVersionView(Vertex v) throws AAIException, UnsupportedEncodingException {
900         String nodeType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null);
901         if (nodeType == null) {
902             throw new AAIException("AAI_6143");
903         }
904         Introspector obj = this.latestLoader.introspectorFromName(nodeType);
905         Set<Vertex> seen = new HashSet<>();
906         int depth = AAIProperties.MAXIMUM_DEPTH;
907         String cleanUp = "false";
908         boolean nodeOnly = false;
909         StopWatch.conditionalStart();
910         Tree<Element> tree = this.engine.getQueryEngine().findSubGraph(v, depth, nodeOnly);
911         TreeBackedVertex treeVertex = new TreeBackedVertex(v, tree);
912         this.dbToObject(obj, treeVertex, seen, depth, nodeOnly, cleanUp);
913         dbTimeMsecs += StopWatch.stopIfStarted();
914         return obj;
915     }
916
917     /**
918      * Copy simple property.
919      *
920      * @param property the property
921      * @param obj      the obj
922      * @param v        the v
923      * @throws InstantiationException    the instantiation exception
924      * @throws IllegalAccessException    the illegal access exception
925      * @throws IllegalArgumentException  the illegal argument exception
926      * @throws InvocationTargetException the invocation target exception
927      * @throws NoSuchMethodException     the no such method exception
928      * @throws SecurityException         the security exception
929      */
930     private void copySimpleProperty(String property, Introspector obj, Vertex v) {
931         final Object temp = getProperty(obj, property, v);
932         if (temp != null) {
933             obj.setValue(property, temp);
934         }
935     }
936
937
938     /**
939      * Load the introspector from the hashmap for the given property key
940      *
941      * @param property - vertex property
942      * @param obj      - introspector object representing the vertex
943      * @param hashMap  - Containing a list of pre-fetched properties for a given vertex
944      */
945     private void copySimplePropertyFromHashMap(String property, Introspector obj, Map<String, Object> hashMap){
946
947         final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(property);
948         String dbPropertyName = property;
949
950         if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) {
951             dbPropertyName = metadata.get(PropertyMetadata.DB_ALIAS);
952         }
953
954         final Object temp = hashMap.getOrDefault(dbPropertyName, null);
955
956         if (temp != null) {
957             obj.setValue(property, temp);
958         }
959     }
960
961     /**
962      * Simple db to object.
963      *
964      * @param obj the obj
965      * @param v   the v
966      * @throws InstantiationException    the instantiation exception
967      * @throws IllegalAccessException    the illegal access exception
968      * @throws IllegalArgumentException  the illegal argument exception
969      * @throws InvocationTargetException the invocation target exception
970      * @throws NoSuchMethodException     the no such method exception
971      * @throws SecurityException         the security exception
972      */
973     private void simpleDbToObject(Introspector obj, Vertex v) {
974         for(String key : obj.getProperties()){
975             this.copySimpleProperty(key, obj, v);
976         }
977     }
978
979
980     public Map<String, Object> convertVertexToHashMap(Introspector obj, Vertex v){
981
982         long startTime = System.currentTimeMillis();
983
984         Set<String> simpleProperties = obj.getSimpleProperties(PropertyPredicates.isVisible());
985         String[] simplePropsArray    = new String[simpleProperties.size()];
986         simplePropsArray             = simpleProperties.toArray(simplePropsArray);
987
988         Map<String, Object> simplePropsHashMap = new HashMap<>(simplePropsArray.length * 2);
989
990         v.properties(simplePropsArray).forEachRemaining((vp) -> simplePropsHashMap.put(vp.key(), vp.value()));
991
992         return simplePropsHashMap;
993     }
994
995     /**
996      * Creates the relationship list.
997      *
998      * @param v       the v
999      * @param obj     the obj
1000      * @param cleanUp the clean up
1001      * @return the object
1002      * @throws InstantiationException       the instantiation exception
1003      * @throws IllegalAccessException       the illegal access exception
1004      * @throws IllegalArgumentException     the illegal argument exception
1005      * @throws InvocationTargetException    the invocation target exception
1006      * @throws NoSuchMethodException        the no such method exception
1007      * @throws SecurityException            the security exception
1008      * @throws UnsupportedEncodingException the unsupported encoding exception
1009      * @throws AAIException                 the AAI exception
1010      * @throws MalformedURLException        the malformed URL exception
1011      * @throws URISyntaxException
1012      */
1013     private Introspector createRelationshipList(Vertex v, Introspector obj, String cleanUp) throws UnsupportedEncodingException, AAIException {
1014
1015         String[] cousinRules = new String[0];
1016
1017         try {
1018             cousinRules = edgeRules.retrieveCachedCousinLabels(obj.getDbName());
1019         } catch (ExecutionException e) {
1020             LOGGER.warn("Encountered an execution exception while retrieving labels for the node type {} using cached", obj.getDbName(), e);
1021         }
1022
1023         List<Vertex> cousins = null;
1024         if(cousinRules != null && cousinRules.length != 0){
1025             cousins = this.engine.getQueryEngine().findCousinVertices(v, cousinRules);
1026         } else {
1027             cousins = this.engine.getQueryEngine().findCousinVertices(v);
1028         }
1029
1030         List<Object> relationshipObjList = obj.getValue("relationship");
1031         String aNodeType = v.property("aai-node-type").value().toString();
1032
1033         TypeAlphabetizer alphabetizer = new TypeAlphabetizer();
1034
1035         EdgeIngestor edgeIngestor = SpringContextAware.getBean(EdgeIngestor.class);
1036         Set<String> keysWithMultipleLabels = edgeIngestor.getMultipleLabelKeys();
1037
1038         // For the given vertex, find all the cousins
1039         // For each cousin retrieve the node type and then
1040         // check if the version is greater than the edge label version
1041         // meaning is the current version equal to greater than the version
1042         // where we introduced the edge labels into the relationship payload
1043         // If it is, then we check if the edge key there are multiple labels
1044         // If there are multiple labels, then we need to go to the database
1045         // to retrieve the labels between itself and cousin vertex
1046         // If there is only single label between the edge a and b, then
1047         // we can retrieve what that is without going to the database
1048         // from using the edge rules json and get the edge rule out of it
1049         EdgeRuleQuery.Builder queryBuilder = new EdgeRuleQuery.Builder(aNodeType);
1050         for (Vertex cousin : cousins) {
1051             VertexProperty vertexProperty = cousin.property("aai-node-type");
1052             String bNodeType = null;
1053             if(vertexProperty.isPresent()){
1054                 bNodeType = cousin.property("aai-node-type").value().toString();
1055             } else {
1056                 // If the vertex is missing the aai-node-type
1057                 // Then its either a bad vertex or its in the process
1058                 // of getting deleted so we should ignore these vertexes
1059                 if(LOGGER.isDebugEnabled()){
1060                     LOGGER.debug("For the vertex {}, unable to retrieve the aai-node-type", v.id().toString());
1061                 } else {
1062                     LOGGER.info("Unable to retrieve the aai-node-type for vertex, for more info enable debug log");
1063                 }
1064                 continue;
1065             }
1066             if (obj.getVersion().compareTo(schemaVersions.getEdgeLabelVersion()) >= 0) {
1067                 String edgeKey = alphabetizer.buildAlphabetizedKey(aNodeType, bNodeType);
1068                 if(keysWithMultipleLabels.contains(edgeKey)){
1069                     List<String> edgeLabels = this.getEdgeLabelsBetween(EdgeType.COUSIN, v, cousin);
1070                     for(String edgeLabel: edgeLabels){
1071                         Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty("relationship");
1072                         Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp, edgeLabel);
1073                         if (result != null) {
1074                             relationshipObjList.add(result);
1075                         }
1076                     }
1077                 } else {
1078
1079                     EdgeRule edgeRule = null;
1080
1081                     // Create a query based on the a nodetype and b nodetype
1082                     // which is also a cousin edge and ensure the version
1083                     // is used properly so for example in order to be backwards
1084                     // compatible if we had allowed a edge between a and b
1085                     // in a previous release and we decided to remove it from
1086                     // the edge rules in the future we can display the edge
1087                     // only for the older apis and the new apis if the edge rule
1088                     // is removed will not be seen in the newer version of the API
1089
1090                     EdgeRuleQuery ruleQuery = queryBuilder
1091                         .to(bNodeType)
1092                         .edgeType(EdgeType.COUSIN)
1093                         .version(obj.getVersion())
1094                         .build();
1095
1096                     try {
1097                         edgeRule = edgeIngestor.getRule(ruleQuery);
1098                     } catch (EdgeRuleNotFoundException e) {
1099                         LOGGER.warn("Caught an edge rule not found exception for query {}, {}," +
1100                             " it could be the edge rule is no longer valid for the existing edge in db",
1101                             ruleQuery, LogFormatTools.getStackTop(e));
1102                         continue;
1103                     } catch (AmbiguousRuleChoiceException e) {
1104                         LOGGER.error("Caught an ambiguous rule not found exception for query {}, {}",
1105                             ruleQuery, LogFormatTools.getStackTop(e));
1106                         continue;
1107                     }
1108
1109                     Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty("relationship");
1110                     Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp,edgeRule.getLabel());
1111                     if (result != null) {
1112                         relationshipObjList.add(result);
1113                     }
1114                 }
1115             } else {
1116                 Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty("relationship");
1117                 Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp, null);
1118                 if (result != null) {
1119                     relationshipObjList.add(result);
1120                 }
1121             }
1122
1123         }
1124
1125         if (relationshipObjList.isEmpty()) {
1126             return null;
1127         } else {
1128             return obj;
1129         }
1130     }
1131
1132     /**
1133      * Process edge relationship.
1134      *
1135      * @param relationshipObj the relationship obj
1136      * @param edge            the edge
1137      * @param cleanUp         the clean up
1138      * @return the object
1139      * @throws InstantiationException       the instantiation exception
1140      * @throws IllegalAccessException       the illegal access exception
1141      * @throws IllegalArgumentException     the illegal argument exception
1142      * @throws InvocationTargetException    the invocation target exception
1143      * @throws NoSuchMethodException        the no such method exception
1144      * @throws SecurityException            the security exception
1145      * @throws UnsupportedEncodingException the unsupported encoding exception
1146      * @throws AAIException                 the AAI exception
1147      * @throws MalformedURLException        the malformed URL exception
1148      * @throws AAIUnknownObjectException
1149      * @throws URISyntaxException
1150      */
1151     private Object processEdgeRelationship(Introspector relationshipObj, Vertex cousin, String cleanUp, String edgeLabel) throws UnsupportedEncodingException, AAIUnknownObjectException {
1152
1153         VertexProperty aaiUriProperty = cousin.property("aai-uri");
1154
1155         if(!aaiUriProperty.isPresent()){
1156             return null;
1157         }
1158
1159         URI uri = UriBuilder.fromUri(aaiUriProperty.value().toString()).build();
1160
1161         URIToRelationshipObject uriParser = null;
1162         Introspector result = null;
1163         try {
1164             uriParser = new URIToRelationshipObject(relationshipObj.getLoader(), uri, this.baseURL);
1165             result = uriParser.getResult();
1166         } catch (AAIException | URISyntaxException e) {
1167             LOGGER.error("Error while processing edge relationship in version " + relationshipObj.getVersion() + " (bad vertex ID=" + ": "
1168                 + e.getMessage() + " " + LogFormatTools.getStackTop(e));
1169             return null;
1170         }
1171
1172         VertexProperty cousinVertexNodeType = cousin.property(AAIProperties.NODE_TYPE);
1173
1174         if(cousinVertexNodeType.isPresent()){
1175             String cousinType = cousinVertexNodeType.value().toString();
1176             if(namedPropNodes.contains(cousinType)){
1177                 this.addRelatedToProperty(result, cousin, cousinType);
1178             }
1179         }
1180
1181         if (edgeLabel != null && result.hasProperty("relationship-label")) {
1182             result.setValue("relationship-label", edgeLabel);
1183         }
1184
1185         return result.getUnderlyingObject();
1186     }
1187
1188     /**
1189      * Gets the URI for vertex.
1190      *
1191      * @param v the v
1192      * @return the URI for vertex
1193      * @throws InstantiationException       the instantiation exception
1194      * @throws IllegalAccessException       the illegal access exception
1195      * @throws IllegalArgumentException     the illegal argument exception
1196      * @throws InvocationTargetException    the invocation target exception
1197      * @throws NoSuchMethodException        the no such method exception
1198      * @throws SecurityException            the security exception
1199      * @throws UnsupportedEncodingException the unsupported encoding exception
1200      * @throws AAIUnknownObjectException
1201      */
1202     public URI getURIForVertex(Vertex v) throws UnsupportedEncodingException {
1203
1204         return getURIForVertex(v, false);
1205     }
1206
1207     public URI getURIForVertex(Vertex v, boolean overwrite) throws UnsupportedEncodingException {
1208         URI uri = UriBuilder.fromPath("/unknown-uri").build();
1209
1210         String aaiUri = v.<String>property(AAIProperties.AAI_URI).orElse(null);
1211
1212         if (aaiUri != null && !overwrite) {
1213             uri = UriBuilder.fromPath(aaiUri).build();
1214         }
1215
1216         return uri;
1217     }
1218
1219     /**
1220      * Gets the URI from list.
1221      *
1222      * @param list the list
1223      * @return the URI from list
1224      * @throws UnsupportedEncodingException the unsupported encoding exception
1225      */
1226     private URI getURIFromList(List<Introspector> list) throws UnsupportedEncodingException {
1227         String uri = "";
1228         StringBuilder sb = new StringBuilder();
1229         for (Introspector i : list) {
1230             sb.insert(0, i.getURI());
1231         }
1232
1233         uri = sb.toString();
1234         return UriBuilder.fromPath(uri).build();
1235     }
1236
1237     public void addRelatedToProperty(Introspector relationship, Vertex cousinVertex, String cousinType) throws AAIUnknownObjectException {
1238         Introspector obj = loader.introspectorFromName(cousinType);
1239         String nameProps = obj.getMetadata(ObjectMetadata.NAME_PROPS);
1240         List<Introspector> relatedToProperties = new ArrayList<>();
1241
1242         if (nameProps != null) {
1243             String[] props = nameProps.split(",");
1244             for (String prop : props) {
1245                 final Object temp = getProperty(obj, prop, cousinVertex);
1246                 Introspector relatedTo = relationship.newIntrospectorInstanceOfNestedProperty("related-to-property");
1247                 relatedTo.setValue("property-key", cousinType + "." + prop);
1248                 relatedTo.setValue("property-value", temp);
1249                 relatedToProperties.add(relatedTo);
1250             }
1251         }
1252
1253         if (!relatedToProperties.isEmpty()) {
1254             List relatedToList = (List) relationship.getValue("related-to-property");
1255             for (Introspector introspector : relatedToProperties) {
1256                 relatedToList.add(introspector.getUnderlyingObject());
1257             }
1258         }
1259
1260     }
1261
1262     private Object getProperty(Introspector obj, String prop, Vertex vertex){
1263
1264         final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(prop);
1265         String dbPropertyName = prop;
1266
1267         if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) {
1268             dbPropertyName = metadata.get(PropertyMetadata.DB_ALIAS);
1269         }
1270
1271         return vertex.<Object>property(dbPropertyName).orElse(null);
1272     }
1273
1274     /**
1275      * Creates the edge.
1276      *
1277      * @param relationship the relationship
1278      * @param inputVertex  the input vertex
1279      * @return true, if successful
1280      * @throws UnsupportedEncodingException the unsupported encoding exception
1281      * @throws AAIException                 the AAI exception
1282      */
1283     public boolean createEdge(Introspector relationship, Vertex inputVertex) throws UnsupportedEncodingException, AAIException {
1284
1285         Vertex relatedVertex = null;
1286         StopWatch.conditionalStart();
1287         QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(relationship);
1288
1289         String label = null;
1290         if (relationship.hasProperty("relationship-label")) {
1291             label = relationship.getValue("relationship-label");
1292         }
1293
1294         List<Vertex> results = parser.getQueryBuilder().toList();
1295         if (results.isEmpty()) {
1296             dbTimeMsecs += StopWatch.stopIfStarted();
1297             AAIException e = new AAIException("AAI_6129", "Node of type " + parser.getResultType() + ". Could not find object at: " + parser.getUri());
1298             e.getTemplateVars().add(parser.getResultType());
1299             e.getTemplateVars().add(parser.getUri().toString());
1300             throw e;
1301         } else {
1302             //still an issue if there's more than one
1303             relatedVertex = results.get(0);
1304         }
1305
1306         if (relatedVertex != null) {
1307
1308             Edge e;
1309             try {
1310                 e = this.getEdgeBetween(EdgeType.COUSIN, inputVertex, relatedVertex, label);
1311                 if (e == null) {
1312                     edgeSer.addEdge(this.engine.asAdmin().getTraversalSource(), inputVertex, relatedVertex, label);
1313                 } else {
1314                     //attempted to link two vertexes already linked
1315                 }
1316             } finally {
1317                 dbTimeMsecs += StopWatch.stopIfStarted();
1318             }
1319         }
1320
1321         dbTimeMsecs += StopWatch.stopIfStarted();
1322         return true;
1323     }
1324
1325     /**
1326      * Gets all the edges between of the type with the specified label.
1327      *
1328      * @param aVertex the out vertex
1329      * @param bVertex the in vertex
1330      * @return the edges between
1331      * @throws AAIException             the AAI exception
1332      * @throws NoEdgeRuleFoundException
1333      */
1334     private Edge getEdgeBetweenWithLabel(EdgeType type, Vertex aVertex, Vertex bVertex, EdgeRule edgeRule) {
1335
1336         Edge result = null;
1337
1338         if (bVertex != null) {
1339             GraphTraversal<Vertex, Edge> findEdgesBetween = null;
1340             if (EdgeType.TREE.equals(type)) {
1341                 GraphTraversal<Vertex,Vertex> findVertex = this.engine.asAdmin().getTraversalSource().V(bVertex);
1342                 if(edgeRule.getDirection().equals(Direction.IN)){
1343                     findEdgesBetween = findVertex.outE(edgeRule.getLabel())
1344                         .has(EdgeProperty.CONTAINS.toString(), edgeRule.getContains())
1345                         .not(
1346                             __.has(EdgeField.PRIVATE.toString(), true)
1347                         );
1348                 } else {
1349                     findEdgesBetween = findVertex.inE(edgeRule.getLabel())
1350                         .has(EdgeProperty.CONTAINS.toString(), edgeRule.getContains())
1351                         .not(
1352                             __.has(EdgeField.PRIVATE.toString(), true)
1353                         );
1354                 }
1355                 findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(aVertex.id())).limit(1);
1356             } else {
1357                 findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE(edgeRule.getLabel());
1358                 findEdgesBetween = findEdgesBetween
1359                     .has(EdgeProperty.CONTAINS.toString(), "NONE")
1360                     .not(
1361                         __.has(EdgeField.PRIVATE.toString(), true)
1362                     );
1363                 findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id())).limit(1);
1364             }
1365             List<Edge> list = findEdgesBetween.toList();
1366             if(!list.isEmpty()){
1367                 result = list.get(0);
1368             }
1369         }
1370
1371         return result;
1372     }
1373
1374     /**
1375      * Gets all the edges between of the type.
1376      *
1377      * @param aVertex the out vertex
1378      * @param bVertex the in vertex
1379      * @return the edges between
1380      * @throws AAIException             the AAI exception
1381      * @throws NoEdgeRuleFoundException
1382      */
1383     private List<Edge> getEdgesBetween(EdgeType type, Vertex aVertex, Vertex bVertex) {
1384
1385         List<Edge> result = new ArrayList<>();
1386
1387         if (bVertex != null) {
1388             GraphTraversal<Vertex, Edge> findEdgesBetween = null;
1389             findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE();
1390             if (EdgeType.TREE.equals(type)) {
1391                 findEdgesBetween = findEdgesBetween
1392                     .not(
1393                         __.or(
1394                             __.has(EdgeProperty.CONTAINS.toString(), "NONE"),
1395                             __.has(EdgeField.PRIVATE.toString(), true)
1396                         )
1397                     );
1398             } else {
1399                 findEdgesBetween = findEdgesBetween
1400                     .has(EdgeProperty.CONTAINS.toString(), "NONE")
1401                     .not(
1402                         __.has(EdgeField.PRIVATE.toString(), true)
1403                     );
1404             }
1405             findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id()));
1406             result = findEdgesBetween.toList();
1407         }
1408
1409         return result;
1410     }
1411
1412     /**
1413      * Gets all the edges string between of the type.
1414      *
1415      * @param aVertex the out vertex
1416      * @param bVertex the in vertex
1417      * @return the edges between
1418      * @throws AAIException the AAI exception
1419      * @throws NoEdgeRuleFoundException
1420      */
1421     private List<String> getEdgeLabelsBetween(EdgeType type, Vertex aVertex, Vertex bVertex) {
1422
1423         List<String> result = new ArrayList<>();
1424
1425         if (bVertex != null) {
1426             GraphTraversal<Vertex, Edge> findEdgesBetween = null;
1427             findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE();
1428             if (EdgeType.TREE.equals(type)) {
1429                 findEdgesBetween = findEdgesBetween
1430                         .not(
1431                                 __.or(
1432                                         __.has(EdgeProperty.CONTAINS.toString(), "NONE"),
1433                                         __.has(EdgeField.PRIVATE.toString(), true)
1434                                 )
1435                         );
1436             } else {
1437                 findEdgesBetween = findEdgesBetween
1438                         .has(EdgeProperty.CONTAINS.toString(), "NONE")
1439                         .not(
1440                                 __.has(EdgeField.PRIVATE.toString(), true)
1441                         );
1442             }
1443             findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id()));
1444             result = findEdgesBetween.label().toList();
1445         }
1446         return result;
1447     }
1448
1449     /**
1450      * Gets all the edges string between of the type.
1451      *
1452      * @param aVertex the out vertex
1453      * @param bVertex the in vertex
1454      * @return the edges between
1455      * @throws AAIException the AAI exception
1456      * @throws NoEdgeRuleFoundException
1457      */
1458     private Long getEdgeLabelsCount(Vertex aVertex, Vertex bVertex) {
1459
1460         Long result = null;
1461
1462         if (bVertex != null) {
1463             GraphTraversal<Vertex, Edge> findEdgesBetween = null;
1464             findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE();
1465             findEdgesBetween = findEdgesBetween
1466                     .has(EdgeProperty.CONTAINS.toString(), "NONE")
1467                     .not(
1468                             __.has(EdgeField.PRIVATE.toString(), true)
1469                     );
1470             findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id()));
1471             result = findEdgesBetween.count().next();
1472         }
1473         return result;
1474     }
1475     /**
1476      * Gets all the edges between the vertexes with the label and type.
1477      *
1478      * @param aVertex the out vertex
1479      * @param bVertex the in vertex
1480      * @param label
1481      * @return the edges between
1482      * @throws AAIException the AAI exception
1483      */
1484     private Edge getEdgesBetween(EdgeType type, Vertex aVertex, Vertex bVertex, String label) throws AAIException {
1485
1486         Edge edge = null;
1487
1488         if (bVertex != null) {
1489             String aType = aVertex.<String>property(AAIProperties.NODE_TYPE).value();
1490             String bType = bVertex.<String>property(AAIProperties.NODE_TYPE).value();
1491             EdgeRuleQuery q = new EdgeRuleQuery.Builder(aType, bType).edgeType(type).label(label).build();
1492             EdgeRule rule;
1493             try {
1494                 rule = edgeRules.getRule(q);
1495             } catch (EdgeRuleNotFoundException e) {
1496                 throw new NoEdgeRuleFoundException(e);
1497             } catch (AmbiguousRuleChoiceException e) {
1498                 throw new MultipleEdgeRuleFoundException(e);
1499             }
1500             edge = this.getEdgeBetweenWithLabel(type, aVertex, bVertex, rule);
1501         }
1502
1503         return edge;
1504     }
1505
1506     /**
1507      * Gets the edge between with the label and edge type.
1508      *
1509      * @param aVertex the out vertex
1510      * @param bVertex the in vertex
1511      * @param label
1512      * @return the edge between
1513      * @throws AAIException             the AAI exception
1514      * @throws NoEdgeRuleFoundException
1515      */
1516     public Edge getEdgeBetween(EdgeType type, Vertex aVertex, Vertex bVertex, String label) throws AAIException {
1517
1518         StopWatch.conditionalStart();
1519         if (bVertex != null) {
1520
1521             Edge edge = this.getEdgesBetween(type, aVertex, bVertex, label);
1522             if (edge != null) {
1523                 dbTimeMsecs += StopWatch.stopIfStarted();
1524                 return edge;
1525             }
1526
1527         }
1528         dbTimeMsecs += StopWatch.stopIfStarted();
1529         return null;
1530     }
1531
1532     public Edge getEdgeBetween(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException {
1533         return this.getEdgeBetween(type, aVertex, bVertex, null);
1534     }
1535
1536
1537     /**
1538      * Delete edge.
1539      *
1540      * @param relationship the relationship
1541      * @param inputVertex  the input vertex
1542      * @return true, if successful
1543      * @throws UnsupportedEncodingException the unsupported encoding exception
1544      * @throws AAIException                 the AAI exception
1545      */
1546     public boolean deleteEdge(Introspector relationship, Vertex inputVertex) throws UnsupportedEncodingException, AAIException {
1547
1548         Vertex relatedVertex = null;
1549         StopWatch.conditionalStart();
1550         QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(relationship);
1551
1552         List<Vertex> results = parser.getQueryBuilder().toList();
1553
1554         String label = null;
1555         if (relationship.hasProperty("relationship-label")) {
1556             label = relationship.getValue("relationship-label");
1557         }
1558
1559         if (results.isEmpty()) {
1560             dbTimeMsecs += StopWatch.stopIfStarted();
1561             return false;
1562         }
1563
1564         relatedVertex = results.get(0);
1565         Edge edge;
1566         try {
1567             edge = this.getEdgeBetween(EdgeType.COUSIN, inputVertex, relatedVertex, label);
1568         } catch (NoEdgeRuleFoundException e) {
1569             dbTimeMsecs += StopWatch.stopIfStarted();
1570             throw new AAIException("AAI_6129", e);
1571         }
1572         if (edge != null) {
1573             edge.remove();
1574             dbTimeMsecs += StopWatch.stopIfStarted();
1575             return true;
1576         } else {
1577             dbTimeMsecs += StopWatch.stopIfStarted();
1578             return false;
1579         }
1580
1581     }
1582
1583     /**
1584      * Delete items with traversal.
1585      *
1586      * @param vertexes the vertexes
1587      * @throws IllegalStateException the illegal state exception
1588      */
1589     public void deleteItemsWithTraversal(List<Vertex> vertexes) throws IllegalStateException {
1590
1591         for (Vertex v : vertexes) {
1592             LOGGER.debug("About to delete the vertex with id: " + v.id());
1593             deleteWithTraversal(v);
1594         }
1595
1596     }
1597
1598     /**
1599      * Delete with traversal.
1600      *
1601      * @param startVertex the start vertex
1602      */
1603     public void deleteWithTraversal(Vertex startVertex) {
1604         StopWatch.conditionalStart();
1605         List<Vertex> results = this.engine.getQueryEngine().findDeletable(startVertex);
1606
1607         for (Vertex v : results) {
1608             LOGGER.warn("Removing vertex " + v.id().toString());
1609
1610             v.remove();
1611         }
1612         dbTimeMsecs += StopWatch.stopIfStarted();
1613     }
1614
1615     /**
1616      * Delete.
1617      *
1618      * @param v               the v
1619      * @param resourceVersion the resource version
1620      * @throws IllegalArgumentException the illegal argument exception
1621      * @throws AAIException             the AAI exception
1622      * @throws InterruptedException     the interrupted exception
1623      */
1624     public void delete(Vertex v, List<Vertex> deletableVertices, String resourceVersion, boolean enableResourceVersion) throws IllegalArgumentException, AAIException {
1625
1626         boolean result = verifyDeleteSemantics(v, resourceVersion, enableResourceVersion);
1627         /*
1628          * The reason why I want to call PreventDeleteSemantics second time is to catch the prevent-deletes in a chain
1629          * These are far-fewer than seeing a prevnt-delete on the vertex to be deleted
1630          * So its better to make these in 2 steps
1631          */
1632         if (result && !deletableVertices.isEmpty()) {
1633             result = verifyPreventDeleteSemantics(deletableVertices);
1634         }
1635         if (result) {
1636
1637             try {
1638                 deleteWithTraversal(v);
1639             } catch (IllegalStateException e) {
1640                 throw new AAIException("AAI_6110", e);
1641             }
1642
1643         }
1644
1645     }
1646
1647
1648     /**
1649      * Delete.
1650      *
1651      * @param v               the v
1652      * @param resourceVersion the resource version
1653      * @throws IllegalArgumentException the illegal argument exception
1654      * @throws AAIException             the AAI exception
1655      * @throws InterruptedException     the interrupted exception
1656      */
1657     public void delete(Vertex v, String resourceVersion, boolean enableResourceVersion) throws IllegalArgumentException, AAIException {
1658
1659         boolean result = verifyDeleteSemantics(v, resourceVersion, enableResourceVersion);
1660
1661         if (result) {
1662
1663             try {
1664                 deleteWithTraversal(v);
1665             } catch (IllegalStateException e) {
1666                 throw new AAIException("AAI_6110", e);
1667             }
1668
1669         }
1670
1671     }
1672
1673     /**
1674      * Verify delete semantics.
1675      *
1676      * @param vertex          the vertex
1677      * @param resourceVersion the resource version
1678      * @return true, if successful
1679      * @throws AAIException the AAI exception
1680      */
1681     private boolean verifyDeleteSemantics(Vertex vertex, String resourceVersion, boolean enableResourceVersion) throws AAIException {
1682         boolean result = true;
1683         String nodeType = "";
1684         String errorDetail = " unknown delete semantic found";
1685         String aaiExceptionCode = "";
1686         nodeType = vertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
1687         if (enableResourceVersion && !this.verifyResourceVersion("delete", nodeType, vertex.<String>property(AAIProperties.RESOURCE_VERSION).orElse(null), resourceVersion, nodeType)) {
1688         }
1689         List<Vertex> vertices = new ArrayList<Vertex>();
1690         vertices.add(vertex);
1691         result = verifyPreventDeleteSemantics(vertices);
1692
1693         return result;
1694     }
1695
1696     /**
1697      * Verify Prevent delete semantics.
1698      *
1699      * @param vertices the list of vertices
1700      * @return true, if successful
1701      * @throws AAIException the AAI exception
1702      */
1703     private boolean verifyPreventDeleteSemantics(List<Vertex> vertices) throws AAIException {
1704         boolean result = true;
1705         String nodeType = "";
1706         String errorDetail = " unknown delete semantic found";
1707         String aaiExceptionCode = "";
1708
1709         StopWatch.conditionalStart();
1710         /*
1711          * This takes in all the vertices in a cascade-delete-chain and checks if there is any edge with a "prevent-delete" condition
1712          * If yes - that should prevent the deletion of the vertex
1713          * Dedup makes sure we dont capture the prevent-delete vertices twice
1714          * The prevent-delete vertices are stored so that the error message displays what prevents the delete
1715          */
1716
1717         List<Object> preventDeleteVertices = this.engine.asAdmin().getReadOnlyTraversalSource().V(vertices).
1718             union(__.inE().has(EdgeProperty.PREVENT_DELETE.toString(), AAIDirection.IN.toString()).outV().values(AAIProperties.NODE_TYPE),
1719                 __.outE().has(EdgeProperty.PREVENT_DELETE.toString(), AAIDirection.OUT.toString()).inV().values(AAIProperties.NODE_TYPE))
1720             .dedup().toList();
1721
1722         dbTimeMsecs += StopWatch.stopIfStarted();
1723         if (!preventDeleteVertices.isEmpty()) {
1724             aaiExceptionCode = "AAI_6110";
1725             errorDetail = String.format("Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types %s", preventDeleteVertices);
1726             result = false;
1727         }
1728         if (!result) {
1729             throw new AAIException(aaiExceptionCode, errorDetail);
1730         }
1731         return result;
1732     }
1733
1734     /**
1735      * Verify resource version.
1736      *
1737      * @param action the action
1738      * @param nodeType the node type
1739      * @param currentResourceVersion the current resource version
1740      * @param resourceVersion the resource version
1741      * @param uri the uri
1742      * @return true, if successful
1743      * @throws AAIException the AAI exception
1744      */
1745     public boolean verifyResourceVersion(String action, String nodeType, String currentResourceVersion, String resourceVersion, String uri) throws AAIException {
1746         String enabled = "";
1747         String errorDetail = "";
1748         String aaiExceptionCode = "";
1749         if (currentResourceVersion == null) {
1750             currentResourceVersion = "";
1751         }
1752
1753         if (resourceVersion == null) {
1754             resourceVersion = "";
1755         }
1756         try {
1757             enabled = AAIConfig.get(AAIConstants.AAI_RESVERSION_ENABLEFLAG);
1758         } catch (AAIException e) {
1759             ErrorLogHelper.logException(e);
1760         }
1761         if (enabled.equals("true")) {
1762             if (!currentResourceVersion.equals(resourceVersion)) {
1763                 if (action.equals("create") && !resourceVersion.equals("")) {
1764                     errorDetail = "resource-version passed for " + action + " of " + uri;
1765                     aaiExceptionCode = "AAI_6135";
1766                 } else if (resourceVersion.equals("")) {
1767                     errorDetail = "resource-version not passed for " + action + " of " + uri;
1768                     aaiExceptionCode = "AAI_6130";
1769                 } else {
1770                     errorDetail = "resource-version MISMATCH for " + action + " of " + uri;
1771                     aaiExceptionCode = "AAI_6131";
1772                 }
1773
1774                 throw new AAIException(aaiExceptionCode, errorDetail);
1775
1776             }
1777         }
1778         return true;
1779     }
1780
1781     /**
1782      * Convert from camel case.
1783      *
1784      * @param name the name
1785      * @return the string
1786      */
1787     private String convertFromCamelCase (String name) {
1788         String result = "";
1789         result = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, name);
1790
1791         NamingExceptions exceptions = NamingExceptions.getInstance();
1792         result = exceptions.getDBName(result);
1793
1794         return result;
1795     }
1796
1797     private boolean canModify(Introspector obj, String propName, String requestContext) {
1798         final String readOnly = obj.getPropertyMetadata(propName).get(PropertyMetadata.READ_ONLY);
1799         if (readOnly != null) {
1800             final String[] items = readOnly.split(",");
1801             for (String item : items) {
1802                 if (requestContext.equals(item)) {
1803                     return false;
1804                 }
1805             }
1806         }
1807         return true;
1808     }
1809
1810     private void executePreSideEffects(Introspector obj, Vertex self) throws AAIException {
1811
1812         SideEffectRunner runner = new SideEffectRunner
1813                 .Builder(this.engine, this).addSideEffect(DataCopy.class).addSideEffect(PrivateEdge.class).build();
1814
1815         runner.execute(obj, self);
1816     }
1817
1818     private void executePostSideEffects(Introspector obj, Vertex self) throws AAIException {
1819
1820         SideEffectRunner runner = new SideEffectRunner
1821                 .Builder(this.engine, this).addSideEffect(DataLinkWriter.class).build();
1822
1823         runner.execute(obj, self);
1824     }
1825
1826     private void enrichData(Introspector obj, Vertex self) throws AAIException  {
1827
1828         SideEffectRunner runner = new SideEffectRunner
1829                 .Builder(this.engine, this).addSideEffect(DataLinkReader.class).build();
1830
1831         runner.execute(obj, self);
1832     }
1833
1834     public double getDBTimeMsecs() {
1835         return (dbTimeMsecs);
1836     }
1837
1838     /**
1839      * Db to object With Filters
1840      * This is for a one-time run with Tenant Isloation to only filter relationships
1841      * TODO: Chnage the original dbToObject to take filter parent/cousins
1842      *
1843      * @param obj               the obj
1844      * @param v                 the vertex from the graph
1845      * @param depth             the depth
1846      * @param nodeOnly          specify if to exclude relationships or not
1847      * @param filterCousinNodes
1848      * @return the introspector
1849      * @throws AAIException                 the AAI exception
1850      * @throws IllegalAccessException       the illegal access exception
1851      * @throws IllegalArgumentException     the illegal argument exception
1852      * @throws InvocationTargetException    the invocation target exception
1853      * @throws SecurityException            the security exception
1854      * @throws InstantiationException       the instantiation exception
1855      * @throws NoSuchMethodException        the no such method exception
1856      * @throws UnsupportedEncodingException the unsupported encoding exception
1857      * @throws MalformedURLException        the malformed URL exception
1858      * @throws AAIUnknownObjectException
1859      * @throws URISyntaxException
1860      */
1861     //TODO - See if you can merge the 2 dbToObjectWithFilters
1862     public Introspector dbToObjectWithFilters(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly, List<String> filterCousinNodes, List<String> filterParentNodes) throws AAIException, UnsupportedEncodingException {
1863         String cleanUp = "false";
1864         if (depth < 0) {
1865             return null;
1866         }
1867         depth--;
1868         seen.add(v);
1869         boolean modified = false;
1870         for (String property : obj.getProperties(PropertyPredicates.isVisible())) {
1871             List<Object> getList = null;
1872             Vertex[] vertices = null;
1873
1874             if (!(obj.isComplexType(property) || obj.isListType(property))) {
1875                 this.copySimpleProperty(property, obj, v);
1876                 modified = true;
1877             } else {
1878                 if (obj.isComplexType(property)) {
1879                     /* container case */
1880
1881                     if (!property.equals("relationship-list") && depth >= 0) {
1882                         Introspector argumentObject = obj.newIntrospectorInstanceOfProperty(property);
1883                         Object result = dbToObjectWithFilters(argumentObject, v, seen, depth + 1, nodeOnly, filterCousinNodes, filterParentNodes);
1884                         if (result != null) {
1885                             obj.setValue(property, argumentObject.getUnderlyingObject());
1886                             modified = true;
1887                         }
1888                     } else if (property.equals("relationship-list") && !nodeOnly) {
1889                         /* relationships need to be handled correctly */
1890                         Introspector relationshipList = obj.newIntrospectorInstanceOfProperty(property);
1891                         relationshipList = createFilteredRelationshipList(v, relationshipList, cleanUp, filterCousinNodes);
1892                         if (relationshipList != null) {
1893                             modified = true;
1894                             obj.setValue(property, relationshipList.getUnderlyingObject());
1895                             modified = true;
1896                         }
1897
1898                     }
1899                 } else if (obj.isListType(property)) {
1900
1901                     if (property.equals("any")) {
1902                         continue;
1903                     }
1904                     String genericType = obj.getGenericTypeClass(property).getSimpleName();
1905                     if (obj.isComplexGenericType(property) && depth >= 0) {
1906                         final String childDbName = convertFromCamelCase(genericType);
1907                         String vType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null);
1908                         EdgeRule rule;
1909
1910                         boolean isthisParentRequired = filterParentNodes.parallelStream().anyMatch(childDbName::contains);
1911
1912                         EdgeRuleQuery q = new EdgeRuleQuery.Builder(vType, childDbName).edgeType(EdgeType.TREE).build();
1913
1914                         try {
1915                             rule = edgeRules.getRule(q);
1916                         } catch (EdgeRuleNotFoundException e) {
1917                             throw new NoEdgeRuleFoundException(e);
1918                         } catch (AmbiguousRuleChoiceException e) {
1919                             throw new MultipleEdgeRuleFoundException(e);
1920                         }
1921                         if (!rule.getContains().equals(AAIDirection.NONE.toString()) && isthisParentRequired) {
1922                             //vertices = this.queryEngine.findRelatedVertices(v, Direction.OUT, rule.getLabel(), childDbName);
1923                             Direction ruleDirection = rule.getDirection();
1924                             Iterator<Vertex> itr = v.vertices(ruleDirection, rule.getLabel());
1925                             List<Vertex> verticesList = (List<Vertex>) IteratorUtils.toList(itr);
1926                             itr = verticesList.stream().filter(item -> {
1927                                 return item.property(AAIProperties.NODE_TYPE).orElse("").equals(childDbName);
1928                             }).iterator();
1929                             if (itr.hasNext()) {
1930                                 getList = (List<Object>) obj.getValue(property);
1931                             }
1932                             int processed = 0;
1933                             int removed = 0;
1934                             while (itr.hasNext()) {
1935                                 Vertex childVertex = itr.next();
1936                                 if (!seen.contains(childVertex)) {
1937                                     Introspector argumentObject = obj.newIntrospectorInstanceOfNestedProperty(property);
1938
1939                                     Object result = dbToObjectWithFilters(argumentObject, childVertex, seen, depth, nodeOnly, filterCousinNodes, filterParentNodes);
1940                                     if (result != null) {
1941                                         getList.add(argumentObject.getUnderlyingObject());
1942                                     }
1943
1944                                     processed++;
1945                                 } else {
1946                                     removed++;
1947                                     LOGGER.warn("Cycle found while serializing vertex id={}", childVertex.id().toString());
1948                                 }
1949                             }
1950                             if (processed == 0) {
1951                                 //vertices were all seen, reset the list
1952                                 getList = null;
1953                             }
1954                             if (processed > 0) {
1955                                 modified = true;
1956                             }
1957                         }
1958                     } else if (obj.isSimpleGenericType(property)) {
1959                         List<Object> temp = this.engine.getListProperty(v, property);
1960                         if (temp != null) {
1961                             getList = (List<Object>) obj.getValue(property);
1962                             getList.addAll(temp);
1963                             modified = true;
1964                         }
1965
1966                     }
1967
1968                 }
1969
1970             }
1971         }
1972
1973         //no changes were made to this obj, discard the instance
1974         if (!modified) {
1975             return null;
1976         }
1977         this.enrichData(obj, v);
1978         return obj;
1979
1980     }
1981
1982     /**
1983      * Creates the relationship list with the filtered node types.
1984      *
1985      * @param v       the v
1986      * @param obj     the obj
1987      * @param cleanUp the clean up
1988      * @return the object
1989      * @throws InstantiationException       the instantiation exception
1990      * @throws IllegalAccessException       the illegal access exception
1991      * @throws IllegalArgumentException     the illegal argument exception
1992      * @throws InvocationTargetException    the invocation target exception
1993      * @throws NoSuchMethodException        the no such method exception
1994      * @throws SecurityException            the security exception
1995      * @throws UnsupportedEncodingException the unsupported encoding exception
1996      * @throws AAIException                 the AAI exception
1997      * @throws MalformedURLException        the malformed URL exception
1998      * @throws URISyntaxException
1999      */
2000     private Introspector createFilteredRelationshipList(Vertex v, Introspector obj, String cleanUp, List<String> filterNodes) throws UnsupportedEncodingException, AAIException {
2001         List<Vertex> allCousins = this.engine.getQueryEngine().findCousinVertices(v);
2002
2003         Iterator<Vertex> cousinVertices = allCousins.stream().filter(item -> {
2004             String node = (String) item.property(AAIProperties.NODE_TYPE).orElse("");
2005             return filterNodes.parallelStream().anyMatch(node::contains);
2006         }).iterator();
2007
2008
2009         List<Vertex> cousins = (List<Vertex>) IteratorUtils.toList(cousinVertices);
2010
2011         //items.parallelStream().anyMatch(inputStr::contains)
2012         List<Object> relationshipObjList = obj.getValue("relationship");
2013         for (Vertex cousin : cousins) {
2014
2015             Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty("relationship");
2016             Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp, null);
2017             if (result != null) {
2018                 relationshipObjList.add(result);
2019             }
2020
2021
2022         }
2023
2024         if (relationshipObjList.isEmpty()) {
2025             return null;
2026         } else {
2027             return obj;
2028         }
2029     }
2030
2031 }