f691310d279298dc88ac8f23cc91dafffdb5b28c
[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.Serial;
25 import java.io.Serializable;
26 import java.lang.invoke.MethodHandles;
27 import java.lang.invoke.VarHandle;
28 import java.lang.reflect.Array;
29 import java.util.AbstractMap.SimpleImmutableEntry;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Collection;
33 import java.util.Deque;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Map.Entry;
38 import java.util.Objects;
39 import java.util.Optional;
40 import java.util.Set;
41 import java.util.function.Function;
42 import org.eclipse.jdt.annotation.NonNull;
43 import org.eclipse.jdt.annotation.Nullable;
44 import org.opendaylight.yangtools.concepts.HierarchicalIdentifier;
45 import org.opendaylight.yangtools.concepts.Immutable;
46 import org.opendaylight.yangtools.concepts.Mutable;
47 import org.opendaylight.yangtools.util.ImmutableOffsetMap;
48 import org.opendaylight.yangtools.util.SingletonSet;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.common.QNameModule;
51 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
52
53 /**
54  * Unique identifier of a particular node instance in the data tree.
55  *
56  * <p>
57  * Java representation of YANG Built-in type {@code instance-identifier}, which conceptually is XPath expression
58  * minimized to uniquely identify element in data tree which conforms to constraints maintained by YANG Model,
59  * effectively this makes Instance Identifier a path to element in data tree.
60  *
61  * <p>
62  * Constraints put in YANG specification on instance-identifier allowed it to be effectively represented in Java and its
63  * evaluation does not require a full-blown XPath processor.
64  *
65  * <h2>Path Arguments</h2>
66  * Path to the node represented in instance identifier consists of {@link PathArgument} which carries necessary
67  * information to uniquely identify node on particular level in the subtree.
68  *
69  * <ul>
70  *   <li>{@link NodeIdentifier} - Identifier of node, which has cardinality {@code 0..1} in particular subtree in data
71  *       tree</li>
72  *   <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item), which has cardinality {@code 0..n}</li>
73  *   <li>{@link NodeWithValue} - Identifier of instance {@code leaf} node or {@code leaf-list} node</li>
74  *   <li>{@link AugmentationIdentifier} - Identifier of instance of {@code augmentation} node</li>
75  * </ul>
76  *
77  * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
78  */
79 public abstract sealed class YangInstanceIdentifier implements HierarchicalIdentifier<YangInstanceIdentifier>
80         permits FixedYangInstanceIdentifier, StackedYangInstanceIdentifier {
81     @Serial
82     private static final long serialVersionUID = 4L;
83     private static final VarHandle TO_STRING_CACHE;
84     private static final VarHandle HASH;
85
86     static {
87         final var lookup = MethodHandles.lookup();
88         try {
89             HASH = lookup.findVarHandle(YangInstanceIdentifier.class, "hash", int.class);
90             TO_STRING_CACHE = lookup.findVarHandle(YangInstanceIdentifier.class, "toStringCache", String.class);
91         } catch (NoSuchFieldException | IllegalAccessException e) {
92             throw new ExceptionInInitializerError(e);
93         }
94     }
95
96     @SuppressWarnings("unused")
97     private int hash;
98     @SuppressWarnings("unused")
99     private transient String toStringCache = null;
100
101     YangInstanceIdentifier() {
102         // Package-private to prevent outside subclassing
103     }
104
105     /**
106      * Return An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual root of the YANG
107      * namespace.
108      *
109      * @return An empty YangInstanceIdentifier
110      */
111     public static @NonNull YangInstanceIdentifier empty() {
112         return FixedYangInstanceIdentifier.EMPTY_INSTANCE;
113     }
114
115     abstract @NonNull YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
116
117     abstract @Nullable List<PathArgument> tryPathArguments();
118
119     abstract @Nullable List<PathArgument> tryReversePathArguments();
120
121     /**
122      * Check if this instance identifier has empty path arguments, e.g. it is
123      * empty and corresponds to {@link #empty()}.
124      *
125      * @return True if this instance identifier is empty, false otherwise.
126      */
127     public abstract boolean isEmpty();
128
129     /**
130      * Return an optimized version of this identifier, useful when the identifier
131      * will be used very frequently.
132      *
133      * @return A optimized equivalent instance.
134      */
135     public abstract @NonNull YangInstanceIdentifier toOptimized();
136
137     /**
138      * Return the conceptual parent {@link YangInstanceIdentifier}, which has
139      * one item less in {@link #getPathArguments()}.
140      *
141      * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #empty()}.
142      */
143     public abstract @Nullable YangInstanceIdentifier getParent();
144
145     /**
146      * Return the conceptual parent {@link YangInstanceIdentifier}, which has one item less in
147      * {@link #getPathArguments()}.
148      *
149      * @return Parent {@link YangInstanceIdentifier}
150      * @throws VerifyException if this object is {@link #empty()}.
151      */
152     public abstract @NonNull YangInstanceIdentifier coerceParent();
153
154     /**
155      * Return the ancestor {@link YangInstanceIdentifier} with a particular depth, e.g. number of path arguments.
156      *
157      * @param depth Ancestor depth
158      * @return Ancestor {@link YangInstanceIdentifier}
159      * @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
160      */
161     public abstract @NonNull YangInstanceIdentifier getAncestor(int depth);
162
163     /**
164      * Returns an ordered iteration of path arguments.
165      *
166      * @return Immutable iteration of path arguments.
167      */
168     public abstract @NonNull List<PathArgument> getPathArguments();
169
170     /**
171      * Returns an iterable of path arguments in reverse order. This is useful
172      * when walking up a tree organized this way.
173      *
174      * @return Immutable iterable of path arguments in reverse order.
175      */
176     public abstract @NonNull List<PathArgument> getReversePathArguments();
177
178     /**
179      * Returns the last PathArgument. This is equivalent of iterating
180      * to the last element of the iterable returned by {@link #getPathArguments()}.
181      *
182      * @return The last past argument, or null if there are no PathArguments.
183      */
184     public abstract PathArgument getLastPathArgument();
185
186     public static @NonNull YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
187         return Iterables.isEmpty(path) ? empty() : new FixedYangInstanceIdentifier(ImmutableList.copyOf(path));
188     }
189
190     public static @NonNull YangInstanceIdentifier create(final PathArgument pathArgument) {
191         return new FixedYangInstanceIdentifier(ImmutableList.of(pathArgument));
192     }
193
194     public static @NonNull YangInstanceIdentifier create(final PathArgument... path) {
195         // We are forcing a copy, since we cannot trust the user
196         return create(Arrays.asList(path));
197     }
198
199     /**
200      * Create a {@link YangInstanceIdentifier} by taking a snapshot of provided path and iterating it backwards.
201      *
202      * @param pathTowardsRoot Path towards root
203      * @return A {@link YangInstanceIdentifier} instance
204      * @throws NullPointerException if {@code pathTowardsRoot} or any of its members is null
205      */
206     public static @NonNull YangInstanceIdentifier createReverse(final Deque<PathArgument> pathTowardsRoot) {
207         final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
208             pathTowardsRoot.size());
209         pathTowardsRoot.descendingIterator().forEachRemaining(builder::add);
210         return YangInstanceIdentifier.create(builder.build());
211     }
212
213     /**
214      * Create a {@link YangInstanceIdentifier} by walking specified stack backwards and extracting path components
215      * from it.
216      *
217      * @param stackTowardsRoot Stack towards root,
218      * @return A {@link YangInstanceIdentifier} instance
219      * @throws NullPointerException if {@code pathTowardsRoot} is null
220      */
221     public static <T> @NonNull YangInstanceIdentifier createReverse(final Deque<? extends T> stackTowardsRoot,
222             final Function<T, PathArgument> function) {
223         final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
224             stackTowardsRoot.size());
225         final Iterator<? extends T> it = stackTowardsRoot.descendingIterator();
226         while (it.hasNext()) {
227             builder.add(function.apply(it.next()));
228         }
229         return YangInstanceIdentifier.create(builder.build());
230     }
231
232     boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
233         return getPathArguments().equals(other.getPathArguments());
234     }
235
236     @Override
237     public final boolean equals(final Object obj) {
238         return this == obj || obj instanceof YangInstanceIdentifier other && pathArgumentsEqual(other);
239     }
240
241     /**
242      * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments.
243      *
244      * @param name QName of {@link NodeIdentifier}
245      * @return Instance Identifier with additional path argument added to the end.
246      */
247     public final @NonNull YangInstanceIdentifier node(final QName name) {
248         return node(new NodeIdentifier(name));
249     }
250
251     /**
252      * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments.
253      *
254      * @param arg Path argument which should be added to the end
255      * @return Instance Identifier with additional path argument added to the end.
256      */
257     public final @NonNull YangInstanceIdentifier node(final PathArgument arg) {
258         return new StackedYangInstanceIdentifier(this, arg);
259     }
260
261     /**
262      * Get the relative path from an ancestor. This method attempts to perform
263      * the reverse of concatenating a base (ancestor) and a path.
264      *
265      * @param ancestor
266      *            Ancestor against which the relative path should be calculated
267      * @return This object's relative path from parent, or Optional.absent() if
268      *         the specified parent is not in fact an ancestor of this object.
269      */
270     public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
271         if (this == ancestor) {
272             return Optional.of(empty());
273         }
274         if (ancestor.isEmpty()) {
275             return Optional.of(this);
276         }
277
278         final Iterator<PathArgument> lit = getPathArguments().iterator();
279         final Iterator<PathArgument> oit = ancestor.getPathArguments().iterator();
280         int common = 0;
281
282         while (oit.hasNext()) {
283             // Ancestor is not really an ancestor
284             if (!lit.hasNext() || !lit.next().equals(oit.next())) {
285                 return Optional.empty();
286             }
287
288             ++common;
289         }
290
291         if (common == 0) {
292             return Optional.of(this);
293         }
294         if (!lit.hasNext()) {
295             return Optional.of(empty());
296         }
297
298         return Optional.of(createRelativeIdentifier(common));
299     }
300
301     @Override
302     public final boolean contains(final YangInstanceIdentifier other) {
303         if (this == other) {
304             return true;
305         }
306
307         checkArgument(other != null, "other should not be null");
308         final Iterator<PathArgument> lit = getPathArguments().iterator();
309         final Iterator<PathArgument> oit = other.getPathArguments().iterator();
310
311         while (lit.hasNext()) {
312             if (!oit.hasNext()) {
313                 return false;
314             }
315
316             if (!lit.next().equals(oit.next())) {
317                 return false;
318             }
319         }
320
321         return true;
322     }
323
324     @Override
325     public final String toString() {
326         /*
327          * The toStringCache is safe, since the object contract requires
328          * immutability of the object and all objects referenced from this
329          * object.
330          * Used lists, maps are immutable. Path Arguments (elements) are also
331          * immutable, since the PathArgument contract requires immutability.
332          * The cache is thread-safe - if multiple computations occurs at the
333          * same time, cache will be overwritten with same result.
334          */
335         final String ret = (String) TO_STRING_CACHE.getAcquire(this);
336         return ret != null ? ret : loadToString();
337     }
338
339     private String loadToString() {
340         final StringBuilder builder = new StringBuilder("/");
341         PathArgument prev = null;
342         for (PathArgument argument : getPathArguments()) {
343             if (prev != null) {
344                 builder.append('/');
345             }
346             builder.append(argument.toRelativeString(prev));
347             prev = argument;
348         }
349
350         final String ret = builder.toString();
351         final String witness = (String) TO_STRING_CACHE.compareAndExchangeRelease(this, null, ret);
352         return witness == null ? ret : witness;
353     }
354
355     @Override
356     public final int hashCode() {
357         /*
358          * The caching is safe, since the object contract requires
359          * immutability of the object and all objects referenced from this
360          * object.
361          * Used lists, maps are immutable. Path Arguments (elements) are also
362          * immutable, since the PathArgument contract requires immutability.
363          */
364         final int local = (int) HASH.getAcquire(this);
365         return local != 0 ? local : loadHashCode();
366     }
367
368     private static int hashCode(final Object value) {
369         if (value == null) {
370             return 0;
371         }
372
373         if (byte[].class.equals(value.getClass())) {
374             return Arrays.hashCode((byte[]) value);
375         }
376
377         if (value.getClass().isArray()) {
378             int hash = 0;
379             int length = Array.getLength(value);
380             for (int i = 0; i < length; i++) {
381                 hash += Objects.hashCode(Array.get(value, i));
382             }
383
384             return hash;
385         }
386
387         return Objects.hashCode(value);
388     }
389
390     private int loadHashCode() {
391         final int computed = computeHashCode();
392         HASH.setRelease(this, computed);
393         return computed;
394     }
395
396     abstract int computeHashCode();
397
398     @Serial
399     final Object writeReplace() {
400         return new YIDv1(this);
401     }
402
403     // Static factories & helpers
404
405     /**
406      * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied
407      * QName.
408      *
409      * @param name QName of first node identifier
410      * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
411      */
412     public static @NonNull YangInstanceIdentifier of(final QName name) {
413         return create(new NodeIdentifier(name));
414     }
415
416     /**
417      * Returns new builder for InstanceIdentifier with empty path arguments.
418      *
419      * @return new builder for InstanceIdentifier with empty path arguments.
420      */
421     public static @NonNull InstanceIdentifierBuilder builder() {
422         return new YangInstanceIdentifierBuilder();
423     }
424
425     /**
426      * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
427      *
428      * @param origin InstanceIdentifier from which path arguments are copied.
429      * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
430      */
431     public static @NonNull InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
432         return new YangInstanceIdentifierBuilder(origin.getPathArguments());
433     }
434
435     /**
436      * Path argument / component of InstanceIdentifier.
437      * Path argument uniquely identifies node in data tree on particular
438      * level.
439      *
440      * <p>
441      * This interface itself is used as common parent for actual
442      * path arguments types and should not be implemented by user code.
443      *
444      * <p>
445      * Path arguments SHOULD contain only minimum of information
446      * required to uniquely identify node on particular subtree level.
447      *
448      * <p>
449      * For actual path arguments types see:
450      * <ul>
451      * <li>{@link NodeIdentifier} - Identifier of container or leaf
452      * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
453      * <li>{@link AugmentationIdentifier} - Identifier of augmentation
454      * <li>{@link NodeWithValue} - Identifier of leaf-list entry
455      * </ul>
456      */
457     public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
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 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 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 }