aboutsummaryrefslogtreecommitdiffstats
path: root/aai-schema-ingest/src/main/java/org/onap/aai/edges/EdgeIngestor.java
blob: 3cf67052e852129570cc1e33aed722283534a83d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-18 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.aai.edges;

import static com.jayway.jsonpath.Criteria.where;
import static com.jayway.jsonpath.Filter.filter;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.jayway.jsonpath.Criteria;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.Filter;

import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

import org.apache.tinkerpop.gremlin.structure.Direction;
import org.onap.aai.edges.enums.DirectionNotation;
import org.onap.aai.edges.enums.EdgeField;
import org.onap.aai.edges.enums.EdgeType;
import org.onap.aai.edges.exceptions.AmbiguousRuleChoiceException;
import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.SchemaVersions;
import org.onap.aai.setup.Translator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * EdgeIngestor - ingests A&AI edge rule schema files per given config, serves that edge rule
 * information, including allowing various filters to extract particular rules.
 */
@Component
public class EdgeIngestor {
    private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(EdgeIngestor.class);
    private Map<SchemaVersion, List<DocumentContext>> versionJsonFilesMap = new TreeMap<>();
    private static final String READ_START = "$.rules.[?]";
    private static final String READ_ALL_START = "$.rules.*";
    private SchemaVersions schemaVersions;

    Map<SchemaVersion, List<String>> filesToIngest;

    private Set<String> multipleLabelKeys;

    private LoadingCache<SchemaFilter, Multimap<String, EdgeRule>> cacheFilterStore;

    private LoadingCache<String, String[]> cousinLabelStore;

    private Set<Translator> translators;

    @Autowired
    public EdgeIngestor(Set<Translator> translatorSet) {
        this.translators = translatorSet;
    }

    @PostConstruct
    public void initialize() {

        for (Translator translator : translators) {
            try {
                LOGGER.debug("Processing the translator");
                translateAll(translator);

            } catch (Exception e) {
                LOGGER.error("Error while Processing the translator" + e.getMessage());
                throw new ExceptionInInitializerError("EdgeIngestor could not ingest schema");
            }
        }
        if (versionJsonFilesMap.isEmpty() || schemaVersions == null) {
            throw new ExceptionInInitializerError("EdgeIngestor could not ingest edgerules");
        }
    }

    public void translateAll(Translator translator) throws ExceptionInInitializerError {
        /*
         * Use SchemaVersions from the Translator
         */
        this.schemaVersions = translator.getSchemaVersions();
        List<SchemaVersion> schemaVersionList = this.schemaVersions.getVersions();
        List<String> jsonPayloads = null;
        JsonIngestor ji = new JsonIngestor();
        Map<SchemaVersion, List<String>> edgeRulesToIngest = new HashMap<>(); // Obtain a map of schema versions to a
                                                                              // list of strings. One List per key

        // Add to the map the JSON file per version.
        for (SchemaVersion version : schemaVersionList) {
            LOGGER.debug("Version being processed" + version);
            // If the flag is set to not use the local files, obtain the Json from the service.
            try {
                jsonPayloads = translator.getJsonPayload(version); // need to change this - need to receive the json
                                                                   // files.
            } catch (IOException e) {
                LOGGER.error("Error in retrieving the JSON Payload" + e.getMessage());
                throw new ExceptionInInitializerError("EdgeIngestor could not ingest schema");
            }
            if (jsonPayloads == null || jsonPayloads.isEmpty()) {
                continue;
            }
            LOGGER.debug("Retrieved json from SchemaService");
            edgeRulesToIngest.put(version, jsonPayloads);
        }
        versionJsonFilesMap = ji.ingestContent(edgeRulesToIngest);

        this.cacheFilterStore = CacheBuilder.newBuilder().maximumSize(2000)
                .build(new CacheLoader<SchemaFilter, Multimap<String, EdgeRule>>() {
                    @Override
                    public Multimap<String, EdgeRule> load(SchemaFilter key) {
                        return extractRules(key);
                    }
                });

        this.cousinLabelStore = CacheBuilder.newBuilder().maximumSize(50).build(new CacheLoader<String, String[]>() {
            @Override
            public String[] load(String key) throws Exception {
                return retrieveCousinLabels(key);
            }
        });
    }

