2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
20 package org.onap.aai.query.builder;
22 import org.apache.tinkerpop.gremlin.process.traversal.P;
23 import org.apache.tinkerpop.gremlin.process.traversal.Path;
24 import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
25 import org.apache.tinkerpop.gremlin.process.traversal.Traversal.Admin;
26 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
27 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
28 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
29 import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
30 import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;
31 import org.apache.tinkerpop.gremlin.structure.Direction;
32 import org.apache.tinkerpop.gremlin.structure.Edge;
33 import org.apache.tinkerpop.gremlin.structure.Vertex;
34 import org.onap.aai.db.props.AAIProperties;
35 import org.onap.aai.exceptions.AAIException;
36 import org.onap.aai.introspection.Introspector;
37 import org.onap.aai.introspection.Loader;
38 import org.onap.aai.schema.enums.ObjectMetadata;
39 import org.onap.aai.schema.enums.PropertyMetadata;
40 import org.onap.aai.edges.EdgeRule;
41 import org.onap.aai.edges.EdgeRuleQuery;
42 import org.onap.aai.edges.enums.EdgeType;
43 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
44 import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
46 import com.google.common.collect.ArrayListMultimap;
47 import com.google.common.collect.Multimap;
52 * The Class GraphTraversalBuilder.
54 public abstract class GraphTraversalBuilder<E> extends QueryBuilder<E> {
56 protected GraphTraversal<Vertex, E> traversal = null;
57 protected Admin<Vertex, E> completeTraversal = null;
60 * Instantiates a new graph traversal builder.
62 * @param loader the loader
64 public GraphTraversalBuilder(Loader loader, GraphTraversalSource source) {
65 super(loader, source);
67 traversal = (GraphTraversal<Vertex, E>) __.<E>start();
72 * Instantiates a new graph traversal builder.
74 * @param loader the loader
75 * @param start the start
77 public GraphTraversalBuilder(Loader loader, GraphTraversalSource source, Vertex start) {
78 super(loader, source, start);
80 traversal = (GraphTraversal<Vertex, E>) __.__(start);
88 public QueryBuilder<Vertex> getVerticesByProperty(String key, Object value) {
90 // correct value call because the index is registered as an Integer
91 traversal.has(key, this.correctObjectType(value));
94 return (QueryBuilder<Vertex>) this;
101 public QueryBuilder<Vertex> getVerticesByProperty(final String key, final List<?> values) {
103 //this is because the index is registered as an Integer
104 List<Object> correctedValues = new ArrayList<>();
105 for (Object item : values) {
106 correctedValues.add(this.correctObjectType(item));
109 traversal.has(key, P.within(correctedValues));
112 return (QueryBuilder<Vertex>) this;
119 public QueryBuilder<Vertex> getVerticesStartsWithProperty(String key, Object value) {
121 // correct value call because the index is registered as an Integer
122 traversal.has(key, org.janusgraph.core.attribute.Text.textPrefix(value));
125 return (QueryBuilder<Vertex>) this;
132 public QueryBuilder<Vertex> getVerticesByProperty(String key) {
136 return (QueryBuilder<Vertex>) this;
143 public QueryBuilder<Vertex> getVerticesExcludeByProperty(String key) {
145 traversal.hasNot(key);
147 return (QueryBuilder<Vertex>) this;
155 public QueryBuilder<Vertex> getVerticesExcludeByProperty(String key, Object value) {
157 // correct value call because the index is registered as an Integer
158 traversal.has(key, P.neq(this.correctObjectType(value)));
161 return (QueryBuilder<Vertex>) this;
168 public QueryBuilder<Vertex> getVerticesExcludeByProperty(final String key, final List<?> values) {
170 //this is because the index is registered as an Integer
171 List<Object> correctedValues = new ArrayList<>();
172 for (Object item : values) {
173 correctedValues.add(this.correctObjectType(item));
176 traversal.has(key, P.without(correctedValues));
179 return (QueryBuilder<Vertex>) this;
183 public QueryBuilder<Vertex> getVerticesGreaterThanProperty(final String key, Object value) {
185 traversal.has(key, P.gte(this.correctObjectType(value)));
188 return (QueryBuilder<Vertex>) this;
192 public QueryBuilder<Vertex> getVerticesLessThanProperty(final String key, Object value) {
194 traversal.has(key, P.lte(this.correctObjectType(value)));
197 return (QueryBuilder<Vertex>) this;
205 public QueryBuilder<Vertex> getChildVerticesFromParent(String parentKey, String parentValue, String childType) {
206 traversal.has(parentKey, parentValue).has(AAIProperties.NODE_TYPE, childType);
208 return (QueryBuilder<Vertex>) this;
215 public QueryBuilder<Vertex> getTypedVerticesByMap(String type, Map<String, String> map) {
217 for (Map.Entry<String, String> es : map.entrySet()) {
218 traversal.has(es.getKey(), es.getValue());
221 traversal.has(AAIProperties.NODE_TYPE, type);
223 return (QueryBuilder<Vertex>) this;
227 public QueryBuilder<Vertex> getVerticesByBooleanProperty(String key, Object value) {
229 boolean bValue = false;
231 if(value instanceof String){
232 bValue = Boolean.valueOf(value.toString());
233 } else if(value instanceof Boolean){
234 bValue = (Boolean) value;
237 traversal.has(key, bValue);
239 return (QueryBuilder<Vertex>) this;
246 public QueryBuilder<Vertex> createKeyQuery(Introspector obj) {
247 Set<String> keys = obj.getKeys();
249 for (String key : keys) {
250 val = obj.getValue(key);
251 Optional<String> metadata = obj.getPropertyMetadata(key, PropertyMetadata.DB_ALIAS);
252 if (metadata.isPresent()) {
253 //use the db name for the field rather than the object model
254 key = metadata.get();
257 //this is because the index is registered as an Integer
258 if (val.getClass().equals(Long.class)) {
259 traversal.has(key,new Integer(val.toString()));
261 traversal.has(key, val);
266 return (QueryBuilder<Vertex>) this;
270 public QueryBuilder<Vertex> exactMatchQuery(Introspector obj) {
271 this.createKeyQuery(obj);
272 allPropertiesQuery(obj);
273 this.createContainerQuery(obj);
274 return (QueryBuilder<Vertex>) this;
277 private void allPropertiesQuery(Introspector obj) {
278 Set<String> props = obj.getProperties();
279 Set<String> keys = obj.getKeys();
281 for (String prop : props) {
282 if (obj.isSimpleType(prop) && !keys.contains(prop)) {
283 val = obj.getValue(prop);
285 Optional<String> metadata = obj.getPropertyMetadata(prop, PropertyMetadata.DB_ALIAS);
286 if (metadata.isPresent()) {
287 //use the db name for the field rather than the object model
288 prop = metadata.get();
290 //this is because the index is registered as an Integer
291 if (val.getClass().equals(Long.class)) {
292 traversal.has(prop,new Integer(val.toString()));
294 traversal.has(prop, val);
307 public QueryBuilder<Vertex> createContainerQuery(Introspector obj) {
308 String type = obj.getChildDBName();
309 String abstractType = obj.getMetadata(ObjectMetadata.ABSTRACT);
310 if (abstractType != null) {
311 String[] inheritors = obj.getMetadata(ObjectMetadata.INHERITORS).split(",");
312 traversal.has(AAIProperties.NODE_TYPE, P.within(inheritors));
314 traversal.has(AAIProperties.NODE_TYPE, type);
318 return (QueryBuilder<Vertex>) this;
322 * @throws NoEdgeRuleFoundException
323 * @throws AAIException
327 public QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException {
328 createTraversal(type, parent, child, false);
329 return (QueryBuilder<Vertex>) this;
334 public QueryBuilder<Vertex> createPrivateEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException {
335 this.createTraversal(type, parent, child, true);
336 return (QueryBuilder<Vertex>) this;
339 private void createTraversal(EdgeType type, Introspector parent, Introspector child, boolean isPrivateEdge) throws AAIException {
340 String isAbstractType = parent.getMetadata(ObjectMetadata.ABSTRACT);
341 if ("true".equals(isAbstractType)) {
342 markParentBoundary();
343 traversal.union(handleAbstractEdge(type, parent, child, isPrivateEdge));
346 this.edgeQueryToVertex(type, parent, child, null);
355 public QueryBuilder<Vertex> createEdgeTraversalWithLabels(EdgeType type, Introspector out, Introspector in, List<String> labels) throws AAIException {
356 this.edgeQueryToVertex(type, out, in, labels);
357 return (QueryBuilder<Vertex>) this;
360 private Traversal<Vertex, Vertex>[] handleAbstractEdge(EdgeType type, Introspector abstractParent, Introspector child, boolean isPrivateEdge) throws AAIException {
361 String childName = child.getDbName();
362 String inheritorMetadata = abstractParent.getMetadata(ObjectMetadata.INHERITORS);
363 String[] inheritors = inheritorMetadata.split(",");
364 List<Traversal<Vertex, Vertex>> unionTraversals = new ArrayList<>(inheritors.length);
366 for (int i = 0; i < inheritors.length; i++) {
367 String inheritor = inheritors[i];
368 EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(inheritor, childName);
369 if (edgeRules.hasRule(qB.build())) {
370 Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
372 rules = edgeRules.getRules(qB.edgeType(type).build());
373 } catch (EdgeRuleNotFoundException e) {
374 throw new NoEdgeRuleFoundException(e);
377 GraphTraversal<Vertex, Vertex> innerTraversal = __.start();
379 final List<String> inLabels = new ArrayList<>();
380 final List<String> outLabels = new ArrayList<>();
382 rules.values().forEach(rule -> {
383 if (rule.getDirection().equals(Direction.IN)) {
384 inLabels.add(rule.getLabel());
386 outLabels.add(rule.getLabel());
390 if (inLabels.isEmpty() && !outLabels.isEmpty()) {
391 innerTraversal.out(outLabels.toArray(new String[outLabels.size()]));
392 } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
393 innerTraversal.in(inLabels.toArray(new String[inLabels.size()]));
395 innerTraversal.union(__.out(outLabels.toArray(new String[outLabels.size()])), __.in(inLabels.toArray(new String[inLabels.size()])));
398 innerTraversal.has(AAIProperties.NODE_TYPE, childName);
399 unionTraversals.add(innerTraversal);
403 return unionTraversals.toArray(new Traversal[unionTraversals.size()]);
406 public QueryBuilder<Edge> getEdgesBetweenWithLabels(EdgeType type, String outNodeType, String inNodeType, List<String> labels) throws AAIException {
407 Introspector outObj = loader.introspectorFromName(outNodeType);
408 Introspector inObj = loader.introspectorFromName(inNodeType);
409 this.edgeQuery(type, outObj, inObj, labels);
411 return (QueryBuilder<Edge>)this;
419 public QueryBuilder<E> union(QueryBuilder... builder) {
420 GraphTraversal<Vertex, Vertex>[] traversals = new GraphTraversal[builder.length];
421 for (int i = 0; i < builder.length; i++) {
422 traversals[i] = (GraphTraversal<Vertex, Vertex>)builder[i].getQuery();
424 this.traversal.union(traversals);
434 public QueryBuilder<E> where(QueryBuilder... builder) {
435 for (int i = 0; i < builder.length; i++) {
436 this.traversal.where((GraphTraversal<Vertex, Vertex>)builder[i].getQuery());
447 public QueryBuilder<E> or(QueryBuilder... builder) {
448 GraphTraversal<Vertex, Vertex>[] traversals = new GraphTraversal[builder.length];
449 for (int i = 0; i < builder.length; i++) {
450 traversals[i] = (GraphTraversal<Vertex, Vertex>)builder[i].getQuery();
452 this.traversal.or(traversals);
459 public QueryBuilder<E> store(String name) {
461 this.traversal.store(name);
468 public QueryBuilder<E> cap(String name) {
469 this.traversal.cap(name);
476 public QueryBuilder<E> unfold() {
477 this.traversal.unfold();
484 public QueryBuilder<E> dedup() {
486 this.traversal.dedup();
493 public QueryBuilder<E> emit() {
495 this.traversal.emit();
503 public QueryBuilder<E> repeat(QueryBuilder<E> builder) {
505 this.traversal.repeat((GraphTraversal<Vertex, E>)builder.getQuery());
512 public QueryBuilder<E> until(QueryBuilder<E> builder) {
513 this.traversal.until((GraphTraversal<Vertex,E>)builder.getQuery());
520 public QueryBuilder<E> groupCount() {
521 this.traversal.groupCount();
528 public QueryBuilder<E> both() {
529 this.traversal.both();
536 public QueryBuilder<Tree> tree() {
538 this.traversal.tree();
541 return (QueryBuilder<Tree>)this;
545 public QueryBuilder<E> by(String name) {
546 this.traversal.by(name);
556 public QueryBuilder<E> simplePath(){
557 this.traversal.simplePath();
566 public QueryBuilder<Path> path(){
567 this.traversal.path();
569 return (QueryBuilder<Path>)this;
573 public QueryBuilder<Edge> outE() {
574 this.traversal.outE();
576 return (QueryBuilder<Edge>)this;
580 public QueryBuilder<Edge> inE() {
581 this.traversal.inE();
583 return (QueryBuilder<Edge>)this;
587 public QueryBuilder<Vertex> outV() {
588 this.traversal.outV();
590 return (QueryBuilder<Vertex>)this;
594 public QueryBuilder<Vertex> inV() {
595 this.traversal.inV();
597 return (QueryBuilder<Vertex>)this;
601 public QueryBuilder<E> as(String name) {
602 this.traversal.as(name);
609 public QueryBuilder<E> not(QueryBuilder<E> builder) {
610 this.traversal.not(builder.getQuery());
617 public QueryBuilder<E> select(String name) {
618 this.traversal.select(name);
628 * @param outObj the out type
629 * @param inObj the in type
630 * @throws NoEdgeRuleFoundException
631 * @throws AAIException
633 private void edgeQueryToVertex(EdgeType type, Introspector outObj, Introspector inObj, List<String> labels) throws AAIException {
634 String outType = outObj.getDbName();
635 String inType = inObj.getDbName();
637 if (outObj.isContainer()) {
638 outType = outObj.getChildDBName();
640 if (inObj.isContainer()) {
641 inType = inObj.getChildDBName();
643 markParentBoundary();
644 Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
645 EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type);
647 if (labels == null) {
649 rules.putAll(edgeRules.getRules(qB.build()));
650 } catch (EdgeRuleNotFoundException e) {
651 //is ok per original functioning of this section
652 //TODO add "best try" sort of flag to the EdgeRuleQuery
653 // to indicate if the exception should be thrown or not
656 for (String label : labels) {
658 rules.putAll(edgeRules.getRules(qB.label(label).build()));
659 } catch (EdgeRuleNotFoundException e) {
660 throw new NoEdgeRuleFoundException(e);
663 if (rules.isEmpty()) {
664 throw new NoEdgeRuleFoundException("No edge rules found for " + outType + " and " + inType + " of type " + type.toString());
669 final List<String> inLabels = new ArrayList<>();
670 final List<String> outLabels = new ArrayList<>();
672 for (EdgeRule rule : rules.values()) {
673 if (labels != null && !labels.contains(rule.getLabel())) {
676 if (Direction.IN.equals(rule.getDirection())) {
677 inLabels.add(rule.getLabel());
679 outLabels.add(rule.getLabel());
684 if (inLabels.isEmpty() && !outLabels.isEmpty()) {
685 traversal.out(outLabels.toArray(new String[outLabels.size()]));
686 } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
687 traversal.in(inLabels.toArray(new String[inLabels.size()]));
689 traversal.union(__.out(outLabels.toArray(new String[outLabels.size()])), __.in(inLabels.toArray(new String[inLabels.size()])));
694 this.createContainerQuery(inObj);
701 * @param outObj the out type
702 * @param inObj the in type
703 * @throws NoEdgeRuleFoundException
704 * @throws AAIException
706 private void edgeQuery(EdgeType type, Introspector outObj, Introspector inObj, List<String> labels) throws AAIException {
707 String outType = outObj.getDbName();
708 String inType = inObj.getDbName();
710 if (outObj.isContainer()) {
711 outType = outObj.getChildDBName();
713 if (inObj.isContainer()) {
714 inType = inObj.getChildDBName();
717 markParentBoundary();
718 Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
719 EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type);
722 if (labels == null) {
723 rules.putAll(edgeRules.getRules(qB.build()));
725 for (String label : labels) {
726 rules.putAll(edgeRules.getRules(qB.label(label).build()));
729 } catch (EdgeRuleNotFoundException e) {
730 throw new NoEdgeRuleFoundException(e);
733 final List<String> inLabels = new ArrayList<>();
734 final List<String> outLabels = new ArrayList<>();
736 for (EdgeRule rule : rules.values()) {
737 if (labels != null && !labels.contains(rule.getLabel())) {
740 if (Direction.IN.equals(rule.getDirection())) {
741 inLabels.add(rule.getLabel());
743 outLabels.add(rule.getLabel());
748 if (inLabels.isEmpty() && !outLabels.isEmpty()) {
749 traversal.outE(outLabels.toArray(new String[outLabels.size()]));
750 } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
751 traversal.inE(inLabels.toArray(new String[inLabels.size()]));
753 traversal.union(__.outE(outLabels.toArray(new String[outLabels.size()])), __.inE(inLabels.toArray(new String[inLabels.size()])));
758 public QueryBuilder<E> limit(long amount) {
759 traversal.limit(amount);
767 public <E2> E2 getQuery() {
768 return (E2)this.traversal;
775 public QueryBuilder<E> getParentQuery() {
777 return cloneQueryAtStep(parentStepIndex);
781 public QueryBuilder<E> getContainerQuery() {
783 if (this.parentStepIndex == 0) {
784 return removeQueryStepsBetween(0, containerStepIndex);
786 return cloneQueryAtStep(containerStepIndex);
794 public void markParentBoundary() {
795 parentStepIndex = stepIndex;
799 public void markContainer() {
800 containerStepIndex = stepIndex;
808 public Vertex getStart() {
812 protected int getParentStepIndex() {
813 return parentStepIndex;
816 protected int getContainerStepIndex() {
817 return containerStepIndex;
820 protected int getStepIndex() {
831 protected abstract QueryBuilder<E> removeQueryStepsBetween(int start, int end);
833 protected void executeQuery() {
837 this.completeTraversal = traversal.asAdmin();
839 admin = source.V().asAdmin();
840 TraversalHelper.insertTraversal(admin.getEndStep(), traversal.asAdmin(), admin);
842 this.completeTraversal = (Admin<Vertex, E>) admin;
849 public boolean hasNext() {
850 if (this.completeTraversal == null) {
854 return this.completeTraversal.hasNext();
859 if (this.completeTraversal == null) {
863 return this.completeTraversal.next();
867 public List<E> toList() {
868 if (this.completeTraversal == null) {
871 return this.completeTraversal.toList();
874 protected QueryBuilder<Edge> has(String key, String value) {
875 traversal.has(key, value);
877 return (QueryBuilder<Edge>)this;