Fix nullness errors reported by Eclipse
[mdsal.git] / binding / yang-binding / src / main / java / org / opendaylight / yangtools / yang / binding / InstanceIdentifier.java
1 /*
2  * Copyright (c) 2013 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.binding;
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.base.MoreObjects;
15 import com.google.common.base.MoreObjects.ToStringHelper;
16 import com.google.common.base.VerifyException;
17 import com.google.common.collect.ImmutableCollection;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.Iterables;
20 import java.io.ObjectStreamException;
21 import java.io.Serializable;
22 import java.util.Collections;
23 import java.util.Iterator;
24 import java.util.Objects;
25 import java.util.Optional;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.yangtools.concepts.Builder;
29 import org.opendaylight.yangtools.concepts.Immutable;
30 import org.opendaylight.yangtools.concepts.Path;
31 import org.opendaylight.yangtools.util.HashCodeBuilder;
32
33 /**
34  * This instance identifier uniquely identifies a specific DataObject in the data tree modeled by YANG.
35  *
36  * <p>
37  * For Example let's say you were trying to refer to a node in inventory which was modeled in YANG as follows,
38  *
39  * <p>
40  * <pre>
41  * module opendaylight-inventory {
42  *      ....
43  *
44  *      container nodes {
45  *        list node {
46  *            key "id";
47  *            ext:context-instance "node-context";
48  *
49  *            uses node;
50  *        }
51  *    }
52  *
53  * }
54  * </pre>
55  *
56  * <p>
57  * You can create an instance identifier as follows to get to a node with id "openflow:1": {@code
58  * InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
59  * }
60  *
61  * <p>
62  * This would be the same as using a path like so, "/nodes/node/openflow:1" to refer to the openflow:1 node
63  */
64 public class InstanceIdentifier<T extends DataObject> implements Path<InstanceIdentifier<? extends DataObject>>,
65         Immutable, Serializable {
66     private static final long serialVersionUID = 3L;
67
68     /*
69      * Protected to differentiate internal and external access. Internal access is required never to modify
70      * the contents. References passed to outside entities have to be wrapped in an unmodifiable view.
71      */
72     final Iterable<PathArgument> pathArguments;
73
74     private final @NonNull Class<T> targetType;
75     private final boolean wildcarded;
76     private final int hash;
77
78     InstanceIdentifier(final Class<T> type, final Iterable<PathArgument> pathArguments, final boolean wildcarded,
79             final int hash) {
80         this.pathArguments = requireNonNull(pathArguments);
81         this.targetType = requireNonNull(type);
82         this.wildcarded = wildcarded;
83         this.hash = hash;
84     }
85
86     /**
87      * Return the type of data which this InstanceIdentifier identifies.
88      *
89      * @return Target type
90      */
91     public final @NonNull Class<T> getTargetType() {
92         return targetType;
93     }
94
95     /**
96      * Perform a safe target type adaptation of this instance identifier to target type. This method is useful when
97      * dealing with type-squashed instances.
98      *
99      * @return Path argument with target type
100      * @throws VerifyException if this instance identifier cannot be adapted to target type
101      * @throws NullPointerException if {@code target} is null
102      */
103     @SuppressWarnings("unchecked")
104     public final <N extends DataObject> @NonNull InstanceIdentifier<N> verifyTarget(final Class<@NonNull N> target) {
105         verify(target.equals(targetType), "Cannot adapt %s to %s", this, target);
106         return (InstanceIdentifier<N>) this;
107     }
108
109     /**
110      * Return the path argument chain which makes up this instance identifier.
111      *
112      * @return Path argument chain. Immutable and does not contain nulls.
113      */
114     public final @NonNull Iterable<PathArgument> getPathArguments() {
115         return Iterables.unmodifiableIterable(pathArguments);
116     }
117
118     /**
119      * Check whether an instance identifier contains any wildcards. A wildcard is an path argument which has a null key.
120      *
121      * @return true if any of the path arguments has a null key.
122      */
123     public final boolean isWildcarded() {
124         return wildcarded;
125     }
126
127     @Override
128     public final int hashCode() {
129         return hash;
130     }
131
132     @Override
133     public final boolean equals(final Object obj) {
134         if (this == obj) {
135             return true;
136         }
137         if (obj == null) {
138             return false;
139         }
140         if (getClass() != obj.getClass()) {
141             return false;
142         }
143
144         final InstanceIdentifier<?> other = (InstanceIdentifier<?>) obj;
145         if (pathArguments == other.pathArguments) {
146             return true;
147         }
148
149         /*
150          * We could now just go and compare the pathArguments, but that
151          * can be potentially expensive. Let's try to avoid that by
152          * checking various things that we have cached from pathArguments
153          * and trying to prove the identifiers are *not* equal.
154          */
155         if (hash != other.hash) {
156             return false;
157         }
158         if (wildcarded != other.wildcarded) {
159             return false;
160         }
161         if (targetType != other.targetType) {
162             return false;
163         }
164         if (fastNonEqual(other)) {
165             return false;
166         }
167
168         // Everything checks out so far, so we have to do a full equals
169         return Iterables.elementsEqual(pathArguments, other.pathArguments);
170     }
171
172     /**
173      * Perform class-specific fast checks for non-equality. This allows subclasses to avoid iterating over the
174      * pathArguments by performing quick checks on their specific fields.
175      *
176      * @param other The other identifier, guaranteed to be the same class
177      * @return true if the other identifier cannot be equal to this one.
178      */
179     protected boolean fastNonEqual(final InstanceIdentifier<?> other) {
180         return false;
181     }
182
183     @Override
184     public final String toString() {
185         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
186     }
187
188     /**
189      * Add class-specific toString attributes.
190      *
191      * @param toStringHelper ToStringHelper instance
192      * @return ToStringHelper instance which was passed in
193      */
194     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
195         return toStringHelper.add("targetType", targetType).add("path", Iterables.toString(pathArguments));
196     }
197
198     /**
199      * Return an instance identifier trimmed at the first occurrence of a specific component type.
200      *
201      * <p>
202      * For example let's say an instance identifier was built like so,
203      * <pre>
204      *      identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class,
205      *                   new NodeKey(new NodeId("openflow:1")).build();
206      * </pre>
207      *
208      * <p>
209      * And you wanted to obtain the Instance identifier which represented Nodes you would do it like so,
210      *
211      * <p>
212      * <pre>
213      *      identifier.firstIdentifierOf(Nodes.class)
214      * </pre>
215      *
216      * @param type component type
217      * @return trimmed instance identifier, or null if the component type
218      *         is not present.
219      */
220     public final <I extends DataObject> @Nullable InstanceIdentifier<I> firstIdentifierOf(
221             final Class<@NonNull I> type) {
222         int count = 1;
223         for (final PathArgument a : pathArguments) {
224             if (type.equals(a.getType())) {
225                 @SuppressWarnings("unchecked")
226                 final InstanceIdentifier<I> ret = (InstanceIdentifier<I>) internalCreate(
227                         Iterables.limit(pathArguments, count));
228                 return ret;
229             }
230
231             ++count;
232         }
233
234         return null;
235     }
236
237     /**
238      * Return the key associated with the first component of specified type in
239      * an identifier.
240      *
241      * @param listItem component type
242      * @return key associated with the component, or null if the component type
243      *         is not present.
244      */
245     public final <N extends Identifiable<K> & DataObject, K extends Identifier<N>> @Nullable K firstKeyOf(
246             final Class<@NonNull N> listItem) {
247         for (final PathArgument i : pathArguments) {
248             if (listItem.equals(i.getType())) {
249                 @SuppressWarnings("unchecked")
250                 final K ret = ((IdentifiableItem<N, K>)i).getKey();
251                 return ret;
252             }
253         }
254
255         return null;
256     }
257
258     /**
259      * Check whether an identifier is contained in this identifier. This is a strict subtree check, which requires all
260      * PathArguments to match exactly.
261      *
262      * <p>
263      * The contains method checks if the other identifier is fully contained within the current identifier. It does this
264      * by looking at only the types of the path arguments and not by comparing the path arguments themselves.
265      *
266      * <p>
267      * To illustrate here is an example which explains the working of this API. Let's say you have two instance
268      * identifiers as follows:
269      * {@code
270      * this = /nodes/node/openflow:1
271      * other = /nodes/node/openflow:2
272      * }
273      * then this.contains(other) will return false.
274      *
275      * @param other Potentially-container instance identifier
276      * @return True if the specified identifier is contained in this identifier.
277      */
278     @Override
279     public final boolean contains(final InstanceIdentifier<? extends DataObject> other) {
280         requireNonNull(other, "other should not be null");
281
282         final Iterator<?> lit = pathArguments.iterator();
283         final Iterator<?> oit = other.pathArguments.iterator();
284
285         while (lit.hasNext()) {
286             if (!oit.hasNext()) {
287                 return false;
288             }
289
290             if (!lit.next().equals(oit.next())) {
291                 return false;
292             }
293         }
294
295         return true;
296     }
297
298     /**
299      * Check whether this instance identifier contains the other identifier after wildcard expansion. This is similar
300      * to {@link #contains(InstanceIdentifier)}, with the exception that a wildcards are assumed to match the their
301      * non-wildcarded PathArgument counterpart.
302      *
303      * @param other Identifier which should be checked for inclusion.
304      * @return true if this identifier contains the other object
305      */
306     public final boolean containsWildcarded(final InstanceIdentifier<?> other) {
307         requireNonNull(other, "other should not be null");
308
309         final Iterator<PathArgument> lit = pathArguments.iterator();
310         final Iterator<PathArgument> oit = other.pathArguments.iterator();
311
312         while (lit.hasNext()) {
313             if (!oit.hasNext()) {
314                 return false;
315             }
316
317             final PathArgument la = lit.next();
318             final PathArgument oa = oit.next();
319
320             if (!la.getType().equals(oa.getType())) {
321                 return false;
322             }
323             if (la instanceof IdentifiableItem<?, ?> && oa instanceof IdentifiableItem<?, ?> && !la.equals(oa)) {
324                 return false;
325             }
326         }
327
328         return true;
329     }
330
331     private <N extends DataObject> @NonNull InstanceIdentifier<N> childIdentifier(final AbstractPathArgument<N> arg) {
332         return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)),
333             HashCodeBuilder.nextHashCode(hash, arg), isWildcarded());
334     }
335
336     /**
337      * Create an InstanceIdentifier for a child container. This method is a more efficient equivalent to
338      * {@code builder().child(container).build()}.
339      *
340      * @param container Container to append
341      * @param <N> Container type
342      * @return An InstanceIdentifier.
343      * @throws NullPointerException if {@code container} is null
344      */
345     public final <N extends ChildOf<? super T>> @NonNull InstanceIdentifier<N> child(
346             final Class<@NonNull N> container) {
347         return childIdentifier(Item.of(container));
348     }
349
350     /**
351      * Create an InstanceIdentifier for a child list item. This method is a more efficient equivalent to
352      * {@code builder().child(listItem, listKey).build()}.
353      *
354      * @param listItem List to append
355      * @param listKey List key
356      * @param <N> List type
357      * @param <K> Key type
358      * @return An InstanceIdentifier.
359      * @throws NullPointerException if any argument is null
360      */
361     @SuppressWarnings("unchecked")
362     public final <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>>
363             @NonNull KeyedInstanceIdentifier<N, K> child(final Class<@NonNull N> listItem, final K listKey) {
364         return (KeyedInstanceIdentifier<N, K>) childIdentifier(IdentifiableItem.of(listItem, listKey));
365     }
366
367     /**
368      * Create an InstanceIdentifier for a child container. This method is a more efficient equivalent to
369      * {@code builder().child(caze, container).build()}.
370      *
371      * @param caze Choice case class
372      * @param container Container to append
373      * @param <C> Case type
374      * @param <N> Container type
375      * @return An InstanceIdentifier.
376      * @throws NullPointerException if any argument is null
377      */
378     // FIXME: add a proper caller
379     public final <C extends ChoiceIn<? super T> & DataObject, N extends ChildOf<? super C>>
380             @NonNull InstanceIdentifier<N> child(final Class<@NonNull C> caze, final Class<@NonNull N> container) {
381         return childIdentifier(Item.of(caze, container));
382     }
383
384     /**
385      * Create an InstanceIdentifier for a child list item. This method is a more efficient equivalent to
386      * {@code builder().child(caze, listItem, listKey).build()}.
387      *
388      * @param caze Choice case class
389      * @param listItem List to append
390      * @param listKey List key
391      * @param <C> Case type
392      * @param <N> List type
393      * @param <K> Key type
394      * @return An InstanceIdentifier.
395      * @throws NullPointerException if any argument is null
396      */
397     // FIXME: add a proper caller
398     @SuppressWarnings("unchecked")
399     public final <C extends ChoiceIn<? super T> & DataObject, K extends Identifier<N>,
400         N extends Identifiable<K> & ChildOf<? super C>> @NonNull KeyedInstanceIdentifier<N, K> child(
401                 final Class<@NonNull C> caze, final Class<@NonNull N> listItem, final K listKey) {
402         return (KeyedInstanceIdentifier<N, K>) childIdentifier(IdentifiableItem.of(caze, listItem, listKey));
403     }
404
405     /**
406      * Create an InstanceIdentifier for a child augmentation. This method is a more efficient equivalent to
407      * {@code builder().augmentation(container).build()}.
408      *
409      * @param container Container to append
410      * @param <N> Container type
411      * @return An InstanceIdentifier.
412      * @throws NullPointerException if {@code container} is null
413      */
414     public final <N extends DataObject & Augmentation<? super T>> @NonNull InstanceIdentifier<N> augmentation(
415             final Class<@NonNull N> container) {
416         return childIdentifier(Item.of(container));
417     }
418
419     /**
420      * Create a builder rooted at this key.
421      *
422      * @return A builder instance
423      */
424     public @NonNull InstanceIdentifierBuilder<T> builder() {
425         return new InstanceIdentifierBuilderImpl<>(Item.of(targetType), pathArguments, hash, isWildcarded());
426     }
427
428     /**
429      * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container.
430      *
431      * @param container Base container
432      * @param <T> Type of the container
433      * @return A new {@link InstanceIdentifierBuilder}
434      * @throws NullPointerException if {@code container} is null
435      */
436     public static <T extends ChildOf<? extends DataRoot>> @NonNull InstanceIdentifierBuilder<T> builder(
437             final Class<T> container) {
438         return new InstanceIdentifierBuilderImpl<T>().addWildNode(Item.of(container));
439     }
440
441     /**
442      * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container in
443      * a {@code grouping} used in the {@code case} statement.
444      *
445      * @param caze Choice case class
446      * @param container Base container
447      * @param <C> Case type
448      * @param <T> Type of the container
449      * @return A new {@link InstanceIdentifierBuilder}
450      * @throws NullPointerException if any argument is null
451      */
452     public static <C extends ChoiceIn<? extends DataRoot> & DataObject, T extends ChildOf<? super C>>
453             @NonNull InstanceIdentifierBuilder<T> builder(final Class<C> caze, final Class<T> container) {
454         return new InstanceIdentifierBuilderImpl<T>().addWildNode(Item.of(caze, container));
455     }
456
457     /**
458      * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an
459      * {@link IdentifiableItem}.
460      *
461      * @param listItem list item class
462      * @param listKey key value
463      * @param <N> List type
464      * @param <K> List key
465      * @return A new {@link InstanceIdentifierBuilder}
466      * @throws NullPointerException if any argument is null
467      */
468     public static <N extends Identifiable<K> & ChildOf<? extends DataRoot>,
469             K extends Identifier<N>> @NonNull InstanceIdentifierBuilder<N> builder(final Class<N> listItem,
470                     final K listKey) {
471         return new InstanceIdentifierBuilderImpl<N>().addNode(IdentifiableItem.of(listItem, listKey));
472     }
473
474     /**
475      * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an
476      * {@link IdentifiableItem} in a {@code grouping} used in the {@code case} statement.
477      *
478      * @param caze Choice case class
479      * @param listItem list item class
480      * @param listKey key value
481      * @param <C> Case type
482      * @param <N> List type
483      * @param <K> List key
484      * @return A new {@link InstanceIdentifierBuilder}
485      * @throws NullPointerException if any argument is null
486      */
487     public static <C extends ChoiceIn<? extends DataRoot> & DataObject,
488             N extends Identifiable<K> & ChildOf<? super C>, K extends Identifier<N>>
489             @NonNull InstanceIdentifierBuilder<N> builder(final Class<C> caze, final Class<N> listItem,
490                     final K listKey) {
491         return new InstanceIdentifierBuilderImpl<N>().addNode(IdentifiableItem.of(caze, listItem, listKey));
492     }
493
494     /**
495      * Create an instance identifier for a very specific object type. This method implements {@link #create(Iterable)}
496      * semantics, except it is used by internal callers, which have assured that the argument is an immutable Iterable.
497      *
498      * @param pathArguments The path to a specific node in the data tree
499      * @return InstanceIdentifier instance
500      * @throws IllegalArgumentException if pathArguments is empty or contains a null element.
501      * @throws NullPointerException if {@code pathArguments} is null
502      */
503     private static @NonNull InstanceIdentifier<?> internalCreate(final Iterable<PathArgument> pathArguments) {
504         final Iterator<? extends PathArgument> it = requireNonNull(pathArguments, "pathArguments may not be null")
505                 .iterator();
506         final HashCodeBuilder<PathArgument> hashBuilder = new HashCodeBuilder<>();
507         boolean wildcard = false;
508         PathArgument arg = null;
509
510         while (it.hasNext()) {
511             arg = it.next();
512             checkArgument(arg != null, "pathArguments may not contain null elements");
513
514             // TODO: sanity check ChildOf<>;
515             hashBuilder.addArgument(arg);
516
517             if (Identifiable.class.isAssignableFrom(arg.getType()) && !(arg instanceof IdentifiableItem<?, ?>)) {
518                 wildcard = true;
519             }
520         }
521         checkArgument(arg != null, "pathArguments may not be empty");
522
523         return trustedCreate(arg, pathArguments, hashBuilder.build(), wildcard);
524     }
525
526     /**
527      * Create an instance identifier for a very specific object type.
528      *
529      * <p>
530      * Example:
531      * <pre>
532      *  List&lt;PathArgument&gt; path = Arrays.asList(new Item(Nodes.class))
533      *  new InstanceIdentifier(path);
534      * </pre>
535      *
536      * @param pathArguments The path to a specific node in the data tree
537      * @return InstanceIdentifier instance
538      * @throws IllegalArgumentException if pathArguments is empty or
539      *         contains a null element.
540      */
541     public static @NonNull InstanceIdentifier<?> create(final Iterable<? extends PathArgument> pathArguments) {
542         if (pathArguments instanceof ImmutableCollection<?>) {
543             @SuppressWarnings("unchecked")
544             final Iterable<PathArgument> immutableArguments = (Iterable<PathArgument>) pathArguments;
545             return internalCreate(immutableArguments);
546         }
547
548         return internalCreate(ImmutableList.copyOf(pathArguments));
549     }
550
551     /**
552      * Create an instance identifier for a very specific object type.
553      *
554      * <p>
555      * For example
556      * <pre>
557      *      new InstanceIdentifier(Nodes.class)
558      * </pre>
559      * would create an InstanceIdentifier for an object of type Nodes
560      *
561      * @param type The type of the object which this instance identifier represents
562      * @return InstanceIdentifier instance
563      */
564     @SuppressWarnings("unchecked")
565     public static <T extends DataObject> @NonNull InstanceIdentifier<T> create(final Class<@NonNull T> type) {
566         return (InstanceIdentifier<T>) create(ImmutableList.of(Item.of(type)));
567     }
568
569     /**
570      * Return the key associated with the last component of the specified identifier.
571      *
572      * @param id instance identifier
573      * @return key associated with the last component
574      * @throws IllegalArgumentException if the supplied identifier type cannot have a key.
575      * @throws NullPointerException if id is null.
576      */
577     public static <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K keyOf(
578             final InstanceIdentifier<N> id) {
579         requireNonNull(id);
580         checkArgument(id instanceof KeyedInstanceIdentifier, "%s does not have a key", id);
581
582         @SuppressWarnings("unchecked")
583         final K ret = ((KeyedInstanceIdentifier<N, K>)id).getKey();
584         return ret;
585     }
586
587     @SuppressWarnings({ "unchecked", "rawtypes" })
588     static <N extends DataObject> @NonNull InstanceIdentifier<N> trustedCreate(final PathArgument arg,
589             final Iterable<PathArgument> pathArguments, final int hash, boolean wildcarded) {
590         if (Identifiable.class.isAssignableFrom(arg.getType()) && !wildcarded) {
591             Identifier<?> key = null;
592             if (arg instanceof IdentifiableItem) {
593                 key = ((IdentifiableItem<?, ?>)arg).getKey();
594             } else {
595                 wildcarded = true;
596             }
597
598             return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key);
599         }
600
601         return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
602     }
603
604     /**
605      * Path argument of {@link InstanceIdentifier}. Interface which implementations are used as path components of the
606      * path in overall data tree.
607      */
608     public interface PathArgument extends Comparable<PathArgument> {
609         /**
610          * Return the data object type backing this PathArgument.
611          *
612          * @return Data object type.
613          */
614         @NonNull Class<? extends DataObject> getType();
615
616         /**
617          * Return an optional enclosing case type. This is used only when {@link #getType()} references a node defined
618          * in a {@code grouping} which is reference inside a {@code case} statement in order to safely reference the
619          * node.
620          *
621          * @return Optional case class.
622          */
623         default Optional<? extends Class<? extends DataObject>> getCaseType() {
624             return Optional.empty();
625         }
626     }
627
628     private abstract static class AbstractPathArgument<T extends DataObject> implements PathArgument, Serializable {
629         private static final long serialVersionUID = 1L;
630
631         private final @NonNull Class<T> type;
632
633         AbstractPathArgument(final Class<T> type) {
634             this.type = requireNonNull(type, "Type may not be null.");
635         }
636
637         @Override
638         public final Class<T> getType() {
639             return type;
640         }
641
642         Object getKey() {
643             return null;
644         }
645
646         @Override
647         public final int hashCode() {
648             return Objects.hash(type, getCaseType(), getKey());
649         }
650
651         @Override
652         public final boolean equals(final Object obj) {
653             if (this == obj) {
654                 return true;
655             }
656             if (!(obj instanceof AbstractPathArgument)) {
657                 return false;
658             }
659             final AbstractPathArgument<?> other = (AbstractPathArgument<?>) obj;
660             return type.equals(other.type) && Objects.equals(getKey(), other.getKey())
661                     && getCaseType().equals(other.getCaseType());
662         }
663
664         @Override
665         public final int compareTo(final PathArgument arg) {
666             final int cmp = compareClasses(type, arg.getType());
667             if (cmp != 0) {
668                 return cmp;
669             }
670             final Optional<? extends Class<?>> caseType = getCaseType();
671             if (!caseType.isPresent()) {
672                 return arg.getCaseType().isPresent() ? -1 : 1;
673             }
674             final Optional<? extends Class<?>> argCaseType = getCaseType();
675             return argCaseType.isPresent() ? compareClasses(caseType.get(), argCaseType.get()) : 1;
676         }
677
678         private static int compareClasses(final Class<?> first, final Class<?> second) {
679             return first.getCanonicalName().compareTo(second.getCanonicalName());
680         }
681     }
682
683     /**
684      * An Item represents an object that probably is only one of it's kind. For example a Nodes object is only one of
685      * a kind. In YANG terms this would probably represent a container.
686      *
687      * @param <T> Item type
688      */
689     public static class Item<T extends DataObject> extends AbstractPathArgument<T> {
690         private static final long serialVersionUID = 1L;
691
692         Item(final Class<T> type) {
693             super(type);
694         }
695
696         /**
697          * Return a PathArgument instance backed by the specified class.
698          *
699          * @param type Backing class
700          * @param <T> Item type
701          * @return A new PathArgument
702          * @throws NullPointerException if {@code} is null.
703          */
704         public static <T extends DataObject> @NonNull Item<T> of(final Class<T> type) {
705             return new Item<>(type);
706         }
707
708         /**
709          * Return a PathArgument instance backed by the specified class, which in turn is defined in a {@code grouping}
710          * used in a corresponding {@code case} statement.
711          *
712          * @param caseType defining case class
713          * @param type Backing class
714          * @param <C> Case type
715          * @param <T> Item type
716          * @return A new PathArgument
717          * @throws NullPointerException if any argument is null.
718          */
719         public static <C extends ChoiceIn<?> & DataObject, T extends ChildOf<? super C>> @NonNull Item<T> of(
720                 final Class<C> caseType, final Class<T> type) {
721             return new CaseItem<>(caseType, type);
722         }
723
724         @Override
725         public String toString() {
726             return getType().getName();
727         }
728     }
729
730     /**
731      * An IdentifiableItem represents a object that is usually present in a collection and can be identified uniquely
732      * by a key. In YANG terms this would probably represent an item in a list.
733      *
734      * @param <I> An object that is identifiable by an identifier
735      * @param <T> The identifier of the object
736      */
737     public static class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>>
738             extends AbstractPathArgument<I> {
739         private static final long serialVersionUID = 1L;
740
741         private final @NonNull T key;
742
743         IdentifiableItem(final Class<I> type, final T key) {
744             super(type);
745             this.key = requireNonNull(key, "Key may not be null.");
746         }
747
748         /**
749          * Return an IdentifiableItem instance backed by the specified class with specified key.
750          *
751          * @param type Backing class
752          * @param key Key
753          * @param <T> List type
754          * @param <I> Key type
755          * @return An IdentifiableItem
756          * @throws NullPointerException if any argument is null.
757          */
758         public static <T extends Identifiable<I> & DataObject, I extends Identifier<T>>
759                 @NonNull IdentifiableItem<T, I> of(final Class<T> type, final I key) {
760             return new IdentifiableItem<>(type, key);
761         }
762
763         /**
764          * Return an IdentifiableItem instance backed by the specified class with specified key. The class is in turn
765          * defined in a {@code grouping} used in a corresponding {@code case} statement.
766          *
767          * @param caseType defining case class
768          * @param type Backing class
769          * @param <C> Case type
770          * @param <T> List type
771          * @param <I> Key type
772          * @return A new PathArgument
773          * @throws NullPointerException if any argument is null.
774          */
775         public static <C extends ChoiceIn<?> & DataObject, T extends ChildOf<? super C> & Identifiable<I>,
776                 I extends Identifier<T>> @NonNull IdentifiableItem<T, I> of(final Class<C> caseType,
777                         final Class<T> type, final I key) {
778             return new CaseIdentifiableItem<>(caseType, type, key);
779         }
780
781         /**
782          * Return the data object type backing this PathArgument.
783          *
784          * @return Data object type.
785          */
786         @Override
787         public final @NonNull T getKey() {
788             return key;
789         }
790
791         @Override
792         public String toString() {
793             return getType().getName() + "[key=" + key + "]";
794         }
795     }
796
797     private static final class CaseItem<C extends ChoiceIn<?> & DataObject, T extends ChildOf<? super C>>
798             extends Item<T> {
799         private static final long serialVersionUID = 1L;
800
801         private final Class<C> caseType;
802
803         CaseItem(final Class<C> caseType, final Class<T> type) {
804             super(type);
805             this.caseType = requireNonNull(caseType);
806         }
807
808         @Override
809         public Optional<Class<C>> getCaseType() {
810             return Optional.of(caseType);
811         }
812     }
813
814     private static final class CaseIdentifiableItem<C extends ChoiceIn<?> & DataObject,
815             T extends ChildOf<? super C> & Identifiable<K>, K extends Identifier<T>> extends IdentifiableItem<T, K> {
816         private static final long serialVersionUID = 1L;
817
818         private final Class<C> caseType;
819
820         CaseIdentifiableItem(final Class<C> caseType, final Class<T> type, final K key) {
821             super(type, key);
822             this.caseType = requireNonNull(caseType);
823         }
824
825         @Override
826         public Optional<Class<C>> getCaseType() {
827             return Optional.of(caseType);
828         }
829     }
830
831     public interface InstanceIdentifierBuilder<T extends DataObject> extends Builder<InstanceIdentifier<T>> {
832         /**
833          * Append the specified container as a child of the current InstanceIdentifier referenced by the builder. This
834          * method should be used when you want to build an instance identifier by appending top-level elements, for
835          * example
836          * <pre>
837          *     InstanceIdentifier.builder().child(Nodes.class).build();
838          * </pre>
839          *
840          * <p>
841          * NOTE :- The above example is only for illustration purposes InstanceIdentifier.builder() has been deprecated
842          * and should not be used. Use InstanceIdentifier.builder(Nodes.class) instead
843          *
844          * @param container Container to append
845          * @param <N> Container type
846          * @return this builder
847          * @throws NullPointerException if {@code container} is null
848          */
849         <N extends ChildOf<? super T>> @NonNull InstanceIdentifierBuilder<N> child(Class<N> container);
850
851         /**
852          * Append the specified container as a child of the current InstanceIdentifier referenced by the builder. This
853          * method should be used when you want to build an instance identifier by appending a container node to the
854          * identifier and the {@code container} is defined in a {@code grouping} used in a {@code case} statement.
855          *
856          * @param caze Choice case class
857          * @param container Container to append
858          * @param <C> Case type
859          * @param <N> Container type
860          * @return this builder
861          * @throws NullPointerException if {@code container} is null
862          */
863         <C extends ChoiceIn<? super T> & DataObject, N extends ChildOf<? super C>>
864                 @NonNull InstanceIdentifierBuilder<N> child(Class<C> caze, Class<N> container);
865
866         /**
867          * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder. This
868          * method should be used when you want to build an instance identifier by appending a specific list element to
869          * the identifier.
870          *
871          * @param listItem List to append
872          * @param listKey List key
873          * @param <N> List type
874          * @param <K> Key type
875          * @return this builder
876          * @throws NullPointerException if any argument is null
877          */
878         <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>>
879                 @NonNull InstanceIdentifierBuilder<N> child(Class<@NonNull N> listItem, K listKey);
880
881         /**
882          * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder. This
883          * method should be used when you want to build an instance identifier by appending a specific list element to
884          * the identifier and the {@code list} is defined in a {@code grouping} used in a {@code case} statement.
885          *
886          * @param caze Choice case class
887          * @param listItem List to append
888          * @param listKey List key
889          * @param <C> Case type
890          * @param <N> List type
891          * @param <K> Key type
892          * @return this builder
893          * @throws NullPointerException if any argument is null
894          */
895         <C extends ChoiceIn<? super T> & DataObject, K extends Identifier<N>,
896                 N extends Identifiable<K> & ChildOf<? super C>> @NonNull InstanceIdentifierBuilder<N> child(
897                         Class<C> caze, Class<N> listItem, K listKey);
898
899         /**
900          * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
901          * the builder.
902          *
903          * @param container augmentation class
904          * @param <N> augmentation type
905          * @return this builder
906          * @throws NullPointerException if {@code container} is null
907          */
908         <N extends DataObject & Augmentation<? super T>> @NonNull InstanceIdentifierBuilder<N> augmentation(
909                 Class<N> container);
910
911         /**
912          * Build the instance identifier.
913          *
914          * @return Resulting instance identifier.
915          */
916         @Override
917         InstanceIdentifier<T> build();
918     }
919
920     private Object writeReplace() throws ObjectStreamException {
921         return new InstanceIdentifierV3<>(this);
922     }
923 }