2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Modifications Copyright © 2018 IBM.
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
22 package org.onap.aai.query.builder;
24 import com.google.common.base.Joiner;
25 import com.google.common.collect.ArrayListMultimap;
26 import com.google.common.collect.Multimap;
28 import org.apache.tinkerpop.gremlin.process.traversal.Path;
29 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
30 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
31 import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
32 import org.apache.tinkerpop.gremlin.structure.Direction;
33 import org.apache.tinkerpop.gremlin.structure.Edge;
34 import org.apache.tinkerpop.gremlin.structure.Vertex;
35 import org.onap.aai.db.props.AAIProperties;
36 import org.onap.aai.exceptions.AAIException;
37 import org.onap.aai.introspection.Introspector;
38 import org.onap.aai.introspection.Loader;
39 import org.onap.aai.restcore.search.GremlinGroovyShellSingleton;
40 import org.onap.aai.schema.enums.ObjectMetadata;
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.serialization.db.exceptions.NoEdgeRuleFoundException;
50 * The Class GremlinQueryBuilder.
52 public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> {
54 private static final String ARGUMENT2 = "#!#argument#!#";
55 private static final String HAS = ".has('";
56 private GremlinGroovyShellSingleton gremlinGroovy = GremlinGroovyShellSingleton.getInstance();
57 private GraphTraversal<?, ?> completeTraversal = null;
58 protected List<String> list = null;
61 * Instantiates a new gremlin query builder.
63 * @param loader the loader
65 public GremlinQueryBuilder(Loader loader, GraphTraversalSource source) {
66 super(loader, source);
67 list = new ArrayList<>();
71 * Instantiates a new gremlin query builder.
73 * @param loader the loader
74 * @param start the start
76 public GremlinQueryBuilder(Loader loader, GraphTraversalSource source, Vertex start) {
77 super(loader, source, start);
78 list = new ArrayList<>();
82 public QueryBuilder<Vertex> exactMatchQuery(Introspector obj) {
83 // TODO not implemented because this is implementation is no longer used
84 this.createKeyQuery(obj);
85 this.createContainerQuery(obj);
86 return (QueryBuilder<Vertex>) this;
93 public QueryBuilder<Vertex> getVerticesByProperty(String key, Object value) {
96 if (value != null && !(value instanceof String) ) {
97 term = value.toString();
99 term = "'" + value + "'";
101 list.add(HAS + key + "', " + term + ")");
103 return (QueryBuilder<Vertex>) this;
107 public QueryBuilder<Vertex> getVerticesByBooleanProperty(String key, Object value) {
108 boolean bValue = false;
110 if(value instanceof String){
111 bValue = Boolean.valueOf(value.toString());
112 } else if(value instanceof Boolean){
113 bValue = (Boolean) value;
116 list.add(HAS + key + "', " + bValue + ")");
118 return (QueryBuilder<Vertex>) this;
125 public QueryBuilder<Vertex> getVerticesByProperty(String key, List<?> values) {
127 String predicate = "P.within(#!#argument#!#)";
128 List<String> arguments = new ArrayList<>();
129 for (Object item : values) {
130 if (item != null && !(item instanceof String)) {
131 arguments.add(item.toString());
133 arguments.add("'" + item + "'");
136 String argument = Joiner.on(",").join(arguments);
137 predicate = predicate.replace(ARGUMENT2, argument);
138 list.add(HAS + key + "', " + predicate + ")");
140 return (QueryBuilder<Vertex>) this;
147 public QueryBuilder<Vertex> getVerticesByProperty(String key) {
149 list.add(HAS + key + "')");
151 return (QueryBuilder<Vertex>) this;
158 public QueryBuilder<Vertex> getVerticesExcludeByProperty(String key) {
160 list.add(".hasNot('" + key + "')");
162 return (QueryBuilder<Vertex>) this;
169 public QueryBuilder<Vertex> getVerticesStartsWithProperty(String key, Object value) {
172 String predicate = "org.janusgraph.core.attribute.Text.textPrefix(#!#argument#!#)";
173 if (value != null && !(value instanceof String) ) {
174 term = value.toString();
176 term = "'" + value + "'";
178 predicate = predicate.replace(ARGUMENT2, term);
179 list.add(HAS + key + "', " + predicate + ")");
181 return (QueryBuilder<Vertex>) this;
188 public QueryBuilder<Vertex> getVerticesExcludeByProperty(String key, Object value) {
191 String predicate = "P.neq(#!#argument#!#)";
192 if (value != null && !(value instanceof String) ) {
193 term = value.toString();
195 term = "'" + value + "'";
197 predicate = predicate.replace(ARGUMENT2, term);
198 list.add(HAS + key + "', " + predicate + ")");
200 return (QueryBuilder<Vertex>) this;
207 public QueryBuilder<Vertex> getVerticesExcludeByProperty(String key, List<?> values) {
209 String predicate = "P.without(#!#argument#!#)";
210 List<String> arguments = new ArrayList<>();
211 for (Object item : values) {
212 if (item != null && !(item instanceof String)) {
213 arguments.add(item.toString());
215 arguments.add("'" + item + "'");
218 String argument = Joiner.on(",").join(arguments);
219 predicate = predicate.replace(ARGUMENT2, argument);
220 list.add(HAS + key + "', " + predicate + ")");
222 return (QueryBuilder<Vertex>) this;
226 public QueryBuilder<Vertex> getVerticesGreaterThanProperty(String key, Object value) {
227 String predicate = "P.gte(#!#argument1#!#)";
229 if (value != null && !(value instanceof String) ) {
230 term = value.toString();
232 term = "'" + value + "'";
234 predicate = predicate.replace("#!#argument1#!#", term);
235 list.add(HAS + key + "', " + predicate + ")");
237 return (QueryBuilder<Vertex>) this;
241 public QueryBuilder<Vertex> getVerticesLessThanProperty(String key, Object value) {
242 String predicate = "P.lte(#!#argument1#!#)";
244 if (value != null && !(value instanceof String) ) {
245 term = value.toString();
247 term = "'" + value + "'";
249 predicate = predicate.replace("#!#argument1#!#", term);
250 list.add(HAS + key + "', " + predicate + ")");
252 return (QueryBuilder<Vertex>) this;
262 public QueryBuilder<Vertex> getChildVerticesFromParent(String parentKey, String parentValue, String childType) {
264 return (QueryBuilder<Vertex>) this;
271 public QueryBuilder<Vertex> getTypedVerticesByMap(String type, Map<String, String> map) {
273 for (Map.Entry<String, String> es : map.entrySet()) {
274 list.add(HAS + es.getKey() + "', '" + es.getValue() + "')");
277 list.add(".has('aai-node-type', '" + type + "')");
279 return (QueryBuilder<Vertex>) this;
286 public QueryBuilder<Vertex> createKeyQuery(Introspector obj) {
287 Set<String> keys = obj.getKeys();
289 for (String key : keys) {
291 this.getVerticesByProperty(key, obj.<Object>getValue(key));
294 return (QueryBuilder<Vertex>) this;
298 * @throws NoEdgeRuleFoundException
299 * @throws AAIException
303 public QueryBuilder createEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException {
304 String parentName = parent.getDbName();
305 String childName = child.getDbName();
306 if (parent.isContainer()) {
307 parentName = parent.getChildDBName();
309 if (child.isContainer()) {
310 childName = child.getChildDBName();
312 this.edgeQueryToVertex(type, parentName, childName, null);
318 public QueryBuilder createPrivateEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException{
319 String parentName = parent.getDbName();
320 String childName = child.getDbName();
321 if (parent.isContainer()) {
322 parentName = parent.getChildDBName();
324 if (child.isContainer()) {
325 childName = child.getChildDBName();
327 this.edgeQueryToVertex(type, parentName, childName, null, true);
336 public QueryBuilder<Vertex> createEdgeTraversalWithLabels(EdgeType type, Introspector out, Introspector in, List<String> labels) throws AAIException {
337 String parentName = out.getDbName();
338 String childName = in.getDbName();
339 if (out.isContainer()) {
340 parentName = out.getChildDBName();
342 if (in.isContainer()) {
343 childName = in.getChildDBName();
345 this.edgeQueryToVertex(type, parentName, childName, labels);
346 return (QueryBuilder<Vertex>) this;
350 public QueryBuilder<Edge> getEdgesBetweenWithLabels(EdgeType type, String outNodeType, String inNodeType, List<String> labels) throws AAIException {
351 this.edgeQuery(type, outNodeType, inNodeType, labels);
352 return (QueryBuilder<Edge>)this;
355 private void edgeQueryToVertex(EdgeType type, String outType, String inType, List<String> labels) throws AAIException {
356 this.edgeQueryToVertex(type, outType, inType, labels, false);
362 * @param outType the out type
363 * @param inType the in type
364 * @throws NoEdgeRuleFoundException
365 * @throws AAIException
367 private void edgeQueryToVertex(EdgeType type, String outType, String inType, List<String> labels, boolean isPrivateEdge) throws AAIException {
368 markParentBoundary();
369 Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
370 EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type).setPrivate(isPrivateEdge);
373 if (labels == null) {
374 rules.putAll(edgeRules.getRules(qB.build()));
376 for (String label : labels) {
377 rules.putAll(edgeRules.getRules(qB.label(label).build()));
380 } catch (EdgeRuleNotFoundException e) {
381 throw new NoEdgeRuleFoundException(e);
384 final List<String> inLabels = new ArrayList<>();
385 final List<String> outLabels = new ArrayList<>();
387 for (EdgeRule rule : rules.values()) {
388 if (labels != null && !labels.contains(rule.getLabel())) {
391 if (Direction.IN.equals(rule.getDirection())) {
392 inLabels.add(rule.getLabel());
394 outLabels.add(rule.getLabel());
399 if(inLabels.isEmpty() && outLabels.isEmpty()) {
400 throw new NoEdgeRuleFoundException("no " + type.toString() + " edge rule between " + outType + " and " + inType );
401 } else if (inLabels.isEmpty() && !outLabels.isEmpty()) {
402 list.add(".out('" + String.join("','", outLabels) + "')");
403 } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
404 list.add(".in('" + String.join("','", inLabels) + "')");
406 list.add(".union(__.in('" + String.join("','", inLabels) + "')" + ", __.out('" + String.join("','", outLabels) + "'))");
409 list.add(HAS + AAIProperties.NODE_TYPE + "', '" + inType + "')");
417 * @param outType the out type
418 * @param inType the in type
419 * @throws NoEdgeRuleFoundException
420 * @throws AAIException
422 private void edgeQuery(EdgeType type, String outType, String inType, List<String> labels) throws AAIException {
423 markParentBoundary();
424 Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
425 EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type);
427 if (labels == null) {
428 rules.putAll(edgeRules.getRules(qB.build()));
430 for (String label : labels) {
431 rules.putAll(edgeRules.getRules(qB.label(label).build()));
434 } catch (EdgeRuleNotFoundException e) {
435 throw new NoEdgeRuleFoundException(e);
438 final List<String> inLabels = new ArrayList<>();
439 final List<String> outLabels = new ArrayList<>();
441 for (EdgeRule rule : rules.values()) {
442 if (labels != null && !labels.contains(rule.getLabel())) {
445 if (Direction.IN.equals(rule.getDirection())) {
446 inLabels.add(rule.getLabel());
448 outLabels.add(rule.getLabel());
453 if(inLabels.isEmpty() && outLabels.isEmpty()) {
454 throw new NoEdgeRuleFoundException("no " + type.toString() + " edge rule between " + outType + " and " + inType );
455 } else if (inLabels.isEmpty() && !outLabels.isEmpty()) {
456 list.add(".outE('" + String.join("','", outLabels) + "')");
457 } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
458 list.add(".inE('" + String.join("','", inLabels) + "')");
460 list.add(".union(__.inE('" + String.join("','", inLabels) + "')" + ", __.outE('" + String.join("','", outLabels) + "'))");
467 public QueryBuilder<E> limit(long amount) {
468 list.add(".limit(" + amount + ")");
475 public QueryBuilder<Vertex> createContainerQuery(Introspector obj) {
476 String type = obj.getChildDBName();
477 String abstractType = obj.getMetadata(ObjectMetadata.ABSTRACT);
478 if (abstractType != null) {
479 String[] inheritors = obj.getMetadata(ObjectMetadata.INHERITORS).split(",");
480 String[] wrapped = new String[inheritors.length];
481 StringBuilder command = new StringBuilder();
482 command.append("P.within(");
483 for (int i = 0; i < inheritors.length; i++) {
484 wrapped[i] = "'" + inheritors[i] + "'";
486 command.append(Joiner.on(",").join(wrapped));
488 list.add(".has('aai-node-type', " + command + ")");
491 list.add(".has('aai-node-type', '" + type + "')");
494 this.markContainer();
495 return (QueryBuilder<Vertex>) this;
499 public QueryBuilder<E> union(QueryBuilder<E>... builder) {
500 markParentBoundary();
501 String[] traversals = new String[builder.length];
502 StringBuilder command = new StringBuilder();
503 for (int i = 0; i < builder.length; i++) {
504 traversals[i] = "__" + builder[i].getQuery();
506 command.append(".union(");
507 command.append(Joiner.on(",").join(traversals));
509 list.add(command.toString());
516 public QueryBuilder<E> where(QueryBuilder<E>... builder) {
517 markParentBoundary();
518 List<String> traversals = new ArrayList<>();
519 for (int i = 0; i < builder.length; i++) {
520 traversals.add(".where(__" + builder[i].getQuery() + ")");
523 list.addAll(traversals);
530 public QueryBuilder<E> or(QueryBuilder<E>... builder) {
531 markParentBoundary();
532 String[] traversals = new String[builder.length];
533 StringBuilder command = new StringBuilder();
534 for (int i = 0; i < builder.length; i++) {
535 traversals[i] = "__" + builder[i].getQuery();
537 command.append(".or(");
538 command.append(Joiner.on(",").join(traversals));
540 list.add(command.toString());
547 public QueryBuilder<E> store(String name) {
548 this.list.add(".store('"+ name + "')");
555 public QueryBuilder<E> cap(String name) {
556 this.list.add(".cap('"+ name + "')");
563 public QueryBuilder<E> unfold() {
564 this.list.add(".unfold()");
571 public QueryBuilder<E> dedup() {
572 this.list.add(".dedup()");
579 public QueryBuilder<E> emit() {
580 this.list.add(".emit()");
587 public QueryBuilder<E> repeat(QueryBuilder<E> builder) {
588 this.list.add(".repeat(__" + builder.getQuery() + ")");
595 public QueryBuilder<E> until(QueryBuilder<E> builder) {
596 this.list.add(".until(__" + builder.getQuery() + ")");
603 public QueryBuilder<E> groupCount() {
604 this.list.add(".groupCount()");
611 public QueryBuilder<E> both() {
612 this.list.add(".both()");
619 public QueryBuilder<Tree> tree() {
620 this.list.add(".tree()");
623 return (QueryBuilder<Tree>)this;
627 public QueryBuilder<E> by(String name) {
628 this.list.add(".by('"+ name + "')");
638 public QueryBuilder<E> simplePath(){
639 this.list.add(".simplePath()");
648 public QueryBuilder<Path> path(){
649 this.list.add(".path()");
651 return (QueryBuilder<Path>)this;
655 public QueryBuilder<Edge> outE() {
656 this.list.add(".outE()");
659 return (QueryBuilder<Edge>)this;
663 public QueryBuilder<Edge> inE() {
664 this.list.add(".inE()");
667 return (QueryBuilder<Edge>)this;
671 public QueryBuilder<Vertex> outV() {
672 this.list.add(".outV()");
675 return (QueryBuilder<Vertex>)this;
679 public QueryBuilder<Vertex> inV() {
680 this.list.add(".inV()");
683 return (QueryBuilder<Vertex>)this;
687 public QueryBuilder<E> not(QueryBuilder<E> builder) {
688 this.list.add(".not(" + "__" + builder.getQuery() + ")");
695 public QueryBuilder<E> as(String name) {
696 this.list.add(".as('" + name + "')");
703 public QueryBuilder<E> select(String name) {
704 this.list.add(".select('" + name + "')");
713 public QueryBuilder<E> getParentQuery() {
714 return cloneQueryAtStep(parentStepIndex);
718 public QueryBuilder<E> getContainerQuery() {
719 return cloneQueryAtStep(containerStepIndex);
726 public <T2> T2 getQuery() {
727 StringBuilder sb = new StringBuilder();
729 for (String piece : this.list) {
733 return (T2)sb.toString();
740 public void markParentBoundary() {
741 parentStepIndex = stepIndex;
745 public void markContainer() {
746 this.containerStepIndex = stepIndex;
753 public Vertex getStart() {
757 protected int getParentStepIndex() {
758 return parentStepIndex;
761 protected int getContainerStepIndex() {
762 return containerStepIndex;
765 protected int getStepIndex() {
769 private void executeQuery() {
770 String queryString = "g" + Joiner.on("").join(list);
771 Map<String, Object> params = new HashMap<>();
772 if (this.start == null) {
773 params.put("g", source.V());
775 params.put("g", source.V(this.start));
777 this.completeTraversal = this.gremlinGroovy.executeTraversal(queryString, params);
780 public boolean hasNext() {
781 if (this.completeTraversal == null) {
785 return this.completeTraversal.hasNext();
790 if (this.completeTraversal == null) {
794 return (E)this.completeTraversal.next();
798 public List<E> toList() {
799 if (this.completeTraversal == null) {
803 return (List<E>)this.completeTraversal.toList();
806 protected QueryBuilder<Edge> has(String key, String value) {
807 this.list.add(HAS + key + "','" + value + "')");
809 return (QueryBuilder<Edge>)this;