    // //-----methods for getting rule info-----//
    //
    /**
     * Gets list of all edge rules defined in the latest version's schema
     *
     * @return Multimap<String, EdgeRule> of node names keys to the EdgeRules associated with those types
     *         where the key takes the form of
     *         {alphabetically first nodetype}|{alphabetically second nodetype}. Map will be empty if
     *         no rules are found.
     *         ex: buildAlphabetizedKey("l-interface", "logical-link") -> "l-interface|logical-link"
     *         buildAlphabetizedKey("logical-link", "l-interface") -> "l-interface|logical-link"
     *
     *         This is alphabetical order to normalize the keys, as sometimes there will be multiple
     *         rules for a pair of node types but the from/to value in the json is flipped for some of them.
     * @throws EdgeRuleNotFoundException if none found
     */
    public Multimap<String, EdgeRule> getAllCurrentRules() throws EdgeRuleNotFoundException {
        return getAllRules(schemaVersions.getDefaultVersion());
    }

    /**
     * Retrieves all the nodes that contain multiple edge labels
     *
     * A lazy instantiation to retrieve all this info on first call
     *
     * @return a set containing a list of strings where each string is
     *         concatenated by a pipe (|) character such as aNodeType|bNodeType
     */
    public Set<String> getMultipleLabelKeys() {

        if (multipleLabelKeys == null) {
            multipleLabelKeys = new HashSet<>();
            try {
                final Multimap<String, EdgeRule> edges = this.getAllCurrentRules();
                if (edges == null || edges.isEmpty()) {
                    LOGGER.warn("Unable to find any edge rules for the latest version");
                    return multipleLabelKeys;
                }
                edges.keySet().forEach(key -> {
                    Collection<EdgeRule> rules = edges.get(key);
                    if (rules.size() > 1) {
                        multipleLabelKeys.add(key);
                    }
                });
            } catch (EdgeRuleNotFoundException e) {
                LOGGER.info("For the latest schema version, unable to find any edges with multiple keys");
            }
        }

        return multipleLabelKeys;
    }

    /**
     * Gets list of all edge rules defined in the given version's schema
     *
     * @return Multimap<String, EdgeRule> of node names keys to the EdgeRules associated with those types
     *         where the key takes the form of
     *         {alphabetically first nodetype}|{alphabetically second nodetype}. Map will be empty if
     *         no rules are found.
     *         ex: buildAlphabetizedKey("l-interface", "logical-link") -> "l-interface|logical-link"
     *         buildAlphabetizedKey("logical-link", "l-interface") -> "l-interface|logical-link"
     *
     *         This is alphabetical order to normalize the keys, as sometimes there will be multiple
     *         rules for a pair of node types but the from/to value in the json is flipped for some of them.
     * @throws EdgeRuleNotFoundException if none found
     */
    public Multimap<String, EdgeRule> getAllRules(SchemaVersion v) throws EdgeRuleNotFoundException {
        Multimap<String, EdgeRule> found = extractRules(null, v);
        if (found.isEmpty()) {
            throw new EdgeRuleNotFoundException("No rules found for version " + v.toString() + ".");
        } else {
            return found;
        }
    }

    /**
     * Finds the rules (if any) matching the given query criteria. If none, the returned Multimap
     * will be empty.
     *
     * @param q - EdgeRuleQuery with filter criteria set
     *
     * @return Multimap<String, EdgeRule> of node names keys to the EdgeRules where the key takes the form of
     *         {alphabetically first nodetype}|{alphabetically second nodetype}. Map will be empty if
     *         no rules are found.
     *         ex: buildAlphabetizedKey("l-interface", "logical-link") -> "l-interface|logical-link"
     *         buildAlphabetizedKey("logical-link", "l-interface") -> "l-interface|logical-link"
     *
     *         This is alphabetical order to normalize the keys, as sometimes there will be multiple
     *         rules for a pair of node types but the from/to value in the json is flipped for some of them.
     * @throws EdgeRuleNotFoundException if none found
     */

