Introduce NormalizedNodes.findDuplicates()
[yangtools.git] / yang / yang-data-api / src / main / java / org / opendaylight / yangtools / yang / data / api / schema / DuplicateFinder.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
3  * This program and the accompanying materials are made available under the
4  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
5  * and is available at http://www.eclipse.org/legal/epl-v10.html
6  */
7 package org.opendaylight.yangtools.yang.data.api.schema;
8
9 import java.util.HashMap;
10 import java.util.IdentityHashMap;
11 import java.util.Map;
12 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
13
14 final class DuplicateFinder {
15     private final Map<NormalizedNode<?, ?>, DuplicateEntry> identities = new IdentityHashMap<>();
16     private final Map<NormalizedNode<?, ?>, DuplicateEntry> duplicates = new HashMap<>();
17
18     private DuplicateFinder() {
19         // Hidden on purpose
20     }
21
22     private void findDuplicates(final YangInstanceIdentifier path, final NormalizedNode<?, ?> node) {
23         final DuplicateEntry i = identities.get(node);
24         if (i == null) {
25             final DuplicateEntry d = duplicates.get(node);
26             if (d == null) {
27                 final DuplicateEntry n = new DuplicateEntry(path);
28                 identities.put(node, n);
29                 duplicates.put(node, n);
30             } else {
31                 d.addDuplicate(path);
32             }
33
34             if (node instanceof NormalizedNodeContainer<?, ?, ?>) {
35                 final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) node;
36
37                 for (NormalizedNode<?, ?> c : container.getValue()) {
38                     findDuplicates(path.node(c.getIdentifier()), c);
39                 }
40             }
41         } else {
42             i.addHardLink(path);
43         }
44     }
45
46     /**
47      * Recursively scan a {@link NormalizedNode} instance and its children and
48      * produce a collection of {@link DuplicateEntry} objects. Each holds the
49      * original definition path and a list of hard/softlinks.
50      *
51      * @param node Root node, may not be null.
52      * @return List of entries
53      */
54     static Map<NormalizedNode<?, ?>, DuplicateEntry> findDuplicates(final NormalizedNode<?, ?> node) {
55         final DuplicateFinder finder = new DuplicateFinder();
56         finder.findDuplicates(YangInstanceIdentifier.EMPTY, node);
57         return finder.identities;
58     }
59 }