454aa1ee08d2cceb9f943c52559a4036244d12f9
[aai/aai-common.git] / aai-core / src / main / java / org / openecomp / aai / serialization / db / EdgeRules.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.openecomp.aai
4  * ================================================================================
5  * Copyright (C) 2017 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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.aai.serialization.db;
22
23 import static com.jayway.jsonpath.Criteria.where;
24 import static com.jayway.jsonpath.Filter.filter;
25
26 import java.io.InputStream;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.EnumMap;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Optional;
34 import java.util.Scanner;
35 import java.util.concurrent.ConcurrentHashMap;
36
37 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
38 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
39 import org.apache.tinkerpop.gremlin.structure.Direction;
40 import org.apache.tinkerpop.gremlin.structure.Edge;
41 import org.apache.tinkerpop.gremlin.structure.Vertex;
42 import org.openecomp.aai.db.props.AAIProperties;
43 import org.openecomp.aai.dbmodel.DbEdgeRules;
44 import org.openecomp.aai.exceptions.AAIException;
45 import org.openecomp.aai.introspection.Version;
46 import org.openecomp.aai.serialization.db.exceptions.EdgeMultiplicityException;
47 import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
48
49 import com.att.eelf.configuration.EELFLogger;
50 import com.att.eelf.configuration.EELFManager;
51 import com.google.common.collect.ArrayListMultimap;
52 import com.google.common.collect.Multimap;
53 import com.jayway.jsonpath.DocumentContext;
54 import com.jayway.jsonpath.Filter;
55 import com.jayway.jsonpath.JsonPath;
56
57 public class EdgeRules {
58         
59         private EELFLogger logger = EELFManager.getInstance().getLogger(EdgeRules.class);
60         
61         private Multimap<String, String> deleteScope =  DbEdgeRules.DefaultDeleteScope;
62         
63         private DocumentContext rulesDoc;
64         
65         /**
66          * Loads the most recent DbEdgeRules json file for later parsing.
67          * Only need most recent version for actual A&AI operations that call this class; 
68          *   the old ones are only used in tests.
69          */
70         private EdgeRules() {
71
72                 String json = this.getEdgeRuleJson(Version.getLatest());
73                 rulesDoc = JsonPath.parse(json);
74                 
75         }
76         
77         /**
78          * Loads the versioned DbEdgeRules json file for later parsing.
79          */
80         @SuppressWarnings("unchecked")
81         private EdgeRules(Version version) {
82                 
83                 String json = this.getEdgeRuleJson(version);
84                 rulesDoc = JsonPath.parse(json);
85                 
86                 if (!Version.isLatest(version)) {
87                         try {
88                                 Class<?> dbEdgeRules = Class.forName("org.openecomp.aai.dbmodel." + version.toString() + ".gen.DbEdgeRules");
89                                 this.deleteScope = (Multimap<String, String>)dbEdgeRules.getDeclaredField("DefaultDeleteScope").get(null);      
90                         } catch (Exception e) {
91                         }
92                 }
93         }
94         
95         private String getEdgeRuleJson(Version version) {
96                 InputStream is = getClass().getResourceAsStream("/dbedgerules/DbEdgeRules_" + version.toString() + ".json");
97
98                 Scanner scanner = new Scanner(is);
99                 String json = scanner.useDelimiter("\\Z").next();
100                 scanner.close();
101                 
102                 return json;
103         }
104         
105         private static class Helper {
106                 private static final EdgeRules INSTANCE = new EdgeRules();
107                 private static final Map<Version, EdgeRules> INSTANCEMAP = new ConcurrentHashMap<>();
108                 private static EdgeRules getVersionedEdgeRules(Version v) {
109                         if (Version.isLatest(v)) {
110                                 return INSTANCE;
111                         }
112                         if (!INSTANCEMAP.containsKey(v)) {
113                                 INSTANCEMAP.put(v, new EdgeRules(v));
114                         }
115                         return INSTANCEMAP.get(v);
116                 }
117         }
118         
119         /**
120          * Gets the single instance of EdgeRules.
121          *
122          * @return single instance of EdgeRules
123          */
124         public static EdgeRules getInstance() {
125                 return Helper.INSTANCE;
126
127         }
128         
129         /**
130          * Gets the versioned instance of EdgeRules.
131          *
132          * @return versioned instance of EdgeRules
133          */
134         public static EdgeRules getInstance(Version v) {
135                 return Helper.getVersionedEdgeRules(v);
136
137         }
138         
139         /**
140          * Adds the tree edge.
141          *
142          * @param aVertex the out vertex
143          * @param bVertex the in vertex
144          * @return the edge
145          * @throws AAIException the AAI exception
146          */
147         public Edge addTreeEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
148                 return this.addEdge(EdgeType.TREE, traversalSource, aVertex, bVertex, false);
149         }
150         
151         /**
152          * Adds the edge.
153          *
154          * @param aVertex the out vertex
155          * @param bVertex the in vertex
156          * @return the edge
157          * @throws AAIException the AAI exception
158          */
159         public Edge addEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
160                 return this.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, false);
161         }
162         
163         /**
164          * Adds the tree edge.
165          *
166          * @param aVertex the out vertex
167          * @param bVertex the in vertex
168          * @return the edge
169          * @throws AAIException the AAI exception
170          */
171         public Edge addTreeEdgeIfPossible(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
172                 return this.addEdge(EdgeType.TREE, traversalSource, aVertex, bVertex, true);
173         }
174         
175         /**
176          * Adds the edge.
177          *
178          * @param aVertex the out vertex
179          * @param bVertex the in vertex
180          * @return the edge
181          * @throws AAIException the AAI exception
182          */
183         public Edge addEdgeIfPossible(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
184                 return this.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, true);
185         }
186         
187         /**
188          * Adds the edge.
189          *
190          * @param type the type
191          * @param aVertex the out vertex
192          * @param bVertex the in vertex
193          * @return the edge
194          * @throws AAIException the AAI exception
195          */
196         private Edge addEdge(EdgeType type, GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex, boolean isBestEffort) throws AAIException {
197
198                 EdgeRule rule = this.getEdgeRule(type, aVertex, bVertex);
199
200                 Edge e = null;
201                 
202                 Optional<String> message = this.validateMultiplicity(rule, traversalSource, aVertex, bVertex);
203                 
204                 if (message.isPresent() && !isBestEffort) {
205                         throw new EdgeMultiplicityException(message.get());
206                 }
207                 if (!message.isPresent()) {
208                         if (rule.getDirection().equals(Direction.OUT)) {
209                                 e = aVertex.addEdge(rule.getLabel(), bVertex);
210                         } else if (rule.getDirection().equals(Direction.IN)) {
211                                 e = bVertex.addEdge(rule.getLabel(), aVertex);
212                         }
213                         
214                         this.addProperties(e, rule);
215                 }
216                 return e;
217         }
218
219         /**
220          * Adds the properties.
221          *
222          * @param edge the edge
223          * @param rule the rule
224          */
225         public void addProperties(Edge edge, EdgeRule rule) {
226                 
227                 // In DbEdgeRules.EdgeRules -- What we have as "edgeRule" is a comma-delimited set of strings.
228                 // The first item is the edgeLabel.
229                 // The second in the list is always "direction" which is always OUT for the way we've implemented it.
230                 // Items starting at "firstTagIndex" and up are all assumed to be booleans that map according to 
231                 // tags as defined in EdgeInfoMap.
232                 // Note - if they are tagged as 'reverse', that means they get the tag name with "-REV" on it
233                 Map<String, String> propMap = rule.getEdgeProperties();
234                 
235                 for (String key : propMap.keySet()) {
236                         String revKeyname = key + "-REV";
237                         String triple = propMap.get(key);
238                         if(triple.equals("true")){
239                                 edge.property(key, true);
240                                 edge.property(revKeyname,false);
241                         } else if (triple.equals("false")) {
242                                 edge.property(key, false);
243                                 edge.property(revKeyname,false);
244                         } else if (triple.equals("reverse")) {
245                                 edge.property(key, false);
246                                 edge.property(revKeyname,true);
247                         }
248                 }
249         }
250         
251         /**
252          * Checks if any edge rules exist between the two given nodes, in either A|B or B|A order.
253          *
254          * @param nodeA - node at one end of the edge
255          * @param nodeB - node at the other end
256          * @return true, if any such rules exist
257          */
258         public boolean hasEdgeRule(String nodeA, String nodeB) {
259                 Filter aToB = filter(
260                                 where("from").is(nodeA).and("to").is(nodeB)
261                                 );
262                 Filter bToA = filter(
263                                 where("from").is(nodeB).and("to").is(nodeA)
264                                 );
265                 
266                 List<Object> results = rulesDoc.read("$.rules.[?]", aToB);
267                 results.addAll(rulesDoc.read("$.rules.[?]", bToA));
268
269                 return !results.isEmpty();
270                 
271         }
272         
273         /**
274          * Checks if any edge rules exist between the two given nodes, in either A|B or B|A order.
275          *
276          * @param aVertex - node at one end of the edge
277          * @param bVertex - node at the other end
278          * @return true, if any such rules exist
279          */
280         public boolean hasEdgeRule(Vertex aVertex, Vertex bVertex) {
281                 String outType = aVertex.<String>property("aai-node-type").orElse(null);
282                 String inType = bVertex.<String>property("aai-node-type").orElse(null);
283                 
284                 return this.hasEdgeRule(outType, inType);
285                 
286         }
287         
288         /**
289          * Gets all the edge rules that exist between the given node types.
290          * The rules will be phrased in terms of out|in, though this will
291          * also find rules defined as in|out (it will flip the direction in
292          * the EdgeRule object returned accordingly to match out|in).
293          * 
294          * @param outType 
295          * @param inType
296          * @return Map<String edgeLabel, EdgeRule rule> where edgeLabel is the label name
297          * @throws AAIException
298          */
299         public Map<String, EdgeRule> getEdgeRules(String outType, String inType) throws AAIException {
300                 Map<String, EdgeRule> result = new HashMap<>();
301                 EdgeRule rule = null;
302                 for (EdgeType type : EdgeType.values()) {
303                         try {
304                                 rule = this.getEdgeRule(type, outType, inType);
305                                 result.put(rule.getLabel(), rule);
306                         } catch (NoEdgeRuleFoundException e) {
307                                 continue;
308                         }
309                 }
310                 
311                 return result;
312         }
313         
314         /**
315          * Gets the edge rule of the given type that exists between A and B.
316          * Will check B|A as well, and flips the direction accordingly if that succeeds
317          * to match the expected A|B return.
318          *
319          * @param type - the type of edge you're looking for
320          * @param nodeA - first node type
321          * @param nodeB - second node type
322          * @return EdgeRule describing the rule in terms of A|B, if there is any such rule
323          * @throws AAIException if no such edge exists
324          */
325         public EdgeRule getEdgeRule(EdgeType type, String nodeA, String nodeB) throws AAIException {
326                 //try A to B
327                 List<Map<String, String>> aToBEdges = rulesDoc.read("$.rules.[?]", buildFilter(type, nodeA, nodeB));
328                 if (!aToBEdges.isEmpty()) {
329                         //lazily stop iterating if we find a match
330                         //should there be a mismatch between type and isParent,
331                         //the caller will receive something.
332                         //this operates on the assumption that there are at most two rules
333                         //for a given vertex pair
334                         return buildRule(aToBEdges.get(0));
335                 }
336                 
337                 //we get here if there was nothing for A to B, so let's try B to A
338                 List<Map<String, String>> bToAEdges = rulesDoc.read("$.rules.[?]", buildFilter(type, nodeB, nodeA));
339                 if (!bToAEdges.isEmpty()) {
340                         return flipDirection(buildRule(bToAEdges.get(0))); //bc we need to return as A|B, so flip the direction to match
341                 }
342                 
343                 //found none
344                 throw new NoEdgeRuleFoundException("no " + type.toString() + " edge between " + nodeA + " and " + nodeB);
345         }
346         
347         /**
348          * Builds a JsonPath filter to search for an edge from nodeA to nodeB with the given edge type (cousin or parent/child)
349          * 
350          * @param type
351          * @param nodeA - start node
352          * @param nodeB - end node
353          * @return
354          */
355         private Filter buildFilter(EdgeType type, String nodeA, String nodeB) {
356                 if (EdgeType.COUSIN.equals(type)) {
357                         return filter(
358                                         where("from").is(nodeA).and("to").is(nodeB).and("isParent").is("false")
359                                         );
360                 } else {
361                         return filter(
362                                         where("from").is(nodeA).and("to").is(nodeB).and("isParent").is("true")).or(
363                                                         where("from").is(nodeA).and("to").is(nodeB).and("isParent").is("reverse")       
364                                         );
365                 }
366         }
367         
368         /**
369          * Puts the give edge rule information into an EdgeRule object. 
370          * 
371          * @param edge - the edge information returned from JsonPath
372          * @return EdgeRule containing that information
373          */
374         private EdgeRule buildRule(Map<String, String> edge) {
375                 EdgeRule rule = new EdgeRule();
376                 rule.setLabel(edge.get("label"));
377                 rule.setDirection(edge.get("direction"));
378                 rule.setMultiplicityRule(edge.get("multiplicity"));
379                 rule.setIsParent(edge.get("isParent"));
380                 rule.setUsesResource(edge.get("usesResource"));
381                 rule.setHasDelTarget(edge.get("hasDelTarget"));
382                 rule.setServiceInfrastructure(edge.get("SVC-INFRA"));
383                 return rule;
384         }
385         
386         /**
387          * If getEdgeRule gets a request for A|B, and it finds something as B|A, the caller still expects
388          * the returned EdgeRule to reflect A|B directionality. This helper method flips B|A direction to
389          * match this expectation.
390          * 
391          * @param rule whose direction needs flipped
392          * @return the updated rule
393          */
394         private EdgeRule flipDirection(EdgeRule rule) {
395                 if (Direction.IN.equals(rule.getDirection())) {
396                         rule.setDirection(Direction.OUT);
397                         return rule;
398                 } else if (Direction.OUT.equals(rule.getDirection())) {
399                         rule.setDirection(Direction.IN);
400                         return rule;
401                 } else { //direction is BOTH, flipping both is still both
402                         return rule; 
403                 }
404         }
405         
406         /**
407          * Gets the edge rule of the given type that exists between A and B.
408          * Will check B|A as well, and flips the direction accordingly if that succeeds
409          * to match the expected A|B return.
410          *
411          * @param type - the type of edge you're looking for
412          * @param aVertex - first node type
413          * @param bVertex - second node type
414          * @return EdgeRule describing the rule in terms of A|B, if there is any such rule
415          * @throws AAIException if no such edge exists
416          */
417         public EdgeRule getEdgeRule(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException {
418                 String outType = aVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
419                 String inType = bVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
420                 
421                 return this.getEdgeRule(type, outType, inType);
422
423                 
424         }
425         
426         /**
427          * Gets the delete semantic.
428          *
429          * @param nodeType the node type
430          * @return the delete semantic
431          */
432         public DeleteSemantic getDeleteSemantic(String nodeType) {
433                 Collection<String> semanticCollection = deleteScope.get(nodeType);
434                 String semantic = semanticCollection.iterator().next();
435                 
436                 return DeleteSemantic.valueOf(semantic);
437                 
438         }
439         
440         /**
441          * Validate multiplicity.
442          *
443          * @param rule the rule
444          * @param aVertex the out vertex
445          * @param bVertex the in vertex
446          * @return true, if successful
447          * @throws AAIException the AAI exception
448          */
449         private Optional<String> validateMultiplicity(EdgeRule rule, GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) {
450
451                 if (rule.getDirection().equals(Direction.OUT)) {
452                         
453                 } else if (rule.getDirection().equals(Direction.IN)) {
454                         Vertex tempV = bVertex;
455                         bVertex = aVertex;
456                         aVertex = tempV;
457                 }
458                                 
459                 String aVertexType = aVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
460                 String bVertexType =  bVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
461                 String label = rule.getLabel();
462                 MultiplicityRule multiplicityRule = rule.getMultiplicityRule();
463                 List<Edge> outEdges = traversalSource.V(aVertex).outE(label).where(__.inV().has(AAIProperties.NODE_TYPE, bVertexType)).toList();
464                 List<Edge> inEdges = traversalSource.V(bVertex).inE(label).where(__.outV().has(AAIProperties.NODE_TYPE, aVertexType)).toList();
465                 String detail = "";
466                 if (multiplicityRule.equals(MultiplicityRule.ONE2ONE)) {
467                         if (inEdges.size() >= 1 || outEdges.size() >= 1 ) {
468                                 detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType;
469                         }
470                 } else if (multiplicityRule.equals(MultiplicityRule.ONE2MANY)) {
471                         if (inEdges.size() >= 1) {
472                                 detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType;
473                         }
474                 } else if (multiplicityRule.equals(MultiplicityRule.MANY2ONE)) {
475                         if (outEdges.size() >= 1) {
476                                 detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType;
477                         }
478                 } else {
479                         
480                 }
481                 
482                 if (!"".equals(detail)) {
483                         return Optional.of(detail);
484                 } else  {
485                         return Optional.empty();
486                 }
487                 
488                                 
489         }
490         
491         /**
492          * Gets all the edge rules we define.
493          * 
494          * @return Multimap<String "from|to", EdgeRule rule>
495          */
496         public Multimap<String, EdgeRule> getAllRules() {
497                 Multimap<String, EdgeRule> result = ArrayListMultimap.create();
498                 
499                 List<Map<String, String>> rules = rulesDoc.read("$.rules.*");
500                 for (Map<String, String> rule : rules) {
501                         EdgeRule er = buildRule(rule);
502                         String name = rule.get("from") + "|" + rule.get("to");
503                         result.put(name, er);
504                 }
505                 
506                 return result;
507         }
508         
509         public Multimap<String, String> getDeleteSemantics() {
510                 return this.deleteScope;
511         }
512         
513 }