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