Remove MountPointIdentifier
[yangtools.git] / data / yang-data-api / src / main / java / org / opendaylight / yangtools / yang / data / api / YangInstanceIdentifier.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.api;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.Beta;
15 import com.google.common.base.VerifyException;
16 import com.google.common.cache.CacheBuilder;
17 import com.google.common.cache.CacheLoader;
18 import com.google.common.cache.LoadingCache;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.ImmutableSet;
22 import com.google.common.collect.Iterables;
23 import com.google.common.collect.Sets;
24 import java.io.Serializable;
25 import java.lang.invoke.MethodHandles;
26 import java.lang.invoke.VarHandle;
27 import java.lang.reflect.Array;
28 import java.util.AbstractMap.SimpleImmutableEntry;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.Collection;
32 import java.util.Deque;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Map.Entry;
37 import java.util.Objects;
38 import java.util.Optional;
39 import java.util.Set;
40 import java.util.function.Function;
41 import org.eclipse.jdt.annotation.NonNull;
42 import org.eclipse.jdt.annotation.Nullable;
43 import org.opendaylight.yangtools.concepts.HierarchicalIdentifier;
44 import org.opendaylight.yangtools.concepts.Immutable;
45 import org.opendaylight.yangtools.concepts.Mutable;
46 import org.opendaylight.yangtools.util.ImmutableOffsetMap;
47 import org.opendaylight.yangtools.util.SingletonSet;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.common.QNameModule;
50 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
51
52 /**
53  * Unique identifier of a particular node instance in the data tree.
54  *
55  * <p>
56  * Java representation of YANG Built-in type {@code instance-identifier}, which conceptually is XPath expression
57  * minimized to uniquely identify element in data tree which conforms to constraints maintained by YANG Model,
58  * effectively this makes Instance Identifier a path to element in data tree.
59  *
60  * <p>
61  * Constraints put in YANG specification on instance-identifier allowed it to be effectively represented in Java and its
62  * evaluation does not require a full-blown XPath processor.
63  *
64  * <h2>Path Arguments</h2>
65  * Path to the node represented in instance identifier consists of {@link PathArgument} which carries necessary
66  * information to uniquely identify node on particular level in the subtree.
67  *
68  * <ul>
69  *   <li>{@link NodeIdentifier} - Identifier of node, which has cardinality {@code 0..1} in particular subtree in data
70  *       tree</li>
71  *   <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item), which has cardinality {@code 0..n}</li>
72  *   <li>{@link NodeWithValue} - Identifier of instance {@code leaf} node or {@code leaf-list} node</li>
73  *   <li>{@link AugmentationIdentifier} - Identifier of instance of {@code augmentation} node</li>
74  * </ul>
75  *
76  * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
77  */
78 public abstract sealed class YangInstanceIdentifier implements HierarchicalIdentifier<YangInstanceIdentifier>
79         permits FixedYangInstanceIdentifier, StackedYangInstanceIdentifier {
80     @java.io.Serial
81     private static final long serialVersionUID = 4L;
82     private static final VarHandle TO_STRING_CACHE;
83     private static final VarHandle HASH;
84
85     static {
86         final var lookup = MethodHandles.lookup();
87         try {
88             HASH = lookup.findVarHandle(YangInstanceIdentifier.class, "hash", int.class);
89             TO_STRING_CACHE = lookup.findVarHandle(YangInstanceIdentifier.class, "toStringCache", String.class);
90         } catch (NoSuchFieldException | IllegalAccessException e) {
91             throw new ExceptionInInitializerError(e);
92         }
93     }
94
95     @SuppressWarnings("unused")
96     private int hash;
97     @SuppressWarnings("unused")
98     private transient String toStringCache = null;
99
100     YangInstanceIdentifier() {
101         // Package-private to prevent outside subclassing
102     }
103
104     /**
105      * Return An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual root of the YANG
106      * namespace.
107      *
108      * @return An empty YangInstanceIdentifier
109      */
110     public static @NonNull YangInstanceIdentifier empty() {
111         return FixedYangInstanceIdentifier.EMPTY_INSTANCE;
112     }
113
114     abstract @NonNull YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
115
116     abstract @Nullable List<PathArgument> tryPathArguments();
117
118     abstract @Nullable List<PathArgument> tryReversePathArguments();
119
120     /**
121      * Check if this instance identifier has empty path arguments, e.g. it is
122      * empty and corresponds to {@link #empty()}.
123      *
124      * @return True if this instance identifier is empty, false otherwise.
125      */
126     public abstract boolean isEmpty();
127
128     /**
129      * Return an optimized version of this identifier, useful when the identifier
130      * will be used very frequently.
131      *
132      * @return A optimized equivalent instance.
133      */
134     public abstract @NonNull YangInstanceIdentifier toOptimized();
135
136     /**
137      * Return the conceptual parent {@link YangInstanceIdentifier}, which has
138      * one item less in {@link #getPathArguments()}.
139      *
140      * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #empty()}.
141      */
142     public abstract @Nullable YangInstanceIdentifier getParent();
143
144     /**
145      * Return the conceptual parent {@link YangInstanceIdentifier}, which has one item less in
146      * {@link #getPathArguments()}.
147      *
148      * @return Parent {@link YangInstanceIdentifier}
149      * @throws VerifyException if this object is {@link #empty()}.
150      */
151     public abstract @NonNull YangInstanceIdentifier coerceParent();
152
153     /**
154      * Return the ancestor {@link YangInstanceIdentifier} with a particular depth, e.g. number of path arguments.
155      *
156      * @param depth Ancestor depth
157      * @return Ancestor {@link YangInstanceIdentifier}
158      * @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
159      */
160     public abstract @NonNull YangInstanceIdentifier getAncestor(int depth);
161
162     /**
163      * Returns an ordered iteration of path arguments.
164      *
165      * @return Immutable iteration of path arguments.
166      */
167     public abstract @NonNull List<PathArgument> getPathArguments();
168
169     /**
170      * Returns an iterable of path arguments in reverse order. This is useful
171      * when walking up a tree organized this way.
172      *
173      * @return Immutable iterable of path arguments in reverse order.
174      */
175     public abstract @NonNull List<PathArgument> getReversePathArguments();
176
177     /**
178      * Returns the last PathArgument. This is equivalent of iterating
179      * to the last element of the iterable returned by {@link #getPathArguments()}.
180      *
181      * @return The last past argument, or null if there are no PathArguments.
182      */
183     public abstract PathArgument getLastPathArgument();
184
185     public static @NonNull YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
186         return Iterables.isEmpty(path) ? empty() : new FixedYangInstanceIdentifier(ImmutableList.copyOf(path));
187     }
188
189     public static @NonNull YangInstanceIdentifier create(final PathArgument pathArgument) {
190         return new FixedYangInstanceIdentifier(ImmutableList.of(pathArgument));
191     }
192
193     public static @NonNull YangInstanceIdentifier create(final PathArgument... path) {
194         // We are forcing a copy, since we cannot trust the user
195         return create(Arrays.asList(path));
196     }
197
198     /**
199      * Create a {@link YangInstanceIdentifier} by taking a snapshot of provided path and iterating it backwards.
200      *
201      * @param pathTowardsRoot Path towards root
202      * @return A {@link YangInstanceIdentifier} instance
203      * @throws NullPointerException if {@code pathTowardsRoot} or any of its members is null
204      */
205     public static @NonNull YangInstanceIdentifier createReverse(final Deque<PathArgument> pathTowardsRoot) {
206         final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
207             pathTowardsRoot.size());
208         pathTowardsRoot.descendingIterator().forEachRemaining(builder::add);
209         return YangInstanceIdentifier.create(builder.build());
210     }
211
212     /**
213      * Create a {@link YangInstanceIdentifier} by walking specified stack backwards and extracting path components
214      * from it.
215      *
216      * @param stackTowardsRoot Stack towards root,
217      * @return A {@link YangInstanceIdentifier} instance
218      * @throws NullPointerException if {@code pathTowardsRoot} is null
219      */
220     public static <T> @NonNull YangInstanceIdentifier createReverse(final Deque<? extends T> stackTowardsRoot,
221             final Function<T, PathArgument> function) {
222         final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
223             stackTowardsRoot.size());
224         final Iterator<? extends T> it = stackTowardsRoot.descendingIterator();
225         while (it.hasNext()) {
226             builder.add(function.apply(it.next()));
227         }
228         return YangInstanceIdentifier.create(builder.build());
229     }
230
231     boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
232         return getPathArguments().equals(other.getPathArguments());
233     }
234
235     @Override
236     public final boolean equals(final Object obj) {
237         return this == obj || obj instanceof YangInstanceIdentifier other && pathArgumentsEqual(other);
238     }
239
240     /**
241      * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments.
242      *
243      * @param name QName of {@link NodeIdentifier}
244      * @return Instance Identifier with additional path argument added to the end.
245      */
246     public final @NonNull YangInstanceIdentifier node(final QName name) {
247         return node(new NodeIdentifier(name));
248     }
249
250     /**
251      * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments.
252      *
253      * @param arg Path argument which should be added to the end
254      * @return Instance Identifier with additional path argument added to the end.
255      */
256     public final @NonNull YangInstanceIdentifier node(final PathArgument arg) {
257         return new StackedYangInstanceIdentifier(this, arg);
258     }
259
260     /**
261      * Get the relative path from an ancestor. This method attempts to perform
262      * the reverse of concatenating a base (ancestor) and a path.
263      *
264      * @param ancestor
265      *            Ancestor against which the relative path should be calculated
266      * @return This object's relative path from parent, or Optional.absent() if
267      *         the specified parent is not in fact an ancestor of this object.
268      */
269     public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
270         if (this == ancestor) {
271             return Optional.of(empty());
272         }
273         if (ancestor.isEmpty()) {
274             return Optional.of(this);
275         }
276
277         final Iterator<PathArgument> lit = getPathArguments().iterator();
278         final Iterator<PathArgument> oit = ancestor.getPathArguments().iterator();
279         int common = 0;
280
281         while (oit.hasNext()) {
282             // Ancestor is not really an ancestor
283             if (!lit.hasNext() || !lit.next().equals(oit.next())) {
284                 return Optional.empty();
285             }
286
287             ++common;
288         }
289
290         if (common == 0) {
291             return Optional.of(this);
292         }
293         if (!lit.hasNext()) {
294             return Optional.of(empty());
295         }
296
297         return Optional.of(createRelativeIdentifier(common));
298     }
299
300     @Override
301     public final boolean contains(final YangInstanceIdentifier other) {
302         if (this == other) {
303             return true;
304         }
305
306         checkArgument(other != null, "other should not be null");
307         final Iterator<PathArgument> lit = getPathArguments().iterator();
308         final Iterator<PathArgument> oit = other.getPathArguments().iterator();
309
310         while (lit.hasNext()) {
311             if (!oit.hasNext()) {
312                 return false;
313             }
314
315             if (!lit.next().equals(oit.next())) {
316                 return false;
317             }
318         }
319
320         return true;
321     }
322
323     @Override
324     public final String toString() {
325         /*
326          * The toStringCache is safe, since the object contract requires
327          * immutability of the object and all objects referenced from this
328          * object.
329          * Used lists, maps are immutable. Path Arguments (elements) are also
330          * immutable, since the PathArgument contract requires immutability.
331          * The cache is thread-safe - if multiple computations occurs at the
332          * same time, cache will be overwritten with same result.
333          */
334         final String ret = (String) TO_STRING_CACHE.getAcquire(this);
335         return ret != null ? ret : loadToString();
336     }
337
338     private String loadToString() {
339         final StringBuilder builder = new StringBuilder("/");
340         PathArgument prev = null;
341         for (PathArgument argument : getPathArguments()) {
342             if (prev != null) {
343                 builder.append('/');
344             }
345             builder.append(argument.toRelativeString(prev));
346             prev = argument;
347         }
348
349         final String ret = builder.toString();
350         final String witness = (String) TO_STRING_CACHE.compareAndExchangeRelease(this, null, ret);
351         return witness == null ? ret : witness;
352     }
353
354     @Override
355     public final int hashCode() {
356         /*
357          * The caching is safe, since the object contract requires
358          * immutability of the object and all objects referenced from this
359          * object.
360          * Used lists, maps are immutable. Path Arguments (elements) are also
361          * immutable, since the PathArgument contract requires immutability.
362          */
363         final int local = (int) HASH.getAcquire(this);
364         return local != 0 ? local : loadHashCode();
365     }
366
367     private static int hashCode(final Object value) {
368         if (value == null) {
369             return 0;
370         }
371
372         if (byte[].class.equals(value.getClass())) {
373             return Arrays.hashCode((byte[]) value);
374         }
375
376         if (value.getClass().isArray()) {
377             int hash = 0;
378             int length = Array.getLength(value);
379             for (int i = 0; i < length; i++) {
380                 hash += Objects.hashCode(Array.get(value, i));
381             }
382
383             return hash;
384         }
385
386         return Objects.hashCode(value);
387     }
388
389     private int loadHashCode() {
390         final int computed = computeHashCode();
391         HASH.setRelease(this, computed);
392         return computed;
393     }
394
395     abstract int computeHashCode();
396
397     @java.io.Serial
398     final Object writeReplace() {
399         return new YIDv1(this);
400     }
401
402     // Static factories & helpers
403
404     /**
405      * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied
406      * QName.
407      *
408      * @param name QName of first node identifier
409      * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
410      */
411     public static @NonNull YangInstanceIdentifier of(final QName name) {
412         return create(new NodeIdentifier(name));
413     }
414
415     /**
416      * Returns new builder for InstanceIdentifier with empty path arguments.
417      *
418      * @return new builder for InstanceIdentifier with empty path arguments.
419      */
420     public static @NonNull InstanceIdentifierBuilder builder() {
421         return new YangInstanceIdentifierBuilder();
422     }
423
424     /**
425      * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
426      *
427      * @param origin InstanceIdentifier from which path arguments are copied.
428      * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
429      */
430     public static @NonNull InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
431         return new YangInstanceIdentifierBuilder(origin.getPathArguments());
432     }
433
434     /**
435      * Path argument / component of InstanceIdentifier.
436      * Path argument uniquely identifies node in data tree on particular
437      * level.
438      *
439      * <p>
440      * This interface itself is used as common parent for actual
441      * path arguments types and should not be implemented by user code.
442      *
443      * <p>
444      * Path arguments SHOULD contain only minimum of information
445      * required to uniquely identify node on particular subtree level.
446      *
447      * <p>
448      * For actual path arguments types see:
449      * <ul>
450      * <li>{@link NodeIdentifier} - Identifier of container or leaf
451      * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
452      * <li>{@link AugmentationIdentifier} - Identifier of augmentation
453      * <li>{@link NodeWithValue} - Identifier of leaf-list entry
454      * </ul>
455      */
456     public sealed interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable
457             permits AbstractPathArgument, AugmentationIdentifier {
458         /**
459          * Returns unique QName of data node as defined in YANG Schema, if available.
460          *
461          * @return Node type
462          * @throws UnsupportedOperationException if node type is not applicable, for example in case of an augmentation.
463          */
464         @NonNull QName getNodeType();
465
466         /**
467          * Return the string representation of this object for use in context
468          * provided by a previous object. This method can be implemented in
469          * terms of {@link #toString()}, but implementations are encourage to
470          * reuse any context already emitted by the previous object.
471          *
472          * @param previous Previous path argument
473          * @return String representation
474          */
475         @NonNull String toRelativeString(PathArgument previous);
476     }
477
478     private abstract static sealed class AbstractPathArgument implements PathArgument {
479         private static final long serialVersionUID = -4546547994250849340L;
480         private final @NonNull QName nodeType;
481         private transient volatile int hashValue;
482
483         protected AbstractPathArgument(final QName nodeType) {
484             this.nodeType = requireNonNull(nodeType);
485         }
486
487         @Override
488         public final QName getNodeType() {
489             return nodeType;
490         }
491
492         @Override
493         @SuppressWarnings("checkstyle:parameterName")
494         public int compareTo(final PathArgument o) {
495             return nodeType.compareTo(o.getNodeType());
496         }
497
498         protected int hashCodeImpl() {
499             return nodeType.hashCode();
500         }
501
502         @Override
503         public final int hashCode() {
504             int local;
505             return (local = hashValue) != 0 ? local : (hashValue = hashCodeImpl());
506         }
507
508         @Override
509         public boolean equals(final Object obj) {
510             if (this == obj) {
511                 return true;
512             }
513             if (obj == null || this.getClass() != obj.getClass()) {
514                 return false;
515             }
516
517             return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
518         }
519
520         @Override
521         public String toString() {
522             return getNodeType().toString();
523         }
524
525         @Override
526         public String toRelativeString(final PathArgument previous) {
527             if (previous instanceof AbstractPathArgument) {
528                 final QNameModule mod = previous.getNodeType().getModule();
529                 if (getNodeType().getModule().equals(mod)) {
530                     return getNodeType().getLocalName();
531                 }
532             }
533
534             return getNodeType().toString();
535         }
536
537         abstract Object writeReplace();
538     }
539
540     /**
541      * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
542      * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
543      */
544     public static final class NodeIdentifier extends AbstractPathArgument {
545         private static final long serialVersionUID = -2255888212390871347L;
546         private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
547                 .build(new CacheLoader<QName, NodeIdentifier>() {
548                     @Override
549                     public NodeIdentifier load(final QName key) {
550                         return new NodeIdentifier(key);
551                     }
552                 });
553
554         public NodeIdentifier(final QName node) {
555             super(node);
556         }
557
558         /**
559          * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
560          * instance cache, resulting in object reuse for equal inputs.
561          *
562          * @param node Node's QName
563          * @return A {@link NodeIdentifier}
564          */
565         public static @NonNull NodeIdentifier create(final QName node) {
566             return CACHE.getUnchecked(node);
567         }
568
569         @Override
570         Object writeReplace() {
571             return new NIv1(this);
572         }
573     }
574
575     /**
576      * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
577      * overall data tree.
578      */
579     public abstract static sealed class NodeIdentifierWithPredicates extends AbstractPathArgument {
580         @Beta
581         public static final class Singleton extends NodeIdentifierWithPredicates {
582             private static final long serialVersionUID = 1L;
583
584             private final @NonNull QName key;
585             private final @NonNull Object value;
586
587             Singleton(final QName node, final QName key, final Object value) {
588                 super(node);
589                 this.key = requireNonNull(key);
590                 this.value = requireNonNull(value);
591             }
592
593             @Override
594             public SingletonSet<Entry<QName, Object>> entrySet() {
595                 return SingletonSet.of(singleEntry());
596             }
597
598             @Override
599             public SingletonSet<QName> keySet() {
600                 return SingletonSet.of(key);
601             }
602
603             @Override
604             public boolean containsKey(final QName qname) {
605                 return key.equals(requireNonNull(qname));
606             }
607
608             @Override
609             public SingletonSet<Object> values() {
610                 return SingletonSet.of(value);
611             }
612
613             @Override
614             public int size() {
615                 return 1;
616             }
617
618             @Override
619             public ImmutableMap<QName, Object> asMap() {
620                 return ImmutableMap.of(key, value);
621             }
622
623             /**
624              * Return the single entry contained in this object. This is equivalent to
625              * {@code entrySet().iterator().next()}.
626              *
627              * @return A single entry.
628              */
629             public @NonNull Entry<QName, Object> singleEntry() {
630                 return new SimpleImmutableEntry<>(key, value);
631             }
632
633             @Override
634             boolean equalMapping(final NodeIdentifierWithPredicates other) {
635                 final Singleton single = (Singleton) other;
636                 return key.equals(single.key) && Objects.deepEquals(value, single.value);
637             }
638
639             @Override
640             Object keyValue(final QName qname) {
641                 return key.equals(qname) ? value : null;
642             }
643         }
644
645         private static final class Regular extends NodeIdentifierWithPredicates {
646             private static final long serialVersionUID = 1L;
647
648             private final @NonNull Map<QName, Object> keyValues;
649
650             Regular(final QName node, final Map<QName, Object> keyValues) {
651                 super(node);
652                 this.keyValues = requireNonNull(keyValues);
653             }
654
655             @Override
656             public Set<Entry<QName, Object>> entrySet() {
657                 return keyValues.entrySet();
658             }
659
660             @Override
661             public Set<QName> keySet() {
662                 return keyValues.keySet();
663             }
664
665             @Override
666             public boolean containsKey(final QName qname) {
667                 return keyValues.containsKey(requireNonNull(qname));
668             }
669
670             @Override
671             public Collection<Object> values() {
672                 return keyValues.values();
673             }
674
675             @Override
676             public int size() {
677                 return keyValues.size();
678             }
679
680             @Override
681             public Map<QName, Object> asMap() {
682                 return keyValues;
683             }
684
685             @Override
686             Object keyValue(final QName qname) {
687                 return keyValues.get(qname);
688             }
689
690             @Override
691             boolean equalMapping(final NodeIdentifierWithPredicates other) {
692                 final Map<QName, Object> otherKeyValues = ((Regular) other).keyValues;
693                 // TODO: benchmark to see if just calling equals() on the two maps is not faster
694                 if (keyValues == otherKeyValues) {
695                     return true;
696                 }
697                 if (keyValues.size() != otherKeyValues.size()) {
698                     return false;
699                 }
700
701                 for (Entry<QName, Object> entry : entrySet()) {
702                     final Object otherValue = otherKeyValues.get(entry.getKey());
703                     if (otherValue == null || !Objects.deepEquals(entry.getValue(), otherValue)) {
704                         return false;
705                     }
706                 }
707
708                 return true;
709             }
710         }
711
712         private static final long serialVersionUID = -4787195606494761540L;
713
714         NodeIdentifierWithPredicates(final QName node) {
715             super(node);
716         }
717
718         public static @NonNull NodeIdentifierWithPredicates of(final QName node) {
719             return new Regular(node, ImmutableMap.of());
720         }
721
722         public static @NonNull NodeIdentifierWithPredicates of(final QName node, final QName key, final Object value) {
723             return new Singleton(node, key, value);
724         }
725
726         public static @NonNull NodeIdentifierWithPredicates of(final QName node, final Entry<QName, Object> entry) {
727             return of(node, entry.getKey(), entry.getValue());
728         }
729
730         public static @NonNull NodeIdentifierWithPredicates of(final QName node, final Map<QName, Object> keyValues) {
731             return keyValues.size() == 1 ? of(keyValues, node)
732                     // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
733                     : new Regular(node, ImmutableOffsetMap.unorderedCopyOf(keyValues));
734         }
735
736         public static @NonNull NodeIdentifierWithPredicates of(final QName node,
737                 final ImmutableOffsetMap<QName, Object> keyValues) {
738             return keyValues.size() == 1 ? of(keyValues, node) : new Regular(node, keyValues);
739         }
740
741         private static @NonNull NodeIdentifierWithPredicates of(final Map<QName, Object> keyValues, final QName node) {
742             return of(node, keyValues.entrySet().iterator().next());
743         }
744
745         /**
746          * Return the set of predicates keys and values. Keys are guaranteeed to be unique.
747          *
748          * @return Predicate set.
749          */
750         public abstract @NonNull Set<Entry<QName, Object>> entrySet();
751
752         /**
753          * Return the predicate key in the iteration order of {@link #entrySet()}.
754          *
755          * @return Predicate values.
756          */
757         public abstract @NonNull Set<QName> keySet();
758
759         /**
760          * Determine whether a particular predicate key is present.
761          *
762          * @param key Predicate key
763          * @return True if the predicate is present, false otherwise
764          * @throws NullPointerException if {@code key} is null
765          */
766         public abstract boolean containsKey(QName key);
767
768         /**
769          * Return the predicate values in the iteration order of {@link #entrySet()}.
770          *
771          * @return Predicate values.
772          */
773         public abstract @NonNull Collection<Object> values();
774
775         @Beta
776         public final @Nullable Object getValue(final QName key) {
777             return keyValue(requireNonNull(key));
778         }
779
780         @Beta
781         public final <T> @Nullable T getValue(final QName key, final Class<T> valueClass) {
782             return valueClass.cast(getValue(key));
783         }
784
785         /**
786          * Return the number of predicates present.
787          *
788          * @return The number of predicates present.
789          */
790         public abstract int size();
791
792         /**
793          * A Map-like view of this identifier's predicates. The view is expected to be stable and effectively-immutable.
794          *
795          * @return Map of predicates.
796          */
797         @Beta
798         public abstract @NonNull Map<QName, Object> asMap();
799
800         @Override
801         protected final int hashCodeImpl() {
802             int result = 31 * super.hashCodeImpl();
803             for (Entry<QName, Object> entry : entrySet()) {
804                 result += entry.getKey().hashCode() + YangInstanceIdentifier.hashCode(entry.getValue());
805             }
806             return result;
807         }
808
809         @Override
810         @SuppressWarnings("checkstyle:equalsHashCode")
811         public final boolean equals(final Object obj) {
812             return super.equals(obj) && equalMapping((NodeIdentifierWithPredicates) obj);
813         }
814
815         abstract boolean equalMapping(NodeIdentifierWithPredicates other);
816
817         abstract @Nullable Object keyValue(@NonNull QName qname);
818
819         @Override
820         public final String toString() {
821             return super.toString() + '[' + asMap() + ']';
822         }
823
824         @Override
825         public final String toRelativeString(final PathArgument previous) {
826             return super.toRelativeString(previous) + '[' + asMap() + ']';
827         }
828
829         @Override
830         final Object writeReplace() {
831             return new NIPv2(this);
832         }
833     }
834
835     /**
836      * Simple path argument identifying a {@link LeafSetEntryNode} leaf
837      * overall data tree.
838      */
839     public static final class NodeWithValue<T> extends AbstractPathArgument {
840         private static final long serialVersionUID = -3637456085341738431L;
841
842         private final @NonNull T value;
843
844         public NodeWithValue(final QName node, final T value) {
845             super(node);
846             this.value = requireNonNull(value);
847         }
848
849         public @NonNull T getValue() {
850             return value;
851         }
852
853         @Override
854         protected int hashCodeImpl() {
855             return 31 * super.hashCodeImpl() + YangInstanceIdentifier.hashCode(value);
856         }
857
858         @Override
859         @SuppressWarnings("checkstyle:equalsHashCode")
860         public boolean equals(final Object obj) {
861             if (!super.equals(obj)) {
862                 return false;
863             }
864             final NodeWithValue<?> other = (NodeWithValue<?>) obj;
865             return Objects.deepEquals(value, other.value);
866         }
867
868         @Override
869         public String toString() {
870             return super.toString() + '[' + value + ']';
871         }
872
873         @Override
874         public String toRelativeString(final PathArgument previous) {
875             return super.toRelativeString(previous) + '[' + value + ']';
876         }
877
878         @Override
879         Object writeReplace() {
880             return new NIVv1(this);
881         }
882     }
883
884     /**
885      * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode}
886      * node in particular subtree.
887      *
888      * <p>
889      * Augmentation is uniquely identified by set of all possible child nodes.
890      * This is possible
891      * to identify instance of augmentation,
892      * since RFC6020 states that <code>augment</code> that augment
893      * statement must not add multiple nodes from same namespace
894      * / module to the target node.
895      *
896      * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
897      */
898     public static final class AugmentationIdentifier implements PathArgument {
899         private static final long serialVersionUID = -8122335594681936939L;
900
901         private static final LoadingCache<ImmutableSet<QName>, AugmentationIdentifier> CACHE = CacheBuilder.newBuilder()
902                 .weakValues().build(new CacheLoader<ImmutableSet<QName>, AugmentationIdentifier>() {
903                     @Override
904                     public AugmentationIdentifier load(final ImmutableSet<QName> key) {
905                         return new AugmentationIdentifier(key);
906                     }
907                 });
908
909         private final @NonNull ImmutableSet<QName> childNames;
910
911         @Override
912         public QName getNodeType() {
913             // This should rather throw exception than return always null
914             throw new UnsupportedOperationException("Augmentation node has no QName");
915         }
916
917         /**
918          * Construct new augmentation identifier using supplied set of possible
919          * child nodes.
920          *
921          * @param childNames
922          *            Set of possible child nodes.
923          */
924         public AugmentationIdentifier(final ImmutableSet<QName> childNames) {
925             this.childNames = requireNonNull(childNames);
926         }
927
928         /**
929          * Construct new augmentation identifier using supplied set of possible
930          * child nodes.
931          *
932          * @param childNames
933          *            Set of possible child nodes.
934          */
935         public AugmentationIdentifier(final Set<QName> childNames) {
936             this.childNames = ImmutableSet.copyOf(childNames);
937         }
938
939         /**
940          * Return an AugmentationIdentifier for a particular set of QNames. Unlike the constructor, this factory method
941          * uses a global instance cache, resulting in object reuse for equal inputs.
942          *
943          * @param childNames Set of possible child nodes
944          * @return An {@link AugmentationIdentifier}
945          */
946         public static @NonNull AugmentationIdentifier create(final ImmutableSet<QName> childNames) {
947             return CACHE.getUnchecked(childNames);
948         }
949
950         /**
951          * Return an AugmentationIdentifier for a particular set of QNames. Unlike the constructor, this factory method
952          * uses a global instance cache, resulting in object reuse for equal inputs.
953          *
954          * @param childNames Set of possible child nodes
955          * @return An {@link AugmentationIdentifier}
956          */
957         public static @NonNull AugmentationIdentifier create(final Set<QName> childNames) {
958             final AugmentationIdentifier existing = CACHE.getIfPresent(childNames);
959             return existing != null ? existing : create(ImmutableSet.copyOf(childNames));
960         }
961
962         /**
963          * Returns set of all possible child nodes.
964          *
965          * @return set of all possible child nodes.
966          */
967         public @NonNull Set<QName> getPossibleChildNames() {
968             return childNames;
969         }
970
971         @Override
972         public String toString() {
973             return "AugmentationIdentifier{" + "childNames=" + childNames + '}';
974         }
975
976         @Override
977         public String toRelativeString(final PathArgument previous) {
978             return toString();
979         }
980
981         @Override
982         public boolean equals(final Object obj) {
983             return this == obj || obj instanceof AugmentationIdentifier other && childNames.equals(other.childNames);
984         }
985
986         @Override
987         public int hashCode() {
988             return childNames.hashCode();
989         }
990
991         @Override
992         @SuppressWarnings("checkstyle:parameterName")
993         public int compareTo(final PathArgument o) {
994             if (!(o instanceof AugmentationIdentifier other)) {
995                 return -1;
996             }
997             Set<QName> otherChildNames = other.getPossibleChildNames();
998             int thisSize = childNames.size();
999             int otherSize = otherChildNames.size();
1000             if (thisSize == otherSize) {
1001                 // Quick Set-based comparison
1002                 if (childNames.equals(otherChildNames)) {
1003                     return 0;
1004                 }
1005
1006                 // We already know the sets are not equal, but have equal size, hence the sets differ in their elements,
1007                 // but potentially share a common set of elements. The most consistent way of comparing them is using
1008                 // total ordering defined by QName's compareTo. Hence convert both sets to lists ordered
1009                 // by QName.compareTo() and decide on the first differing element.
1010                 final List<QName> diff = new ArrayList<>(Sets.symmetricDifference(childNames, otherChildNames));
1011                 verify(!diff.isEmpty(), "Augmentation identifiers %s and %s report no difference", this, o);
1012                 diff.sort(QName::compareTo);
1013                 return childNames.contains(diff.get(0)) ? -1 : 1;
1014             } else if (thisSize < otherSize) {
1015                 return 1;
1016             } else {
1017                 return -1;
1018             }
1019         }
1020
1021         private Object writeReplace() {
1022             return new AIv1(this);
1023         }
1024     }
1025
1026     /**
1027      * Fluent Builder of Instance Identifier instances.
1028      */
1029     public interface InstanceIdentifierBuilder extends Mutable {
1030         /**
1031          * Adds a {@link PathArgument} to path arguments of resulting instance identifier.
1032          *
1033          * @param arg A {@link PathArgument} to be added
1034          * @return this builder
1035          */
1036         @NonNull InstanceIdentifierBuilder node(PathArgument arg);
1037
1038         /**
1039          * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
1040          *
1041          * @param nodeType QName of {@link NodeIdentifier} which will be added
1042          * @return this builder
1043          */
1044         @NonNull InstanceIdentifierBuilder node(QName nodeType);
1045
1046         /**
1047          * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting
1048          * instance identifier.
1049          *
1050          * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
1051          * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
1052          * @return this builder
1053          */
1054         @NonNull InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
1055
1056         /**
1057          * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
1058          *
1059          * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
1060          * @param key QName of key which will be added
1061          * @param value value of key which will be added
1062          * @return this builder
1063          */
1064         @NonNull InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
1065
1066         /**
1067          * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
1068          *
1069          * @param args {@link PathArgument}s to be added
1070          * @return this builder
1071          * @throws NullPointerException if any of the arguments is null
1072          */
1073         @NonNull InstanceIdentifierBuilder append(Collection<? extends PathArgument> args);
1074
1075         /**
1076          * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
1077          *
1078          * @param args {@link PathArgument}s to be added
1079          * @return this builder
1080          * @throws NullPointerException if any of the arguments is null
1081          */
1082         default @NonNull InstanceIdentifierBuilder append(final PathArgument... args) {
1083             return append(Arrays.asList(args));
1084         }
1085
1086         /**
1087          * Builds an {@link YangInstanceIdentifier} with path arguments from this builder.
1088          *
1089          * @return {@link YangInstanceIdentifier}
1090          */
1091         @NonNull YangInstanceIdentifier build();
1092     }
1093 }