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.GremlinGroovyShell;
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 GremlinGroovyShell gremlinGroovy = new GremlinGroovyShell();
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;
110 public QueryBuilder<Vertex> getVerticesByNumberProperty(String key, Object value) {
111 list.add(HAS + key + "', " + value + ")");
113 return (QueryBuilder<Vertex>) this;
117 public QueryBuilder<Vertex> getVerticesByBooleanProperty(String key, Object value) {
118 boolean bValue = false;
120 if(value instanceof String){
121 bValue = Boolean.valueOf(value.toString());
122 } else if(value instanceof Boolean){
123 bValue = (Boolean) value;
126 list.add(HAS + key + "', " + bValue + ")");
128 return (QueryBuilder<Vertex>) this;
135 public QueryBuilder<Vertex> getVerticesByProperty(String key, List<?> values) {
137 String predicate = "P.within(#!#argument#!#)";
138 List<String> arguments = new ArrayList<>();
139 for (Object item : values) {
140 if (item != null && !(item instanceof String)) {
141 arguments.add(item.toString());
143 arguments.add("'" + item + "'");
146 String argument = Joiner.on(",").join(arguments);
147 predicate = predicate.replace(ARGUMENT2, argument);
148 list.add(HAS + key + "', " + predicate + ")");
150 return (QueryBuilder<Vertex>) this;
157 public QueryBuilder<Vertex> getVerticesByProperty(String key) {
159 list.add(HAS + key + "')");
161 return (QueryBuilder<Vertex>) this;
168 public QueryBuilder<Vertex> getVerticesExcludeByProperty(String key) {
170 list.add(".hasNot('" + key + "')");
172 return (QueryBuilder<Vertex>) this;
179 public QueryBuilder<Vertex> getVerticesStartsWithProperty(String key, Object value) {
182 String predicate = "org.janusgraph.core.attribute.Text.textPrefix(#!#argument#!#)";
183 if (value != null && !(value instanceof String) ) {
184 term = value.toString();
186 term = "'" + value + "'";
188 predicate = predicate.replace(ARGUMENT2, term);
189 list.add(HAS + key + "', " + predicate + ")");
191 return (QueryBuilder<Vertex>) this;
198 public QueryBuilder<Vertex> getVerticesExcludeByProperty(String key, Object value) {
201 String predicate = "P.neq(#!#argument#!#)";
202 if (value != null && !(value instanceof String) ) {
203 term = value.toString();
205 term = "'" + value + "'";
207 predicate = predicate.replace(ARGUMENT2, term);
208 list.add(HAS + key + "', " + predicate + ")");
210 return (QueryBuilder<Vertex>) this;
217 public QueryBuilder<Vertex> getVerticesExcludeByProperty(String key, List<?> values) {
219 String predicate = "P.without(#!#argument#!#)";
220 List<String> arguments = new ArrayList<>();
221 for (Object item : values) {
222 if (item != null && !(item instanceof String)) {
223 arguments.add(item.toString());
225 arguments.add("'" + item + "'");
228 String argument = Joiner.on(",").join(arguments);
229 predicate = predicate.replace(ARGUMENT2, argument);
230 list.add(HAS + key + "', " + predicate + ")");
232 return (QueryBuilder<Vertex>) this;
236 public QueryBuilder<Vertex> getVerticesGreaterThanProperty(String key, Object value) {
237 String predicate = "P.gte(#!#argument1#!#)";
239 if (value != null && !(value instanceof String) ) {
240 term = value.toString();
242 term = "'" + value + "'";
244 predicate = predicate.replace("#!#argument1#!#", term);
245 list.add(HAS + key + "', " + predicate + ")");
247 return (QueryBuilder<Vertex>) this;
251 public QueryBuilder<Vertex> getVerticesLessThanProperty(String key, Object value) {
252 String predicate = "P.lte(#!#argument1#!#)";
254 if (value != null && !(value instanceof String) ) {
255 term = value.toString();
257 term = "'" + value + "'";
259 predicate = predicate.replace("#!#argument1#!#", term);
260 list.add(HAS + key + "', " + predicate + ")");
262 return (QueryBuilder<Vertex>) this;
272 public QueryBuilder<Vertex> getChildVerticesFromParent(String parentKey, String parentValue, String childType) {
274 return (QueryBuilder<Vertex>) this;
281 public QueryBuilder<Vertex> getTypedVerticesByMap(String type, Map<String, String> map) {
283 for (Map.Entry<String, String> es : map.entrySet()) {
284 list.add(HAS + es.getKey() + "', '" + es.getValue() + "')");
287 list.add(".has('aai-node-type', '" + type + "')");
289 return (QueryBuilder<Vertex>) this;
296 public QueryBuilder<Vertex> createKeyQuery(Introspector obj) {
297 Set<String> keys = obj.getKeys();
299 for (String key : keys) {
301 this.getVerticesByProperty(key, obj.<Object>getValue(key));
304 return (QueryBuilder<Vertex>) this;
308 * @throws NoEdgeRuleFoundException
309 * @throws AAIException
313 public QueryBuilder createEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException {
314 String parentName = parent.getDbName();
315 String childName = child.getDbName();
316 if (parent.isContainer()) {
317 parentName = parent.getChildDBName();
319 if (child.isContainer()) {
320 childName = child.getChildDBName();
322 this.edgeQueryToVertex(type, parentName, childName, null);
328 public QueryBuilder createPrivateEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException{
329 String parentName = parent.getDbName();
330 String childName = child.getDbName();
331 if (parent.isContainer()) {
332 parentName = parent.getChildDBName();
334 if (child.isContainer()) {
335 childName = child.getChildDBName();
337 this.edgeQueryToVertex(type, parentName, childName, null, true);
346 public QueryBuilder<Vertex> createEdgeTraversalWithLabels(EdgeType type, Introspector out, Introspector in, List<String> labels) throws AAIException {
347 String parentName = out.getDbName();
348 String childName = in.getDbName();
349 if (out.isContainer()) {
350 parentName = out.getChildDBName();
352 if (in.isContainer()) {
353 childName = in.getChildDBName();
355 this.edgeQueryToVertex(type, parentName, childName, labels);
356 return (QueryBuilder<Vertex>) this;
360 public QueryBuilder<Edge> getEdgesBetweenWithLabels(EdgeType type, String outNodeType, String inNodeType, List<String> labels) throws AAIException {
361 this.edgeQuery(type, outNodeType, inNodeType, labels);
362 return (QueryBuilder<Edge>)this;
365 private void edgeQueryToVertex(EdgeType type, String outType, String inType, List<String> labels) throws AAIException {
366 this.edgeQueryToVertex(type, outType, inType, labels, false);
372 * @param outType the out type
373 * @param inType the in type
374 * @throws NoEdgeRuleFoundException
375 * @throws AAIException
377 private void edgeQueryToVertex(EdgeType type, String outType, String inType, List<String> labels, boolean isPrivateEdge) throws AAIException {
378 markParentBoundary();
379 Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
380 EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type).setPrivate(isPrivateEdge);
383 if (labels == null) {
384 rules.putAll(edgeRules.getRules(qB.build()));
386 for (String label : labels) {
387 rules.putAll(edgeRules.getRules(qB.label(label).build()));
390 } catch (EdgeRuleNotFoundException e) {
391 throw new NoEdgeRuleFoundException(e);
394 final List<String> inLabels = new ArrayList<>();
395 final List<String> outLabels = new ArrayList<>();
397 for (EdgeRule rule : rules.values()) {
398 if (labels != null && !labels.contains(rule.getLabel())) {
401 if (Direction.IN.equals(rule.getDirection())) {
402 inLabels.add(rule.getLabel());
403 if(inType.equals(outType)) {//code to handle when a type edges to itself, to add both in and out
404 outLabels.add(rule.getLabel());
407 outLabels.add(rule.getLabel());
408 if(inType.equals(outType)) {//code to handle when a type edges to itself, to add both in and out
409 inLabels.add(rule.getLabel());
415 if(inLabels.isEmpty() && outLabels.isEmpty()) {
416 throw new NoEdgeRuleFoundException("no " + type.toString() + " edge rule between " + outType + " and " + inType );
417 } else if (inLabels.isEmpty() && !outLabels.isEmpty()) {
418 list.add(".out('" + String.join("','", outLabels) + "')");
419 } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
420 list.add(".in('" + String.join("','", inLabels) + "')");
422 list.add(".union(__.in('" + String.join("','", inLabels) + "')" + ", __.out('" + String.join("','", outLabels) + "'))");
425 list.add(HAS + AAIProperties.NODE_TYPE + "', '" + inType + "')");
433 * @param outType the out type
434 * @param inType the in type
435 * @throws NoEdgeRuleFoundException
436 * @throws AAIException
438 private void edgeQuery(EdgeType type, String outType, String inType, List<String> labels) throws AAIException {
439 markParentBoundary();
440 Multimap<String, EdgeRule> rules = ArrayListMultimap.create();
441 EdgeRuleQuery.Builder qB = new EdgeRuleQuery.Builder(outType, inType).edgeType(type);
443 if (labels == null) {
444 rules.putAll(edgeRules.getRules(qB.build()));
446 for (String label : labels) {
447 rules.putAll(edgeRules.getRules(qB.label(label).build()));
450 } catch (EdgeRuleNotFoundException e) {
451 throw new NoEdgeRuleFoundException(e);
454 final List<String> inLabels = new ArrayList<>();
455 final List<String> outLabels = new ArrayList<>();
457 for (EdgeRule rule : rules.values()) {
458 if (labels != null && !labels.contains(rule.getLabel())) {
461 if (Direction.IN.equals(rule.getDirection())) {
462 inLabels.add(rule.getLabel());
464 outLabels.add(rule.getLabel());
469 if(inLabels.isEmpty() && outLabels.isEmpty()) {
470 throw new NoEdgeRuleFoundException("no " + type.toString() + " edge rule between " + outType + " and " + inType );
471 } else if (inLabels.isEmpty() && !outLabels.isEmpty()) {
472 list.add(".outE('" + String.join("','", outLabels) + "')");
473 } else if (outLabels.isEmpty() && !inLabels.isEmpty()) {
474 list.add(".inE('" + String.join("','", inLabels) + "')");
476 list.add(".union(__.inE('" + String.join("','", inLabels) + "')" + ", __.outE('" + String.join("','", outLabels) + "'))");
483 public QueryBuilder<E> limit(long amount) {
484 list.add(".limit(" + amount + ")");
491 public QueryBuilder<Vertex> createContainerQuery(Introspector obj) {
492 String type = obj.getChildDBName();
493 String abstractType = obj.getMetadata(ObjectMetadata.ABSTRACT);
494 if (abstractType != null) {
495 String[] inheritors = obj.getMetadata(ObjectMetadata.INHERITORS).split(",");
496 String[] wrapped = new String[inheritors.length];
497 StringBuilder command = new StringBuilder();
498 command.append("P.within(");
499 for (int i = 0; i < inheritors.length; i++) {
500 wrapped[i] = "'" + inheritors[i] + "'";
502 command.append(Joiner.on(",").join(wrapped));
504 list.add(".has('aai-node-type', " + command + ")");
507 list.add(".has('aai-node-type', '" + type + "')");
510 this.markContainer();
511 return (QueryBuilder<Vertex>) this;
515 public QueryBuilder<E> union(QueryBuilder<E>... builder) {
516 markParentBoundary();
517 String[] traversals = new String[builder.length];
518 StringBuilder command = new StringBuilder();
519 for (int i = 0; i < builder.length; i++) {
520 traversals[i] = "__" + builder[i].getQuery();
522 command.append(".union(");
523 command.append(Joiner.on(",").join(traversals));
525 list.add(command.toString());
532 public QueryBuilder<E> where(QueryBuilder<E>... builder) {
533 markParentBoundary();
534 List<String> traversals = new ArrayList<>();
535 for (int i = 0; i < builder.length; i++) {
536 traversals.add(".where(__" + builder[i].getQuery() + ")");
539 list.addAll(traversals);
546 public QueryBuilder<E> or(QueryBuilder<E>... builder) {
547 markParentBoundary();
548 String[] traversals = new String[builder.length];
549 StringBuilder command = new StringBuilder();
550 for (int i = 0; i < builder.length; i++) {
551 traversals[i] = "__" + builder[i].getQuery();
553 command.append(".or(");
554 command.append(Joiner.on(",").join(traversals));
556 list.add(command.toString());
563 public QueryBuilder<E> store(String name) {
564 this.list.add(".store('"+ name + "')");
571 public QueryBuilder<E> cap(String name) {
572 this.list.add(".cap('"+ name + "')");
579 public QueryBuilder<E> unfold() {
580 this.list.add(".unfold()");
587 public QueryBuilder<E> dedup() {
588 this.list.add(".dedup()");
595 public QueryBuilder<E> emit() {
596 this.list.add(".emit()");
603 public QueryBuilder<E> repeat(QueryBuilder<E> builder) {
604 this.list.add(".repeat(__" + builder.getQuery() + ")");
611 public QueryBuilder<E> until(QueryBuilder<E> builder) {
612 this.list.add(".until(__" + builder.getQuery() + ")");
619 public QueryBuilder<E> groupCount() {
620 this.list.add(".groupCount()");
627 public QueryBuilder<E> both() {
628 this.list.add(".both()");
635 public QueryBuilder<Tree> tree() {
636 this.list.add(".tree()");
639 return (QueryBuilder<Tree>)this;
643 public QueryBuilder<E> by(String name) {
644 this.list.add(".by('"+ name + "')");
654 public QueryBuilder<E> simplePath(){
655 this.list.add(".simplePath()");
664 public QueryBuilder<Path> path(){
665 this.list.add(".path()");
667 return (QueryBuilder<Path>)this;
671 public QueryBuilder<Edge> outE() {
672 this.list.add(".outE()");
675 return (QueryBuilder<Edge>)this;
679 public QueryBuilder<Edge> inE() {
680 this.list.add(".inE()");
683 return (QueryBuilder<Edge>)this;
687 public QueryBuilder<Vertex> outV() {
688 this.list.add(".outV()");
691 return (QueryBuilder<Vertex>)this;
695 public QueryBuilder<Vertex> inV() {
696 this.list.add(".inV()");
699 return (QueryBuilder<Vertex>)this;
703 public QueryBuilder<E> not(QueryBuilder<E> builder) {
704 this.list.add(".not(" + "__" + builder.getQuery() + ")");
711 public QueryBuilder<E> as(String name) {
712 this.list.add(".as('" + name + "')");
719 public QueryBuilder<E> select(String name) {
720 this.list.add(".select('" + name + "')");
727 public QueryBuilder<E> select(String... names) {
728 String stepString = ".select('";
729 for(int i = 0; i<names.length; i++) {
730 stepString = stepString + names[i] +"'";
731 if(i!=(names.length-1)) {
732 stepString = stepString + ",'";
735 stepString = stepString + ")";
736 this.list.add(stepString);
745 public QueryBuilder<E> getParentQuery() {
746 return cloneQueryAtStep(parentStepIndex);
750 public QueryBuilder<E> getContainerQuery() {
751 return cloneQueryAtStep(containerStepIndex);
758 public <T2> T2 getQuery() {
759 StringBuilder sb = new StringBuilder();
761 for (String piece : this.list) {
765 return (T2)sb.toString();
772 public void markParentBoundary() {
773 parentStepIndex = stepIndex;
777 public void markContainer() {
778 this.containerStepIndex = stepIndex;
785 public Vertex getStart() {
789 protected int getParentStepIndex() {
790 return parentStepIndex;
793 protected int getContainerStepIndex() {
794 return containerStepIndex;
797 protected int getStepIndex() {
801 private void executeQuery() {
802 String queryString = "g" + Joiner.on("").join(list);
803 Map<String, Object> params = new HashMap<>();
804 if (this.start == null) {
805 params.put("g", source.V());
807 params.put("g", source.V(this.start));
809 this.completeTraversal = this.gremlinGroovy.executeTraversal(queryString, params);
812 public boolean hasNext() {
813 if (this.completeTraversal == null) {
817 return this.completeTraversal.hasNext();
822 if (this.completeTraversal == null) {
826 return (E)this.completeTraversal.next();
830 public List<E> toList() {
831 if (this.completeTraversal == null) {
835 return (List<E>)this.completeTraversal.toList();
838 protected QueryBuilder<Edge> has(String key, String value) {
839 this.list.add(HAS + key + "','" + value + "')");
841 return (QueryBuilder<Edge>)this;