Correct InstanceIdentifier.trustedCreate()
[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, final boolean wildcarded) {
627         if (arg instanceof IdentifiableItem<?, ?> identifiable) {
628             return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, identifiable.getKey());
629         }
630
631         final var type = arg.getType();
632         return new InstanceIdentifier(type, pathArguments, wildcarded || Identifiable.class.isAssignableFrom(type),
633             hash);
634     }
635
636     /**
637      * Path argument of {@link InstanceIdentifier}. Interface which implementations are used as path components of the
638      * path in overall data tree.
639      */
640     public interface PathArgument extends Comparable<PathArgument> {
641         /**
642          * Return the data object type backing this PathArgument.
643          *
644          * @return Data object type.
645          */
646         @NonNull Class<? extends DataObject> getType();
647
648         /**
649          * Return an optional enclosing case type. This is used only when {@link #getType()} references a node defined
650          * in a {@code grouping} which is reference inside a {@code case} statement in order to safely reference the
651          * node.
652          *
653          * @return Optional case class.
654          */
655         default Optional<? extends Class<? extends DataObject>> getCaseType() {
656             return Optional.empty();
657         }
658     }
659
660     private abstract static class AbstractPathArgument<T extends DataObject> implements PathArgument, Serializable {
661         @Serial
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         @Serial
724         private static final long serialVersionUID = 1L;
725
726         Item(final Class<T> type) {
727             super(type);
728         }
729
730         /**
731          * Return a PathArgument instance backed by the specified class.
732          *
733          * @param type Backing class
734          * @param <T> Item type
735          * @return A new PathArgument
736          * @throws NullPointerException if {@code} is null.
737          */
738         public static <T extends DataObject> @NonNull Item<T> of(final Class<T> type) {
739             return new Item<>(type);
740         }
741
742         /**
743          * Return a PathArgument instance backed by the specified class, which in turn is defined in a {@code grouping}
744          * used in a corresponding {@code case} statement.
745          *
746          * @param caseType defining case class
747          * @param type Backing class
748          * @param <C> Case type
749          * @param <T> Item type
750          * @return A new PathArgument
751          * @throws NullPointerException if any argument is null.
752          */
753         public static <C extends ChoiceIn<?> & DataObject, T extends ChildOf<? super C>> @NonNull Item<T> of(
754                 final Class<C> caseType, final Class<T> type) {
755             return new CaseItem<>(caseType, type);
756         }
757
758         @Override
759         public String toString() {
760             return getType().getName();
761         }
762     }
763
764     /**
765      * An IdentifiableItem represents a object that is usually present in a collection and can be identified uniquely
766      * by a key. In YANG terms this would probably represent an item in a list.
767      *
768      * @param <I> An object that is identifiable by an identifier
769      * @param <T> The identifier of the object
770      */
771     public static class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>>
772             extends AbstractPathArgument<I> {
773         @Serial
774         private static final long serialVersionUID = 1L;
775
776         private final @NonNull T key;
777
778         IdentifiableItem(final Class<I> type, final T key) {
779             super(type);
780             this.key = requireNonNull(key, "Key may not be null.");
781         }
782
783         /**
784          * Return an IdentifiableItem instance backed by the specified class with specified key.
785          *
786          * @param type Backing class
787          * @param key Key
788          * @param <T> List type
789          * @param <I> Key type
790          * @return An IdentifiableItem
791          * @throws NullPointerException if any argument is null.
792          */
793         public static <T extends Identifiable<I> & DataObject, I extends Identifier<T>>
794                 @NonNull IdentifiableItem<T, I> of(final Class<T> type, final I key) {
795             return new IdentifiableItem<>(type, key);
796         }
797
798         /**
799          * Return an IdentifiableItem instance backed by the specified class with specified key. The class is in turn
800          * defined in a {@code grouping} used in a corresponding {@code case} statement.
801          *
802          * @param caseType defining case class
803          * @param type Backing class
804          * @param <C> Case type
805          * @param <T> List type
806          * @param <I> Key type
807          * @return A new PathArgument
808          * @throws NullPointerException if any argument is null.
809          */
810         public static <C extends ChoiceIn<?> & DataObject, T extends ChildOf<? super C> & Identifiable<I>,
811                 I extends Identifier<T>> @NonNull IdentifiableItem<T, I> of(final Class<C> caseType,
812                         final Class<T> type, final I key) {
813             return new CaseIdentifiableItem<>(caseType, type, key);
814         }
815
816         /**
817          * Return the data object type backing this PathArgument.
818          *
819          * @return Data object type.
820          */
821         @Override
822         public final @NonNull T getKey() {
823             return key;
824         }
825
826         @Override
827         public String toString() {
828             return getType().getName() + "[key=" + key + "]";
829         }
830     }
831
832     private static final class CaseItem<C extends ChoiceIn<?> & DataObject, T extends ChildOf<? super C>>
833             extends Item<T> {
834         @Serial
835         private static final long serialVersionUID = 1L;
836
837         private final Class<C> caseType;
838
839         CaseItem(final Class<C> caseType, final Class<T> type) {
840             super(type);
841             this.caseType = requireNonNull(caseType);
842         }
843
844         @Override
845         public Optional<Class<C>> getCaseType() {
846             return Optional.of(caseType);
847         }
848     }
849
850     private static final class CaseIdentifiableItem<C extends ChoiceIn<?> & DataObject,
851             T extends ChildOf<? super C> & Identifiable<K>, K extends Identifier<T>> extends IdentifiableItem<T, K> {
852         @Serial
853         private static final long serialVersionUID = 1L;
854
855         private final Class<C> caseType;
856
857         CaseIdentifiableItem(final Class<C> caseType, final Class<T> type, final K key) {
858             super(type, key);
859             this.caseType = requireNonNull(caseType);
860         }
861
862         @Override
863         public Optional<Class<C>> getCaseType() {
864             return Optional.of(caseType);
865         }
866     }
867
868     // FIXME: rename to 'Builder'
869     // FIXME: introduce KeyedBuilder with specialized build() method
870     public interface InstanceIdentifierBuilder<T extends DataObject> {
871         /**
872          * Append the specified container as a child of the current InstanceIdentifier referenced by the builder. This
873          * method should be used when you want to build an instance identifier by appending top-level elements, for
874          * example
875          * <pre>
876          *     InstanceIdentifier.builder().child(Nodes.class).build();
877          * </pre>
878          *
879          * <p>
880          * NOTE :- The above example is only for illustration purposes InstanceIdentifier.builder() has been deprecated
881          * and should not be used. Use InstanceIdentifier.builder(Nodes.class) instead
882          *
883          * @param container Container to append
884          * @param <N> Container type
885          * @return this builder
886          * @throws NullPointerException if {@code container} is null
887          */
888         <N extends ChildOf<? super T>> @NonNull InstanceIdentifierBuilder<N> child(Class<N> container);
889
890         /**
891          * Append the specified container as a child of the current InstanceIdentifier referenced by the builder. This
892          * method should be used when you want to build an instance identifier by appending a container node to the
893          * identifier and the {@code container} is defined in a {@code grouping} used in a {@code case} statement.
894          *
895          * @param caze Choice case class
896          * @param container Container to append
897          * @param <C> Case type
898          * @param <N> Container type
899          * @return this builder
900          * @throws NullPointerException if {@code container} is null
901          */
902         <C extends ChoiceIn<? super T> & DataObject, N extends ChildOf<? super C>>
903                 @NonNull InstanceIdentifierBuilder<N> child(Class<C> caze, Class<N> container);
904
905         /**
906          * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder. This
907          * method should be used when you want to build an instance identifier by appending a specific list element to
908          * the identifier.
909          *
910          * @param listItem List to append
911          * @param listKey List key
912          * @param <N> List type
913          * @param <K> Key type
914          * @return this builder
915          * @throws NullPointerException if any argument is null
916          */
917         <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>>
918                 @NonNull InstanceIdentifierBuilder<N> child(Class<@NonNull N> listItem, K listKey);
919
920         /**
921          * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder. This
922          * method should be used when you want to build an instance identifier by appending a specific list element to
923          * the identifier and the {@code list} is defined in a {@code grouping} used in a {@code case} statement.
924          *
925          * @param caze Choice case class
926          * @param listItem List to append
927          * @param listKey List key
928          * @param <C> Case type
929          * @param <N> List type
930          * @param <K> Key type
931          * @return this builder
932          * @throws NullPointerException if any argument is null
933          */
934         <C extends ChoiceIn<? super T> & DataObject, K extends Identifier<N>,
935                 N extends Identifiable<K> & ChildOf<? super C>> @NonNull InstanceIdentifierBuilder<N> child(
936                         Class<C> caze, Class<N> listItem, K listKey);
937
938         /**
939          * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
940          * the builder.
941          *
942          * @param container augmentation class
943          * @param <N> augmentation type
944          * @return this builder
945          * @throws NullPointerException if {@code container} is null
946          */
947         <N extends DataObject & Augmentation<? super T>> @NonNull InstanceIdentifierBuilder<N> augmentation(
948                 Class<N> container);
949
950         /**
951          * Build the instance identifier.
952          *
953          * @return Resulting instance identifier.
954          */
955         @NonNull InstanceIdentifier<T> build();
956     }
957
958     @Serial
959     private Object writeReplace() throws ObjectStreamException {
960         return new InstanceIdentifierV3<>(this);
961     }
962 }