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