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=========================================================
21 package org.onap.aai.query.builder;
23 import com.google.common.collect.ArrayListMultimap;
24 import com.google.common.collect.Multimap;
28 import org.apache.tinkerpop.gremlin.process.traversal.P;
29 import org.apache.tinkerpop.gremlin.process.traversal.Path;
30 import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
31 import org.apache.tinkerpop.gremlin.process.traversal.Traversal.Admin;
32 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
33 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
34 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
35 import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
36 import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;
37 import org.apache.tinkerpop.gremlin.structure.Direction;
38 import org.apache.tinkerpop.gremlin.structure.Edge;
39 import org.apache.tinkerpop.gremlin.structure.Vertex;
40 import org.onap.aai.db.props.AAIProperties;
41 import org.onap.aai.edges.EdgeRule;
42 import org.onap.aai.edges.EdgeRuleQuery;
43 import org.onap.aai.edges.enums.EdgeType;
44 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
45 import org.onap.aai.exceptions.AAIException;
46 import org.onap.aai.introspection.Introspector;
47 import org.onap.aai.introspection.Loader;
48 import org.onap.aai.schema.enums.ObjectMetadata;
49 import org.onap.aai.schema.enums.PropertyMetadata;
50 import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
53 * The Class GraphTraversalBuilder.
55 public abstract class GraphTraversalBuilder<E> extends QueryBuilder<E> {
57 protected GraphTraversal<Vertex, E> traversal = null;
58 protected Admin<Vertex, E> completeTraversal = null;
61 * Instantiates a new graph traversal builder.
63 * @param loader the loader
65 public GraphTraversalBuilder(Loader loader, GraphTraversalSource source) {
66 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 this.vertexHas(key, this.correctObjectType(value));
93 return (QueryBuilder<Vertex>) this;
97 protected void vertexHas(String key, Object value) {
98 traversal.has(key, value);
102 protected void vertexHasNot(String key) {
103 traversal.hasNot(key);
107 protected void vertexHas(String key) {
111 //TODO: Remove this once we test this - at this point i dont thib this is required
112 //because predicare is an object
114 protected void vertexHas(final String key, final P<?> predicate) {
115 traversal.has(key, predicate);
122 public QueryBuilder<Vertex> getVerticesByProperty(final String key, final List<?> values) {
124 // this is because the index is registered as an Integer
125 List<Object> correctedValues = new ArrayList<>();
126 for (Object item : values) {
127 correctedValues.add(this.correctObjectType(item));
130 this.vertexHas(key, P.within(correctedValues));
132 return (QueryBuilder<Vertex>) this;
138 public QueryBuilder<Vertex> getVerticesByCommaSeperatedValue(String key, String value) {
139 ArrayList<String> values = new ArrayList<>(Arrays.asList(value.split(",")));
140 int size = values.size();
141 for (int i = 0; i < size; i++) {
142 values.set(i, values.get(i).trim());
144 this.vertexHas(key, P.within(values));
147 return (QueryBuilder<Vertex>) this;
154 public QueryBuilder<Vertex> getVerticesStartsWithProperty(String key, Object value) {
156 // correct value call because the index is registered as an Integer
157 //TODO Check if this needs to be in QB and add these as internal
158 this.vertexHas(key, org.janusgraph.core.attribute.Text.textPrefix(value));
161 return (QueryBuilder<Vertex>) this;
168 public QueryBuilder<Vertex> getVerticesByProperty(String key) {
171 return (QueryBuilder<Vertex>) this;
178 public QueryBuilder<Vertex> getVerticesExcludeByProperty(String key) {
179 this.vertexHasNot(key);
181 return (QueryBuilder<Vertex>) this;
188 public QueryBuilder<Vertex> getVerticesExcludeByProperty(String key, Object value) {
190 // correct value call because the index is registered as an Integer
191 this.vertexHas(key, P.neq(this.correctObjectType(value)));
193 return (QueryBuilder<Vertex>) this;
200 public QueryBuilder<Vertex> getVerticesExcludeByProperty(final String key, final List<?> values) {
202 // this is because the index is registered as an Integer
203 List<Object> correctedValues = new ArrayList<>();
204 for (Object item : values) {
205 correctedValues.add(this.correctObjectType(item));
208 this.vertexHas(key, P.without(correctedValues));
210 return (QueryBuilder<Vertex>) this;
214 public QueryBuilder<Vertex> getVerticesGreaterThanProperty(final String key, Object value) {
215 this.vertexHas(key, P.gte(this.correctObjectType(value)));
218 return (QueryBuilder<Vertex>) this;
222 public QueryBuilder<Vertex> getVerticesLessThanProperty(final String key, Object value) {
223 this.vertexHas(key, P.lte(this.correctObjectType(value)));
226 return (QueryBuilder<Vertex>) this;
233 public QueryBuilder<Vertex> getChildVerticesFromParent(String parentKey, String parentValue, String childType) {
234 traversal.has(parentKey, parentValue).has(AAIProperties.NODE_TYPE, childType);
236 return (QueryBuilder<Vertex>) this;
243 public QueryBuilder<Vertex> getTypedVerticesByMap(String type, Map<String, String> map) {
245 for (Map.Entry<String, String> es : map.entrySet()) {
246 this.vertexHas(es.getKey(), es.getValue());
249 traversal.has(AAIProperties.NODE_TYPE, type);
251 return (QueryBuilder<Vertex>) this;
255 public QueryBuilder<Vertex> getVerticesByBooleanProperty(String key, Object value) {
257 if (value != null && !"".equals(value)) {
258 boolean bValue = false;
260 if (value instanceof String) {// "true"
261 bValue = Boolean.valueOf(value.toString());
262 } else if (value instanceof Boolean) {// true
263 bValue = (Boolean) value;
266 this.vertexHas(key, bValue);
269 return (QueryBuilder<Vertex>) this;
276 public QueryBuilder<Vertex> createKeyQuery(Introspector obj) {
277 Set<String> keys = obj.getKeys();
279 for (String key : keys) {
280 val = obj.getValue(key);
281 Optional<String> metadata = obj.getPropertyMetadata(key, PropertyMetadata.DB_ALIAS);
282 if (metadata.isPresent()) {
283 // use the db name for the field rather than the object model
284 key = metadata.get();
287 // this is because the index is registered as an Integer
288 if (val.getClass().equals(Long.class)) {
289 this.vertexHas(key, new Integer(val.toString()));
291 this.vertexHas(key, val);
296 return (QueryBuilder<Vertex>) this;
300 public QueryBuilder<Vertex> exactMatchQuery(Introspector obj) {
301 this.createKeyQuery(obj);
302 allPropertiesQuery(obj);
303 this.createContainerQuery(obj);
304 return (QueryBuilder<Vertex>) this;
307 private void allPropertiesQuery(Introspector obj) {
308 Set<String> props = obj.getProperties();
309 Set<String> keys = obj.getKeys();
311 for (String prop : props) {
312 if (obj.isSimpleType(prop) && !keys.contains(prop)) {
313 val = obj.getValue(prop);
315 Optional<String> metadata = obj.getPropertyMetadata(prop, PropertyMetadata.DB_ALIAS);
316 if (metadata.isPresent()) {
317 // use the db name for the field rather than the object model
318 prop = metadata.get();
320 // this is because the index is registered as an Integer
321 if (val.getClass().equals(Long.class)) {
322 this.vertexHas(prop, new Integer(val.toString()));
324 this.vertexHas(prop, val);
337 public QueryBuilder<Vertex> createContainerQuery(Introspector obj) {
338 String type = obj.getChildDBName();
339 String abstractType = obj.getMetadata(ObjectMetadata.ABSTRACT);
340 if (abstractType != null) {
341 String[] inheritors = obj.getMetadata(ObjectMetadata.INHERITORS).split(",");
342 traversal.has(AAIProperties.NODE_TYPE, P.within(inheritors));
344 traversal.has(AAIProperties.NODE_TYPE, type);
348 return (QueryBuilder<Vertex>) this;
352 * @throws NoEdgeRuleFoundException
353 * @throws AAIException
357 public QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, Introspector parent, Introspector child)
358 throws AAIException {
359 createTraversal(type, parent, child, false);
360 return (QueryBuilder<Vertex>) this;
365 public QueryBuilder<Vertex> createPrivateEdgeTraversal(EdgeType type, Introspector parent, Introspector child)
366 throws AAIException {
367 this.createTraversal(type, parent, child, true);
368 return (QueryBuilder<Vertex>) this;
371 private void createTraversal(EdgeType type, Introspector parent, Introspector child, boolean isPrivateEdge)
372 throws AAIException {
373 String isAbstractType = parent.getMetadata(ObjectMetadata.ABSTRACT);
374 if ("true".equals(isAbstractType)) {
375 markParentBoundary();
376 traversal.union(handleAbstractEdge(type, parent, child, isPrivateEdge));
379 this.edgeQueryToVertex(type, parent, child, null);
387 public QueryBuilder<Vertex> createEdgeTraversalWithLabels(EdgeType type, Introspector out, Introspector in,
388 List<String> labels) throws AAIException {
389 this.edgeQueryToVertex(type, out, in, labels);
390 return (QueryBuilder<Vertex>) this;
393 private Traversal<Vertex, Vertex>[] handleAbstractEdge(EdgeType type, Introspector abstractParent,
394 Introspector child, boolean isPrivateEdge) throws AAIException {
395 String childName = child.getDbName();
396 String inheritorMetadata = abstractParent.getMetadata(ObjectMetadata.INHERITORS);
397 String[] inheritors = inheritorMetadata.split(",");
398 List<Traversal<Vertex, Vertex>> unionTraversals = new ArrayList<>(inheritors.length);
400 for (int i = 0; i < inheritors.length; i++) {
401 String inheritor = inheritors[i];
402 EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(inheritor, childName);
403 if (edgeRules.hasRule(qB.build())) {
404 Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
406 rules = edgeRules.getRules(qB.edgeType(type).build());
407 } catch (EdgeRuleNotFoundException e) {
408 throw new NoEdgeRuleFoundException(e);
411 GraphTraversal<Vertex, Vertex> innerTraversal = __.start();
413 final List<String> inLabels = new ArrayList<>();
414 final List<String> outLabels = new ArrayList<>();
416 rules.values().forEach(rule -> {
417 if (rule.getDirection().equals(Direction.IN)) {
418 inLabels.add(rule.getLabel());
420 outLabels.add(rule.getLabel());
424 if (inLabels.isEmpty() && !outLabels.isEmpty()) {
425 innerTraversal.out(outLabels.toArray(new String[outLabels.size()]));
426 } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
427 innerTraversal.in(inLabels.toArray(new String[inLabels.size()]));
429 innerTraversal.union(__.out(outLabels.toArray(new String[outLabels.size()])),
430 __.in(inLabels.toArray(new String[inLabels.size()])));
433 innerTraversal.has(AAIProperties.NODE_TYPE, childName);
434 unionTraversals.add(innerTraversal);
438 return unionTraversals.toArray(new Traversal[unionTraversals.size()]);
441 public QueryBuilder<Edge> getEdgesBetweenWithLabels(EdgeType type, String outNodeType, String inNodeType,
442 List<String> labels) throws AAIException {
443 Introspector outObj = loader.introspectorFromName(outNodeType);
444 Introspector inObj = loader.introspectorFromName(inNodeType);
445 this.edgeQuery(type, outObj, inObj, labels);
447 return (QueryBuilder<Edge>) this;
454 public QueryBuilder<E> union(QueryBuilder... builder) {
455 GraphTraversal<Vertex, Vertex>[] traversals = new GraphTraversal[builder.length];
456 for (int i = 0; i < builder.length; i++) {
457 traversals[i] = (GraphTraversal<Vertex, Vertex>) builder[i].getQuery();
459 this.traversal.union(traversals);
469 public QueryBuilder<E> where(QueryBuilder... builder) {
470 for (int i = 0; i < builder.length; i++) {
471 this.traversal.where((GraphTraversal<Vertex, Vertex>) builder[i].getQuery());
482 public QueryBuilder<E> or(QueryBuilder... builder) {
483 GraphTraversal<Vertex, Vertex>[] traversals = new GraphTraversal[builder.length];
484 for (int i = 0; i < builder.length; i++) {
485 traversals[i] = (GraphTraversal<Vertex, Vertex>) builder[i].getQuery();
487 this.traversal.or(traversals);
494 public QueryBuilder<E> store(String name) {
496 this.traversal.store(name);
503 public QueryBuilder<E> cap(String name) {
504 this.traversal.cap(name);
511 public QueryBuilder<E> unfold() {
512 this.traversal.unfold();
519 public QueryBuilder<E> dedup() {
521 this.traversal.dedup();
528 public QueryBuilder<E> emit() {
530 this.traversal.emit();
538 public QueryBuilder<E> repeat(QueryBuilder<E> builder) {
540 this.traversal.repeat((GraphTraversal<Vertex, E>) builder.getQuery());
547 public QueryBuilder<E> until(QueryBuilder<E> builder) {
548 this.traversal.until((GraphTraversal<Vertex, E>) builder.getQuery());
555 public QueryBuilder<E> groupCount() {
556 this.traversal.groupCount();
563 public QueryBuilder<E> both() {
564 this.traversal.both();
571 public QueryBuilder<Tree> tree() {
573 this.traversal.tree();
576 return (QueryBuilder<Tree>) this;
580 public QueryBuilder<E> by(String name) {
581 this.traversal.by(name);
588 public QueryBuilder<E> valueMap() {
589 this.traversal.valueMap();
596 public QueryBuilder<E> valueMap(String... names) {
597 this.traversal.valueMap(names);
608 public QueryBuilder<E> simplePath() {
609 this.traversal.simplePath();
618 public QueryBuilder<Path> path() {
619 this.traversal.path();
621 return (QueryBuilder<Path>) this;
625 public QueryBuilder<Edge> outE() {
626 this.traversal.outE();
628 return (QueryBuilder<Edge>) this;
632 public QueryBuilder<Edge> inE() {
633 this.traversal.inE();
635 return (QueryBuilder<Edge>) this;
639 public QueryBuilder<Vertex> outV() {
640 this.traversal.outV();
642 return (QueryBuilder<Vertex>) this;
646 public QueryBuilder<Vertex> inV() {
647 this.traversal.inV();
649 return (QueryBuilder<Vertex>) this;
653 public QueryBuilder<E> as(String name) {
654 this.traversal.as(name);
661 public QueryBuilder<E> not(QueryBuilder<E> builder) {
662 this.traversal.not(builder.getQuery());
669 public QueryBuilder<E> select(String name) {
670 this.traversal.select(name);
678 public QueryBuilder<E> select(String... names) {
679 if (names.length == 1) {
680 this.traversal.select(names[0]);
681 } else if (names.length == 2) {
682 this.traversal.select(names[0], names[1]);
683 } else if (names.length > 2) {
684 String[] otherNames = Arrays.copyOfRange(names, 2, names.length);
685 this.traversal.select(names[0], names[1], otherNames);
696 * @param outObj the out type
697 * @param inObj the in type
698 * @throws NoEdgeRuleFoundException
699 * @throws AAIException
701 private void edgeQueryToVertex(EdgeType type, Introspector outObj, Introspector inObj, List<String> labels)
702 throws AAIException {
703 String outType = outObj.getDbName();
704 String inType = inObj.getDbName();
706 if (outObj.isContainer()) {
707 outType = outObj.getChildDBName();
709 if (inObj.isContainer()) {
710 inType = inObj.getChildDBName();
712 markParentBoundary();
713 Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
714 EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type);
716 if (labels == null) {
718 rules.putAll(edgeRules.getRules(qB.build()));
719 } catch (EdgeRuleNotFoundException e) {
720 // is ok per original functioning of this section
721 // TODO add "best try" sort of flag to the EdgeRuleQuery
722 // to indicate if the exception should be thrown or not
725 for (String label : labels) {
727 rules.putAll(edgeRules.getRules(qB.label(label).build()));
728 } catch (EdgeRuleNotFoundException e) {
729 throw new NoEdgeRuleFoundException(e);
732 if (rules.isEmpty()) {
733 throw new NoEdgeRuleFoundException(
734 "No edge rules found for " + outType + " and " + inType + " of type " + type.toString());
738 final List<String> inLabels = new ArrayList<>();
739 final List<String> outLabels = new ArrayList<>();
741 for (EdgeRule rule : rules.values()) {
742 if (labels != null && !labels.contains(rule.getLabel())) {
745 if (Direction.IN.equals(rule.getDirection())) {
746 inLabels.add(rule.getLabel());
748 outLabels.add(rule.getLabel());
753 if (inLabels.isEmpty() && !outLabels.isEmpty()) {
754 traversal.out(outLabels.toArray(new String[outLabels.size()]));
755 } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
756 traversal.in(inLabels.toArray(new String[inLabels.size()]));
758 traversal.union(__.out(outLabels.toArray(new String[outLabels.size()])),
759 __.in(inLabels.toArray(new String[inLabels.size()])));
764 this.createContainerQuery(inObj);
771 * @param outObj the out type
772 * @param inObj the in type
773 * @throws NoEdgeRuleFoundException
774 * @throws AAIException
776 private void edgeQuery(EdgeType type, Introspector outObj, Introspector inObj, List<String> labels)
777 throws AAIException {
778 String outType = outObj.getDbName();
779 String inType = inObj.getDbName();
781 if (outObj.isContainer()) {
782 outType = outObj.getChildDBName();
784 if (inObj.isContainer()) {
785 inType = inObj.getChildDBName();
788 markParentBoundary();
789 Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
790 EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type);
793 if (labels == null) {
794 rules.putAll(edgeRules.getRules(qB.build()));
796 for (String label : labels) {
797 rules.putAll(edgeRules.getRules(qB.label(label).build()));
800 } catch (EdgeRuleNotFoundException e) {
801 throw new NoEdgeRuleFoundException(e);
804 final List<String> inLabels = new ArrayList<>();
805 final List<String> outLabels = new ArrayList<>();
807 for (EdgeRule rule : rules.values()) {
808 if (labels != null && !labels.contains(rule.getLabel())) {
811 if (Direction.IN.equals(rule.getDirection())) {
812 inLabels.add(rule.getLabel());
814 outLabels.add(rule.getLabel());
819 if (inLabels.isEmpty() && !outLabels.isEmpty()) {
820 traversal.outE(outLabels.toArray(new String[outLabels.size()]));
821 } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
822 traversal.inE(inLabels.toArray(new String[inLabels.size()]));
824 traversal.union(__.outE(outLabels.toArray(new String[outLabels.size()])),
825 __.inE(inLabels.toArray(new String[inLabels.size()])));
830 public QueryBuilder<E> limit(long amount) {
831 traversal.limit(amount);
839 public <E2> E2 getQuery() {
840 return (E2) this.traversal;
847 public QueryBuilder<E> getParentQuery() {
849 return cloneQueryAtStep(parentStepIndex);
853 public QueryBuilder<E> getContainerQuery() {
855 if (this.parentStepIndex == 0) {
856 return removeQueryStepsBetween(0, containerStepIndex);
858 return cloneQueryAtStep(containerStepIndex);
866 public void markParentBoundary() {
867 parentStepIndex = stepIndex;
871 public void markContainer() {
872 containerStepIndex = stepIndex;
879 public Vertex getStart() {
883 protected int getParentStepIndex() {
884 return parentStepIndex;
887 protected int getContainerStepIndex() {
888 return containerStepIndex;
891 protected int getStepIndex() {
902 protected abstract QueryBuilder<E> removeQueryStepsBetween(int start, int end);
904 protected void executeQuery() {
908 this.completeTraversal = traversal.asAdmin();
910 admin = source.V().asAdmin();
911 TraversalHelper.insertTraversal(admin.getEndStep(), traversal.asAdmin(), admin);
913 this.completeTraversal = (Admin<Vertex, E>) admin;
920 public boolean hasNext() {
921 if (this.completeTraversal == null) {
925 return this.completeTraversal.hasNext();
930 if (this.completeTraversal == null) {
934 return this.completeTraversal.next();
938 public List<E> toList() {
939 if (this.completeTraversal == null) {
942 return this.completeTraversal.toList();
945 protected QueryBuilder<Edge> has(String key, String value) {
946 traversal.has(key, value);
948 return (QueryBuilder<Edge>) this;