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