Add InstanceIdentifier.verifyTarget()
[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<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(final Class<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<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(final Class<N> container) {
345         return childIdentifier(Item.of(container));
346     }
347
348     /**
349      * Create an InstanceIdentifier for a child list item. This method is a more efficient equivalent to
350      * {@code builder().child(listItem, listKey).build()}.
351      *
352      * @param listItem List to append
353      * @param listKey List key
354      * @param <N> List type
355      * @param <K> Key type
356      * @return An InstanceIdentifier.
357      * @throws NullPointerException if any argument is null
358      */
359     @SuppressWarnings("unchecked")
360     public final <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>>
361             @NonNull KeyedInstanceIdentifier<N, K> child(final Class<N> listItem, final K listKey) {
362         return (KeyedInstanceIdentifier<N, K>) childIdentifier(IdentifiableItem.of(listItem, listKey));
363     }
364
365     /**
366      * Create an InstanceIdentifier for a child container. This method is a more efficient equivalent to
367      * {@code builder().child(caze, container).build()}.
368      *
369      * @param caze Choice case class
370      * @param container Container to append
371      * @param <C> Case type
372      * @param <N> Container type
373      * @return An InstanceIdentifier.
374      * @throws NullPointerException if any argument is null
375      */
376     public final <C extends ChoiceIn<? super T> & DataObject, N extends ChildOf<? super C>>
377             @NonNull InstanceIdentifier<N> child(final Class<C> caze, final Class<N> container) {
378         return childIdentifier(Item.of(caze, container));
379     }
380
381     /**
382      * Create an InstanceIdentifier for a child list item. This method is a more efficient equivalent to
383      * {@code builder().child(caze, listItem, listKey).build()}.
384      *
385      * @param caze Choice case class
386      * @param listItem List to append
387      * @param listKey List key
388      * @param <C> Case type
389      * @param <N> List type
390      * @param <K> Key type
391      * @return An InstanceIdentifier.
392      * @throws NullPointerException if any argument is null
393      */
394     @SuppressWarnings("unchecked")
395     public final <C extends ChoiceIn<? super T> & DataObject, K extends Identifier<N>,
396         N extends Identifiable<K> & ChildOf<? super C>> @NonNull KeyedInstanceIdentifier<N, K> child(
397                 final Class<C> caze, final Class<N> listItem, final K listKey) {
398         return (KeyedInstanceIdentifier<N, K>) childIdentifier(IdentifiableItem.of(caze, listItem, listKey));
399     }
400
401     /**
402      * Create an InstanceIdentifier for a child augmentation. This method is a more efficient equivalent to
403      * {@code builder().augmentation(container).build()}.
404      *
405      * @param container Container to append
406      * @param <N> Container type
407      * @return An InstanceIdentifier.
408      * @throws NullPointerException if {@code container} is null
409      */
410     public final <N extends DataObject & Augmentation<? super T>> @NonNull InstanceIdentifier<N> augmentation(
411             final Class<N> container) {
412         return childIdentifier(Item.of(container));
413     }
414
415     /**
416      * Create a builder rooted at this key.
417      *
418      * @return A builder instance
419      */
420     public @NonNull InstanceIdentifierBuilder<T> builder() {
421         return new InstanceIdentifierBuilderImpl<>(Item.of(targetType), pathArguments, hash, isWildcarded());
422     }
423
424     /**
425      * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container.
426      *
427      * @param container Base container
428      * @param <T> Type of the container
429      * @return A new {@link InstanceIdentifierBuilder}
430      * @throws NullPointerException if {@code container} is null
431      */
432     public static <T extends ChildOf<? extends DataRoot>> @NonNull InstanceIdentifierBuilder<T> builder(
433             final Class<T> container) {
434         return new InstanceIdentifierBuilderImpl<T>().addWildNode(Item.of(container));
435     }
436
437     /**
438      * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container in
439      * a {@code grouping} used in the {@code case} statement.
440      *
441      * @param caze Choice case class
442      * @param container Base container
443      * @param <C> Case type
444      * @param <T> Type of the container
445      * @return A new {@link InstanceIdentifierBuilder}
446      * @throws NullPointerException if any argument is null
447      */
448     public static <C extends ChoiceIn<? extends DataRoot> & DataObject, T extends ChildOf<? super C>>
449             @NonNull InstanceIdentifierBuilder<T> builder(final Class<C> caze, final Class<T> container) {
450         return new InstanceIdentifierBuilderImpl<T>().addWildNode(Item.of(caze, container));
451     }
452
453     /**
454      * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an
455      * {@link IdentifiableItem}.
456      *
457      * @param listItem list item class
458      * @param listKey key value
459      * @param <N> List type
460      * @param <K> List key
461      * @return A new {@link InstanceIdentifierBuilder}
462      * @throws NullPointerException if any argument is null
463      */
464     public static <N extends Identifiable<K> & ChildOf<? extends DataRoot>,
465             K extends Identifier<N>> @NonNull InstanceIdentifierBuilder<N> builder(final Class<N> listItem,
466                     final K listKey) {
467         return new InstanceIdentifierBuilderImpl<N>().addNode(IdentifiableItem.of(listItem, listKey));
468     }
469
470     /**
471      * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an
472      * {@link IdentifiableItem} in a {@code grouping} used in the {@code case} statement.
473      *
474      * @param caze Choice case class
475      * @param listItem list item class
476      * @param listKey key value
477      * @param <C> Case type
478      * @param <N> List type
479      * @param <K> List key
480      * @return A new {@link InstanceIdentifierBuilder}
481      * @throws NullPointerException if any argument is null
482      */
483     public static <C extends ChoiceIn<? extends DataRoot> & DataObject,
484             N extends Identifiable<K> & ChildOf<? super C>, K extends Identifier<N>>
485             @NonNull InstanceIdentifierBuilder<N> builder(final Class<C> caze, final Class<N> listItem,
486                     final K listKey) {
487         return new InstanceIdentifierBuilderImpl<N>().addNode(IdentifiableItem.of(caze, listItem, listKey));
488     }
489
490     /**
491      * Create an instance identifier for a very specific object type. This method implements {@link #create(Iterable)}
492      * semantics, except it is used by internal callers, which have assured that the argument is an immutable Iterable.
493      *
494      * @param pathArguments The path to a specific node in the data tree
495      * @return InstanceIdentifier instance
496      * @throws IllegalArgumentException if pathArguments is empty or contains a null element.
497      * @throws NullPointerException if {@code pathArguments} is null
498      */
499     private static @NonNull InstanceIdentifier<?> internalCreate(final Iterable<PathArgument> pathArguments) {
500         final Iterator<? extends PathArgument> it = requireNonNull(pathArguments, "pathArguments may not be null")
501                 .iterator();
502         final HashCodeBuilder<PathArgument> hashBuilder = new HashCodeBuilder<>();
503         boolean wildcard = false;
504         PathArgument arg = null;
505
506         while (it.hasNext()) {
507             arg = it.next();
508             checkArgument(arg != null, "pathArguments may not contain null elements");
509
510             // TODO: sanity check ChildOf<>;
511             hashBuilder.addArgument(arg);
512
513             if (Identifiable.class.isAssignableFrom(arg.getType()) && !(arg instanceof IdentifiableItem<?, ?>)) {
514                 wildcard = true;
515             }
516         }
517         checkArgument(arg != null, "pathArguments may not be empty");
518
519         return trustedCreate(arg, pathArguments, hashBuilder.build(), wildcard);
520     }
521
522     /**
523      * Create an instance identifier for a very specific object type.
524      *
525      * <p>
526      * Example:
527      * <pre>
528      *  List&lt;PathArgument&gt; path = Arrays.asList(new Item(Nodes.class))
529      *  new InstanceIdentifier(path);
530      * </pre>
531      *
532      * @param pathArguments The path to a specific node in the data tree
533      * @return InstanceIdentifier instance
534      * @throws IllegalArgumentException if pathArguments is empty or
535      *         contains a null element.
536      */
537     public static @NonNull InstanceIdentifier<?> create(final Iterable<? extends PathArgument> pathArguments) {
538         if (pathArguments instanceof ImmutableCollection<?>) {
539             @SuppressWarnings("unchecked")
540             final Iterable<PathArgument> immutableArguments = (Iterable<PathArgument>) pathArguments;
541             return internalCreate(immutableArguments);
542         }
543
544         return internalCreate(ImmutableList.copyOf(pathArguments));
545     }
546
547     /**
548      * Create an instance identifier for a very specific object type.
549      *
550      * <p>
551      * For example
552      * <pre>
553      *      new InstanceIdentifier(Nodes.class)
554      * </pre>
555      * would create an InstanceIdentifier for an object of type Nodes
556      *
557      * @param type The type of the object which this instance identifier represents
558      * @return InstanceIdentifier instance
559      */
560     @SuppressWarnings("unchecked")
561     public static <T extends DataObject> @NonNull InstanceIdentifier<T> create(final Class<T> type) {
562         return (InstanceIdentifier<T>) create(ImmutableList.of(Item.of(type)));
563     }
564
565     /**
566      * Return the key associated with the last component of the specified identifier.
567      *
568      * @param id instance identifier
569      * @return key associated with the last component
570      * @throws IllegalArgumentException if the supplied identifier type cannot have a key.
571      * @throws NullPointerException if id is null.
572      */
573     public static <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K keyOf(
574             final InstanceIdentifier<N> id) {
575         requireNonNull(id);
576         checkArgument(id instanceof KeyedInstanceIdentifier, "%s does not have a key", id);
577
578         @SuppressWarnings("unchecked")
579         final K ret = ((KeyedInstanceIdentifier<N, K>)id).getKey();
580         return ret;
581     }
582
583     @SuppressWarnings({ "unchecked", "rawtypes" })
584     static <N extends DataObject> @NonNull InstanceIdentifier<N> trustedCreate(final PathArgument arg,
585             final Iterable<PathArgument> pathArguments, final int hash, boolean wildcarded) {
586         if (Identifiable.class.isAssignableFrom(arg.getType()) && !wildcarded) {
587             Identifier<?> key = null;
588             if (arg instanceof IdentifiableItem) {
589                 key = ((IdentifiableItem<?, ?>)arg).getKey();
590             } else {
591                 wildcarded = true;
592             }
593
594             return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key);
595         }
596
597         return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
598     }
599
600     /**
601      * Path argument of {@link InstanceIdentifier}. Interface which implementations are used as path components of the
602      * path in overall data tree.
603      */
604     public interface PathArgument extends Comparable<PathArgument> {
605         /**
606          * Return the data object type backing this PathArgument.
607          *
608          * @return Data object type.
609          */
610         @NonNull Class<? extends DataObject> getType();
611
612         /**
613          * Return an optional enclosing case type. This is used only when {@link #getType()} references a node defined
614          * in a {@code grouping} which is reference inside a {@code case} statement in order to safely reference the
615          * node.
616          *
617          * @return Optional case class.
618          */
619         default Optional<? extends Class<? extends DataObject>> getCaseType() {
620             return Optional.empty();
621         }
622     }
623
624     private abstract static class AbstractPathArgument<T extends DataObject> implements PathArgument, Serializable {
625         private static final long serialVersionUID = 1L;
626
627         private final @NonNull Class<T> type;
628
629         AbstractPathArgument(final Class<T> type) {
630             this.type = requireNonNull(type, "Type may not be null.");
631         }
632
633         @Override
634         public final Class<T> getType() {
635             return type;
636         }
637
638         Object getKey() {
639             return null;
640         }
641
642         @Override
643         public final int hashCode() {
644             return Objects.hash(type, getCaseType(), getKey());
645         }
646
647         @Override
648         public final boolean equals(final Object obj) {
649             if (this == obj) {
650                 return true;
651             }
652             if (!(obj instanceof AbstractPathArgument)) {
653                 return false;
654             }
655             final AbstractPathArgument<?> other = (AbstractPathArgument<?>) obj;
656             return type.equals(other.type) && Objects.equals(getKey(), other.getKey())
657                     && getCaseType().equals(other.getCaseType());
658         }
659
660         @Override
661         public final int compareTo(final PathArgument arg) {
662             final int cmp = compareClasses(type, arg.getType());
663             if (cmp != 0) {
664                 return cmp;
665             }
666             final Optional<? extends Class<?>> caseType = getCaseType();
667             if (!caseType.isPresent()) {
668                 return arg.getCaseType().isPresent() ? -1 : 1;
669             }
670             final Optional<? extends Class<?>> argCaseType = getCaseType();
671             return argCaseType.isPresent() ? compareClasses(caseType.get(), argCaseType.get()) : 1;
672         }
673
674         private static int compareClasses(final Class<?> first, final Class<?> second) {
675             return first.getCanonicalName().compareTo(second.getCanonicalName());
676         }
677     }
678
679     /**
680      * An Item represents an object that probably is only one of it's kind. For example a Nodes object is only one of
681      * a kind. In YANG terms this would probably represent a container.
682      *
683      * @param <T> Item type
684      */
685     public static class Item<T extends DataObject> extends AbstractPathArgument<T> {
686         private static final long serialVersionUID = 1L;
687
688         Item(final Class<T> type) {
689             super(type);
690         }
691
692         /**
693          * Return a PathArgument instance backed by the specified class.
694          *
695          * @param type Backing class
696          * @param <T> Item type
697          * @return A new PathArgument
698          * @throws NullPointerException if {@code} is null.
699          */
700         public static <T extends DataObject> @NonNull Item<T> of(final Class<T> type) {
701             return new Item<>(type);
702         }
703
704         /**
705          * Return a PathArgument instance backed by the specified class, which in turn is defined in a {@code grouping}
706          * used in a corresponding {@code case} statement.
707          *
708          * @param caseType defining case class
709          * @param type Backing class
710          * @param <C> Case type
711          * @param <T> Item type
712          * @return A new PathArgument
713          * @throws NullPointerException if any argument is null.
714          */
715         public static <C extends ChoiceIn<?> & DataObject, T extends ChildOf<? super C>> @NonNull Item<T> of(
716                 final Class<C> caseType, final Class<T> type) {
717             return new CaseItem<>(caseType, type);
718         }
719
720         @Override
721         public String toString() {
722             return getType().getName();
723         }
724     }
725
726     /**
727      * An IdentifiableItem represents a object that is usually present in a collection and can be identified uniquely
728      * by a key. In YANG terms this would probably represent an item in a list.
729      *
730      * @param <I> An object that is identifiable by an identifier
731      * @param <T> The identifier of the object
732      */
733     public static class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>>
734             extends AbstractPathArgument<I> {
735         private static final long serialVersionUID = 1L;
736
737         private final @NonNull T key;
738
739         IdentifiableItem(final Class<I> type, final T key) {
740             super(type);
741             this.key = requireNonNull(key, "Key may not be null.");
742         }
743
744         /**
745          * Return an IdentifiableItem instance backed by the specified class with specified key.
746          *
747          * @param type Backing class
748          * @param key Key
749          * @param <T> List type
750          * @param <I> Key type
751          * @return An IdentifiableItem
752          * @throws NullPointerException if any argument is null.
753          */
754         public static <T extends Identifiable<I> & DataObject, I extends Identifier<T>>
755                 @NonNull IdentifiableItem<T, I> of(final Class<T> type, final I key) {
756             return new IdentifiableItem<>(type, key);
757         }
758
759         /**
760          * Return an IdentifiableItem instance backed by the specified class with specified key. The class is in turn
761          * defined in a {@code grouping} used in a corresponding {@code case} statement.
762          *
763          * @param caseType defining case class
764          * @param type Backing class
765          * @param <C> Case type
766          * @param <T> List type
767          * @param <I> Key type
768          * @return A new PathArgument
769          * @throws NullPointerException if any argument is null.
770          */
771         public static <C extends ChoiceIn<?> & DataObject, T extends ChildOf<? super C> & Identifiable<I>,
772                 I extends Identifier<T>> @NonNull IdentifiableItem<T, I> of(final Class<C> caseType,
773                         final Class<T> type, final I key) {
774             return new CaseIdentifiableItem<>(caseType, type, key);
775         }
776
777         /**
778          * Return the data object type backing this PathArgument.
779          *
780          * @return Data object type.
781          */
782         @Override
783         public final @NonNull T getKey() {
784             return key;
785         }
786
787         @Override
788         public String toString() {
789             return getType().getName() + "[key=" + key + "]";
790         }
791     }
792
793     private static final class CaseItem<C extends ChoiceIn<?> & DataObject, T extends ChildOf<? super C>>
794             extends Item<T> {
795         private static final long serialVersionUID = 1L;
796
797         private final Class<C> caseType;
798
799         CaseItem(final Class<C> caseType, final Class<T> type) {
800             super(type);
801             this.caseType = requireNonNull(caseType);
802         }
803
804         @Override
805         public Optional<Class<C>> getCaseType() {
806             return Optional.of(caseType);
807         }
808     }
809
810     private static final class CaseIdentifiableItem<C extends ChoiceIn<?> & DataObject,
811             T extends ChildOf<? super C> & Identifiable<K>, K extends Identifier<T>> extends IdentifiableItem<T, K> {
812         private static final long serialVersionUID = 1L;
813
814         private final Class<C> caseType;
815
816         CaseIdentifiableItem(final Class<C> caseType, final Class<T> type, final K key) {
817             super(type, key);
818             this.caseType = requireNonNull(caseType);
819         }
820
821         @Override
822         public Optional<Class<C>> getCaseType() {
823             return Optional.of(caseType);
824         }
825     }
826
827     public interface InstanceIdentifierBuilder<T extends DataObject> extends Builder<InstanceIdentifier<T>> {
828         /**
829          * Append the specified container as a child of the current InstanceIdentifier referenced by the builder. This
830          * method should be used when you want to build an instance identifier by appending top-level elements, for
831          * example
832          * <pre>
833          *     InstanceIdentifier.builder().child(Nodes.class).build();
834          * </pre>
835          *
836          * <p>
837          * NOTE :- The above example is only for illustration purposes InstanceIdentifier.builder() has been deprecated
838          * and should not be used. Use InstanceIdentifier.builder(Nodes.class) instead
839          *
840          * @param container Container to append
841          * @param <N> Container type
842          * @return this builder
843          * @throws NullPointerException if {@code container} is null
844          */
845         <N extends ChildOf<? super T>> @NonNull InstanceIdentifierBuilder<N> child(Class<N> container);
846
847         /**
848          * Append the specified container as a child of the current InstanceIdentifier referenced by the builder. This
849          * method should be used when you want to build an instance identifier by appending a container node to the
850          * identifier and the {@code container} is defined in a {@code grouping} used in a {@code case} statement.
851          *
852          * @param caze Choice case class
853          * @param container Container to append
854          * @param <C> Case type
855          * @param <N> Container type
856          * @return this builder
857          * @throws NullPointerException if {@code container} is null
858          */
859         <C extends ChoiceIn<? super T> & DataObject, N extends ChildOf<? super C>>
860                 @NonNull InstanceIdentifierBuilder<N> child(Class<C> caze, Class<N> container);
861
862         /**
863          * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder. This
864          * method should be used when you want to build an instance identifier by appending a specific list element to
865          * the identifier.
866          *
867          * @param listItem List to append
868          * @param listKey List key
869          * @param <N> List type
870          * @param <K> Key type
871          * @return this builder
872          * @throws NullPointerException if any argument is null
873          */
874         <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>>
875                 @NonNull InstanceIdentifierBuilder<N> child(Class<N> listItem, K listKey);
876
877         /**
878          * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder. This
879          * method should be used when you want to build an instance identifier by appending a specific list element to
880          * the identifier and the {@code list} is defined in a {@code grouping} used in a {@code case} statement.
881          *
882          * @param caze Choice case class
883          * @param listItem List to append
884          * @param listKey List key
885          * @param <C> Case type
886          * @param <N> List type
887          * @param <K> Key type
888          * @return this builder
889          * @throws NullPointerException if any argument is null
890          */
891         <C extends ChoiceIn<? super T> & DataObject, K extends Identifier<N>,
892                 N extends Identifiable<K> & ChildOf<? super C>> @NonNull InstanceIdentifierBuilder<N> child(
893                         Class<C> caze, Class<N> listItem, K listKey);
894
895         /**
896          * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
897          * the builder.
898          *
899          * @param container augmentation class
900          * @param <N> augmentation type
901          * @return this builder
902          * @throws NullPointerException if {@code container} is null
903          */
904         <N extends DataObject & Augmentation<? super T>> @NonNull InstanceIdentifierBuilder<N> augmentation(
905                 Class<N> container);
906
907         /**
908          * Build the instance identifier.
909          *
910          * @return Resulting instance identifier.
911          */
912         @Override
913         InstanceIdentifier<T> build();
914     }
915
916     private Object writeReplace() throws ObjectStreamException {
917         return new InstanceIdentifierV3<>(this);
918     }
919 }