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