2 * ============LICENSE_START=======================================================
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
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.openecomp.aai.serialization.db;
23 import static com.jayway.jsonpath.Criteria.where;
24 import static com.jayway.jsonpath.Filter.filter;
26 import java.io.InputStream;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.List;
31 import java.util.Map.Entry;
32 import java.util.Optional;
33 import java.util.Scanner;
35 import java.util.concurrent.ConcurrentHashMap;
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.exceptions.AAIException;
44 import org.openecomp.aai.introspection.Version;
45 import org.openecomp.aai.serialization.db.exceptions.EdgeMultiplicityException;
46 import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
48 import com.att.eelf.configuration.EELFLogger;
49 import com.att.eelf.configuration.EELFManager;
50 import com.google.common.collect.ArrayListMultimap;
51 import com.google.common.collect.Multimap;
52 import com.jayway.jsonpath.DocumentContext;
53 import com.jayway.jsonpath.Filter;
54 import com.jayway.jsonpath.JsonPath;
56 public class EdgeRules {
58 private EELFLogger logger = EELFManager.getInstance().getLogger(EdgeRules.class);
60 private DocumentContext rulesDoc;
63 * Loads the most recent DbEdgeRules json file for later parsing.
64 * Only need most recent version for actual A&AI operations that call this class;
65 * the old ones are only used in tests.
69 String json = this.getEdgeRuleJson(Version.getLatest());
70 rulesDoc = JsonPath.parse(json);
74 private EdgeRules(String rulesFilename) {
75 String json = this.getEdgeRuleJson(rulesFilename);
76 rulesDoc = JsonPath.parse(json);
79 private String getEdgeRuleJson(String rulesFilename) {
80 InputStream is = getClass().getResourceAsStream(rulesFilename);
82 Scanner scanner = new Scanner(is);
83 String json = scanner.useDelimiter("\\Z").next();
90 * Loads the versioned DbEdgeRules json file for later parsing.
92 @SuppressWarnings("unchecked")
93 private EdgeRules(Version version) {
94 String json = this.getEdgeRuleJson(version);
95 rulesDoc = JsonPath.parse(json);
98 private String getEdgeRuleJson(Version version) {
99 InputStream is = getClass().getResourceAsStream("/dbedgerules/DbEdgeRules_" + version.toString() + ".json");
101 Scanner scanner = new Scanner(is);
102 String json = scanner.useDelimiter("\\Z").next();
108 private static class Helper {
109 private static final EdgeRules INSTANCE = new EdgeRules();
110 private static final Map<Version, EdgeRules> INSTANCEMAP = new ConcurrentHashMap<>();
112 private static EdgeRules getEdgeRulesByFilename(String rulesFilename) {
113 return new EdgeRules(rulesFilename);
116 private static EdgeRules getVersionedEdgeRules(Version v) {
117 if (Version.isLatest(v)) {
120 if (!INSTANCEMAP.containsKey(v)) {
121 INSTANCEMAP.put(v, new EdgeRules(v));
123 return INSTANCEMAP.get(v);
128 * Gets the single instance of EdgeRules.
130 * @return single instance of EdgeRules
132 public static EdgeRules getInstance() {
133 return Helper.INSTANCE;
138 * Gets the versioned instance of EdgeRules.
140 * @return versioned instance of EdgeRules
142 public static EdgeRules getInstance(Version v) {
143 return Helper.getVersionedEdgeRules(v);
148 * Loads edge rules from the given file.
150 * @param rulesFilename - name of the file to load rules from
151 * @return the EdgeRules instance
153 public static EdgeRules getInstance(String rulesFilename) {
154 return Helper.getEdgeRulesByFilename(rulesFilename);
158 * Adds the tree edge.
160 * @param aVertex the out vertex
161 * @param bVertex the in vertex
163 * @throws AAIException the AAI exception
165 public Edge addTreeEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
166 return this.addEdge(EdgeType.TREE, traversalSource, aVertex, bVertex, false);
172 * @param aVertex the out vertex
173 * @param bVertex the in vertex
175 * @throws AAIException the AAI exception
177 public Edge addEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
178 return this.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, false);
182 * Adds the tree edge.
184 * @param aVertex the out vertex
185 * @param bVertex the in vertex
187 * @throws AAIException the AAI exception
189 public Edge addTreeEdgeIfPossible(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
190 return this.addEdge(EdgeType.TREE, traversalSource, aVertex, bVertex, true);
196 * @param aVertex the out vertex
197 * @param bVertex the in vertex
199 * @throws AAIException the AAI exception
201 public Edge addEdgeIfPossible(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException {
202 return this.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, true);
208 * @param type the type
209 * @param aVertex the out vertex
210 * @param bVertex the in vertex
212 * @throws AAIException the AAI exception
214 private Edge addEdge(EdgeType type, GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex, boolean isBestEffort) throws AAIException {
216 EdgeRule rule = this.getEdgeRule(type, aVertex, bVertex);
220 Optional<String> message = this.validateMultiplicity(rule, traversalSource, aVertex, bVertex);
222 if (message.isPresent() && !isBestEffort) {
223 throw new EdgeMultiplicityException(message.get());
225 if (!message.isPresent()) {
226 if (rule.getDirection().equals(Direction.OUT)) {
227 e = aVertex.addEdge(rule.getLabel(), bVertex);
228 } else if (rule.getDirection().equals(Direction.IN)) {
229 e = bVertex.addEdge(rule.getLabel(), aVertex);
232 this.addProperties(e, rule);
238 * Adds the properties.
240 * @param edge the edge
241 * @param rule the rule
243 public void addProperties(Edge edge, EdgeRule rule) {
245 // In DbEdgeRules.EdgeRules -- What we have as "edgeRule" is a comma-delimited set of strings.
246 // The first item is the edgeLabel.
247 // The second in the list is always "direction" which is always OUT for the way we've implemented it.
248 // Items starting at "firstTagIndex" and up are all assumed to be booleans that map according to
249 // tags as defined in EdgeInfoMap.
250 // Note - if they are tagged as 'reverse', that means they get the tag name with "-REV" on it
251 Map<EdgeProperty, String> propMap = rule.getEdgeProperties();
253 for (Entry<EdgeProperty, String> entry : propMap.entrySet()) {
254 edge.property(entry.getKey().toString(), entry.getValue());
259 * Checks if any edge rules exist between the two given nodes, in either A|B or B|A order.
261 * @param nodeA - node at one end of the edge
262 * @param nodeB - node at the other end
263 * @return true, if any such rules exist
265 public boolean hasEdgeRule(String nodeA, String nodeB) {
266 Filter aToB = filter(
267 where("from").is(nodeA).and("to").is(nodeB)
269 Filter bToA = filter(
270 where("from").is(nodeB).and("to").is(nodeA)
273 List<Map<String, String>> results = readRules(aToB);
274 results.addAll(readRules(bToA));
276 return !results.isEmpty();
281 * Checks if any edge rules exist between the two given nodes, in either A|B or B|A order.
283 * @param aVertex - node at one end of the edge
284 * @param bVertex - node at the other end
285 * @return true, if any such rules exist
287 public boolean hasEdgeRule(Vertex aVertex, Vertex bVertex) {
288 String outType = aVertex.<String>property("aai-node-type").orElse(null);
289 String inType = bVertex.<String>property("aai-node-type").orElse(null);
291 return this.hasEdgeRule(outType, inType);
296 * Gets all the edge rules that exist between the given node types.
297 * The rules will be phrased in terms of out|in, though this will
298 * also find rules defined as in|out (it will flip the direction in
299 * the EdgeRule object returned accordingly to match out|in).
303 * @return Map<String edgeLabel, EdgeRule rule> where edgeLabel is the label name
304 * @throws AAIException
306 public Map<String, EdgeRule> getEdgeRules(String outType, String inType) throws AAIException {
307 Map<String, EdgeRule> result = new HashMap<>();
308 EdgeRule rule = null;
309 for (EdgeType type : EdgeType.values()) {
311 rule = this.getEdgeRule(type, outType, inType);
312 result.put(rule.getLabel(), rule);
313 } catch (NoEdgeRuleFoundException e) {
324 * Gets the edge rule of the given type that exists between A and B.
325 * Will check B|A as well, and flips the direction accordingly if that succeeds
326 * to match the expected A|B return.
328 * @param type - the type of edge you're looking for
329 * @param nodeA - first node type
330 * @param nodeB - second node type
331 * @return EdgeRule describing the rule in terms of A|B, if there is any such rule
332 * @throws AAIException if no such edge exists
334 public EdgeRule getEdgeRule(EdgeType type, String nodeA, String nodeB) throws AAIException {
336 List<Map<String, String>> aToBEdges = readRules(buildFilter(type, nodeA, nodeB));
337 if (!aToBEdges.isEmpty()) {
338 //lazily stop iterating if we find a match
339 //should there be a mismatch between type and isParent,
340 //the caller will receive something.
341 //this operates on the assumption that there are at most two rules
342 //for a given vertex pair
343 verifyRule(aToBEdges.get(0));
344 return buildRule(aToBEdges.get(0));
347 //we get here if there was nothing for A to B, so let's try B to A
348 List<Map<String, String>> bToAEdges = readRules(buildFilter(type, nodeB, nodeA));
349 if (!bToAEdges.isEmpty()) {
350 verifyRule(bToAEdges.get(0));
351 return flipDirection(buildRule(bToAEdges.get(0))); //bc we need to return as A|B, so flip the direction to match
355 throw new NoEdgeRuleFoundException("no " + type.toString() + " edge between " + nodeA + " and " + nodeB);
359 * Builds a JsonPath filter to search for an edge from nodeA to nodeB with the given edge type (cousin or parent/child)
362 * @param nodeA - start node
363 * @param nodeB - end node
366 private Filter buildFilter(EdgeType type, String nodeA, String nodeB) {
367 if (EdgeType.COUSIN.equals(type)) {
369 where("from").is(nodeA).and("to").is(nodeB).and(EdgeProperty.CONTAINS.toString()).is(AAIDirection.NONE.toString())
373 where("from").is(nodeA).and("to").is(nodeB).and(EdgeProperty.CONTAINS.toString()).is("${direction}")).or(
374 where("from").is(nodeA).and("to").is(nodeB).and(EdgeProperty.CONTAINS.toString()).is("!${direction}")
380 * Puts the give edge rule information into an EdgeRule object.
382 * @param edge - the edge information returned from JsonPath
383 * @return EdgeRule containing that information
385 private EdgeRule buildRule(Map<String, String> map) {
386 Map<String, String> edge = new EdgePropertyMap<>();
389 EdgeRule rule = new EdgeRule();
390 rule.setLabel(edge.get("label"));
391 rule.setDirection(edge.get("direction"));
392 rule.setMultiplicityRule(edge.get("multiplicity"));
393 rule.setContains(edge.get(EdgeProperty.CONTAINS.toString()));
394 rule.setDeleteOtherV(edge.get(EdgeProperty.DELETE_OTHER_V.toString()));
395 rule.setServiceInfrastructure(edge.get(EdgeProperty.SVC_INFRA.toString()));
396 rule.setPreventDelete(edge.get(EdgeProperty.PREVENT_DELETE.toString()));
402 * If getEdgeRule gets a request for A|B, and it finds something as B|A, the caller still expects
403 * the returned EdgeRule to reflect A|B directionality. This helper method flips B|A direction to
404 * match this expectation.
406 * @param rule whose direction needs flipped
407 * @return the updated rule
409 private EdgeRule flipDirection(EdgeRule rule) {
410 if (Direction.IN.equals(rule.getDirection())) {
411 rule.setDirection(Direction.OUT);
413 } else if (Direction.OUT.equals(rule.getDirection())) {
414 rule.setDirection(Direction.IN);
416 } else { //direction is BOTH, flipping both is still both
422 * Gets the edge rule of the given type that exists between A and B.
423 * Will check B|A as well, and flips the direction accordingly if that succeeds
424 * to match the expected A|B return.
426 * @param type - the type of edge you're looking for
427 * @param aVertex - first node type
428 * @param bVertex - second node type
429 * @return EdgeRule describing the rule in terms of A|B, if there is any such rule
430 * @throws AAIException if no such edge exists
432 public EdgeRule getEdgeRule(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException {
433 String outType = aVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
434 String inType = bVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
436 return this.getEdgeRule(type, outType, inType);
442 * Validate multiplicity.
444 * @param rule the rule
445 * @param aVertex the out vertex
446 * @param bVertex the in vertex
447 * @return true, if successful
448 * @throws AAIException the AAI exception
450 private Optional<String> validateMultiplicity(EdgeRule rule, GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) {
452 if (rule.getDirection().equals(Direction.OUT)) {
454 } else if (rule.getDirection().equals(Direction.IN)) {
455 Vertex tempV = bVertex;
460 String aVertexType = aVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
461 String bVertexType = bVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
462 String label = rule.getLabel();
463 MultiplicityRule multiplicityRule = rule.getMultiplicityRule();
464 List<Edge> outEdges = traversalSource.V(aVertex).outE(label).where(__.inV().has(AAIProperties.NODE_TYPE, bVertexType)).toList();
465 List<Edge> inEdges = traversalSource.V(bVertex).inE(label).where(__.outV().has(AAIProperties.NODE_TYPE, aVertexType)).toList();
467 if (multiplicityRule.equals(MultiplicityRule.ONE2ONE)) {
468 if (inEdges.size() >= 1 || outEdges.size() >= 1 ) {
469 detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType;
471 } else if (multiplicityRule.equals(MultiplicityRule.ONE2MANY)) {
472 if (inEdges.size() >= 1) {
473 detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType;
475 } else if (multiplicityRule.equals(MultiplicityRule.MANY2ONE)) {
476 if (outEdges.size() >= 1) {
477 detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType;
483 if (!"".equals(detail)) {
484 return Optional.of(detail);
486 return Optional.empty();
493 * Verifies that all required properties are defined in the given edge rule.
494 * If they are not, throws a RuntimeException.
496 * @param rule - Map<String edge property, String edge property value> representing
499 private void verifyRule(Map<String, String> rule) {
500 for (EdgeProperty prop : EdgeProperty.values()) {
501 if (!rule.containsKey(prop.toString())) {
502 /* Throws RuntimeException as rule definition errors
503 * cannot be recovered from, and should never happen anyway
504 * because these are configuration files, so requiring all
505 * downstream code to check for this exception seems inappropriate.
506 * It's instantiated with an AAIException to make sure all
507 * relevant information is present in the error message.
509 throw new RuntimeException(new AAIException("AAI_4005",
510 "Rule between " + rule.get("from") + " and " + rule.get("to") +
511 " is missing property " + prop + "."));
517 * Reads all the edge rules from the loaded json file.
519 * @return List<Map<String edge property, String edge property value>>
520 * Each map represents a rule read from the json.
522 private List<Map<String, String>> readRules() {
523 return readRules(null);
527 * Reads the edge rules from the loaded json file, using the given filter
528 * to get specific rules. If filter is null, will get all rules.
530 * @param filter - may be null to indicate get all
531 * @return List<Map<String edge property, String edge property value>>
532 * Each map represents a rule read from the json.
534 private List<Map<String, String>> readRules(Filter filter) {
535 List<Map<String, String>> results;
536 if (filter == null) { //no filter means get all
537 results = rulesDoc.read("$.rules.*");
539 results = rulesDoc.read("$.rules.[?]", filter);
541 for (Map<String, String> result : results) {
548 * Gets all the edge rules we define.
550 * @return Multimap<String "from|to", EdgeRule rule>
552 public Multimap<String, EdgeRule> getAllRules() {
553 Multimap<String, EdgeRule> result = ArrayListMultimap.create();
555 List<Map<String, String>> rules = readRules();
556 for (Map<String, String> rule : rules) {
557 EdgeRule er = buildRule(rule);
558 String name = rule.get("from") + "|" + rule.get("to");
559 result.put(name, er);
566 * Gets all edge rules that define a child relationship from
567 * the given node type.
572 public Set<EdgeRule> getChildren(String nodeType) {
574 final Filter filter = filter(
575 where("from").is(nodeType).and(EdgeProperty.CONTAINS.toString()).is("${direction}")
576 ).or(where("to").is(nodeType).and(EdgeProperty.CONTAINS.toString()).is("!${direction}"));
578 final List<Map<String, String>> rules = readRules(filter);
579 final Set<EdgeRule> result = new HashSet<>();
580 rules.forEach(item -> {
582 result.add(buildRule(item));