9d107b1f7d0f85249040872cd4724d930fe63c26
[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
932         final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(property);
933         String dbPropertyName = property;
934
935         if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) {
936             dbPropertyName = metadata.get(PropertyMetadata.DB_ALIAS);
937         }
938
939
940         final Object temp = v.<Object>property(dbPropertyName).orElse(null);
941         if (temp != null) {
942             obj.setValue(property, temp);
943         }
944     }
945
946
947     /**
948      * Load the introspector from the hashmap for the given property key
949      *
950      * @param property - vertex property
951      * @param obj      - introspector object representing the vertex
952      * @param hashMap  - Containing a list of pre-fetched properties for a given vertex
953      */
954     private void copySimplePropertyFromHashMap(String property, Introspector obj, Map<String, Object> hashMap){
955
956         final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(property);
957         String dbPropertyName = property;
958
959         if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) {
960             dbPropertyName = metadata.get(PropertyMetadata.DB_ALIAS);
961         }
962
963         final Object temp = hashMap.getOrDefault(dbPropertyName, null);
964
965         if (temp != null) {
966             obj.setValue(property, temp);
967         }
968     }
969
970     /**
971      * Simple db to object.
972      *
973      * @param obj the obj
974      * @param v   the v
975      * @throws InstantiationException    the instantiation exception
976      * @throws IllegalAccessException    the illegal access exception
977      * @throws IllegalArgumentException  the illegal argument exception
978      * @throws InvocationTargetException the invocation target exception
979      * @throws NoSuchMethodException     the no such method exception
980      * @throws SecurityException         the security exception
981      */
982     private void simpleDbToObject(Introspector obj, Vertex v) {
983         for(String key : obj.getProperties()){
984             this.copySimpleProperty(key, obj, v);
985         }
986     }
987
988
989     public Map<String, Object> convertVertexToHashMap(Introspector obj, Vertex v){
990
991         long startTime = System.currentTimeMillis();
992
993         Set<String> simpleProperties = obj.getSimpleProperties(PropertyPredicates.isVisible());
994         String[] simplePropsArray    = new String[simpleProperties.size()];
995         simplePropsArray             = simpleProperties.toArray(simplePropsArray);
996
997         Map<String, Object> simplePropsHashMap = new HashMap<>(simplePropsArray.length * 2);
998
999         v.properties(simplePropsArray).forEachRemaining((vp) -> simplePropsHashMap.put(vp.key(), vp.value()));
1000
1001         return simplePropsHashMap;
1002     }
1003
1004     /**
1005      * Creates the relationship list.
1006      *
1007      * @param v       the v
1008      * @param obj     the obj
1009      * @param cleanUp the clean up
1010      * @return the object
1011      * @throws InstantiationException       the instantiation exception
1012      * @throws IllegalAccessException       the illegal access exception
1013      * @throws IllegalArgumentException     the illegal argument exception
1014      * @throws InvocationTargetException    the invocation target exception
1015      * @throws NoSuchMethodException        the no such method exception
1016      * @throws SecurityException            the security exception
1017      * @throws UnsupportedEncodingException the unsupported encoding exception
1018      * @throws AAIException                 the AAI exception
1019      * @throws MalformedURLException        the malformed URL exception
1020      * @throws URISyntaxException
1021      */
1022     private Introspector createRelationshipList(Vertex v, Introspector obj, String cleanUp) throws UnsupportedEncodingException, AAIException {
1023
1024         String[] cousinRules = new String[0];
1025
1026         try {
1027             cousinRules = edgeRules.retrieveCachedCousinLabels(obj.getDbName());
1028         } catch (ExecutionException e) {
1029             LOGGER.warn("Encountered an execution exception while retrieving labels for the node type {} using cached", obj.getDbName(), e);
1030         }
1031
1032         List<Vertex> cousins = null;
1033         if(cousinRules != null && cousinRules.length != 0){
1034             cousins = this.engine.getQueryEngine().findCousinVertices(v, cousinRules);
1035         } else {
1036             cousins = this.engine.getQueryEngine().findCousinVertices(v);
1037         }
1038
1039         List<Object> relationshipObjList = obj.getValue("relationship");
1040         String aNodeType = v.property("aai-node-type").value().toString();
1041
1042         TypeAlphabetizer alphabetizer = new TypeAlphabetizer();
1043
1044         EdgeIngestor edgeIngestor = SpringContextAware.getBean(EdgeIngestor.class);
1045         Set<String> keysWithMultipleLabels = edgeIngestor.getMultipleLabelKeys();
1046
1047         // For the given vertex, find all the cousins
1048         // For each cousin retrieve the node type and then
1049         // check if the version is greater than the edge label version
1050         // meaning is the current version equal to greater than the version
1051         // where we introduced the edge labels into the relationship payload
1052         // If it is, then we check if the edge key there are multiple labels
1053         // If there are multiple labels, then we need to go to the database
1054         // to retrieve the labels between itself and cousin vertex
1055         // If there is only single label between the edge a and b, then
1056         // we can retrieve what that is without going to the database
1057         // from using the edge rules json and get the edge rule out of it
1058         EdgeRuleQuery.Builder queryBuilder = new EdgeRuleQuery.Builder(aNodeType);
1059         for (Vertex cousin : cousins) {
1060             VertexProperty vertexProperty = cousin.property("aai-node-type");
1061             String bNodeType = null;
1062             if(vertexProperty.isPresent()){
1063                 bNodeType = cousin.property("aai-node-type").value().toString();
1064             } else {
1065                 // If the vertex is missing the aai-node-type
1066                 // Then its either a bad vertex or its in the process
1067                 // of getting deleted so we should ignore these vertexes
1068                 if(LOGGER.isDebugEnabled()){
1069                     LOGGER.debug("For the vertex {}, unable to retrieve the aai-node-type", v.id().toString());
1070                 } else {
1071                     LOGGER.info("Unable to retrieve the aai-node-type for vertex, for more info enable debug log");
1072                 }
1073                 continue;
1074             }
1075             if (obj.getVersion().compareTo(schemaVersions.getEdgeLabelVersion()) >= 0) {
1076                 String edgeKey = alphabetizer.buildAlphabetizedKey(aNodeType, bNodeType);
1077                 if(keysWithMultipleLabels.contains(edgeKey)){
1078                     List<String> edgeLabels = this.getEdgeLabelsBetween(EdgeType.COUSIN, v, cousin);
1079                     for(String edgeLabel: edgeLabels){
1080                         Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty("relationship");
1081                         Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp, edgeLabel);
1082                         if (result != null) {
1083                             relationshipObjList.add(result);
1084                         }
1085                     }
1086                 } else {
1087
1088                     EdgeRule edgeRule = null;
1089
1090                     // Create a query based on the a nodetype and b nodetype
1091                     // which is also a cousin edge and ensure the version
1092                     // is used properly so for example in order to be backwards
1093                     // compatible if we had allowed a edge between a and b
1094                     // in a previous release and we decided to remove it from
1095                     // the edge rules in the future we can display the edge
1096                     // only for the older apis and the new apis if the edge rule
1097                     // is removed will not be seen in the newer version of the API
1098
1099                     EdgeRuleQuery ruleQuery = queryBuilder
1100                         .to(bNodeType)
1101                         .edgeType(EdgeType.COUSIN)
1102                         .version(obj.getVersion())
1103                         .build();
1104
1105                     try {
1106                         edgeRule = edgeIngestor.getRule(ruleQuery);
1107                     } catch (EdgeRuleNotFoundException e) {
1108                         LOGGER.warn("Caught an edge rule not found exception for query {}, {}," +
1109                             " it could be the edge rule is no longer valid for the existing edge in db",
1110                             ruleQuery, LogFormatTools.getStackTop(e));
1111                         continue;
1112                     } catch (AmbiguousRuleChoiceException e) {
1113                         LOGGER.error("Caught an ambiguous rule not found exception for query {}, {}",
1114                             ruleQuery, LogFormatTools.getStackTop(e));
1115                         continue;
1116                     }
1117
1118                     Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty("relationship");
1119                     Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp,edgeRule.getLabel());
1120                     if (result != null) {
1121                         relationshipObjList.add(result);
1122                     }
1123                 }
1124             } else {
1125                 Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty("relationship");
1126                 Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp, null);
1127                 if (result != null) {
1128                     relationshipObjList.add(result);
1129                 }
1130             }
1131
1132         }
1133
1134         if (relationshipObjList.isEmpty()) {
1135             return null;
1136         } else {
1137             return obj;
1138         }
1139     }
1140
1141     /**
1142      * Process edge relationship.
1143      *
1144      * @param relationshipObj the relationship obj
1145      * @param edge            the edge
1146      * @param cleanUp         the clean up
1147      * @return the object
1148      * @throws InstantiationException       the instantiation exception
1149      * @throws IllegalAccessException       the illegal access exception
1150      * @throws IllegalArgumentException     the illegal argument exception
1151      * @throws InvocationTargetException    the invocation target exception
1152      * @throws NoSuchMethodException        the no such method exception
1153      * @throws SecurityException            the security exception
1154      * @throws UnsupportedEncodingException the unsupported encoding exception
1155      * @throws AAIException                 the AAI exception
1156      * @throws MalformedURLException        the malformed URL exception
1157      * @throws AAIUnknownObjectException
1158      * @throws URISyntaxException
1159      */
1160     private Object processEdgeRelationship(Introspector relationshipObj, Vertex cousin, String cleanUp, String edgeLabel) throws UnsupportedEncodingException, AAIUnknownObjectException {
1161
1162         VertexProperty aaiUriProperty = cousin.property("aai-uri");
1163
1164         if(!aaiUriProperty.isPresent()){
1165             return null;
1166         }
1167
1168         URI uri = UriBuilder.fromUri(aaiUriProperty.value().toString()).build();
1169
1170         URIToRelationshipObject uriParser = null;
1171         Introspector result = null;
1172         try {
1173             uriParser = new URIToRelationshipObject(relationshipObj.getLoader(), uri, this.baseURL);
1174             result = uriParser.getResult();
1175         } catch (AAIException | URISyntaxException e) {
1176             LOGGER.error("Error while processing edge relationship in version " + relationshipObj.getVersion() + " (bad vertex ID=" + ": "
1177                 + e.getMessage() + " " + LogFormatTools.getStackTop(e));
1178             return null;
1179         }
1180
1181         VertexProperty cousinVertexNodeType = cousin.property(AAIProperties.NODE_TYPE);
1182
1183         if(cousinVertexNodeType.isPresent()){
1184             if(namedPropNodes.contains(cousinVertexNodeType.value().toString())){
1185                 Introspector cousinObj = loader.introspectorFromName(cousinVertexNodeType.value().toString());
1186                 this.simpleDbToObject(cousinObj, cousin);
1187                 this.addRelatedToProperty(result, cousinObj);
1188             }
1189         }
1190
1191         if (edgeLabel != null && result.hasProperty("relationship-label")) {
1192             result.setValue("relationship-label", edgeLabel);
1193         }
1194
1195         return result.getUnderlyingObject();
1196     }
1197
1198     /**
1199      * Gets the URI for vertex.
1200      *
1201      * @param v the v
1202      * @return the URI for vertex
1203      * @throws InstantiationException       the instantiation exception
1204      * @throws IllegalAccessException       the illegal access exception
1205      * @throws IllegalArgumentException     the illegal argument exception
1206      * @throws InvocationTargetException    the invocation target exception
1207      * @throws NoSuchMethodException        the no such method exception
1208      * @throws SecurityException            the security exception
1209      * @throws UnsupportedEncodingException the unsupported encoding exception
1210      * @throws AAIUnknownObjectException
1211      */
1212     public URI getURIForVertex(Vertex v) throws UnsupportedEncodingException {
1213
1214         return getURIForVertex(v, false);
1215     }
1216
1217     public URI getURIForVertex(Vertex v, boolean overwrite) throws UnsupportedEncodingException {
1218         URI uri = UriBuilder.fromPath("/unknown-uri").build();
1219
1220         String aaiUri = v.<String>property(AAIProperties.AAI_URI).orElse(null);
1221
1222         if (aaiUri != null && !overwrite) {
1223             uri = UriBuilder.fromPath(aaiUri).build();
1224         }
1225
1226         return uri;
1227     }
1228
1229     /**
1230      * Gets the URI from list.
1231      *
1232      * @param list the list
1233      * @return the URI from list
1234      * @throws UnsupportedEncodingException the unsupported encoding exception
1235      */
1236     private URI getURIFromList(List<Introspector> list) throws UnsupportedEncodingException {
1237         String uri = "";
1238         StringBuilder sb = new StringBuilder();
1239         for (Introspector i : list) {
1240             sb.insert(0, i.getURI());
1241         }
1242
1243         uri = sb.toString();
1244         return UriBuilder.fromPath(uri).build();
1245     }
1246
1247     /**
1248      * Adds the r
1249      *
1250      * @param relationship the relationship
1251      * @param child        the throws IllegalArgumentException, AAIUnknownObjectException child
1252      * @throws AAIUnknownObjectException
1253      * @throws IllegalArgumentException  elated to property.
1254      */
1255     public void addRelatedToProperty(Introspector relationship, Introspector child) throws AAIUnknownObjectException {
1256         String nameProps = child.getMetadata(ObjectMetadata.NAME_PROPS);
1257         List<Introspector> relatedToProperties = new ArrayList<>();
1258
1259         if (nameProps != null) {
1260             String[] props = nameProps.split(",");
1261             for (String prop : props) {
1262                 Introspector relatedTo = relationship.newIntrospectorInstanceOfNestedProperty("related-to-property");
1263                 relatedTo.setValue("property-key", child.getDbName() + "." + prop);
1264                 relatedTo.setValue("property-value", child.getValue(prop));
1265                 relatedToProperties.add(relatedTo);
1266             }
1267         }
1268
1269         if (!relatedToProperties.isEmpty()) {
1270             List relatedToList = (List) relationship.getValue("related-to-property");
1271             for (Introspector obj : relatedToProperties) {
1272                 relatedToList.add(obj.getUnderlyingObject());
1273             }
1274         }
1275
1276     }
1277
1278     /**
1279      * Creates the edge.
1280      *
1281      * @param relationship the relationship
1282      * @param inputVertex  the input vertex
1283      * @return true, if successful
1284      * @throws UnsupportedEncodingException the unsupported encoding exception
1285      * @throws AAIException                 the AAI exception
1286      */
1287     public boolean createEdge(Introspector relationship, Vertex inputVertex) throws UnsupportedEncodingException, AAIException {
1288
1289         Vertex relatedVertex = null;
1290         StopWatch.conditionalStart();
1291         QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(relationship);
1292
1293         String label = null;
1294         if (relationship.hasProperty("relationship-label")) {
1295             label = relationship.getValue("relationship-label");
1296         }
1297
1298         List<Vertex> results = parser.getQueryBuilder().toList();
1299         if (results.isEmpty()) {
1300             dbTimeMsecs += StopWatch.stopIfStarted();
1301             AAIException e = new AAIException("AAI_6129", "Node of type " + parser.getResultType() + ". Could not find object at: " + parser.getUri());
1302             e.getTemplateVars().add(parser.getResultType());
1303             e.getTemplateVars().add(parser.getUri().toString());
1304             throw e;
1305         } else {
1306             //still an issue if there's more than one
1307             relatedVertex = results.get(0);
1308         }
1309
1310         if (relatedVertex != null) {
1311
1312             Edge e;
1313             try {
1314                 e = this.getEdgeBetween(EdgeType.COUSIN, inputVertex, relatedVertex, label);
1315                 if (e == null) {
1316                     edgeSer.addEdge(this.engine.asAdmin().getTraversalSource(), inputVertex, relatedVertex, label);
1317                 } else {
1318                     //attempted to link two vertexes already linked
1319                 }
1320             } finally {
1321                 dbTimeMsecs += StopWatch.stopIfStarted();
1322             }
1323         }
1324
1325         dbTimeMsecs += StopWatch.stopIfStarted();
1326         return true;
1327     }
1328
1329     /**
1330      * Gets all the edges between of the type with the specified label.
1331      *
1332      * @param aVertex the out vertex
1333      * @param bVertex the in vertex
1334      * @return the edges between
1335      * @throws AAIException             the AAI exception
1336      * @throws NoEdgeRuleFoundException
1337      */
1338     private Edge getEdgeBetweenWithLabel(EdgeType type, Vertex aVertex, Vertex bVertex, EdgeRule edgeRule) {
1339
1340         Edge result = null;
1341
1342         if (bVertex != null) {
1343             GraphTraversal<Vertex, Edge> findEdgesBetween = null;
1344             if (EdgeType.TREE.equals(type)) {
1345                 GraphTraversal<Vertex,Vertex> findVertex = this.engine.asAdmin().getTraversalSource().V(bVertex);
1346                 if(edgeRule.getDirection().equals(Direction.IN)){
1347                     findEdgesBetween = findVertex.outE(edgeRule.getLabel())
1348                         .has(EdgeProperty.CONTAINS.toString(), edgeRule.getContains())
1349                         .not(
1350                             __.has(EdgeField.PRIVATE.toString(), true)
1351                         );
1352                 } else {
1353                     findEdgesBetween = findVertex.inE(edgeRule.getLabel())
1354                         .has(EdgeProperty.CONTAINS.toString(), edgeRule.getContains())
1355                         .not(
1356                             __.has(EdgeField.PRIVATE.toString(), true)
1357                         );
1358                 }
1359                 findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(aVertex.id())).limit(1);
1360             } else {
1361                 findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE(edgeRule.getLabel());
1362                 findEdgesBetween = findEdgesBetween
1363                     .has(EdgeProperty.CONTAINS.toString(), "NONE")
1364                     .not(
1365                         __.has(EdgeField.PRIVATE.toString(), true)
1366                     );
1367                 findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id())).limit(1);
1368             }
1369             List<Edge> list = findEdgesBetween.toList();
1370             if(!list.isEmpty()){
1371                 result = list.get(0);
1372             }
1373         }
1374
1375         return result;
1376     }
1377
1378     /**
1379      * Gets all the edges between of the type.
1380      *
1381      * @param aVertex the out vertex
1382      * @param bVertex the in vertex
1383      * @return the edges between
1384      * @throws AAIException             the AAI exception
1385      * @throws NoEdgeRuleFoundException
1386      */
1387     private List<Edge> getEdgesBetween(EdgeType type, Vertex aVertex, Vertex bVertex) {
1388
1389         List<Edge> result = new ArrayList<>();
1390
1391         if (bVertex != null) {
1392             GraphTraversal<Vertex, Edge> findEdgesBetween = null;
1393             findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE();
1394             if (EdgeType.TREE.equals(type)) {
1395                 findEdgesBetween = findEdgesBetween
1396                     .not(
1397                         __.or(
1398                             __.has(EdgeProperty.CONTAINS.toString(), "NONE"),
1399                             __.has(EdgeField.PRIVATE.toString(), true)
1400                         )
1401                     );
1402             } else {
1403                 findEdgesBetween = findEdgesBetween
1404                     .has(EdgeProperty.CONTAINS.toString(), "NONE")
1405                     .not(
1406                         __.has(EdgeField.PRIVATE.toString(), true)
1407                     );
1408             }
1409             findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id()));
1410             result = findEdgesBetween.toList();
1411         }
1412
1413         return result;
1414     }
1415
1416     /**
1417      * Gets all the edges string between of the type.
1418      *
1419      * @param aVertex the out vertex
1420      * @param bVertex the in vertex
1421      * @return the edges between
1422      * @throws AAIException the AAI exception
1423      * @throws NoEdgeRuleFoundException
1424      */
1425     private List<String> getEdgeLabelsBetween(EdgeType type, Vertex aVertex, Vertex bVertex) {
1426
1427         List<String> result = new ArrayList<>();
1428
1429         if (bVertex != null) {
1430             GraphTraversal<Vertex, Edge> findEdgesBetween = null;
1431             findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE();
1432             if (EdgeType.TREE.equals(type)) {
1433                 findEdgesBetween = findEdgesBetween
1434                         .not(
1435                                 __.or(
1436                                         __.has(EdgeProperty.CONTAINS.toString(), "NONE"),
1437                                         __.has(EdgeField.PRIVATE.toString(), true)
1438                                 )
1439                         );
1440             } else {
1441                 findEdgesBetween = findEdgesBetween
1442                         .has(EdgeProperty.CONTAINS.toString(), "NONE")
1443                         .not(
1444                                 __.has(EdgeField.PRIVATE.toString(), true)
1445                         );
1446             }
1447             findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id()));
1448             result = findEdgesBetween.label().toList();
1449         }
1450         return result;
1451     }
1452
1453     /**
1454      * Gets all the edges string between of the type.
1455      *
1456      * @param aVertex the out vertex
1457      * @param bVertex the in vertex
1458      * @return the edges between
1459      * @throws AAIException the AAI exception
1460      * @throws NoEdgeRuleFoundException
1461      */
1462     private Long getEdgeLabelsCount(Vertex aVertex, Vertex bVertex) {
1463
1464         Long result = null;
1465
1466         if (bVertex != null) {
1467             GraphTraversal<Vertex, Edge> findEdgesBetween = null;
1468             findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE();
1469             findEdgesBetween = findEdgesBetween
1470                     .has(EdgeProperty.CONTAINS.toString(), "NONE")
1471                     .not(
1472                             __.has(EdgeField.PRIVATE.toString(), true)
1473                     );
1474             findEdgesBetween = findEdgesBetween.filter(__.otherV().hasId(bVertex.id()));
1475             result = findEdgesBetween.count().next();
1476         }
1477         return result;
1478     }
1479     /**
1480      * Gets all the edges between the vertexes with the label and type.
1481      *
1482      * @param aVertex the out vertex
1483      * @param bVertex the in vertex
1484      * @param label
1485      * @return the edges between
1486      * @throws AAIException the AAI exception
1487      */
1488     private Edge getEdgesBetween(EdgeType type, Vertex aVertex, Vertex bVertex, String label) throws AAIException {
1489
1490         Edge edge = null;
1491
1492         if (bVertex != null) {
1493             String aType = aVertex.<String>property(AAIProperties.NODE_TYPE).value();
1494             String bType = bVertex.<String>property(AAIProperties.NODE_TYPE).value();
1495             EdgeRuleQuery q = new EdgeRuleQuery.Builder(aType, bType).edgeType(type).label(label).build();
1496             EdgeRule rule;
1497             try {
1498                 rule = edgeRules.getRule(q);
1499             } catch (EdgeRuleNotFoundException e) {
1500                 throw new NoEdgeRuleFoundException(e);
1501             } catch (AmbiguousRuleChoiceException e) {
1502                 throw new MultipleEdgeRuleFoundException(e);
1503             }
1504             edge = this.getEdgeBetweenWithLabel(type, aVertex, bVertex, rule);
1505         }
1506
1507         return edge;
1508     }
1509
1510     /**
1511      * Gets the edge between with the label and edge type.
1512      *
1513      * @param aVertex the out vertex
1514      * @param bVertex the in vertex
1515      * @param label
1516      * @return the edge between
1517      * @throws AAIException             the AAI exception
1518      * @throws NoEdgeRuleFoundException
1519      */
1520     public Edge getEdgeBetween(EdgeType type, Vertex aVertex, Vertex bVertex, String label) throws AAIException {
1521
1522         StopWatch.conditionalStart();
1523         if (bVertex != null) {
1524
1525             Edge edge = this.getEdgesBetween(type, aVertex, bVertex, label);
1526             if (edge != null) {
1527                 dbTimeMsecs += StopWatch.stopIfStarted();
1528                 return edge;
1529             }
1530
1531         }
1532         dbTimeMsecs += StopWatch.stopIfStarted();
1533         return null;
1534     }
1535
1536     public Edge getEdgeBetween(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException {
1537         return this.getEdgeBetween(type, aVertex, bVertex, null);
1538     }
1539
1540
1541     /**
1542      * Delete edge.
1543      *
1544      * @param relationship the relationship
1545      * @param inputVertex  the input vertex
1546      * @return true, if successful
1547      * @throws UnsupportedEncodingException the unsupported encoding exception
1548      * @throws AAIException                 the AAI exception
1549      */
1550     public boolean deleteEdge(Introspector relationship, Vertex inputVertex) throws UnsupportedEncodingException, AAIException {
1551
1552         Vertex relatedVertex = null;
1553         StopWatch.conditionalStart();
1554         QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(relationship);
1555
1556         List<Vertex> results = parser.getQueryBuilder().toList();
1557
1558         String label = null;
1559         if (relationship.hasProperty("relationship-label")) {
1560             label = relationship.getValue("relationship-label");
1561         }
1562
1563         if (results.isEmpty()) {
1564             dbTimeMsecs += StopWatch.stopIfStarted();
1565             return false;
1566         }
1567
1568         relatedVertex = results.get(0);
1569         Edge edge;
1570         try {
1571             edge = this.getEdgeBetween(EdgeType.COUSIN, inputVertex, relatedVertex, label);
1572         } catch (NoEdgeRuleFoundException e) {
1573             dbTimeMsecs += StopWatch.stopIfStarted();
1574             throw new AAIException("AAI_6129", e);
1575         }
1576         if (edge != null) {
1577             edge.remove();
1578             dbTimeMsecs += StopWatch.stopIfStarted();
1579             return true;
1580         } else {
1581             dbTimeMsecs += StopWatch.stopIfStarted();
1582             return false;
1583         }
1584
1585     }
1586
1587     /**
1588      * Delete items with traversal.
1589      *
1590      * @param vertexes the vertexes
1591      * @throws IllegalStateException the illegal state exception
1592      */
1593     public void deleteItemsWithTraversal(List<Vertex> vertexes) throws IllegalStateException {
1594
1595         for (Vertex v : vertexes) {
1596             LOGGER.debug("About to delete the vertex with id: " + v.id());
1597             deleteWithTraversal(v);
1598         }
1599
1600     }
1601
1602     /**
1603      * Delete with traversal.
1604      *
1605      * @param startVertex the start vertex
1606      */
1607     public void deleteWithTraversal(Vertex startVertex) {
1608         StopWatch.conditionalStart();
1609         List<Vertex> results = this.engine.getQueryEngine().findDeletable(startVertex);
1610
1611         for (Vertex v : results) {
1612             LOGGER.warn("Removing vertex " + v.id().toString());
1613
1614             v.remove();
1615         }
1616         dbTimeMsecs += StopWatch.stopIfStarted();
1617     }
1618
1619     /**
1620      * Delete.
1621      *
1622      * @param v               the v
1623      * @param resourceVersion the resource version
1624      * @throws IllegalArgumentException the illegal argument exception
1625      * @throws AAIException             the AAI exception
1626      * @throws InterruptedException     the interrupted exception
1627      */
1628     public void delete(Vertex v, List<Vertex> deletableVertices, String resourceVersion, boolean enableResourceVersion) throws IllegalArgumentException, AAIException {
1629
1630         boolean result = verifyDeleteSemantics(v, resourceVersion, enableResourceVersion);
1631         /*
1632          * The reason why I want to call PreventDeleteSemantics second time is to catch the prevent-deletes in a chain
1633          * These are far-fewer than seeing a prevnt-delete on the vertex to be deleted
1634          * So its better to make these in 2 steps
1635          */
1636         if (result && !deletableVertices.isEmpty()) {
1637             result = verifyPreventDeleteSemantics(deletableVertices);
1638         }
1639         if (result) {
1640
1641             try {
1642                 deleteWithTraversal(v);
1643             } catch (IllegalStateException e) {
1644                 throw new AAIException("AAI_6110", e);
1645             }
1646
1647         }
1648
1649     }
1650
1651
1652     /**
1653      * Delete.
1654      *
1655      * @param v               the v
1656      * @param resourceVersion the resource version
1657      * @throws IllegalArgumentException the illegal argument exception
1658      * @throws AAIException             the AAI exception
1659      * @throws InterruptedException     the interrupted exception
1660      */
1661     public void delete(Vertex v, String resourceVersion, boolean enableResourceVersion) throws IllegalArgumentException, AAIException {
1662
1663         boolean result = verifyDeleteSemantics(v, resourceVersion, enableResourceVersion);
1664
1665         if (result) {
1666
1667             try {
1668                 deleteWithTraversal(v);
1669             } catch (IllegalStateException e) {
1670                 throw new AAIException("AAI_6110", e);
1671             }
1672
1673         }
1674
1675     }
1676
1677     /**
1678      * Verify delete semantics.
1679      *
1680      * @param vertex          the vertex
1681      * @param resourceVersion the resource version
1682      * @return true, if successful
1683      * @throws AAIException the AAI exception
1684      */
1685     private boolean verifyDeleteSemantics(Vertex vertex, String resourceVersion, boolean enableResourceVersion) throws AAIException {
1686         boolean result = true;
1687         String nodeType = "";
1688         String errorDetail = " unknown delete semantic found";
1689         String aaiExceptionCode = "";
1690         nodeType = vertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
1691         if (enableResourceVersion && !this.verifyResourceVersion("delete", nodeType, vertex.<String>property(AAIProperties.RESOURCE_VERSION).orElse(null), resourceVersion, nodeType)) {
1692         }
1693         List<Vertex> vertices = new ArrayList<Vertex>();
1694         vertices.add(vertex);
1695         result = verifyPreventDeleteSemantics(vertices);
1696
1697         return result;
1698     }
1699
1700     /**
1701      * Verify Prevent delete semantics.
1702      *
1703      * @param vertices the list of vertices
1704      * @return true, if successful
1705      * @throws AAIException the AAI exception
1706      */
1707     private boolean verifyPreventDeleteSemantics(List<Vertex> vertices) throws AAIException {
1708         boolean result = true;
1709         String nodeType = "";
1710         String errorDetail = " unknown delete semantic found";
1711         String aaiExceptionCode = "";
1712
1713         StopWatch.conditionalStart();
1714         /*
1715          * This takes in all the vertices in a cascade-delete-chain and checks if there is any edge with a "prevent-delete" condition
1716          * If yes - that should prevent the deletion of the vertex
1717          * Dedup makes sure we dont capture the prevent-delete vertices twice
1718          * The prevent-delete vertices are stored so that the error message displays what prevents the delete
1719          */
1720
1721         List<Object> preventDeleteVertices = this.engine.asAdmin().getReadOnlyTraversalSource().V(vertices).
1722             union(__.inE().has(EdgeProperty.PREVENT_DELETE.toString(), AAIDirection.IN.toString()).outV().values(AAIProperties.NODE_TYPE),
1723                 __.outE().has(EdgeProperty.PREVENT_DELETE.toString(), AAIDirection.OUT.toString()).inV().values(AAIProperties.NODE_TYPE))
1724             .dedup().toList();
1725
1726         dbTimeMsecs += StopWatch.stopIfStarted();
1727         if (!preventDeleteVertices.isEmpty()) {
1728             aaiExceptionCode = "AAI_6110";
1729             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);
1730             result = false;
1731         }
1732         if (!result) {
1733             throw new AAIException(aaiExceptionCode, errorDetail);
1734         }
1735         return result;
1736     }
1737
1738     /**
1739      * Verify resource version.
1740      *
1741      * @param action the action
1742      * @param nodeType the node type
1743      * @param currentResourceVersion the current resource version
1744      * @param resourceVersion the resource version
1745      * @param uri the uri
1746      * @return true, if successful
1747      * @throws AAIException the AAI exception
1748      */
1749     public boolean verifyResourceVersion(String action, String nodeType, String currentResourceVersion, String resourceVersion, String uri) throws AAIException {
1750         String enabled = "";
1751         String errorDetail = "";
1752         String aaiExceptionCode = "";
1753         if (currentResourceVersion == null) {
1754             currentResourceVersion = "";
1755         }
1756
1757         if (resourceVersion == null) {
1758             resourceVersion = "";
1759         }
1760         try {
1761             enabled = AAIConfig.get(AAIConstants.AAI_RESVERSION_ENABLEFLAG);
1762         } catch (AAIException e) {
1763             ErrorLogHelper.logException(e);
1764         }
1765         if (enabled.equals("true")) {
1766             if (!currentResourceVersion.equals(resourceVersion)) {
1767                 if (action.equals("create") && !resourceVersion.equals("")) {
1768                     errorDetail = "resource-version passed for " + action + " of " + uri;
1769                     aaiExceptionCode = "AAI_6135";
1770                 } else if (resourceVersion.equals("")) {
1771                     errorDetail = "resource-version not passed for " + action + " of " + uri;
1772                     aaiExceptionCode = "AAI_6130";
1773                 } else {
1774                     errorDetail = "resource-version MISMATCH for " + action + " of " + uri;
1775                     aaiExceptionCode = "AAI_6131";
1776                 }
1777
1778                 throw new AAIException(aaiExceptionCode, errorDetail);
1779
1780             }
1781         }
1782         return true;
1783     }
1784
1785     /**
1786      * Convert from camel case.
1787      *
1788      * @param name the name
1789      * @return the string
1790      */
1791     private String convertFromCamelCase (String name) {
1792         String result = "";
1793         result = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, name);
1794
1795         NamingExceptions exceptions = NamingExceptions.getInstance();
1796         result = exceptions.getDBName(result);
1797
1798         return result;
1799     }
1800
1801     private boolean canModify(Introspector obj, String propName, String requestContext) {
1802         final String readOnly = obj.getPropertyMetadata(propName).get(PropertyMetadata.READ_ONLY);
1803         if (readOnly != null) {
1804             final String[] items = readOnly.split(",");
1805             for (String item : items) {
1806                 if (requestContext.equals(item)) {
1807                     return false;
1808                 }
1809             }
1810         }
1811         return true;
1812     }
1813
1814     private void executePreSideEffects(Introspector obj, Vertex self) throws AAIException {
1815
1816         SideEffectRunner runner = new SideEffectRunner
1817                 .Builder(this.engine, this).addSideEffect(DataCopy.class).addSideEffect(PrivateEdge.class).build();
1818
1819         runner.execute(obj, self);
1820     }
1821
1822     private void executePostSideEffects(Introspector obj, Vertex self) throws AAIException {
1823
1824         SideEffectRunner runner = new SideEffectRunner
1825                 .Builder(this.engine, this).addSideEffect(DataLinkWriter.class).build();
1826
1827         runner.execute(obj, self);
1828     }
1829
1830     private void enrichData(Introspector obj, Vertex self) throws AAIException  {
1831
1832         SideEffectRunner runner = new SideEffectRunner
1833                 .Builder(this.engine, this).addSideEffect(DataLinkReader.class).build();
1834
1835         runner.execute(obj, self);
1836     }
1837
1838     public double getDBTimeMsecs() {
1839         return (dbTimeMsecs);
1840     }
1841
1842     /**
1843      * Db to object With Filters
1844      * This is for a one-time run with Tenant Isloation to only filter relationships
1845      * TODO: Chnage the original dbToObject to take filter parent/cousins
1846      *
1847      * @param obj               the obj
1848      * @param v                 the vertex from the graph
1849      * @param depth             the depth
1850      * @param nodeOnly          specify if to exclude relationships or not
1851      * @param filterCousinNodes
1852      * @return the introspector
1853      * @throws AAIException                 the AAI exception
1854      * @throws IllegalAccessException       the illegal access exception
1855      * @throws IllegalArgumentException     the illegal argument exception
1856      * @throws InvocationTargetException    the invocation target exception
1857      * @throws SecurityException            the security exception
1858      * @throws InstantiationException       the instantiation exception
1859      * @throws NoSuchMethodException        the no such method exception
1860      * @throws UnsupportedEncodingException the unsupported encoding exception
1861      * @throws MalformedURLException        the malformed URL exception
1862      * @throws AAIUnknownObjectException
1863      * @throws URISyntaxException
1864      */
1865     //TODO - See if you can merge the 2 dbToObjectWithFilters
1866     public Introspector dbToObjectWithFilters(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly, List<String> filterCousinNodes, List<String> filterParentNodes) throws AAIException, UnsupportedEncodingException {
1867         String cleanUp = "false";
1868         if (depth < 0) {
1869             return null;
1870         }
1871         depth--;
1872         seen.add(v);
1873         boolean modified = false;
1874         for (String property : obj.getProperties(PropertyPredicates.isVisible())) {
1875             List<Object> getList = null;
1876             Vertex[] vertices = null;
1877
1878             if (!(obj.isComplexType(property) || obj.isListType(property))) {
1879                 this.copySimpleProperty(property, obj, v);
1880                 modified = true;
1881             } else {
1882                 if (obj.isComplexType(property)) {
1883                     /* container case */
1884
1885                     if (!property.equals("relationship-list") && depth >= 0) {
1886                         Introspector argumentObject = obj.newIntrospectorInstanceOfProperty(property);
1887                         Object result = dbToObjectWithFilters(argumentObject, v, seen, depth + 1, nodeOnly, filterCousinNodes, filterParentNodes);
1888                         if (result != null) {
1889                             obj.setValue(property, argumentObject.getUnderlyingObject());
1890                             modified = true;
1891                         }
1892                     } else if (property.equals("relationship-list") && !nodeOnly) {
1893                         /* relationships need to be handled correctly */
1894                         Introspector relationshipList = obj.newIntrospectorInstanceOfProperty(property);
1895                         relationshipList = createFilteredRelationshipList(v, relationshipList, cleanUp, filterCousinNodes);
1896                         if (relationshipList != null) {
1897                             modified = true;
1898                             obj.setValue(property, relationshipList.getUnderlyingObject());
1899                             modified = true;
1900                         }
1901
1902                     }
1903                 } else if (obj.isListType(property)) {
1904
1905                     if (property.equals("any")) {
1906                         continue;
1907                     }
1908                     String genericType = obj.getGenericTypeClass(property).getSimpleName();
1909                     if (obj.isComplexGenericType(property) && depth >= 0) {
1910                         final String childDbName = convertFromCamelCase(genericType);
1911                         String vType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null);
1912                         EdgeRule rule;
1913
1914                         boolean isthisParentRequired = filterParentNodes.parallelStream().anyMatch(childDbName::contains);
1915
1916                         EdgeRuleQuery q = new EdgeRuleQuery.Builder(vType, childDbName).edgeType(EdgeType.TREE).build();
1917
1918                         try {
1919                             rule = edgeRules.getRule(q);
1920                         } catch (EdgeRuleNotFoundException e) {
1921                             throw new NoEdgeRuleFoundException(e);
1922                         } catch (AmbiguousRuleChoiceException e) {
1923                             throw new MultipleEdgeRuleFoundException(e);
1924                         }
1925                         if (!rule.getContains().equals(AAIDirection.NONE.toString()) && isthisParentRequired) {
1926                             //vertices = this.queryEngine.findRelatedVertices(v, Direction.OUT, rule.getLabel(), childDbName);
1927                             Direction ruleDirection = rule.getDirection();
1928                             Iterator<Vertex> itr = v.vertices(ruleDirection, rule.getLabel());
1929                             List<Vertex> verticesList = (List<Vertex>) IteratorUtils.toList(itr);
1930                             itr = verticesList.stream().filter(item -> {
1931                                 return item.property(AAIProperties.NODE_TYPE).orElse("").equals(childDbName);
1932                             }).iterator();
1933                             if (itr.hasNext()) {
1934                                 getList = (List<Object>) obj.getValue(property);
1935                             }
1936                             int processed = 0;
1937                             int removed = 0;
1938                             while (itr.hasNext()) {
1939                                 Vertex childVertex = itr.next();
1940                                 if (!seen.contains(childVertex)) {
1941                                     Introspector argumentObject = obj.newIntrospectorInstanceOfNestedProperty(property);
1942
1943                                     Object result = dbToObjectWithFilters(argumentObject, childVertex, seen, depth, nodeOnly, filterCousinNodes, filterParentNodes);
1944                                     if (result != null) {
1945                                         getList.add(argumentObject.getUnderlyingObject());
1946                                     }
1947
1948                                     processed++;
1949                                 } else {
1950                                     removed++;
1951                                     LOGGER.warn("Cycle found while serializing vertex id={}", childVertex.id().toString());
1952                                 }
1953                             }
1954                             if (processed == 0) {
1955                                 //vertices were all seen, reset the list
1956                                 getList = null;
1957                             }
1958                             if (processed > 0) {
1959                                 modified = true;
1960                             }
1961                         }
1962                     } else if (obj.isSimpleGenericType(property)) {
1963                         List<Object> temp = this.engine.getListProperty(v, property);
1964                         if (temp != null) {
1965                             getList = (List<Object>) obj.getValue(property);
1966                             getList.addAll(temp);
1967                             modified = true;
1968                         }
1969
1970                     }
1971
1972                 }
1973
1974             }
1975         }
1976
1977         //no changes were made to this obj, discard the instance
1978         if (!modified) {
1979             return null;
1980         }
1981         this.enrichData(obj, v);
1982         return obj;
1983
1984     }
1985
1986     /**
1987      * Creates the relationship list with the filtered node types.
1988      *
1989      * @param v       the v
1990      * @param obj     the obj
1991      * @param cleanUp the clean up
1992      * @return the object
1993      * @throws InstantiationException       the instantiation exception
1994      * @throws IllegalAccessException       the illegal access exception
1995      * @throws IllegalArgumentException     the illegal argument exception
1996      * @throws InvocationTargetException    the invocation target exception
1997      * @throws NoSuchMethodException        the no such method exception
1998      * @throws SecurityException            the security exception
1999      * @throws UnsupportedEncodingException the unsupported encoding exception
2000      * @throws AAIException                 the AAI exception
2001      * @throws MalformedURLException        the malformed URL exception
2002      * @throws URISyntaxException
2003      */
2004     private Introspector createFilteredRelationshipList(Vertex v, Introspector obj, String cleanUp, List<String> filterNodes) throws UnsupportedEncodingException, AAIException {
2005         List<Vertex> allCousins = this.engine.getQueryEngine().findCousinVertices(v);
2006
2007         Iterator<Vertex> cousinVertices = allCousins.stream().filter(item -> {
2008             String node = (String) item.property(AAIProperties.NODE_TYPE).orElse("");
2009             return filterNodes.parallelStream().anyMatch(node::contains);
2010         }).iterator();
2011
2012
2013         List<Vertex> cousins = (List<Vertex>) IteratorUtils.toList(cousinVertices);
2014
2015         //items.parallelStream().anyMatch(inputStr::contains)
2016         List<Object> relationshipObjList = obj.getValue("relationship");
2017         for (Vertex cousin : cousins) {
2018
2019             Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty("relationship");
2020             Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp, null);
2021             if (result != null) {
2022                 relationshipObjList.add(result);
2023             }
2024
2025
2026         }
2027
2028         if (relationshipObjList.isEmpty()) {
2029             return null;
2030         } else {
2031             return obj;
2032         }
2033     }
2034
2035 }