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