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