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