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