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