BUG-582: optimize InstanceIdentifier.firstIdentifierOf()
[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>) internalCreate(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. This method
389      * implements {@link #create(Iterable)} semantics, except it is used by internal
390      * callers, which have assured that the argument is an immutable Iterable.
391      *
392      *
393      * @param pathArguments The path to a specific node in the data tree
394      * @return InstanceIdentifier instance
395      * @throws IllegalArgumentException if pathArguments is empty or
396      *         contains a null element.
397      */
398     private static InstanceIdentifier<?> internalCreate(final Iterable<PathArgument> pathArguments) {
399         final Iterator<? extends PathArgument> it = Preconditions.checkNotNull(pathArguments, "pathArguments may not be null").iterator();
400         final HashCodeBuilder<PathArgument> hashBuilder = new HashCodeBuilder<>();
401         boolean wildcard = false;
402         PathArgument a = null;
403
404         while (it.hasNext()) {
405             a = it.next();
406             Preconditions.checkArgument(a != null, "pathArguments may not contain null elements");
407
408             // TODO: sanity check ChildOf<>;
409             hashBuilder.addArgument(a);
410
411             if (Identifiable.class.isAssignableFrom(a.getType()) && !(a instanceof IdentifiableItem<?, ?>)) {
412                 wildcard = true;
413             }
414         }
415         Preconditions.checkArgument(a != null, "pathArguments may not be empty");
416
417         return trustedCreate(a, pathArguments, hashBuilder.toInstance(), wildcard);
418     }
419
420     /**
421      * Create an instance identifier for a very specific object type.
422      *
423      * Example
424      * <pre>
425      *  List<PathArgument> path = Arrays.asList(new Item(Nodes.class))
426      *  new InstanceIdentifier(path);
427      * </pre>
428      *
429      * @param pathArguments The path to a specific node in the data tree
430      * @return InstanceIdentifier instance
431      * @throws IllegalArgumentException if pathArguments is empty or
432      *         contains a null element.
433      */
434     public static InstanceIdentifier<?> create(final Iterable<? extends PathArgument> pathArguments) {
435         if (pathArguments instanceof ImmutableCollection<?>) {
436             @SuppressWarnings("unchecked")
437             final Iterable<PathArgument> immutableArguments = (Iterable<PathArgument>) pathArguments;
438             return internalCreate(immutableArguments);
439         } else {
440             return internalCreate(ImmutableList.copyOf(pathArguments));
441         }
442     }
443
444     /**
445      * Create an instance identifier for a very specific object type.
446      *
447      * For example
448      * <pre>
449      *      new InstanceIdentifier(Nodes.class)
450      * </pre>
451      * would create an InstanceIdentifier for an object of type Nodes
452      *
453      * @param type The type of the object which this instance identifier represents
454      * @return InstanceIdentifier instance
455      */
456     @SuppressWarnings("unchecked")
457     public static <T extends DataObject> InstanceIdentifier<T> create(final Class<T> type) {
458         return (InstanceIdentifier<T>) create(Collections.<PathArgument> singletonList(new Item<>(type)));
459     }
460
461     /**
462      * Return the key associated with the last component of the specified identifier.
463      *
464      * @param id instance identifier
465      * @return key associated with the last component
466      */
467     public static <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K keyOf(final InstanceIdentifier<N> id) {
468         @SuppressWarnings("unchecked")
469         final K ret = ((KeyedInstanceIdentifier<N, K>)id).getKey();
470         return ret;
471     }
472
473     @SuppressWarnings({ "unchecked", "rawtypes" })
474     static InstanceIdentifier<?> trustedCreate(final PathArgument arg, final Iterable<PathArgument> pathArguments, final int hash, boolean wildcarded) {
475         if (Identifiable.class.isAssignableFrom(arg.getType()) && !(wildcarded)) {
476             Identifier<?> key = null;
477             if (arg instanceof IdentifiableItem<?, ?>) {
478                 key = ((IdentifiableItem<?, ?>)arg).key;
479             } else {
480                 wildcarded = true;
481             }
482
483             return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key);
484         } else {
485             return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
486         }
487     }
488
489     /**
490      * Path argument of {@link InstanceIdentifier}.
491      * <p>
492      * Interface which implementations are used as path components of the
493      * path in overall data tree.
494      */
495     public interface PathArgument {
496         Class<? extends DataObject> getType();
497     }
498
499     private static abstract class AbstractPathArgument<T extends DataObject> implements PathArgument {
500         private final Class<T> type;
501
502         protected AbstractPathArgument(final Class<T> type) {
503             this.type = Preconditions.checkNotNull(type, "Type may not be null.");
504         }
505
506         @Override
507         public final Class<T> getType() {
508             return type;
509         }
510
511         @Override
512         public int hashCode() {
513             final int prime = 31;
514             int result = 1;
515             result = prime * result + ((type == null) ? 0 : type.hashCode());
516             return result;
517         }
518
519         @Override
520         public boolean equals(final Object obj) {
521             if (this == obj) {
522                 return true;
523             }
524             if (obj == null) {
525                 return false;
526             }
527             if (getClass() != obj.getClass()) {
528                 return false;
529             }
530             final AbstractPathArgument<?> other = (AbstractPathArgument<?>) obj;
531             if (type == null) {
532                 if (other.type != null) {
533                     return false;
534                 }
535             } else if (!type.equals(other.type)) {
536                 return false;
537             }
538             return true;
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         public Item(final Class<T> type) {
550             super(type);
551         }
552
553         @Override
554         public String toString() {
555             return getType().getName();
556         }
557     }
558
559     /**
560      * An IdentifiableItem represents a object that is usually present in a collection and can be identified uniquely
561      * by a key. In YANG terms this would probably represent an item in a list.
562      *
563      * @param <I> An object that is identifiable by an identifier
564      * @param <T> The identifier of the object
565      */
566     public static final class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>> extends AbstractPathArgument<I> {
567         private final T key;
568
569         public IdentifiableItem(final Class<I> type, final T key) {
570             super(type);
571             this.key = Preconditions.checkNotNull(key, "Key may not be null.");
572         }
573
574         public T getKey() {
575             return this.key;
576         }
577
578         @Override
579         public boolean equals(final Object obj) {
580             return super.equals(obj) && obj.hashCode() == hashCode() && key.equals(((IdentifiableItem<?, ?>) obj).getKey());
581         }
582
583         @Override
584         public int hashCode() {
585             return key.hashCode();
586         }
587
588         @Override
589         public String toString() {
590             return getType().getName() + "[key=" + key + "]";
591         }
592     }
593
594
595     public interface InstanceIdentifierBuilder<T extends DataObject> extends Builder<InstanceIdentifier<T>> {
596         /**
597          * Append the specified container as a child of the current InstanceIdentifier referenced by the builder.
598          *
599          * This method should be used when you want to build an instance identifier by appending top-level
600          * elements
601          *
602          * Example,
603          * <pre>
604          *     InstanceIdentifier.builder().child(Nodes.class).build();
605          *
606          * </pre>
607          *
608          * NOTE :- The above example is only for illustration purposes InstanceIdentifier.builder() has been deprecated
609          * and should not be used. Use InstanceIdentifier.builder(Nodes.class) instead
610          *
611          * @param container
612          * @param <N>
613          * @return
614          */
615         <N extends ChildOf<? super T>> InstanceIdentifierBuilder<N> child(
616                 Class<N> container);
617
618         /**
619          * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder.
620          *
621          * This method should be used when you want to build an instance identifier by appending a specific list element
622          * to the identifier
623          *
624          * @param listItem
625          * @param listKey
626          * @param <N>
627          * @param <K>
628          * @return
629          */
630         <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> InstanceIdentifierBuilder<N> child(
631                 Class<N> listItem, K listKey);
632
633         /**
634          * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
635          * the builder
636          *
637          * @param container
638          * @param <N>
639          * @return
640          */
641         <N extends DataObject & Augmentation<? super T>> InstanceIdentifierBuilder<N> augmentation(
642                 Class<N> container);
643
644         /**
645          * Build the instance identifier.
646          *
647          * @return
648          */
649         InstanceIdentifier<T> build();
650     }
651 }