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