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