2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.binding;
10 import java.util.Collections;
11 import java.util.Iterator;
12 import java.util.List;
14 import org.opendaylight.yangtools.concepts.Builder;
15 import org.opendaylight.yangtools.concepts.Immutable;
16 import org.opendaylight.yangtools.concepts.Path;
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;
27 * This instance identifier uniquely identifies a specific DataObject in the data tree modeled by YANG.
29 * For Example let's say you were trying to refer to a node in inventory which was modeled in YANG as follows,
32 * module opendaylight-inventory {
38 * ext:context-instance "node-context";
47 * You could create an instance identifier as follows to get to a node with id "openflow:1"
49 * InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
51 * This would be the same as using a path like so, "/nodes/node/openflow:1" to refer to the openflow:1 node
54 public class InstanceIdentifier<T extends DataObject> implements Path<InstanceIdentifier<? extends DataObject>>, Immutable {
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.
60 protected final Iterable<PathArgument> pathArguments;
61 private final Class<T> targetType;
62 private final boolean wildcarded;
63 private final int hash;
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;
73 * Return the type of data which this InstanceIdentifier identifies.
77 public final Class<T> getTargetType() {
82 * Return the path argument chain which makes up this instance identifier.
84 * @return Path argument chain. Immutable and does not contain nulls.
86 public final Iterable<PathArgument> getPathArguments() {
87 return Iterables.unmodifiableIterable(pathArguments);
91 * Check whether an instance identifier contains any wildcards. A wildcard
92 * is an path argument which has a null key.
94 * @return @true if any of the path arguments has a null key.
96 public final boolean isWildcarded() {
101 public final int hashCode() {
106 public final boolean equals(final Object obj) {
113 if (getClass() != obj.getClass()) {
117 final InstanceIdentifier<?> other = (InstanceIdentifier<?>) obj;
118 if (pathArguments == other.pathArguments) {
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.
128 if (hash != other.hash) {
131 if (wildcarded != other.wildcarded) {
134 if (targetType != other.targetType) {
137 if (fastNonEqual(other)) {
141 // Everything checks out so far, so we have to do a full equals
142 return Iterables.elementsEqual(pathArguments, other.pathArguments);
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.
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.
153 protected boolean fastNonEqual(final InstanceIdentifier<?> other) {
158 public final String toString() {
159 return addToStringAttributes(Objects.toStringHelper(this)).toString();
163 * Add class-specific toString attributes.
165 * @param toStringHelper ToStringHelper instance
166 * @return ToStringHelper instance which was passed in
168 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
169 return toStringHelper.add("targetType", targetType).add("path", Iterables.toString(getPathArguments()));
173 * Return an instance identifier trimmed at the first occurrence of a
174 * specific component type.
176 * For example let's say an instance identifier was built like so,
178 * identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
181 * And you wanted to obtain the Instance identifier which represented Nodes you would do it like so,
184 * identifier.firstIdentifierOf(Nodes.class)
187 * @param type component type
188 * @return trimmed instance identifier, or null if the component type
191 public final <I extends DataObject> InstanceIdentifier<I> firstIdentifierOf(final Class<I> type) {
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));
207 * Return the key associated with the first component of specified type in
210 * @param listItem component type
211 * @param listKey component key type
212 * @return key associated with the component, or null if the component type
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();
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.
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.
235 * To illustrate here is an example which explains the working of this API.
237 * Let's say you have two instance identifiers as follows,
239 * this = /nodes/node/openflow:1
240 * other = /nodes/node/openflow:2
242 * then this.contains(other) will return false.
248 public final boolean contains(final InstanceIdentifier<? extends DataObject> other) {
249 Preconditions.checkNotNull(other, "other should not be null");
251 final Iterator<?> lit = pathArguments.iterator();
252 final Iterator<?> oit = other.pathArguments.iterator();
254 while (lit.hasNext()) {
255 if (!oit.hasNext()) {
259 if (!lit.next().equals(oit.next())) {
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.
272 * @param other Identifier which should be checked for inclusion.
273 * @return @true if this identifier contains the other object
275 public final boolean containsWildcarded(final InstanceIdentifier<?> other) {
276 Preconditions.checkNotNull(other, "other should not be null");
278 final Iterator<PathArgument> lit = pathArguments.iterator();
279 final Iterator<PathArgument> oit = other.pathArguments.iterator();
281 while (lit.hasNext()) {
282 if (!oit.hasNext()) {
286 final PathArgument la = lit.next();
287 final PathArgument oa = oit.next();
289 if (!la.getType().equals(oa.getType())) {
292 if (la instanceof IdentifiableItem<?, ?> && oa instanceof IdentifiableItem<?, ?> && !la.equals(oa)) {
301 * Create a builder rooted at this key.
303 * @return A builder instance
305 public InstanceIdentifierBuilder<T> builder() {
306 return new InstanceIdentifierBuilderImpl<T>(new Item<T>(targetType), pathArguments, hash, isWildcarded());
309 private InstanceIdentifier<?> childIdentifier(final PathArgument arg) {
310 return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)), HashCodeBuilder.nextHashCode(hash, arg), isWildcarded());
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);
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);
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);
334 private List<PathArgument> legacyCache;
337 * @deprecated Use {@link #getPathArguments()} instead.
340 public final List<PathArgument> getPath() {
341 if (legacyCache == null) {
342 legacyCache = ImmutableList.<PathArgument>copyOf(getPathArguments());
349 * Create a new InstanceIdentifierBuilder given a base InstanceIdentifier
355 * @deprecated Use {@link #builder()} instead.
358 public static <T extends DataObject> InstanceIdentifierBuilder<T> builder(final InstanceIdentifier<T> base) {
359 return base.builder();
363 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container
369 public static <T extends ChildOf<? extends DataRoot>> InstanceIdentifierBuilder<T> builder(final Class<T> container) {
370 return new InstanceIdentifierBuilderImpl<T>().addNode(container);
374 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an IdentifiableItem
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);
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.
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.
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;
404 while (it.hasNext()) {
406 Preconditions.checkArgument(a != null, "pathArguments may not contain null elements");
408 // TODO: sanity check ChildOf<>;
409 hashBuilder.addArgument(a);
411 if (Identifiable.class.isAssignableFrom(a.getType()) && !(a instanceof IdentifiableItem<?, ?>)) {
415 Preconditions.checkArgument(a != null, "pathArguments may not be empty");
417 return trustedCreate(a, pathArguments, hashBuilder.toInstance(), wildcard);
421 * Create an instance identifier for a very specific object type.
425 * List<PathArgument> path = Arrays.asList(new Item(Nodes.class))
426 * new InstanceIdentifier(path);
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.
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);
440 return internalCreate(ImmutableList.copyOf(pathArguments));
445 * Create an instance identifier for a very specific object type.
449 * new InstanceIdentifier(Nodes.class)
451 * would create an InstanceIdentifier for an object of type Nodes
453 * @param type The type of the object which this instance identifier represents
454 * @return InstanceIdentifier instance
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)));
462 * Return the key associated with the last component of the specified identifier.
464 * @param id instance identifier
465 * @return key associated with the last component
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();
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;
483 return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key);
485 return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
490 * Path argument of {@link InstanceIdentifier}.
492 * Interface which implementations are used as path components of the
493 * path in overall data tree.
495 public interface PathArgument {
496 Class<? extends DataObject> getType();
499 private static abstract class AbstractPathArgument<T extends DataObject> implements PathArgument {
500 private final Class<T> type;
502 protected AbstractPathArgument(final Class<T> type) {
503 this.type = Preconditions.checkNotNull(type, "Type may not be null.");
507 public final Class<T> getType() {
512 public int hashCode() {
513 return type.hashCode();
517 public boolean equals(final Object obj) {
524 if (getClass() != obj.getClass()) {
527 final AbstractPathArgument<?> other = (AbstractPathArgument<?>) obj;
528 return type.equals(other.type);
533 * An Item represents an object that probably is only one of it's kind. For example a Nodes object is only one of
534 * a kind. In YANG terms this would probably represent a container.
538 public static final class Item<T extends DataObject> extends AbstractPathArgument<T> {
539 public Item(final Class<T> type) {
544 public String toString() {
545 return getType().getName();
550 * An IdentifiableItem represents a object that is usually present in a collection and can be identified uniquely
551 * by a key. In YANG terms this would probably represent an item in a list.
553 * @param <I> An object that is identifiable by an identifier
554 * @param <T> The identifier of the object
556 public static final class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>> extends AbstractPathArgument<I> {
559 public IdentifiableItem(final Class<I> type, final T key) {
561 this.key = Preconditions.checkNotNull(key, "Key may not be null.");
569 public boolean equals(final Object obj) {
570 return super.equals(obj) && obj.hashCode() == hashCode() && key.equals(((IdentifiableItem<?, ?>) obj).getKey());
574 public int hashCode() {
575 return key.hashCode();
579 public String toString() {
580 return getType().getName() + "[key=" + key + "]";
585 public interface InstanceIdentifierBuilder<T extends DataObject> extends Builder<InstanceIdentifier<T>> {
587 * Append the specified container as a child of the current InstanceIdentifier referenced by the builder.
589 * This method should be used when you want to build an instance identifier by appending top-level
594 * InstanceIdentifier.builder().child(Nodes.class).build();
598 * NOTE :- The above example is only for illustration purposes InstanceIdentifier.builder() has been deprecated
599 * and should not be used. Use InstanceIdentifier.builder(Nodes.class) instead
605 <N extends ChildOf<? super T>> InstanceIdentifierBuilder<N> child(
609 * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder.
611 * This method should be used when you want to build an instance identifier by appending a specific list element
620 <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> InstanceIdentifierBuilder<N> child(
621 Class<N> listItem, K listKey);
624 * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
631 <N extends DataObject & Augmentation<? super T>> InstanceIdentifierBuilder<N> augmentation(
635 * Build the instance identifier.
639 InstanceIdentifier<T> build();