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