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);
626 public QueryBuilder<E> select(String... names) {
627 if(names.length == 1) {
628 this.traversal.select(names[0]);
630 else if(names.length == 2) {
631 this.traversal.select(names[0], names[1]);
633 else if(names.length > 2){
634 String[] otherNames = Arrays.copyOfRange(names, 2, names.length);
635 this.traversal.select(names[0], names[1], otherNames);
646 * @param outObj the out type
647 * @param inObj the in type
648 * @throws NoEdgeRuleFoundException
649 * @throws AAIException
651 private void edgeQueryToVertex(EdgeType type, Introspector outObj, Introspector inObj, List<String> labels) throws AAIException {
652 String outType = outObj.getDbName();
653 String inType = inObj.getDbName();
655 if (outObj.isContainer()) {
656 outType = outObj.getChildDBName();
658 if (inObj.isContainer()) {
659 inType = inObj.getChildDBName();
661 markParentBoundary();
662 Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
663 EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type);
665 if (labels == null) {
667 rules.putAll(edgeRules.getRules(qB.build()));
668 } catch (EdgeRuleNotFoundException e) {
669 //is ok per original functioning of this section
670 //TODO add "best try" sort of flag to the EdgeRuleQuery
671 // to indicate if the exception should be thrown or not
674 for (String label : labels) {
676 rules.putAll(edgeRules.getRules(qB.label(label).build()));
677 } catch (EdgeRuleNotFoundException e) {
678 throw new NoEdgeRuleFoundException(e);
681 if (rules.isEmpty()) {
682 throw new NoEdgeRuleFoundException("No edge rules found for " + outType + " and " + inType + " of type " + type.toString());
687 final List<String> inLabels = new ArrayList<>();
688 final List<String> outLabels = new ArrayList<>();
690 for (EdgeRule rule : rules.values()) {
691 if (labels != null && !labels.contains(rule.getLabel())) {
694 if (Direction.IN.equals(rule.getDirection())) {
695 inLabels.add(rule.getLabel());
697 outLabels.add(rule.getLabel());
702 if (inLabels.isEmpty() && !outLabels.isEmpty()) {
703 traversal.out(outLabels.toArray(new String[outLabels.size()]));
704 } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
705 traversal.in(inLabels.toArray(new String[inLabels.size()]));
707 traversal.union(__.out(outLabels.toArray(new String[outLabels.size()])), __.in(inLabels.toArray(new String[inLabels.size()])));
712 this.createContainerQuery(inObj);
719 * @param outObj the out type
720 * @param inObj the in type
721 * @throws NoEdgeRuleFoundException
722 * @throws AAIException
724 private void edgeQuery(EdgeType type, Introspector outObj, Introspector inObj, List<String> labels) throws AAIException {
725 String outType = outObj.getDbName();
726 String inType = inObj.getDbName();
728 if (outObj.isContainer()) {
729 outType = outObj.getChildDBName();
731 if (inObj.isContainer()) {
732 inType = inObj.getChildDBName();
735 markParentBoundary();
736 Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
737 EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type);
740 if (labels == null) {
741 rules.putAll(edgeRules.getRules(qB.build()));
743 for (String label : labels) {
744 rules.putAll(edgeRules.getRules(qB.label(label).build()));
747 } catch (EdgeRuleNotFoundException e) {
748 throw new NoEdgeRuleFoundException(e);
751 final List<String> inLabels = new ArrayList<>();
752 final List<String> outLabels = new ArrayList<>();
754 for (EdgeRule rule : rules.values()) {
755 if (labels != null && !labels.contains(rule.getLabel())) {
758 if (Direction.IN.equals(rule.getDirection())) {
759 inLabels.add(rule.getLabel());
761 outLabels.add(rule.getLabel());
766 if (inLabels.isEmpty() && !outLabels.isEmpty()) {
767 traversal.outE(outLabels.toArray(new String[outLabels.size()]));
768 } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
769 traversal.inE(inLabels.toArray(new String[inLabels.size()]));
771 traversal.union(__.outE(outLabels.toArray(new String[outLabels.size()])), __.inE(inLabels.toArray(new String[inLabels.size()])));
776 public QueryBuilder<E> limit(long amount) {
777 traversal.limit(amount);
785 public <E2> E2 getQuery() {
786 return (E2)this.traversal;
793 public QueryBuilder<E> getParentQuery() {
795 return cloneQueryAtStep(parentStepIndex);
799 public QueryBuilder<E> getContainerQuery() {
801 if (this.parentStepIndex == 0) {
802 return removeQueryStepsBetween(0, containerStepIndex);
804 return cloneQueryAtStep(containerStepIndex);
812 public void markParentBoundary() {
813 parentStepIndex = stepIndex;
817 public void markContainer() {
818 containerStepIndex = stepIndex;
826 public Vertex getStart() {
830 protected int getParentStepIndex() {
831 return parentStepIndex;
834 protected int getContainerStepIndex() {
835 return containerStepIndex;
838 protected int getStepIndex() {
849 protected abstract QueryBuilder<E> removeQueryStepsBetween(int start, int end);
851 protected void executeQuery() {
855 this.completeTraversal = traversal.asAdmin();
857 admin = source.V().asAdmin();
858 TraversalHelper.insertTraversal(admin.getEndStep(), traversal.asAdmin(), admin);
860 this.completeTraversal = (Admin<Vertex, E>) admin;
867 public boolean hasNext() {
868 if (this.completeTraversal == null) {
872 return this.completeTraversal.hasNext();
877 if (this.completeTraversal == null) {
881 return this.completeTraversal.next();
885 public List<E> toList() {
886 if (this.completeTraversal == null) {
889 return this.completeTraversal.toList();
892 protected QueryBuilder<Edge> has(String key, String value) {
893 traversal.has(key, value);
895 return (QueryBuilder<Edge>)this;