e012aef3735f3f9c981cbbe026417c3c8223f850
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / serialization / engines / query / GraphTraversalQueryEngine.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
21 package org.onap.aai.serialization.engines.query;
22
23 import static org.onap.aai.edges.enums.AAIDirection.IN;
24 import static org.onap.aai.edges.enums.AAIDirection.NONE;
25 import static org.onap.aai.edges.enums.AAIDirection.OUT;
26 import static org.onap.aai.edges.enums.EdgeField.PRIVATE;
27 import static org.onap.aai.edges.enums.EdgeProperty.CONTAINS;
28 import static org.onap.aai.edges.enums.EdgeProperty.DELETE_OTHER_V;
29
30 import java.util.List;
31 import java.util.Set;
32
33 import org.apache.tinkerpop.gremlin.process.traversal.Order;
34 import org.apache.tinkerpop.gremlin.process.traversal.P;
35 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
36 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
37 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
38 import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
39 import org.apache.tinkerpop.gremlin.structure.Direction;
40 import org.apache.tinkerpop.gremlin.structure.Edge;
41 import org.apache.tinkerpop.gremlin.structure.Element;
42 import org.apache.tinkerpop.gremlin.structure.Vertex;
43 import org.onap.aai.db.props.AAIProperties;
44 import org.onap.aai.introspection.Loader;
45 import org.onap.aai.logging.StopWatch;
46
47 /*
48  * This class needs some big explanation despite its compact size.
49  * This controls all the queries performed by the CRUD API in A&AI.
50  * findParents, findChildren, and findDeletable require special attention
51  *   These methods use 'repeat'. You cannot use 'emit' with repeat currently
52  *   as it is extremely buggy as of tinkerpop-3.0.1-incubating. The way around
53  *   it (for now) is to sideEffect all the vertices we traverse into an ArrayList.
54  *
55  */
56 public class GraphTraversalQueryEngine extends QueryEngine {
57
58     /**
59      * Instantiates a new graph traversal query engine.
60      *
61      * @param g graph traversal source to traverse the graph
62      */
63     public GraphTraversalQueryEngine(GraphTraversalSource g) {
64         super(g);
65     }
66
67     /**
68      * {@inheritDoc}
69      */
70     @Override
71     public List<Vertex> findParents(Vertex start) {
72         try {
73             StopWatch.conditionalStart();
74
75             @SuppressWarnings("unchecked")
76             final GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).emit(v -> true)
77                     .repeat(__.union(__.inE().has(CONTAINS.toString(), OUT.toString()).outV(),
78                             __.outE().has(CONTAINS.toString(), IN.toString()).inV()));
79             return pipe.toList();
80         } finally {
81             dbTimeMsecs += StopWatch.stopIfStarted();
82         }
83     }
84
85     /**
86      * {@inheritDoc}
87      */
88     @Override
89     public List<Vertex> findParents(String[] uris) {
90         try {
91             StopWatch.conditionalStart();
92             final GraphTraversal<Vertex, Vertex> pipe =
93                     this.g.V().has(AAIProperties.AAI_URI, P.within(uris)).order().by(AAIProperties.AAI_URI, Order.decr);
94             return pipe.toList();
95         } finally {
96             dbTimeMsecs += StopWatch.stopIfStarted();
97         }
98     }
99
100     /**
101      * {@inheritDoc}
102      */
103     @Override
104     public List<Vertex> findAllChildren(Vertex start) {
105
106         @SuppressWarnings("unchecked")
107         GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).emit(v -> true)
108                 .repeat(__.union(__.outE().has(CONTAINS.toString(), OUT.toString()).inV(),
109                         __.inE().has(CONTAINS.toString(), IN.toString()).outV()));
110
111         return pipe.toList();
112
113     }
114
115     /**
116      * {@inheritDoc}
117      */
118     @Override
119     public List<Vertex> findChildrenOfType(Vertex start, String type) {
120         @SuppressWarnings("unchecked")
121         GraphTraversal<Vertex, Vertex> pipe = this.g.V(start)
122                 .union(__.outE().has(CONTAINS.toString(), OUT.toString()).inV(),
123                         __.inE().has(CONTAINS.toString(), IN.toString()).outV())
124                 .has(AAIProperties.NODE_TYPE, type).dedup();
125
126         return pipe.toList();
127     }
128
129     /**
130      * {@inheritDoc}
131      */
132     @Override
133     public List<Vertex> findChildren(Vertex start) {
134         @SuppressWarnings("unchecked")
135         GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).union(__.outE().has(CONTAINS.toString(), OUT.toString()),
136                 __.inE().has(CONTAINS.toString(), IN.toString())).otherV().dedup();
137
138         return pipe.toList();
139     }
140
141     /**
142      * {@inheritDoc}
143      */
144     @Override
145     public List<Vertex> findDeletable(Vertex start) {
146         try {
147             StopWatch.conditionalStart();
148             @SuppressWarnings("unchecked")
149             GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).emit(v -> true)
150                     .repeat(__.union(__.outE().has(DELETE_OTHER_V.toString(), OUT.toString()).inV(),
151                             __.inE().has(DELETE_OTHER_V.toString(), IN.toString()).outV()))
152                     .dedup();
153
154             return pipe.toList();
155         } finally {
156             dbTimeMsecs += StopWatch.stopIfStarted();
157         }
158     }
159
160     /**
161      * {@inheritDoc}
162      */
163     @Override
164     public List<Vertex> findDeletable(List<Vertex> startVertexes) {
165         try {
166             StopWatch.conditionalStart();
167             Vertex[] vertices = new Vertex[startVertexes.size()];
168             vertices = startVertexes.toArray(vertices);
169             GraphTraversal<Vertex, Vertex> pipe = this.g.V(vertices).emit(v -> true)
170                     .repeat(__.union(__.outE().has(DELETE_OTHER_V.toString(), OUT.toString()).inV(),
171                             __.inE().has(DELETE_OTHER_V.toString(), IN.toString()).outV()))
172                     .dedup();
173
174             return pipe.toList();
175         } finally {
176             dbTimeMsecs += StopWatch.stopIfStarted();
177         }
178     }
179
180     /**
181      * {@inheritDoc}
182      */
183     @Override
184     public List<Vertex> findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) {
185         GraphTraversal<Vertex, Vertex> pipe = this.g.V(start);
186         switch (direction) {
187             case OUT:
188                 pipe.out(label);
189                 break;
190             case IN:
191                 pipe.in(label);
192                 break;
193             case BOTH:
194                 pipe.both(label);
195                 break;
196             default:
197                 break;
198         }
199
200         pipe.has(AAIProperties.NODE_TYPE, nodeType).dedup();
201         return pipe.toList();
202     }
203
204     @Override
205     public Tree<Element> findSubGraph(Vertex start, int iterations, boolean nodeOnly) {
206         final GraphTraversal<Vertex, ?> t = this.g.V(start).emit(v -> true).times(iterations)
207                 .repeat(__.union(__.outE().has(CONTAINS.toString(), OUT.toString()).inV(),
208                         __.inE().has(CONTAINS.toString(), IN.toString()).outV()));
209
210         if (!nodeOnly) {
211             t.union(__.identity(), __.bothE().has(CONTAINS.toString(), NONE.toString()).dedup().otherV());
212         }
213         t.tree();
214         if (t.hasNext()) {
215             return (Tree) t.next();
216         } else {
217             return new Tree();
218         }
219     }
220
221     @Override
222     public List<Edge> findEdgesForVersion(Vertex start, Loader loader) {
223         // From the given start vertex find both the
224         // out edges that has property CONTAINS set to NONE
225         // whose in vertexes has an object that is declared in the oxm
226         // And do the same thing vice versa to get a list of edges
227         // Then check that the edge should not have the property private set to true
228         // and remove the duplicates and return the list of edges
229         final Set<String> objects = loader.getAllObjects().keySet();
230         GraphTraversal<Vertex, Edge> pipeline = this.g.V(start)
231                 .union(__.inE().has(CONTAINS.toString(), NONE.toString())
232                         .where(__.outV().has(AAIProperties.NODE_TYPE, P.within(objects))),
233                         __.outE().has(CONTAINS.toString(), NONE.toString())
234                                 .where(__.inV().has(AAIProperties.NODE_TYPE, P.within(objects))))
235                 .not(__.has("private", true)).dedup();
236
237         return pipeline.toList();
238     }
239
240     @Override
241     public List<Vertex> findCousinVertices(Vertex start, String... labels) {
242         // Start at the given vertex
243         // Do a union to copy the start vertex to be run against all
244         // so for the start vertex it gets all of in edges that contains other v set to none
245         // and also all the other out edges with contains other v set to none
246         // And filter the edges based on the property private not set
247         // so that means it will be a regular edge
248         // and find the other end of the vertex so if setup like this:
249         // v2 -> e1 -> v3
250         // It will return v3
251         GraphTraversal<Vertex, Vertex> pipeline = this.g.V(start)
252                 .union(__.inE(labels).has(CONTAINS.toString(), NONE.toString()),
253                         __.outE(labels).has(CONTAINS.toString(), NONE.toString()))
254                 .not(__.has(PRIVATE.toString(), true)).otherV().dedup();
255
256         return pipeline.toList();
257     }
258
259     public double getDBTimeMsecs() {
260         return (dbTimeMsecs);
261     }
262 }