Migrate Optional.get() callers
[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  * InstanceIdentifier.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         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 = InstanceIdentifier.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<?> oit = other.pathArguments.iterator();
286
287         for (PathArgument pathArgument : pathArguments) {
288             if (!oit.hasNext()) {
289                 return false;
290             }
291
292             if (!pathArgument.equals(oit.next())) {
293                 return false;
294             }
295         }
296
297         return true;
298     }
299
300     /**
301      * Check whether this instance identifier contains the other identifier after wildcard expansion. This is similar
302      * to {@link #contains(InstanceIdentifier)}, with the exception that a wildcards are assumed to match the their
303      * non-wildcarded PathArgument counterpart.
304      *
305      * @param other Identifier which should be checked for inclusion.
306      * @return true if this identifier contains the other object
307      */
308     public final boolean containsWildcarded(final InstanceIdentifier<?> other) {
309         requireNonNull(other, "other should not be null");
310
311         final Iterator<PathArgument> oit = other.pathArguments.iterator();
312
313         for (PathArgument la : pathArguments) {
314             if (!oit.hasNext()) {
315                 return false;
316             }
317
318             final PathArgument oa = oit.next();
319
320             if (!la.getType().equals(oa.getType())) {
321                 return false;
322             }
323             if (la instanceof IdentifiableItem<?, ?> && oa instanceof IdentifiableItem<?, ?> && !la.equals(oa)) {
324                 return false;
325             }
326         }
327
328         return true;
329     }
330
331     private <N extends DataObject> @NonNull InstanceIdentifier<N> childIdentifier(final AbstractPathArgument<N> arg) {
332         return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)),
333             HashCodeBuilder.nextHashCode(hash, arg), wildcarded);
334     }
335
336     /**
337      * Create an InstanceIdentifier for a child container. This method is a more efficient equivalent to
338      * {@code builder().child(container).build()}.
339      *
340      * @param container Container to append
341      * @param <N> Container type
342      * @return An InstanceIdentifier.
343      * @throws NullPointerException if {@code container} is null
344      */
345     public final <N extends ChildOf<? super T>> @NonNull InstanceIdentifier<N> child(
346             final Class<@NonNull N> container) {
347         return childIdentifier(Item.of(container));
348     }
349
350     /**
351      * Create an InstanceIdentifier for a child list item. This method is a more efficient equivalent to
352      * {@code builder().child(listItem, listKey).build()}.
353      *
354      * @param listItem List to append
355      * @param listKey List key
356      * @param <N> List type
357      * @param <K> Key type
358      * @return An InstanceIdentifier.
359      * @throws NullPointerException if any argument is null
360      */
361     @SuppressWarnings("unchecked")
362     public final <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>>
363             @NonNull KeyedInstanceIdentifier<N, K> child(final Class<@NonNull N> listItem, final K listKey) {
364         return (KeyedInstanceIdentifier<N, K>) childIdentifier(IdentifiableItem.of(listItem, listKey));
365     }
366
367     /**
368      * Create an InstanceIdentifier for a child container. This method is a more efficient equivalent to
369      * {@code builder().child(caze, container).build()}.
370      *
371      * @param caze Choice case class
372      * @param container Container to append
373      * @param <C> Case type
374      * @param <N> Container type
375      * @return An InstanceIdentifier.
376      * @throws NullPointerException if any argument is null
377      */
378     // FIXME: add a proper caller
379     public final <C extends ChoiceIn<? super T> & DataObject, N extends ChildOf<? super C>>
380             @NonNull InstanceIdentifier<N> child(final Class<@NonNull C> caze, final Class<@NonNull N> container) {
381         return childIdentifier(Item.of(caze, container));
382     }
383
384     /**
385      * Create an InstanceIdentifier for a child list item. This method is a more efficient equivalent to
386      * {@code builder().child(caze, listItem, listKey).build()}.
387      *
388      * @param caze Choice case class
389      * @param listItem List to append
390      * @param listKey List key
391      * @param <C> Case type
392      * @param <N> List type
393      * @param <K> Key type
394      * @return An InstanceIdentifier.
395      * @throws NullPointerException if any argument is null
396      */
397     // FIXME: add a proper caller
398     @SuppressWarnings("unchecked")
399     public final <C extends ChoiceIn<? super T> & DataObject, K extends Identifier<N>,
400         N extends Identifiable<K> & ChildOf<? super C>> @NonNull KeyedInstanceIdentifier<N, K> child(
401                 final Class<@NonNull C> caze, final Class<@NonNull N> listItem, final K listKey) {
402         return (KeyedInstanceIdentifier<N, K>) childIdentifier(IdentifiableItem.of(caze, listItem, listKey));
403     }
404
405     /**
406      * Create an InstanceIdentifier for a child augmentation. This method is a more efficient equivalent to
407      * {@code builder().augmentation(container).build()}.
408      *
409      * @param container Container to append
410      * @param <N> Container type
411      * @return An InstanceIdentifier.
412      * @throws NullPointerException if {@code container} is null
413      */
414     public final <N extends DataObject & Augmentation<? super T>> @NonNull InstanceIdentifier<N> augmentation(
415             final Class<@NonNull N> container) {
416         return childIdentifier(Item.of(container));
417     }
418
419     @Serial
420     private Object writeReplace() throws ObjectStreamException {
421         return new InstanceIdentifierV3<>(this);
422     }
423
424     /**
425      * Create a builder rooted at this key.
426      *
427      * @return A builder instance
428      */
429     // FIXME: rename this method to 'toBuilder()'
430     public @NonNull Builder<T> builder() {
431         return new RegularBuilder<>(this);
432     }
433
434     /**
435      * Create a {@link Builder} for a specific type of InstanceIdentifier as specified by container.
436      *
437      * @param container Base container
438      * @param <T> Type of the container
439      * @return A new {@link Builder}
440      * @throws NullPointerException if {@code container} is null
441      */
442     public static <T extends ChildOf<? extends DataRoot>> @NonNull Builder<T> builder(
443             final Class<T> container) {
444         return new RegularBuilder<>(Item.of(container));
445     }
446
447     /**
448      * Create a {@link Builder} for a specific type of InstanceIdentifier as specified by container in
449      * a {@code grouping} used in the {@code case} statement.
450      *
451      * @param caze Choice case class
452      * @param container Base container
453      * @param <C> Case type
454      * @param <T> Type of the container
455      * @return A new {@link Builder}
456      * @throws NullPointerException if any argument is null
457      */
458     public static <C extends ChoiceIn<? extends DataRoot> & DataObject, T extends ChildOf<? super C>>
459             @NonNull Builder<T> builder(final Class<C> caze, final Class<T> container) {
460         return new RegularBuilder<>(Item.of(caze, container));
461     }
462
463     /**
464      * Create a {@link Builder} for a specific type of InstanceIdentifier which represents an {@link IdentifiableItem}.
465      *
466      * @param listItem list item class
467      * @param listKey key value
468      * @param <N> List type
469      * @param <K> List key
470      * @return A new {@link Builder}
471      * @throws NullPointerException if any argument is null
472      */
473     public static <N extends Identifiable<K> & ChildOf<? extends DataRoot>,
474             K extends Identifier<N>> @NonNull KeyedBuilder<N, K> builder(final Class<N> listItem,
475                     final K listKey) {
476         return new KeyedBuilder<>(IdentifiableItem.of(listItem, listKey));
477     }
478
479     /**
480      * Create a {@link Builder} for a specific type of InstanceIdentifier which represents an {@link IdentifiableItem}
481      *  in a {@code grouping} used in the {@code case} statement.
482      *
483      * @param caze Choice case class
484      * @param listItem list item class
485      * @param listKey key value
486      * @param <C> Case type
487      * @param <N> List type
488      * @param <K> List key
489      * @return A new {@link Builder}
490      * @throws NullPointerException if any argument is null
491      */
492     public static <C extends ChoiceIn<? extends DataRoot> & DataObject,
493             N extends Identifiable<K> & ChildOf<? super C>, K extends Identifier<N>>
494             @NonNull KeyedBuilder<N, K> builder(final Class<C> caze, final Class<N> listItem,
495                     final K listKey) {
496         return new KeyedBuilder<>(IdentifiableItem.of(caze, listItem, listKey));
497     }
498
499     public static <R extends DataRoot & DataObject, T extends ChildOf<? super R>>
500             @NonNull Builder<T> builderOfInherited(final Class<R> root, final Class<T> container) {
501         // FIXME: we are losing root identity, hence namespaces may not work correctly
502         return new RegularBuilder<>(Item.of(container));
503     }
504
505     public static <R extends DataRoot & DataObject, C extends ChoiceIn<? super R> & DataObject,
506             T extends ChildOf<? super C>>
507             @NonNull Builder<T> builderOfInherited(final Class<R> root,
508                 final Class<C> caze, final Class<T> container) {
509         // FIXME: we are losing root identity, hence namespaces may not work correctly
510         return new RegularBuilder<>(Item.of(caze, container));
511     }
512
513     public static <R extends DataRoot & DataObject, N extends Identifiable<K> & ChildOf<? super R>,
514             K extends Identifier<N>>
515             @NonNull KeyedBuilder<N, K> builderOfInherited(final Class<R> root,
516                 final Class<N> listItem, final K listKey) {
517         // FIXME: we are losing root identity, hence namespaces may not work correctly
518         return new KeyedBuilder<>(IdentifiableItem.of(listItem, listKey));
519     }
520
521     public static <R extends DataRoot & DataObject, C extends ChoiceIn<? super R> & DataObject,
522             N extends Identifiable<K> & ChildOf<? super C>, K extends Identifier<N>>
523             @NonNull KeyedBuilder<N, K> builderOfInherited(final Class<R> root,
524                 final Class<C> caze, final Class<N> listItem, final K listKey) {
525         // FIXME: we are losing root identity, hence namespaces may not work correctly
526         return new KeyedBuilder<>(IdentifiableItem.of(caze, listItem, listKey));
527     }
528
529     /**
530      * Create an instance identifier for a very specific object type. This method implements {@link #create(Iterable)}
531      * semantics, except it is used by internal callers, which have assured that the argument is an immutable Iterable.
532      *
533      * @param pathArguments The path to a specific node in the data tree
534      * @return InstanceIdentifier instance
535      * @throws IllegalArgumentException if pathArguments is empty or contains a null element.
536      * @throws NullPointerException if {@code pathArguments} is null
537      */
538     private static @NonNull InstanceIdentifier<?> internalCreate(final Iterable<PathArgument> pathArguments) {
539         final var it = requireNonNull(pathArguments, "pathArguments may not be null").iterator();
540         checkArgument(it.hasNext(), "pathArguments may not be empty");
541
542         final HashCodeBuilder<PathArgument> hashBuilder = new HashCodeBuilder<>();
543         boolean wildcard = false;
544         PathArgument arg;
545
546         do {
547             arg = it.next();
548             // Non-null is implied by our callers
549             final var type = verifyNotNull(arg).getType();
550             checkArgument(ChildOf.class.isAssignableFrom(type) || Augmentation.class.isAssignableFrom(type),
551                 "%s is not a valid path argument", type);
552
553             hashBuilder.addArgument(arg);
554
555             if (Identifiable.class.isAssignableFrom(type) && !(arg instanceof IdentifiableItem)) {
556                 wildcard = true;
557             }
558         } while (it.hasNext());
559
560         return trustedCreate(arg, pathArguments, hashBuilder.build(), wildcard);
561     }
562
563     /**
564      * Create an instance identifier for a sequence of {@link PathArgument} steps. The steps are required to be formed
565      * of classes extending either {@link ChildOf} or {@link Augmentation} contracts. This method does not check whether
566      * or not the sequence is structurally sound, for example that an {@link Augmentation} follows an
567      * {@link Augmentable} step. Furthermore the compile-time indicated generic type of the returned object does not
568      * necessarily match the contained state.
569      *
570      * <p>
571      * Failure to observe precautions to validate the list's contents may yield an object which mey be rejected at
572      * run-time or lead to undefined behaviour.
573      *
574      * @param pathArguments The path to a specific node in the data tree
575      * @return InstanceIdentifier instance
576      * @throws NullPointerException if {@code pathArguments} is, or contains an item which is, {@code null}
577      * @throws IllegalArgumentException if {@code pathArguments} is empty or contains an item which does not represent
578      *                                  a valid addressing step.
579      */
580     @SuppressWarnings("unchecked")
581     public static <T extends DataObject> @NonNull InstanceIdentifier<T> unsafeOf(
582             final List<? extends PathArgument> pathArguments) {
583         return (InstanceIdentifier<T>) internalCreate(ImmutableList.copyOf(pathArguments));
584     }
585
586     /**
587      * Create an instance identifier for a very specific object type.
588      *
589      * <p>
590      * For example
591      * <pre>
592      *      new InstanceIdentifier(Nodes.class)
593      * </pre>
594      * would create an InstanceIdentifier for an object of type Nodes
595      *
596      * @param type The type of the object which this instance identifier represents
597      * @return InstanceIdentifier instance
598      */
599     // FIXME: considering removing in favor of always going through a builder
600     @SuppressWarnings("unchecked")
601     public static <T extends ChildOf<? extends DataRoot>> @NonNull InstanceIdentifier<T> create(
602             final Class<@NonNull T> type) {
603         return (InstanceIdentifier<T>) internalCreate(ImmutableList.of(Item.of(type)));
604     }
605
606     /**
607      * Return the key associated with the last component of the specified identifier.
608      *
609      * @param id instance identifier
610      * @return key associated with the last component
611      * @throws IllegalArgumentException if the supplied identifier type cannot have a key.
612      * @throws NullPointerException if id is null.
613      */
614     // FIXME: reconsider naming and design of this method
615     public static <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K keyOf(
616             final InstanceIdentifier<N> id) {
617         requireNonNull(id);
618         checkArgument(id instanceof KeyedInstanceIdentifier, "%s does not have a key", id);
619
620         @SuppressWarnings("unchecked")
621         final K ret = ((KeyedInstanceIdentifier<N, K>)id).getKey();
622         return ret;
623     }
624
625     @SuppressWarnings({ "unchecked", "rawtypes" })
626     static <N extends DataObject> @NonNull InstanceIdentifier<N> trustedCreate(final PathArgument arg,
627             final Iterable<PathArgument> pathArguments, final int hash, final boolean wildcarded) {
628         if (arg instanceof IdentifiableItem<?, ?> identifiable) {
629             return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, identifiable.getKey());
630         }
631
632         final var type = arg.getType();
633         return new InstanceIdentifier(type, pathArguments, wildcarded || Identifiable.class.isAssignableFrom(type),
634             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         @Serial
663         private static final long serialVersionUID = 1L;
664
665         private final @NonNull Class<T> type;
666
667         AbstractPathArgument(final Class<T> type) {
668             this.type = requireNonNull(type, "Type may not be null.");
669         }
670
671         @Override
672         public final Class<T> getType() {
673             return type;
674         }
675
676         Object getKey() {
677             return null;
678         }
679
680         @Override
681         public final int hashCode() {
682             return Objects.hash(type, getCaseType(), getKey());
683         }
684
685         @Override
686         public final boolean equals(final Object obj) {
687             return this == obj || obj instanceof AbstractPathArgument<?> other && type.equals(other.type)
688                 && Objects.equals(getKey(), other.getKey()) && getCaseType().equals(other.getCaseType());
689         }
690
691         @Override
692         public final int compareTo(final PathArgument arg) {
693             final int cmp = compareClasses(type, arg.getType());
694             if (cmp != 0) {
695                 return cmp;
696             }
697             final Optional<? extends Class<?>> caseType = getCaseType();
698             if (!caseType.isPresent()) {
699                 return arg.getCaseType().isPresent() ? -1 : 1;
700             }
701             final Optional<? extends Class<?>> argCaseType = getCaseType();
702             return argCaseType.isPresent() ? compareClasses(caseType.orElseThrow(), argCaseType.orElseThrow()) : 1;
703         }
704
705         private static int compareClasses(final Class<?> first, final Class<?> second) {
706             return first.getCanonicalName().compareTo(second.getCanonicalName());
707         }
708     }
709
710     /**
711      * An Item represents an object that probably is only one of it's kind. For example a Nodes object is only one of
712      * a kind. In YANG terms this would probably represent a container.
713      *
714      * @param <T> Item type
715      */
716     public static class Item<T extends DataObject> extends AbstractPathArgument<T> {
717         @Serial
718         private static final long serialVersionUID = 1L;
719
720         Item(final Class<T> type) {
721             super(type);
722         }
723
724         /**
725          * Return a PathArgument instance backed by the specified class.
726          *
727          * @param type Backing class
728          * @param <T> Item type
729          * @return A new PathArgument
730          * @throws NullPointerException if {@code} is null.
731          */
732         public static <T extends DataObject> @NonNull Item<T> of(final Class<T> type) {
733             return new Item<>(type);
734         }
735
736         /**
737          * Return a PathArgument instance backed by the specified class, which in turn is defined in a {@code grouping}
738          * used in a corresponding {@code case} statement.
739          *
740          * @param caseType defining case class
741          * @param type Backing class
742          * @param <C> Case type
743          * @param <T> Item type
744          * @return A new PathArgument
745          * @throws NullPointerException if any argument is null.
746          */
747         public static <C extends ChoiceIn<?> & DataObject, T extends ChildOf<? super C>> @NonNull Item<T> of(
748                 final Class<C> caseType, final Class<T> type) {
749             return new CaseItem<>(caseType, type);
750         }
751
752         @Override
753         public String toString() {
754             return getType().getName();
755         }
756     }
757
758     /**
759      * An IdentifiableItem represents a object that is usually present in a collection and can be identified uniquely
760      * by a key. In YANG terms this would probably represent an item in a list.
761      *
762      * @param <I> An object that is identifiable by an identifier
763      * @param <T> The identifier of the object
764      */
765     public static class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>>
766             extends AbstractPathArgument<I> {
767         @Serial
768         private static final long serialVersionUID = 1L;
769
770         private final @NonNull T key;
771
772         IdentifiableItem(final Class<I> type, final T key) {
773             super(type);
774             this.key = requireNonNull(key, "Key may not be null.");
775         }
776
777         /**
778          * Return an IdentifiableItem instance backed by the specified class with specified key.
779          *
780          * @param type Backing class
781          * @param key Key
782          * @param <T> List type
783          * @param <I> Key type
784          * @return An IdentifiableItem
785          * @throws NullPointerException if any argument is null.
786          */
787         public static <T extends Identifiable<I> & DataObject, I extends Identifier<T>>
788                 @NonNull IdentifiableItem<T, I> of(final Class<T> type, final I key) {
789             return new IdentifiableItem<>(type, key);
790         }
791
792         /**
793          * Return an IdentifiableItem instance backed by the specified class with specified key. The class is in turn
794          * defined in a {@code grouping} used in a corresponding {@code case} statement.
795          *
796          * @param caseType defining case class
797          * @param type Backing class
798          * @param <C> Case type
799          * @param <T> List type
800          * @param <I> Key type
801          * @return A new PathArgument
802          * @throws NullPointerException if any argument is null.
803          */
804         public static <C extends ChoiceIn<?> & DataObject, T extends ChildOf<? super C> & Identifiable<I>,
805                 I extends Identifier<T>> @NonNull IdentifiableItem<T, I> of(final Class<C> caseType,
806                         final Class<T> type, final I key) {
807             return new CaseIdentifiableItem<>(caseType, type, key);
808         }
809
810         /**
811          * Return the data object type backing this PathArgument.
812          *
813          * @return Data object type.
814          */
815         @Override
816         public final @NonNull T getKey() {
817             return key;
818         }
819
820         @Override
821         public String toString() {
822             return getType().getName() + "[key=" + key + "]";
823         }
824     }
825
826     private static final class CaseItem<C extends ChoiceIn<?> & DataObject, T extends ChildOf<? super C>>
827             extends Item<T> {
828         @Serial
829         private static final long serialVersionUID = 1L;
830
831         private final Class<C> caseType;
832
833         CaseItem(final Class<C> caseType, final Class<T> type) {
834             super(type);
835             this.caseType = requireNonNull(caseType);
836         }
837
838         @Override
839         public Optional<Class<C>> getCaseType() {
840             return Optional.of(caseType);
841         }
842     }
843
844     private static final class CaseIdentifiableItem<C extends ChoiceIn<?> & DataObject,
845             T extends ChildOf<? super C> & Identifiable<K>, K extends Identifier<T>> extends IdentifiableItem<T, K> {
846         @Serial
847         private static final long serialVersionUID = 1L;
848
849         private final Class<C> caseType;
850
851         CaseIdentifiableItem(final Class<C> caseType, final Class<T> type, final K key) {
852             super(type, key);
853             this.caseType = requireNonNull(caseType);
854         }
855
856         @Override
857         public Optional<Class<C>> getCaseType() {
858             return Optional.of(caseType);
859         }
860     }
861
862     /**
863      * A builder of {@link InstanceIdentifier} objects.
864      *
865      * @param <T> Instance identifier target type
866      */
867     public abstract static sealed class Builder<T extends DataObject> {
868         private final ImmutableList.Builder<PathArgument> pathBuilder;
869         private final HashCodeBuilder<PathArgument> hashBuilder;
870         private final Iterable<? extends PathArgument> basePath;
871
872         private boolean wildcard;
873
874         Builder(final Builder<?> prev, final PathArgument item, final boolean isWildcard) {
875             pathBuilder = prev.pathBuilder;
876             hashBuilder = prev.hashBuilder;
877             basePath = prev.basePath;
878             wildcard = prev.wildcard;
879             appendItem(item, isWildcard);
880         }
881
882         Builder(final InstanceIdentifier<T> identifier) {
883             pathBuilder = ImmutableList.builder();
884             hashBuilder = new HashCodeBuilder<>(identifier.hashCode());
885             wildcard = identifier.isWildcarded();
886             basePath = identifier.pathArguments;
887         }
888
889         Builder(final PathArgument item, final boolean wildcard) {
890             pathBuilder = ImmutableList.builder();
891             hashBuilder = new HashCodeBuilder<>();
892             basePath = null;
893             hashBuilder.addArgument(item);
894             pathBuilder.add(item);
895             this.wildcard = wildcard;
896         }
897
898         final boolean wildcard() {
899             return wildcard;
900         }
901
902         /**
903          * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
904          * the builder.
905          *
906          * @param container augmentation class
907          * @param <N> augmentation type
908          * @return this builder
909          * @throws NullPointerException if {@code container} is null
910          */
911         public final <N extends DataObject & Augmentation<? super T>> Builder<N> augmentation(
912                 final Class<N> container) {
913             return append(Item.of(container), false);
914         }
915
916         /**
917          * Append the specified container 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 top-level elements, for
919          * example
920          * <pre>
921          *     InstanceIdentifier.builder().child(Nodes.class).build();
922          * </pre>
923          *
924          * <p>
925          * NOTE :- The above example is only for illustration purposes InstanceIdentifier.builder() has been deprecated
926          * and should not be used. Use InstanceIdentifier.builder(Nodes.class) instead
927          *
928          * @param container Container to append
929          * @param <N> Container type
930          * @return this builder
931          * @throws NullPointerException if {@code container} is null
932          */
933         public final <N extends ChildOf<? super T>> Builder<N> child(final Class<N> container) {
934             return append(Item.of(container), Identifiable.class.isAssignableFrom(container));
935         }
936
937         /**
938          * Append the specified container as a child of the current InstanceIdentifier referenced by the builder. This
939          * method should be used when you want to build an instance identifier by appending a container node to the
940          * identifier and the {@code container} is defined in a {@code grouping} used in a {@code case} statement.
941          *
942          * @param caze Choice case class
943          * @param container Container to append
944          * @param <C> Case type
945          * @param <N> Container type
946          * @return this builder
947          * @throws NullPointerException if {@code container} is null
948          */
949         public final <C extends ChoiceIn<? super T> & DataObject, N extends ChildOf<? super C>> Builder<N> child(
950                 final Class<C> caze, final Class<N> container) {
951             return append(Item.of(caze, container), Identifiable.class.isAssignableFrom(container));
952         }
953
954         /**
955          * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder. This
956          * method should be used when you want to build an instance identifier by appending a specific list element to
957          * the identifier.
958          *
959          * @param listItem List to append
960          * @param listKey List key
961          * @param <N> List type
962          * @param <K> Key type
963          * @return this builder
964          * @throws NullPointerException if any argument is null
965          */
966         public final <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> KeyedBuilder<N, K> child(
967                 final Class<@NonNull N> listItem, final K listKey) {
968             return append(IdentifiableItem.of(listItem, listKey));
969         }
970
971         /**
972          * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder. This
973          * method should be used when you want to build an instance identifier by appending a specific list element to
974          * the identifier and the {@code list} is defined in a {@code grouping} used in a {@code case} statement.
975          *
976          * @param caze Choice case class
977          * @param listItem List to append
978          * @param listKey List key
979          * @param <C> Case type
980          * @param <N> List type
981          * @param <K> Key type
982          * @return this builder
983          * @throws NullPointerException if any argument is null
984          */
985         public final <C extends ChoiceIn<? super T> & DataObject, K extends Identifier<N>,
986                 N extends Identifiable<K> & ChildOf<? super C>> KeyedBuilder<N, K> child(final Class<C> caze,
987                     final Class<N> listItem, final K listKey) {
988             return append(IdentifiableItem.of(caze, listItem, listKey));
989         }
990
991         /**
992          * Build the instance identifier.
993          *
994          * @return Resulting {@link InstanceIdentifier}.
995          */
996         public abstract @NonNull InstanceIdentifier<T> build();
997
998         @Override
999         public final int hashCode() {
1000             return hashBuilder.build();
1001         }
1002
1003         @Override
1004         public final boolean equals(final Object obj) {
1005             return this == obj || obj instanceof Builder<?> other
1006                 && wildcard == other.wildcard && hashCode() == other.hashCode()
1007                 && Iterables.elementsEqual(pathArguments(), other.pathArguments());
1008         }
1009
1010         final Iterable<PathArgument> pathArguments() {
1011             final var args = pathBuilder.build();
1012             return basePath == null ? args : Iterables.concat(basePath, args);
1013         }
1014
1015         final void appendItem(final PathArgument item, final boolean isWildcard) {
1016             hashBuilder.addArgument(item);
1017             pathBuilder.add(item);
1018             wildcard |= isWildcard;
1019         }
1020
1021         abstract <X extends DataObject> @NonNull RegularBuilder<X> append(Item<X> item, boolean isWildcard);
1022
1023         abstract <X extends DataObject & Identifiable<Y>, Y extends Identifier<X>>
1024             @NonNull KeyedBuilder<X, Y> append(IdentifiableItem<X, Y> item);
1025     }
1026
1027     public static final class KeyedBuilder<T extends DataObject & Identifiable<K>, K extends Identifier<T>>
1028             extends Builder<T> {
1029         private @NonNull IdentifiableItem<T, K> lastItem;
1030
1031         KeyedBuilder(final IdentifiableItem<T, K> item) {
1032             super(item, false);
1033             lastItem = requireNonNull(item);
1034         }
1035
1036         KeyedBuilder(final KeyedInstanceIdentifier<T, K> identifier) {
1037             super(identifier);
1038             lastItem = IdentifiableItem.of(identifier.getTargetType(), identifier.getKey());
1039         }
1040
1041         private KeyedBuilder(final RegularBuilder<?> prev, final IdentifiableItem<T, K> item) {
1042             super(prev, item, false);
1043             lastItem = requireNonNull(item);
1044         }
1045
1046         /**
1047          * Build the instance identifier.
1048          *
1049          * @return Resulting {@link KeyedInstanceIdentifier}.
1050          */
1051         @Override
1052         public @NonNull KeyedInstanceIdentifier<T, K> build() {
1053             return new KeyedInstanceIdentifier<>(lastItem.getType(), pathArguments(), wildcard(), hashCode(),
1054                 lastItem.getKey());
1055         }
1056
1057         @Override
1058         <X extends DataObject> @NonNull RegularBuilder<X> append(final Item<X> item, final boolean isWildcard) {
1059             return new RegularBuilder<>(this, item, isWildcard);
1060         }
1061
1062         @Override
1063         @SuppressWarnings({ "rawtypes", "unchecked" })
1064         <X extends DataObject & Identifiable<Y>, Y extends Identifier<X>> KeyedBuilder<X, Y> append(
1065                 final IdentifiableItem<X, Y> item) {
1066             appendItem(item, false);
1067             lastItem = (IdentifiableItem) item;
1068             return (KeyedBuilder<X, Y>) this;
1069         }
1070     }
1071
1072     private static final class RegularBuilder<T extends DataObject> extends Builder<T> {
1073         private @NonNull Class<T> type;
1074
1075         RegularBuilder(final Item<T> item) {
1076             super(item, Identifiable.class.isAssignableFrom(item.getType()));
1077             type = item.getType();
1078         }
1079
1080         RegularBuilder(final InstanceIdentifier<T> identifier) {
1081             super(identifier);
1082             type = identifier.getTargetType();
1083         }
1084
1085         private RegularBuilder(final KeyedBuilder<?, ?> prev, final Item<T> item, final boolean wildcard) {
1086             super(prev, item, wildcard);
1087             type = item.getType();
1088         }
1089
1090         @Override
1091         public InstanceIdentifier<T> build() {
1092             return new InstanceIdentifier<>(type, pathArguments(), wildcard(), hashCode());
1093         }
1094
1095         @Override
1096         @SuppressWarnings({ "rawtypes", "unchecked" })
1097         <X extends DataObject> RegularBuilder<X> append(final Item<X> item, final boolean isWildcard) {
1098             appendItem(item, isWildcard);
1099             type = (Class) item.getType();
1100             return (RegularBuilder<X>) this;
1101         }
1102
1103         @Override
1104         <X extends DataObject & Identifiable<Y>, Y extends Identifier<X>> KeyedBuilder<X, Y> append(
1105                 final IdentifiableItem<X, Y> item) {
1106             return new KeyedBuilder<>(this, item);
1107         }
1108     }
1109 }