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