    public Multimap<String, EdgeRule> getRules(EdgeRuleQuery q) throws EdgeRuleNotFoundException {
        Multimap<String, EdgeRule> found = null;
        if (q.getVersion().isPresent()) {
            found = extractRules(q.getFilter(), q.getVersion().get());
        } else {
            found = extractRules(q.getFilter(), schemaVersions.getDefaultVersion());
        }
        if (found.isEmpty()) {
            throw new EdgeRuleNotFoundException("No rules found for " + q.toString());
        } else {
            Multimap<String, EdgeRule> copy = ArrayListMultimap.create();
            found.entries().stream().forEach((entry) -> {
                EdgeRule rule = new EdgeRule(entry.getValue());
                if (!q.getFromType().equals(rule.getFrom())) {
                    /*
                     * To maintain backwards compatibility with old EdgeRules API,
                     * where the direction of the returned EdgeRule would be
                     * flipped (if necessary) to match the directionality of
                     * the input params.
                     * ie, If the rule is from=A,to=B,direction=OUT,
                     * if the user asked (A,B) the direction would be OUT,
                     * if they asked (B,A), it would be IN to match.
                     */
                    rule.flipDirection();
                }
                copy.put(entry.getKey(), rule);
            });

            return copy;
        }
    }

    /**
     * Gets the rule satisfying the given filter criteria. If there are more than one
     * that match, return the default rule. If there is no clear default to return, or
     * no rules match at all, error.
     *
     * @param q - EdgeRuleQuery with filter criteria set
     * @return EdgeRule satisfying given criteria
     * @throws EdgeRuleNotFoundException if none found that match
     * @throws AmbiguousRuleChoiceException if multiple match but no way to choice one from them
     *         Specifically, if multiple node type pairs come back (ie bar|foo and asdf|foo,
     *         no way to know which is appropriate over the others),
     *         or if there is a mix of Tree and Cousin edges because again there is no way to
     *         know which is "defaulter" than the other.
     *         The default property only clarifies among multiple cousin edges of the same node pair,
     *         ex: which l-interface|logical-link rule to default to.
     */
    public EdgeRule getRule(EdgeRuleQuery q) throws EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
        Multimap<String, EdgeRule> found = null;
        if (q.getVersion().isPresent()) {
            found = extractRules(q.getFilter(), q.getVersion().get());
        } else {
            found = extractRules(q.getFilter(), schemaVersions.getDefaultVersion());
        }

        if (found.isEmpty()) {
            throw new EdgeRuleNotFoundException("No rule found for " + q.toString() + ".");
        }

        EdgeRule rule = null;
        if (found.keys().size() == 1) { // only one found, cool we're done
            for (Entry<String, EdgeRule> e : found.entries()) {
                rule = e.getValue();
            }
        } else {
            rule = getDefaultRule(found);
        }

