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