BUG-592: Rework instance identifier
[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 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 (hash != other.hash) {
119             return false;
120         }
121
122         return Iterables.elementsEqual(pathArguments, other.pathArguments);
123     }
124
125     @Override
126     public final String toString() {
127         return addToStringAttributes(Objects.toStringHelper(this)).toString();
128     }
129
130     /**
131      * Add class-specific toString attributes.
132      *
133      * @param toStringHelper ToStringHelper instance
134      * @return ToStringHelper instance which was passed in
135      */
136     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
137         return toStringHelper.add("targetType", targetType).add("path", Iterables.toString(getPathArguments()));
138     }
139
140     /**
141      * Return an instance identifier trimmed at the first occurrence of a
142      * specific component type.
143      *
144      * For example let's say an instance identifier was built like so,
145      * <pre>
146      *      identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
147      * </pre>
148      *
149      * And you wanted to obtain the Instance identifier which represented Nodes you would do it like so,
150      *
151      * <pre>
152      *      identifier.firstIdentifierOf(Nodes.class)
153      * </pre>
154      *
155      * @param type component type
156      * @return trimmed instance identifier, or null if the component type
157      *         is not present.
158      */
159     public final <I extends DataObject> InstanceIdentifier<I> firstIdentifierOf(final Class<I> type) {
160         int i = 1;
161         for (final PathArgument a : getPathArguments()) {
162             if (type.equals(a.getType())) {
163                 @SuppressWarnings("unchecked")
164                 final InstanceIdentifier<I> ret = (InstanceIdentifier<I>) create(Iterables.limit(getPathArguments(), i));
165                 return ret;
166             }
167
168             ++i;
169         }
170
171         return null;
172     }
173
174     /**
175      * Return the key associated with the first component of specified type in
176      * an identifier.
177      *
178      * @param listItem component type
179      * @param listKey component key type
180      * @return key associated with the component, or null if the component type
181      *         is not present.
182      */
183     public final <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K firstKeyOf(final Class<N> listItem, final Class<K> listKey) {
184         for (final PathArgument i : getPathArguments()) {
185             if (listItem.equals(i.getType())) {
186                 @SuppressWarnings("unchecked")
187                 final K ret = ((IdentifiableItem<N, K>)i).getKey();
188                 return ret;
189             }
190         }
191
192         return null;
193     }
194
195     /**
196      * Check whether an identifier is contained in this identifier. This is a strict subtree check, which requires all
197      * PathArguments to match exactly, e.g.
198      *
199      *
200      * The contains method checks if the other identifier is fully contained within the current identifier. It does this
201      * by looking at only the types of the path arguments and not by comparing the path arguments themselves.
202      *
203      * To illustrate here is an example which explains the working of this API.
204      *
205      * Let's say you have two instance identifiers as follows,
206      *
207      * this = /nodes/node/openflow:1
208      * other = /nodes/node/openflow:2
209      *
210      * then this.contains(other) will return false.
211      *
212      * @param other
213      * @return
214      */
215     @Override
216     public final boolean contains(final InstanceIdentifier<? extends DataObject> other) {
217         Preconditions.checkNotNull(other, "other should not be null");
218
219         final Iterator<?> lit = pathArguments.iterator();
220         final Iterator<?> oit = other.pathArguments.iterator();
221
222         while (lit.hasNext()) {
223             if (!oit.hasNext()) {
224                 return false;
225             }
226
227             if (!lit.next().equals(oit.next())) {
228                 return false;
229             }
230         }
231
232         return true;
233     }
234
235     /**
236      * Check whether this instance identifier contains the other identifier after wildcard expansion. This is similar
237      * to {@link #contains(InstanceIdentifier)}, with the exception that a wildcards are assumed to match the their
238      * non-wildcarded PathArgument counterpart.
239      *
240      * @param other Identifier which should be checked for inclusion.
241      * @return @true if this identifier contains the other object
242      */
243     public final boolean containsWildcarded(final InstanceIdentifier<?> other) {
244         Preconditions.checkNotNull(other, "other should not be null");
245
246         final Iterator<PathArgument> lit = pathArguments.iterator();
247         final Iterator<PathArgument> oit = other.pathArguments.iterator();
248
249         while (lit.hasNext()) {
250             if (!oit.hasNext()) {
251                 return false;
252             }
253
254             final PathArgument la = lit.next();
255             final PathArgument oa = oit.next();
256
257             if (!la.getType().equals(oa.getType())) {
258                 return false;
259             }
260             if (la instanceof IdentifiableItem<?, ?> && oa instanceof IdentifiableItem<?, ?> && !la.equals(oa)) {
261                 return false;
262             }
263         }
264
265         return true;
266     }
267
268     /**
269      * Create a builder rooted at this key.
270      *
271      * @return A builder instance
272      */
273     public InstanceIdentifierBuilder<T> builder() {
274         return new InstanceIdentifierBuilderImpl<T>(new Item<T>(targetType), pathArguments, hash, isWildcarded());
275     }
276
277     private InstanceIdentifier<?> childIdentifier(final PathArgument arg) {
278         return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)), HashCodeBuilder.nextHashCode(hash, arg), isWildcarded());
279     }
280
281     @SuppressWarnings("unchecked")
282     public final <N extends ChildOf<? super T>> InstanceIdentifier<N> child(final Class<N> container) {
283         final PathArgument arg = new Item<>(container);
284         return (InstanceIdentifier<N>) childIdentifier(arg);
285     }
286
287     @SuppressWarnings("unchecked")
288     public final <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> InstanceIdentifier<N> child(
289             final Class<N> listItem, final K listKey) {
290         final PathArgument arg = new IdentifiableItem<>(listItem, listKey);
291         return (InstanceIdentifier<N>) childIdentifier(arg);
292     }
293
294     @SuppressWarnings("unchecked")
295     public final <N extends DataObject & Augmentation<? super T>> InstanceIdentifier<N> augmentation(
296             final Class<N> container) {
297         final PathArgument arg = new Item<>(container);
298         return (InstanceIdentifier<N>) childIdentifier(arg);
299     }
300
301     @Deprecated
302     private List<PathArgument> legacyCache;
303
304     /**
305      * @deprecated Use {@link #getPathArguments()} instead.
306      */
307     @Deprecated
308     public final List<PathArgument> getPath() {
309         if (legacyCache == null) {
310             legacyCache = ImmutableList.<PathArgument>copyOf(getPathArguments());
311         }
312
313         return legacyCache;
314     }
315
316     /**
317      * Create a new InstanceIdentifierBuilder given a base InstanceIdentifier
318      *
319      * @param basePath
320      * @param <T>
321      * @return
322      *
323      * @deprecated Use {@link #builder()} instead.
324      */
325     @Deprecated
326     public static <T extends DataObject> InstanceIdentifierBuilder<T> builder(final InstanceIdentifier<T> base) {
327         return base.builder();
328     }
329
330     /**
331      * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container
332      *
333      * @param container
334      * @param <T>
335      * @return
336      */
337     public static <T extends ChildOf<? extends DataRoot>> InstanceIdentifierBuilder<T> builder(final Class<T> container) {
338         return new InstanceIdentifierBuilderImpl<T>().addNode(container);
339     }
340
341     /**
342      * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an IdentifiableItem
343      *
344      * @param listItem
345      * @param listKey
346      * @param <N>
347      * @param <K>
348      * @return
349      */
350     public static <N extends Identifiable<K> & ChildOf<? extends DataRoot>, K extends Identifier<N>> InstanceIdentifierBuilder<N> builder(
351             final Class<N> listItem, final K listKey) {
352         return new InstanceIdentifierBuilderImpl<N>().addNode(listItem, listKey);
353     }
354
355     /**
356      * Create an instance identifier for a very specific object type.
357      *
358      * Example
359      * <pre>
360      *  List<PathArgument> path = Arrays.asList(new Item(Nodes.class))
361      *  new InstanceIdentifier(path);
362      * </pre>
363      *
364      * @param pathArguments The path to a specific node in the data tree
365      * @return InstanceIdentifier instance
366      * @throws IllegalArgumentException if pathArguments is empty or
367      *         contains a null element.
368      */
369     public static InstanceIdentifier<?> create(final Iterable<? extends PathArgument> pathArguments) {
370         final Iterator<? extends PathArgument> it = Preconditions.checkNotNull(pathArguments, "pathArguments may not be null").iterator();
371         final HashCodeBuilder<PathArgument> hashBuilder = new HashCodeBuilder<>();
372         boolean wildcard = false;
373         PathArgument a = null;
374
375         while (it.hasNext()) {
376             a = it.next();
377             Preconditions.checkArgument(a != null, "pathArguments may not contain null elements");
378
379             // TODO: sanity check ChildOf<>;
380             hashBuilder.addArgument(a);
381
382             if (Identifiable.class.isAssignableFrom(a.getType()) && !(a instanceof IdentifiableItem<?, ?>)) {
383                 wildcard = true;
384             }
385         }
386         Preconditions.checkArgument(a != null, "pathArguments may not be empty");
387
388         final Iterable<PathArgument> immutableArguments;
389         if (pathArguments instanceof ImmutableCollection<?>) {
390             immutableArguments = (Iterable<PathArgument>) pathArguments;
391         } else {
392             immutableArguments = ImmutableList.copyOf(pathArguments);
393         }
394
395         return trustedCreate(a, immutableArguments, hashBuilder.toInstance(), wildcard);
396     }
397
398     /**
399      * Create an instance identifier for a very specific object type.
400      *
401      * For example
402      * <pre>
403      *      new InstanceIdentifier(Nodes.class)
404      * </pre>
405      * would create an InstanceIdentifier for an object of type Nodes
406      *
407      * @param type The type of the object which this instance identifier represents
408      * @return InstanceIdentifier instance
409      */
410     @SuppressWarnings("unchecked")
411     public static <T extends DataObject> InstanceIdentifier<T> create(final Class<T> type) {
412         return (InstanceIdentifier<T>) create(Collections.<PathArgument> singletonList(new Item<>(type)));
413     }
414
415     /**
416      * Return the key associated with the last component of the specified identifier.
417      *
418      * @param id instance identifier
419      * @return key associated with the last component
420      */
421     public static <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K keyOf(final InstanceIdentifier<N> id) {
422         @SuppressWarnings("unchecked")
423         final K ret = ((KeyedInstanceIdentifier<N, K>)id).getKey();
424         return ret;
425     }
426
427     @SuppressWarnings({ "unchecked", "rawtypes" })
428     static InstanceIdentifier<?> trustedCreate(final PathArgument arg, final Iterable<PathArgument> pathArguments, final int hash, boolean wildcarded) {
429         if (Identifiable.class.isAssignableFrom(arg.getType())) {
430             Identifier<?> key = null;
431             if (arg instanceof IdentifiableItem<?, ?>) {
432                 key = ((IdentifiableItem<?, ?>)arg).key;
433             } else {
434                 wildcarded = true;
435             }
436
437             return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key);
438         } else {
439             return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
440         }
441     }
442
443     /**
444      * Path argument of {@link InstanceIdentifier}.
445      * <p>
446      * Interface which implementations are used as path components of the
447      * path in overall data tree.
448      */
449     public interface PathArgument {
450         Class<? extends DataObject> getType();
451     }
452
453     private static abstract class AbstractPathArgument<T extends DataObject> implements PathArgument {
454         private final Class<T> type;
455
456         protected AbstractPathArgument(final Class<T> type) {
457             this.type = Preconditions.checkNotNull(type, "Type may not be null.");
458         }
459
460         @Override
461         public final Class<T> getType() {
462             return type;
463         }
464
465         @Override
466         public int hashCode() {
467             final int prime = 31;
468             int result = 1;
469             result = prime * result + ((type == null) ? 0 : type.hashCode());
470             return result;
471         }
472
473         @Override
474         public boolean equals(final Object obj) {
475             if (this == obj) {
476                 return true;
477             }
478             if (obj == null) {
479                 return false;
480             }
481             if (getClass() != obj.getClass()) {
482                 return false;
483             }
484             final AbstractPathArgument<?> other = (AbstractPathArgument<?>) obj;
485             if (type == null) {
486                 if (other.type != null) {
487                     return false;
488                 }
489             } else if (!type.equals(other.type)) {
490                 return false;
491             }
492             return true;
493         }
494     }
495
496     /**
497      * An Item represents an object that probably is only one of it's kind. For example a Nodes object is only one of
498      * a kind. In YANG terms this would probably represent a container.
499      *
500      * @param <T>
501      */
502     public static final class Item<T extends DataObject> extends AbstractPathArgument<T> {
503         public Item(final Class<T> type) {
504             super(type);
505         }
506
507         @Override
508         public String toString() {
509             return getType().getName();
510         }
511     }
512
513     /**
514      * An IdentifiableItem represents a object that is usually present in a collection and can be identified uniquely
515      * by a key. In YANG terms this would probably represent an item in a list.
516      *
517      * @param <I> An object that is identifiable by an identifier
518      * @param <T> The identifier of the object
519      */
520     public static final class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>> extends AbstractPathArgument<I> {
521         private final T key;
522
523         public IdentifiableItem(final Class<I> type, final T key) {
524             super(type);
525             this.key = Preconditions.checkNotNull(key, "Key may not be null.");
526         }
527
528         public T getKey() {
529             return this.key;
530         }
531
532         @Override
533         public boolean equals(final Object obj) {
534             return super.equals(obj) && obj.hashCode() == hashCode() && key.equals(((IdentifiableItem<?, ?>) obj).getKey());
535         }
536
537         @Override
538         public int hashCode() {
539             return key.hashCode();
540         }
541
542         @Override
543         public String toString() {
544             return getType().getName() + "[key=" + key + "]";
545         }
546     }
547
548
549     public interface InstanceIdentifierBuilder<T extends DataObject> extends Builder<InstanceIdentifier<T>> {
550         /**
551          * Append the specified container as a child of the current InstanceIdentifier referenced by the builder.
552          *
553          * This method should be used when you want to build an instance identifier by appending top-level
554          * elements
555          *
556          * Example,
557          * <pre>
558          *     InstanceIdentifier.builder().child(Nodes.class).build();
559          *
560          * </pre>
561          *
562          * NOTE :- The above example is only for illustration purposes InstanceIdentifier.builder() has been deprecated
563          * and should not be used. Use InstanceIdentifier.builder(Nodes.class) instead
564          *
565          * @param container
566          * @param <N>
567          * @return
568          */
569         <N extends ChildOf<? super T>> InstanceIdentifierBuilder<N> child(
570                 Class<N> container);
571
572         /**
573          * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder.
574          *
575          * This method should be used when you want to build an instance identifier by appending a specific list element
576          * to the identifier
577          *
578          * @param listItem
579          * @param listKey
580          * @param <N>
581          * @param <K>
582          * @return
583          */
584         <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> InstanceIdentifierBuilder<N> child(
585                 Class<N> listItem, K listKey);
586
587         /**
588          * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
589          * the builder
590          *
591          * @param container
592          * @param <N>
593          * @return
594          */
595         <N extends DataObject & Augmentation<? super T>> InstanceIdentifierBuilder<N> augmentation(
596                 Class<N> container);
597
598         /**
599          * Build the instance identifier.
600          *
601          * @return
602          */
603         InstanceIdentifier<T> build();
604     }
605 }