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