        if (rule == null) { // should never get here though
            throw new EdgeRuleNotFoundException("No rule found for " + q.toString() + ".");
        } else {
            rule = new EdgeRule(rule);
            if (!q.getFromType().equals(rule.getFrom())) {
                /*
                 * To maintain backwards compatibility with old EdgeRules API,
                 * where the direction of the returned EdgeRule would be
                 * flipped (if necessary) to match the directionality of
                 * the input params.
                 * ie, If the rule is from=A,to=B,direction=OUT,
                 * if the user asked (A,B) the direction would be OUT,
                 * if they asked (B,A), it would be IN to match.
                 */
                rule.flipDirection();
            }
            return rule;
        }
    }

    private EdgeRule getDefaultRule(Multimap<String, EdgeRule> found) throws AmbiguousRuleChoiceException {
        if (found.keySet().size() > 1) { // ie multiple node pairs (a|c and b|c not just all a|c) case
            StringBuilder sb = new StringBuilder();
            for (String k : found.keySet()) {
                sb.append(k).append(" ");
            }
            throw new AmbiguousRuleChoiceException(
                    "No way to select single rule from these pairs: " + sb.toString() + ".");
        }

        int defaultCount = 0;
        EdgeRule defRule = null;
        for (Entry<String, EdgeRule> e : found.entries()) {
            EdgeRule rule = e.getValue();
            if (rule.isDefault()) {
                defaultCount++;
                defRule = rule;
            }
        }
        if (defaultCount > 1) {
            throw new AmbiguousRuleChoiceException("Multiple defaults found.");
        } else if (defaultCount == 0) {
            throw new AmbiguousRuleChoiceException("No default found.");
        }

        return defRule;
    }

    /**
     * Checks if there exists any rule that satisfies the given filter criteria.
     *
     * @param q - EdgeRuleQuery with filter criteria set
     * @return boolean
     */
    public boolean hasRule(EdgeRuleQuery q) {
        if (q.getVersion().isPresent()) {
            return !extractRules(q.getFilter(), q.getVersion().get()).isEmpty();
        } else {
            return !extractRules(q.getFilter(), schemaVersions.getDefaultVersion()).isEmpty();
        }
    }

    /**
     * Gets all cousin rules for the given node type in the latest schema version.
     *
     * @param nodeType
     * @return Multimap<String, EdgeRule> of node names keys to the EdgeRules where the key takes the form of
     *         {alphabetically first nodetype}|{alphabetically second nodetype}. Map will be empty if
     *         no rules are found.
     *         ex: buildAlphabetizedKey("l-interface", "logical-link") -> "l-interface|logical-link"
     *         buildAlphabetizedKey("logical-link", "l-interface") -> "l-interface|logical-link"
     *
     *         This is alphabetical order to normalize the keys, as sometimes there will be multiple
     *         rules for a pair of node types but the from/to value in the json is flipped for some of them.
     */
    public Multimap<String, EdgeRule> getCousinRules(String nodeType) {
        return getCousinRules(nodeType, schemaVersions.getDefaultVersion()); // default to latest
    }

    public String[] retrieveCousinLabels(String nodeType) {

        Multimap<String, EdgeRule> cousinRules = getCousinRules(nodeType);
        String[] cousinLabels = new String[cousinRules.size()];

        return cousinRules.entries().stream().map(entry -> entry.getValue().getLabel()).collect(Collectors.toList())
                .toArray(cousinLabels);
    }

    public String[] retrieveCachedCousinLabels(String nodeType) throws ExecutionException {
        return cousinLabelStore.get(nodeType);
    }

    /**
     * Gets all cousin rules for the given node type in the given schema version.
     *
     * @param nodeType
     * @param v - the version of the edge rules to query
     * @return Multimap<String, EdgeRule> of node names keys to the EdgeRules where the key takes the form of
     *         {alphabetically first nodetype}|{alphabetically second nodetype}. Map will be empty if
     *         no rules are found.
     *         ex: buildAlphabetizedKey("l-interface", "logical-link") -> "l-interface|logical-link"
     *         buildAlphabetizedKey("logical-link", "l-interface") -> "l-interface|logical-link"
     *
     *         This is alphabetical order to normalize the keys, as sometimes there will be multiple
     *         rules for a pair of node types but the from/to value in the json is flipped for some of them.
     */
    public Multimap<String, EdgeRule> getCousinRules(String nodeType, SchemaVersion v) {
        return extractRules(new EdgeRuleQuery.Builder(nodeType).edgeType(EdgeType.COUSIN).build().getFilter(), v);
    }

    /**
     * Returns if the given node type has any cousin relationships in the current version.
     * 
     * @param nodeType
     * @return boolean
     */
    public boolean hasCousinRule(String nodeType) {
        return hasCousinRule(nodeType, schemaVersions.getDefaultVersion());
    }

    /**
     * Returns if the given node type has any cousin relationships in the given version.
     * 
     * @param nodeType
     * @return boolean
     */
    public boolean hasCousinRule(String nodeType, SchemaVersion v) {
        return !getCousinRules(nodeType, v).isEmpty();
    }

    /**
     * Gets all rules where "{given nodeType} contains {otherType}" in the latest schema version.
     *
     * @param nodeType - node type that is the container in the returned relationships
     * @return Multimap<String, EdgeRule> of node names keys to the EdgeRules where the key takes the form of
     *         {alphabetically first nodetype}|{alphabetically second nodetype}. Map will be empty if
     *         no rules are found.
     *         ex: buildAlphabetizedKey("l-interface", "logical-link") -> "l-interface|logical-link"
     *         buildAlphabetizedKey("logical-link", "l-interface") -> "l-interface|logical-link"
     *
     *         This is alphabetical order to normalize the keys, as sometimes there will be multiple
     *         rules for a pair of node types but the from/to value in the json is flipped for some of them.
     */
    public Multimap<String, EdgeRule> getChildRules(String nodeType) {
        return getChildRules(nodeType, schemaVersions.getDefaultVersion());
    }

    /**
     * Gets all rules where "{given nodeType} contains {otherType}" in the given schema version.
     *
     * @param nodeType - node type that is the container in the returned relationships
     * @return Multimap<String, EdgeRule> of node names keys to the EdgeRules where the key takes the form of
     *         {alphabetically first nodetype}|{alphabetically second nodetype}. Map will be empty if
     *         no rules are found.
     *         ex: buildAlphabetizedKey("l-interface", "logical-link") -> "l-interface|logical-link"
     *         buildAlphabetizedKey("logical-link", "l-interface") -> "l-interface|logical-link"
     *
     *         This is alphabetical order to normalize the keys, as sometimes there will be multiple
     *         rules for a pair of node types but the from/to value in the json is flipped for some of them.
     */
    public Multimap<String, EdgeRule> getChildRules(String nodeType, SchemaVersion v) {
        Filter from = assembleFilterSegments(where(EdgeField.FROM.toString()).is(nodeType),
                getSameDirectionContainmentCriteria());
        Filter to = assembleFilterSegments(where(EdgeField.TO.toString()).is(nodeType),
                getOppositeDirectionContainmentCriteria());
        Filter total = from.or(to);

        return extractRules(total, v);
    }

    /**
     * Returns if the given node type has any child relationships (ie it contains another node type) in the current
     * version.
     * 
     * @param nodeType
     * @return boolean
     */
    public boolean hasChildRule(String nodeType) {
        return hasChildRule(nodeType, schemaVersions.getDefaultVersion());
    }

    /**
     * Returns if the given node type has any child relationships (ie it contains another node type) in the given
     * version.
     * 
     * @param nodeType
     * @return boolean
     */
    public boolean hasChildRule(String nodeType, SchemaVersion v) {
        return !getChildRules(nodeType, v).isEmpty();
    }

    /**
     * Gets all rules where "{given nodeType} is contained by {otherType}" in the latest schema version.
     *
     * @param nodeType - node type that is the containee in the returned relationships
     * @return Multimap<String, EdgeRule> of node names keys to the EdgeRules where the key takes the form of
     *         {alphabetically first nodetype}|{alphabetically second nodetype}. Map will be empty if
     *         no rules are found.
     *         ex: buildAlphabetizedKey("l-interface", "logical-link") -> "l-interface|logical-link"
     *         buildAlphabetizedKey("logical-link", "l-interface") -> "l-interface|logical-link"
     *
     *         This is alphabetical order to normalize the keys, as sometimes there will be multiple
     *         rules for a pair of node types but the from/to value in the json is flipped for some of them.
     */
    public Multimap<String, EdgeRule> getParentRules(String nodeType) {
        return getParentRules(nodeType, schemaVersions.getDefaultVersion());
    }

    /**
     * Gets all rules where "{given nodeType} is contained by {otherType}" in the given schema version.
     *
     * @param nodeType - node type that is the containee in the returned relationships
     * @return Multimap<String, EdgeRule> of node names keys to the EdgeRules where the key takes the form of
     *         {alphabetically first nodetype}|{alphabetically second nodetype}. Map will be empty if
     *         no rules are found.
     *         ex: buildAlphabetizedKey("l-interface", "logical-link") -> "l-interface|logical-link"
     *         buildAlphabetizedKey("logical-link", "l-interface") -> "l-interface|logical-link"
     *
     *         This is alphabetical order to normalize the keys, as sometimes there will be multiple
     *         rules for a pair of node types but the from/to value in the json is flipped for some of them.
     */
    public Multimap<String, EdgeRule> getParentRules(String nodeType, SchemaVersion v) {
        Filter from = assembleFilterSegments(where(EdgeField.FROM.toString()).is(nodeType),
                getOppositeDirectionContainmentCriteria());
        Filter to = assembleFilterSegments(where(EdgeField.TO.toString()).is(nodeType),
                getSameDirectionContainmentCriteria());
        Filter total = from.or(to);

        return extractRules(total, v);
    }

    /**
     * Returns if the given node type has any parent relationships (ie it is contained by another node type) in the
     * current version.
     * 
     * @param nodeType
     * @return boolean
     */
    public boolean hasParentRule(String nodeType) {
        return hasParentRule(nodeType, schemaVersions.getDefaultVersion());
    }

    /**
     * Returns if the given node type has any parent relationships (ie it is contained by another node type) in the
     * given version.
     * 
     * @param nodeType
     * @return boolean
     */
    public boolean hasParentRule(String nodeType, SchemaVersion v) {
        return !getParentRules(nodeType, v).isEmpty();
    }

    /**
     * Applies the given filter to the DocumentContext(s) for the given version to extract
     * edge rules, and converts this extracted information into the Multimap form
     *
     * @param filter - JsonPath filter to read the DocumentContexts with. May be null
     *        to denote no filter, ie get all.
     * @param v - The schema version to extract from
     * @return Multimap<String, EdgeRule> of node names keys to the EdgeRules where the key takes the form of
     *         {alphabetically first nodetype}|{alphabetically second nodetype}. Map will be empty if
     *         no rules are found.
     *         ex: buildAlphabetizedKey("l-interface", "logical-link") -> "l-interface|logical-link"
     *         buildAlphabetizedKey("logical-link", "l-interface") -> "l-interface|logical-link"
     *
     *         This is alphabetical order to normalize the keys, as sometimes there will be multiple
     *         rules for a pair of node types but the from/to value in the json is flipped for some of them.
     */
    private Multimap<String, EdgeRule> extractRules(Filter filter, SchemaVersion v) {
        SchemaFilter schemaFilter = new SchemaFilter(filter, v);
        try {
            return cacheFilterStore.get(schemaFilter);
        } catch (ExecutionException e) {
            LOGGER.info("Encountered exception during the retrieval of the rules");
            return ArrayListMultimap.create();
        }
    }

    public Multimap<String, EdgeRule> extractRules(SchemaFilter schemaFilter) {
        List<Map<String, String>> foundRules = new ArrayList<>();
        List<DocumentContext> docs = versionJsonFilesMap.get(schemaFilter.getSchemaVersion());
        if (docs != null) {
            for (DocumentContext doc : docs) {
                if (schemaFilter.getFilter() == null) {
                    foundRules.addAll(doc.read(READ_ALL_START));
                } else {
                    foundRules.addAll(doc.read(READ_START, Filter.parse(schemaFilter.getFilter())));
                }
            }
        }

        return convertToEdgeRules(foundRules);
    }

    // -----filter building helpers-----//
    /**
     * ANDs together the given start criteria with each criteria in the pieces list, and
     * then ORs together these segments into one filter.
     *
     * JsonPath doesn't have an OR method on Criteria, only on Filters, so assembling
     * a complete filter requires this sort of roundabout construction.
     *
     * @param start - Criteria of the form where(from/to).is(nodeType)
     *        (ie the start of any A&AI edge rule query)
     * @param pieces - Other Criteria to be applied
     * @return Filter constructed from the given Criteria
     */
    private Filter assembleFilterSegments(Criteria start, List<Criteria> pieces) {
        List<Filter> segments = new ArrayList<>();
        for (Criteria c : pieces) {
            segments.add(filter(start).and(c));
        }
        Filter assembled = segments.remove(0);
        for (Filter f : segments) {
            assembled = assembled.or(f);
        }
        return assembled;
    }

    /**
     * Builds the sub-Criteria for a containment edge rule query where the direction
     * and containment fields must match.
     *
     * Used for getChildRules() where the container node type is in the "from" position and
     * for getParentRules() where the containee type is in the "to" position.
     *
     * @return List<Criteria> covering property permutations defined with either notation or explicit direction
     */
    private List<Criteria> getSameDirectionContainmentCriteria() {
        List<Criteria> crits = new ArrayList<>();

        crits.add(where(EdgeField.CONTAINS.toString()).is(DirectionNotation.DIRECTION.toString()));

        crits.add(where(EdgeField.DIRECTION.toString()).is(Direction.OUT.toString()).and(EdgeField.CONTAINS.toString())
                .is(Direction.OUT.toString()));

        crits.add(where(EdgeField.DIRECTION.toString()).is(Direction.IN.toString()).and(EdgeField.CONTAINS.toString())
                .is(Direction.IN.toString()));

        return crits;
    }

    /**
     * Builds the sub-Criteria for a containment edge rule query where the direction
     * and containment fields must not match.
     *
     * Used for getChildRules() where the container node type is in the "to" position and
     * for getParentRules() where the containee type is in the "from" position.
     *
     * @return List<Criteria> covering property permutations defined with either notation or explicit direction
     */
    private List<Criteria> getOppositeDirectionContainmentCriteria() {
        List<Criteria> crits = new ArrayList<>();

        crits.add(where(EdgeField.CONTAINS.toString()).is(DirectionNotation.OPPOSITE.toString()));

        crits.add(where(EdgeField.DIRECTION.toString()).is(Direction.OUT.toString()).and(EdgeField.CONTAINS.toString())
                .is(Direction.IN.toString()));

        crits.add(where(EdgeField.DIRECTION.toString()).is(Direction.IN.toString()).and(EdgeField.CONTAINS.toString())
                .is(Direction.OUT.toString()));

        return crits;
    }

    // -----rule packaging helpers-----//
    /**
     * Converts the raw output from reading the json file to the Multimap<String key, EdgeRule> format
     *
     * @param allFound - raw edge rule output read from json file(s)
     *        (could be empty if none found)
     * @return Multimap<String, EdgeRule> of node names keys to the EdgeRules where the key takes the form of
     *         {alphabetically first nodetype}|{alphabetically second nodetype}. Will be empty if input
     *         was empty.
     *         ex: buildAlphabetizedKey("l-interface", "logical-link") -> "l-interface|logical-link"
     *         buildAlphabetizedKey("logical-link", "l-interface") -> "l-interface|logical-link"
     *
     *         This is alphabetical order to normalize the keys, as sometimes there will be multiple
     *         rules for a pair of node types but the from/to value in the json is flipped for some of them.
     */
    private Multimap<String, EdgeRule> convertToEdgeRules(List<Map<String, String>> allFound) {
        Multimap<String, EdgeRule> rules = ArrayListMultimap.create();

        TypeAlphabetizer alpher = new TypeAlphabetizer();

        for (Map<String, String> raw : allFound) {
            EdgeRule converted = new EdgeRule(raw);
            if (converted.getFrom().equals(converted.getTo())) {
                /*
                 * the way the code worked in the past was with outs and
                 * when we switched it to in the same-node-type to
                 * same-node-type parent child edges were failing because all
                 * of the calling code would pass the parent as the left argument,
                 * so it was either in that method swap the parent/child,
                 * flip the edge rule or make all callers swap. the last seemed
                 * like a bad idea. and felt like the edge flip was the better
                 * of the remaining 2
                 */
                converted.flipDirection();
            }
            String alphabetizedKey =
                    alpher.buildAlphabetizedKey(raw.get(EdgeField.FROM.toString()), raw.get(EdgeField.TO.toString()));
            rules.put(alphabetizedKey, converted);
        }

        return rules;
    }

}