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 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;
25 * This instance identifier uniquely identifies a specific DataObject in the data tree modeled by YANG.
27 * For Example let's say you were trying to refer to a node in inventory which was modeled in YANG as follows,
30 * module opendaylight-inventory {
36 * ext:context-instance "node-context";
45 * You could create an instance identifier as follows to get to a node with id "openflow:1"
47 * InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
49 * This would be the same as using a path like so, "/nodes/node/openflow:1" to refer to the openflow:1 node
52 public class InstanceIdentifier<T extends DataObject> implements Path<InstanceIdentifier<? extends DataObject>>, Immutable {
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.
58 protected final Iterable<PathArgument> pathArguments;
59 private final Class<T> targetType;
60 private final boolean wildcarded;
61 private final int hash;
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;
71 * Return the type of data which this InstanceIdentifier identifies.
75 public final Class<T> getTargetType() {
80 * Return the path argument chain which makes up this instance identifier.
82 * @return Path argument chain. Immutable and does not contain nulls.
84 public final Iterable<PathArgument> getPathArguments() {
85 return Iterables.unmodifiableIterable(pathArguments);
89 * Check whether an instance identifier contains any wildcards. A wildcard
90 * is an path argument which has a null key.
92 * @return @true if any of the path arguments has a null key.
94 public final boolean isWildcarded() {
99 public final int hashCode() {
104 public final boolean equals(final Object obj) {
111 if (getClass() != obj.getClass()) {
115 final InstanceIdentifier<?> other = (InstanceIdentifier<?>) obj;
116 if (pathArguments == other.pathArguments) {
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.
126 if (hash != other.hash) {
129 if (wildcarded != other.wildcarded) {
132 if (targetType != other.targetType) {
135 if (fastNonEqual(other)) {
139 // Everything checks out so far, so we have to do a full equals
140 return Iterables.elementsEqual(pathArguments, other.pathArguments);
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.
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.
151 protected boolean fastNonEqual(final InstanceIdentifier<?> other) {
156 public final String toString() {
157 return addToStringAttributes(Objects.toStringHelper(this)).toString();
161 * Add class-specific toString attributes.
163 * @param toStringHelper ToStringHelper instance
164 * @return ToStringHelper instance which was passed in
166 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
167 return toStringHelper.add("targetType", targetType).add("path", Iterables.toString(getPathArguments()));
171 * Return an instance identifier trimmed at the first occurrence of a
172 * specific component type.
174 * For example let's say an instance identifier was built like so,
176 * identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
179 * And you wanted to obtain the Instance identifier which represented Nodes you would do it like so,
182 * identifier.firstIdentifierOf(Nodes.class)
185 * @param type component type
186 * @return trimmed instance identifier, or null if the component type
189 public final <I extends DataObject> InstanceIdentifier<I> firstIdentifierOf(final Class<I> type) {
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));
205 * Return the key associated with the first component of specified type in
208 * @param listItem component type
209 * @param listKey component key type
210 * @return key associated with the component, or null if the component type
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();
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.
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.
233 * To illustrate here is an example which explains the working of this API.
235 * Let's say you have two instance identifiers as follows,
237 * this = /nodes/node/openflow:1
238 * other = /nodes/node/openflow:2
240 * then this.contains(other) will return false.
246 public final boolean contains(final InstanceIdentifier<? extends DataObject> other) {
247 Preconditions.checkNotNull(other, "other should not be null");
249 final Iterator<?> lit = pathArguments.iterator();
250 final Iterator<?> oit = other.pathArguments.iterator();
252 while (lit.hasNext()) {
253 if (!oit.hasNext()) {
257 if (!lit.next().equals(oit.next())) {
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.
270 * @param other Identifier which should be checked for inclusion.
271 * @return @true if this identifier contains the other object
273 public final boolean containsWildcarded(final InstanceIdentifier<?> other) {
274 Preconditions.checkNotNull(other, "other should not be null");
276 final Iterator<PathArgument> lit = pathArguments.iterator();
277 final Iterator<PathArgument> oit = other.pathArguments.iterator();
279 while (lit.hasNext()) {
280 if (!oit.hasNext()) {
284 final PathArgument la = lit.next();
285 final PathArgument oa = oit.next();
287 if (!la.getType().equals(oa.getType())) {
290 if (la instanceof IdentifiableItem<?, ?> && oa instanceof IdentifiableItem<?, ?> && !la.equals(oa)) {
299 * Create a builder rooted at this key.
301 * @return A builder instance
303 public InstanceIdentifierBuilder<T> builder() {
304 return new InstanceIdentifierBuilderImpl<T>(new Item<T>(targetType), pathArguments, hash, isWildcarded());
307 private InstanceIdentifier<?> childIdentifier(final PathArgument arg) {
308 return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)), HashCodeBuilder.nextHashCode(hash, arg), isWildcarded());
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);
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);
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);
332 private List<PathArgument> legacyCache;
335 * @deprecated Use {@link #getPathArguments()} instead.
338 public final List<PathArgument> getPath() {
339 if (legacyCache == null) {
340 legacyCache = ImmutableList.<PathArgument>copyOf(getPathArguments());
347 * Create a new InstanceIdentifierBuilder given a base InstanceIdentifier
353 * @deprecated Use {@link #builder()} instead.
356 public static <T extends DataObject> InstanceIdentifierBuilder<T> builder(final InstanceIdentifier<T> base) {
357 return base.builder();
361 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container
367 public static <T extends ChildOf<? extends DataRoot>> InstanceIdentifierBuilder<T> builder(final Class<T> container) {
368 return new InstanceIdentifierBuilderImpl<T>().addNode(container);
372 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an IdentifiableItem
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);
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.
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.
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;
402 while (it.hasNext()) {
404 Preconditions.checkArgument(a != null, "pathArguments may not contain null elements");
406 // TODO: sanity check ChildOf<>;
407 hashBuilder.addArgument(a);
409 if (Identifiable.class.isAssignableFrom(a.getType()) && !(a instanceof IdentifiableItem<?, ?>)) {
413 Preconditions.checkArgument(a != null, "pathArguments may not be empty");
415 return trustedCreate(a, pathArguments, hashBuilder.toInstance(), wildcard);
419 * Create an instance identifier for a very specific object type.
423 * List<PathArgument> path = Arrays.asList(new Item(Nodes.class))
424 * new InstanceIdentifier(path);
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.
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);
438 return internalCreate(ImmutableList.copyOf(pathArguments));
443 * Create an instance identifier for a very specific object type.
447 * new InstanceIdentifier(Nodes.class)
449 * would create an InstanceIdentifier for an object of type Nodes
451 * @param type The type of the object which this instance identifier represents
452 * @return InstanceIdentifier instance
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)));
460 * Return the key associated with the last component of the specified identifier.
462 * @param id instance identifier
463 * @return key associated with the last component
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();
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;
481 return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key);
483 return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
488 * Path argument of {@link InstanceIdentifier}.
490 * Interface which implementations are used as path components of the
491 * path in overall data tree.
493 public interface PathArgument extends Comparable<PathArgument> {
494 Class<? extends DataObject> getType();
497 private static abstract class AbstractPathArgument<T extends DataObject> implements PathArgument {
498 private final Class<T> type;
500 protected AbstractPathArgument(final Class<T> type) {
501 this.type = Preconditions.checkNotNull(type, "Type may not be null.");
505 public final Class<T> getType() {
510 public int hashCode() {
511 return type.hashCode();
515 public boolean equals(final Object obj) {
522 if (getClass() != obj.getClass()) {
525 final AbstractPathArgument<?> other = (AbstractPathArgument<?>) obj;
526 return type.equals(other.type);
530 public int compareTo(PathArgument arg) {
531 return type.getCanonicalName().compareTo(arg.getType().getCanonicalName());
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.
541 public static final class Item<T extends DataObject> extends AbstractPathArgument<T> {
542 public Item(final Class<T> type) {
547 public String toString() {
548 return getType().getName();
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.
556 * @param <I> An object that is identifiable by an identifier
557 * @param <T> The identifier of the object
559 public static final class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>> extends AbstractPathArgument<I> {
562 public IdentifiableItem(final Class<I> type, final T key) {
564 this.key = Preconditions.checkNotNull(key, "Key may not be null.");
572 public boolean equals(final Object obj) {
573 return super.equals(obj) && key.equals(((IdentifiableItem<?, ?>) obj).getKey());
577 public int hashCode() {
578 return super.hashCode() * 31 + key.hashCode();
582 public String toString() {
583 return getType().getName() + "[key=" + key + "]";
588 public interface InstanceIdentifierBuilder<T extends DataObject> extends Builder<InstanceIdentifier<T>> {
590 * Append the specified container as a child of the current InstanceIdentifier referenced by the builder.
592 * This method should be used when you want to build an instance identifier by appending top-level
597 * InstanceIdentifier.builder().child(Nodes.class).build();
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
608 <N extends ChildOf<? super T>> InstanceIdentifierBuilder<N> child(
612 * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder.
614 * This method should be used when you want to build an instance identifier by appending a specific list element
623 <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> InstanceIdentifierBuilder<N> child(
624 Class<N> listItem, K listKey);
627 * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
634 <N extends DataObject & Augmentation<? super T>> InstanceIdentifierBuilder<N> augmentation(
638 * Build the instance identifier.
642 InstanceIdentifier<T> build();