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