Merge "BUG-1414: fix InstanceIdentifier.child(Class, Object)"
[yangtools.git] / yang / 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 com.google.common.base.Objects;
11 import com.google.common.base.Objects.ToStringHelper;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableCollection;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.Iterables;
16
17 import java.util.Collections;
18 import java.util.Iterator;
19 import java.util.List;
20
21 import org.opendaylight.yangtools.concepts.Builder;
22 import org.opendaylight.yangtools.concepts.Immutable;
23 import org.opendaylight.yangtools.concepts.Path;
24 import org.opendaylight.yangtools.util.HashCodeBuilder;
25
26 /**
27  *
28  * This instance identifier uniquely identifies a specific DataObject in the data tree modeled by YANG.
29  *
30  * For Example let's say you were trying to refer to a node in inventory which was modeled in YANG as follows,
31  *
32  * <pre>
33  * module opendaylight-inventory {
34  *      ....
35  *
36  *      container nodes {
37  *        list node {
38  *            key "id";
39  *            ext:context-instance "node-context";
40  *
41  *            uses node;
42  *        }
43  *    }
44  *
45  * }
46  * </pre>
47  *
48  * You could create an instance identifier as follows to get to a node with id "openflow:1"
49  *
50  * InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
51  *
52  * This would be the same as using a path like so, "/nodes/node/openflow:1" to refer to the openflow:1 node
53  *
54  */
55 public class InstanceIdentifier<T extends DataObject> implements Path<InstanceIdentifier<? extends DataObject>>, Immutable {
56     /*
57      * Protected to differentiate internal and external access. Internal
58      * access is required never to modify the contents. References passed
59      * to outside entities have to be wrapped in an unmodifiable view.
60      */
61     protected final Iterable<PathArgument> pathArguments;
62     private final Class<T> targetType;
63     private final boolean wildcarded;
64     private final int hash;
65
66     InstanceIdentifier(final Class<T> type, final Iterable<PathArgument> pathArguments, final boolean wildcarded, final int hash) {
67         this.pathArguments = Preconditions.checkNotNull(pathArguments);
68         this.targetType = Preconditions.checkNotNull(type);
69         this.wildcarded = wildcarded;
70         this.hash = hash;
71     }
72
73     /**
74      * Return the type of data which this InstanceIdentifier identifies.
75      *
76      * @return Target type
77      */
78     public final Class<T> getTargetType() {
79         return targetType;
80     }
81
82     /**
83      * Return the path argument chain which makes up this instance identifier.
84      *
85      * @return Path argument chain. Immutable and does not contain nulls.
86      */
87     public final Iterable<PathArgument> getPathArguments() {
88         return Iterables.unmodifiableIterable(pathArguments);
89     }
90
91     /**
92      * Check whether an instance identifier contains any wildcards. A wildcard
93      * is an path argument which has a null key.
94      *
95      * @return @true if any of the path arguments has a null key.
96      */
97     public final boolean isWildcarded() {
98         return wildcarded;
99     }
100
101     @Override
102     public final int hashCode() {
103         return hash;
104     }
105
106     @Override
107     public final boolean equals(final Object obj) {
108         if (this == obj) {
109             return true;
110         }
111         if (obj == null) {
112             return false;
113         }
114         if (getClass() != obj.getClass()) {
115             return false;
116         }
117
118         final InstanceIdentifier<?> other = (InstanceIdentifier<?>) obj;
119         if (pathArguments == other.pathArguments) {
120             return true;
121         }
122
123         /*
124          * We could now just go and compare the pathArguments, but that
125          * can be potentially expensive. Let's try to avoid that by
126          * checking various things that we have cached from pathArguments
127          * and trying to prove the identifiers are *not* equal.
128          */
129         if (hash != other.hash) {
130             return false;
131         }
132         if (wildcarded != other.wildcarded) {
133             return false;
134         }
135         if (targetType != other.targetType) {
136             return false;
137         }
138         if (fastNonEqual(other)) {
139             return false;
140         }
141
142         // Everything checks out so far, so we have to do a full equals
143         return Iterables.elementsEqual(pathArguments, other.pathArguments);
144     }
145
146     /**
147      * Perform class-specific fast checks for non-equality. This allows
148      * subclasses to avoid iterating over the pathArguments by performing
149      * quick checks on their specific fields.
150      *
151      * @param other The other identifier, guaranteed to be the same class
152      * @return @true if the other identifier cannot be equal to this one.
153      */
154     protected boolean fastNonEqual(final InstanceIdentifier<?> other) {
155         return false;
156     }
157
158     @Override
159     public final String toString() {
160         return addToStringAttributes(Objects.toStringHelper(this)).toString();
161     }
162
163     /**
164      * Add class-specific toString attributes.
165      *
166      * @param toStringHelper ToStringHelper instance
167      * @return ToStringHelper instance which was passed in
168      */
169     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
170         return toStringHelper.add("targetType", targetType).add("path", Iterables.toString(getPathArguments()));
171     }
172
173     /**
174      * Return an instance identifier trimmed at the first occurrence of a
175      * specific component type.
176      *
177      * For example let's say an instance identifier was built like so,
178      * <pre>
179      *      identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
180      * </pre>
181      *
182      * And you wanted to obtain the Instance identifier which represented Nodes you would do it like so,
183      *
184      * <pre>
185      *      identifier.firstIdentifierOf(Nodes.class)
186      * </pre>
187      *
188      * @param type component type
189      * @return trimmed instance identifier, or null if the component type
190      *         is not present.
191      */
192     public final <I extends DataObject> InstanceIdentifier<I> firstIdentifierOf(final Class<I> type) {
193         int i = 1;
194         for (final PathArgument a : getPathArguments()) {
195             if (type.equals(a.getType())) {
196                 @SuppressWarnings("unchecked")
197                 final InstanceIdentifier<I> ret = (InstanceIdentifier<I>) internalCreate(Iterables.limit(getPathArguments(), i));
198                 return ret;
199             }
200
201             ++i;
202         }
203
204         return null;
205     }
206
207     /**
208      * Return the key associated with the first component of specified type in
209      * an identifier.
210      *
211      * @param listItem component type
212      * @param listKey component key type
213      * @return key associated with the component, or null if the component type
214      *         is not present.
215      */
216     public final <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K firstKeyOf(final Class<N> listItem, final Class<K> listKey) {
217         for (final PathArgument i : getPathArguments()) {
218             if (listItem.equals(i.getType())) {
219                 @SuppressWarnings("unchecked")
220                 final K ret = ((IdentifiableItem<N, K>)i).getKey();
221                 return ret;
222             }
223         }
224
225         return null;
226     }
227
228     /**
229      * Check whether an identifier is contained in this identifier. This is a strict subtree check, which requires all
230      * PathArguments to match exactly, e.g.
231      *
232      *
233      * The contains method checks if the other identifier is fully contained within the current identifier. It does this
234      * by looking at only the types of the path arguments and not by comparing the path arguments themselves.
235      *
236      * To illustrate here is an example which explains the working of this API.
237      *
238      * Let's say you have two instance identifiers as follows,
239      *
240      * this = /nodes/node/openflow:1
241      * other = /nodes/node/openflow:2
242      *
243      * then this.contains(other) will return false.
244      *
245      * @param other
246      * @return
247      */
248     @Override
249     public final boolean contains(final InstanceIdentifier<? extends DataObject> other) {
250         Preconditions.checkNotNull(other, "other should not be null");
251
252         final Iterator<?> lit = pathArguments.iterator();
253         final Iterator<?> oit = other.pathArguments.iterator();
254
255         while (lit.hasNext()) {
256             if (!oit.hasNext()) {
257                 return false;
258             }
259
260             if (!lit.next().equals(oit.next())) {
261                 return false;
262             }
263         }
264
265         return true;
266     }
267
268     /**
269      * Check whether this instance identifier contains the other identifier after wildcard expansion. This is similar
270      * to {@link #contains(InstanceIdentifier)}, with the exception that a wildcards are assumed to match the their
271      * non-wildcarded PathArgument counterpart.
272      *
273      * @param other Identifier which should be checked for inclusion.
274      * @return @true if this identifier contains the other object
275      */
276     public final boolean containsWildcarded(final InstanceIdentifier<?> other) {
277         Preconditions.checkNotNull(other, "other should not be null");
278
279         final Iterator<PathArgument> lit = pathArguments.iterator();
280         final Iterator<PathArgument> oit = other.pathArguments.iterator();
281
282         while (lit.hasNext()) {
283             if (!oit.hasNext()) {
284                 return false;
285             }
286
287             final PathArgument la = lit.next();
288             final PathArgument oa = oit.next();
289
290             if (!la.getType().equals(oa.getType())) {
291                 return false;
292             }
293             if (la instanceof IdentifiableItem<?, ?> && oa instanceof IdentifiableItem<?, ?> && !la.equals(oa)) {
294                 return false;
295             }
296         }
297
298         return true;
299     }
300
301     /**
302      * Create a builder rooted at this key.
303      *
304      * @return A builder instance
305      */
306     public InstanceIdentifierBuilder<T> builder() {
307         return new InstanceIdentifierBuilderImpl<T>(new Item<T>(targetType), pathArguments, hash, isWildcarded());
308     }
309
310     private InstanceIdentifier<?> childIdentifier(final PathArgument arg) {
311         return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)), HashCodeBuilder.nextHashCode(hash, arg), isWildcarded());
312     }
313
314     @SuppressWarnings("unchecked")
315     public final <N extends ChildOf<? super T>> InstanceIdentifier<N> child(final Class<N> container) {
316         final PathArgument arg = new Item<>(container);
317         return (InstanceIdentifier<N>) childIdentifier(arg);
318     }
319
320     @SuppressWarnings("unchecked")
321     public final <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> KeyedInstanceIdentifier<N, K> child(
322             final Class<N> listItem, final K listKey) {
323         final PathArgument arg = new IdentifiableItem<>(listItem, listKey);
324         return (KeyedInstanceIdentifier<N, K>) childIdentifier(arg);
325     }
326
327     @SuppressWarnings("unchecked")
328     public final <N extends DataObject & Augmentation<? super T>> InstanceIdentifier<N> augmentation(
329             final Class<N> container) {
330         final PathArgument arg = new Item<>(container);
331         return (InstanceIdentifier<N>) childIdentifier(arg);
332     }
333
334     @Deprecated
335     private List<PathArgument> legacyCache;
336
337     /**
338      * @deprecated Use {@link #getPathArguments()} instead.
339      */
340     @Deprecated
341     public final List<PathArgument> getPath() {
342         if (legacyCache == null) {
343             legacyCache = ImmutableList.<PathArgument>copyOf(getPathArguments());
344         }
345
346         return legacyCache;
347     }
348
349     /**
350      * Create a new InstanceIdentifierBuilder given a base InstanceIdentifier
351      *
352      * @param basePath
353      * @param <T>
354      * @return
355      *
356      * @deprecated Use {@link #builder()} instead.
357      */
358     @Deprecated
359     public static <T extends DataObject> InstanceIdentifierBuilder<T> builder(final InstanceIdentifier<T> base) {
360         return base.builder();
361     }
362
363     /**
364      * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container
365      *
366      * @param container
367      * @param <T>
368      * @return
369      */
370     public static <T extends ChildOf<? extends DataRoot>> InstanceIdentifierBuilder<T> builder(final Class<T> container) {
371         return new InstanceIdentifierBuilderImpl<T>().addNode(container);
372     }
373
374     /**
375      * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an IdentifiableItem
376      *
377      * @param listItem
378      * @param listKey
379      * @param <N>
380      * @param <K>
381      * @return
382      */
383     public static <N extends Identifiable<K> & ChildOf<? extends DataRoot>, K extends Identifier<N>> InstanceIdentifierBuilder<N> builder(
384             final Class<N> listItem, final K listKey) {
385         return new InstanceIdentifierBuilderImpl<N>().addNode(listItem, listKey);
386     }
387
388     /**
389      * Create an instance identifier for a very specific object type. This method
390      * implements {@link #create(Iterable)} semantics, except it is used by internal
391      * callers, which have assured that the argument is an immutable Iterable.
392      *
393      *
394      * @param pathArguments The path to a specific node in the data tree
395      * @return InstanceIdentifier instance
396      * @throws IllegalArgumentException if pathArguments is empty or
397      *         contains a null element.
398      */
399     private static InstanceIdentifier<?> internalCreate(final Iterable<PathArgument> pathArguments) {
400         final Iterator<? extends PathArgument> it = Preconditions.checkNotNull(pathArguments, "pathArguments may not be null").iterator();
401         final HashCodeBuilder<PathArgument> hashBuilder = new HashCodeBuilder<>();
402         boolean wildcard = false;
403         PathArgument a = null;
404
405         while (it.hasNext()) {
406             a = it.next();
407             Preconditions.checkArgument(a != null, "pathArguments may not contain null elements");
408
409             // TODO: sanity check ChildOf<>;
410             hashBuilder.addArgument(a);
411
412             if (Identifiable.class.isAssignableFrom(a.getType()) && !(a instanceof IdentifiableItem<?, ?>)) {
413                 wildcard = true;
414             }
415         }
416         Preconditions.checkArgument(a != null, "pathArguments may not be empty");
417
418         return trustedCreate(a, pathArguments, hashBuilder.toInstance(), wildcard);
419     }
420
421     /**
422      * Create an instance identifier for a very specific object type.
423      *
424      * Example
425      * <pre>
426      *  List<PathArgument> path = Arrays.asList(new Item(Nodes.class))
427      *  new InstanceIdentifier(path);
428      * </pre>
429      *
430      * @param pathArguments The path to a specific node in the data tree
431      * @return InstanceIdentifier instance
432      * @throws IllegalArgumentException if pathArguments is empty or
433      *         contains a null element.
434      */
435     public static InstanceIdentifier<?> create(final Iterable<? extends PathArgument> pathArguments) {
436         if (pathArguments instanceof ImmutableCollection<?>) {
437             @SuppressWarnings("unchecked")
438             final Iterable<PathArgument> immutableArguments = (Iterable<PathArgument>) pathArguments;
439             return internalCreate(immutableArguments);
440         } else {
441             return internalCreate(ImmutableList.copyOf(pathArguments));
442         }
443     }
444
445     /**
446      * Create an instance identifier for a very specific object type.
447      *
448      * For example
449      * <pre>
450      *      new InstanceIdentifier(Nodes.class)
451      * </pre>
452      * would create an InstanceIdentifier for an object of type Nodes
453      *
454      * @param type The type of the object which this instance identifier represents
455      * @return InstanceIdentifier instance
456      */
457     @SuppressWarnings("unchecked")
458     public static <T extends DataObject> InstanceIdentifier<T> create(final Class<T> type) {
459         return (InstanceIdentifier<T>) create(Collections.<PathArgument> singletonList(new Item<>(type)));
460     }
461
462     /**
463      * Return the key associated with the last component of the specified identifier.
464      *
465      * @param id instance identifier
466      * @return key associated with the last component
467      */
468     public static <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K keyOf(final InstanceIdentifier<N> id) {
469         @SuppressWarnings("unchecked")
470         final K ret = ((KeyedInstanceIdentifier<N, K>)id).getKey();
471         return ret;
472     }
473
474     @SuppressWarnings({ "unchecked", "rawtypes" })
475     static InstanceIdentifier<?> trustedCreate(final PathArgument arg, final Iterable<PathArgument> pathArguments, final int hash, boolean wildcarded) {
476         if (Identifiable.class.isAssignableFrom(arg.getType()) && !(wildcarded)) {
477             Identifier<?> key = null;
478             if (arg instanceof IdentifiableItem<?, ?>) {
479                 key = ((IdentifiableItem<?, ?>)arg).key;
480             } else {
481                 wildcarded = true;
482             }
483
484             return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key);
485         } else {
486             return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
487         }
488     }
489
490     /**
491      * Path argument of {@link InstanceIdentifier}.
492      * <p>
493      * Interface which implementations are used as path components of the
494      * path in overall data tree.
495      */
496     public interface PathArgument extends Comparable<PathArgument> {
497         Class<? extends DataObject> getType();
498     }
499
500     private static abstract class AbstractPathArgument<T extends DataObject> implements PathArgument {
501         private final Class<T> type;
502
503         protected AbstractPathArgument(final Class<T> type) {
504             this.type = Preconditions.checkNotNull(type, "Type may not be null.");
505         }
506
507         @Override
508         public final Class<T> getType() {
509             return type;
510         }
511
512         @Override
513         public int hashCode() {
514             return type.hashCode();
515         }
516
517         @Override
518         public boolean equals(final Object obj) {
519             if (this == obj) {
520                 return true;
521             }
522             if (obj == null) {
523                 return false;
524             }
525             if (getClass() != obj.getClass()) {
526                 return false;
527             }
528             final AbstractPathArgument<?> other = (AbstractPathArgument<?>) obj;
529             return type.equals(other.type);
530         }
531
532         @Override
533         public int compareTo(final PathArgument arg) {
534             return type.getCanonicalName().compareTo(arg.getType().getCanonicalName());
535         }
536     }
537
538     /**
539      * An Item represents an object that probably is only one of it's kind. For example a Nodes object is only one of
540      * a kind. In YANG terms this would probably represent a container.
541      *
542      * @param <T>
543      */
544     public static final class Item<T extends DataObject> extends AbstractPathArgument<T> {
545         public Item(final Class<T> type) {
546             super(type);
547         }
548
549         @Override
550         public String toString() {
551             return getType().getName();
552         }
553     }
554
555     /**
556      * An IdentifiableItem represents a object that is usually present in a collection and can be identified uniquely
557      * by a key. In YANG terms this would probably represent an item in a list.
558      *
559      * @param <I> An object that is identifiable by an identifier
560      * @param <T> The identifier of the object
561      */
562     public static final class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>> extends AbstractPathArgument<I> {
563         private final T key;
564
565         public IdentifiableItem(final Class<I> type, final T key) {
566             super(type);
567             this.key = Preconditions.checkNotNull(key, "Key may not be null.");
568         }
569
570         public T getKey() {
571             return this.key;
572         }
573
574         @Override
575         public boolean equals(final Object obj) {
576             return super.equals(obj) && key.equals(((IdentifiableItem<?, ?>) obj).getKey());
577         }
578
579         @Override
580         public int hashCode() {
581             return super.hashCode() * 31 + key.hashCode();
582         }
583
584         @Override
585         public String toString() {
586             return getType().getName() + "[key=" + key + "]";
587         }
588     }
589
590
591     public interface InstanceIdentifierBuilder<T extends DataObject> extends Builder<InstanceIdentifier<T>> {
592         /**
593          * Append the specified container as a child of the current InstanceIdentifier referenced by the builder.
594          *
595          * This method should be used when you want to build an instance identifier by appending top-level
596          * elements
597          *
598          * Example,
599          * <pre>
600          *     InstanceIdentifier.builder().child(Nodes.class).build();
601          *
602          * </pre>
603          *
604          * NOTE :- The above example is only for illustration purposes InstanceIdentifier.builder() has been deprecated
605          * and should not be used. Use InstanceIdentifier.builder(Nodes.class) instead
606          *
607          * @param container
608          * @param <N>
609          * @return
610          */
611         <N extends ChildOf<? super T>> InstanceIdentifierBuilder<N> child(
612                 Class<N> container);
613
614         /**
615          * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder.
616          *
617          * This method should be used when you want to build an instance identifier by appending a specific list element
618          * to the identifier
619          *
620          * @param listItem
621          * @param listKey
622          * @param <N>
623          * @param <K>
624          * @return
625          */
626         <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> InstanceIdentifierBuilder<N> child(
627                 Class<N> listItem, K listKey);
628
629         /**
630          * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
631          * the builder
632          *
633          * @param container
634          * @param <N>
635          * @return
636          */
637         <N extends DataObject & Augmentation<? super T>> InstanceIdentifierBuilder<N> augmentation(
638                 Class<N> container);
639
640         /**
641          * Build the instance identifier.
642          *
643          * @return
644          */
645         InstanceIdentifier<T> build();
646     }
647 }