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