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;
22 import org.opendaylight.yangtools.util.HashCodeBuilder;
26 * This instance identifier uniquely identifies a specific DataObject in the data tree modeled by YANG.
28 * For Example let's say you were trying to refer to a node in inventory which was modeled in YANG as follows,
31 * module opendaylight-inventory {
37 * ext:context-instance "node-context";
46 * You could create an instance identifier as follows to get to a node with id "openflow:1"
48 * InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
50 * This would be the same as using a path like so, "/nodes/node/openflow:1" to refer to the openflow:1 node
53 public class InstanceIdentifier<T extends DataObject> implements Path<InstanceIdentifier<? extends DataObject>>, Immutable {
55 * Protected to differentiate internal and external access. Internal
56 * access is required never to modify the contents. References passed
57 * to outside entities have to be wrapped in an unmodifiable view.
59 protected final Iterable<PathArgument> pathArguments;
60 private final Class<T> targetType;
61 private final boolean wildcarded;
62 private final int hash;
64 InstanceIdentifier(final Class<T> type, final Iterable<PathArgument> pathArguments, final boolean wildcarded, final int hash) {
65 this.pathArguments = Preconditions.checkNotNull(pathArguments);
66 this.targetType = Preconditions.checkNotNull(type);
67 this.wildcarded = wildcarded;
72 * Return the type of data which this InstanceIdentifier identifies.
76 public final Class<T> getTargetType() {
81 * Return the path argument chain which makes up this instance identifier.
83 * @return Path argument chain. Immutable and does not contain nulls.
85 public final Iterable<PathArgument> getPathArguments() {
86 return Iterables.unmodifiableIterable(pathArguments);
90 * Check whether an instance identifier contains any wildcards. A wildcard
91 * is an path argument which has a null key.
93 * @return @true if any of the path arguments has a null key.
95 public final boolean isWildcarded() {
100 public final int hashCode() {
105 public final boolean equals(final Object obj) {
112 if (getClass() != obj.getClass()) {
116 final InstanceIdentifier<?> other = (InstanceIdentifier<?>) obj;
117 if (pathArguments == other.pathArguments) {
122 * We could now just go and compare the pathArguments, but that
123 * can be potentially expensive. Let's try to avoid that by
124 * checking various things that we have cached from pathArguments
125 * and trying to prove the identifiers are *not* equal.
127 if (hash != other.hash) {
130 if (wildcarded != other.wildcarded) {
133 if (targetType != other.targetType) {
136 if (fastNonEqual(other)) {
140 // Everything checks out so far, so we have to do a full equals
141 return Iterables.elementsEqual(pathArguments, other.pathArguments);
145 * Perform class-specific fast checks for non-equality. This allows
146 * subclasses to avoid iterating over the pathArguments by performing
147 * quick checks on their specific fields.
149 * @param other The other identifier, guaranteed to be the same class
150 * @return @true if the other identifier cannot be equal to this one.
152 protected boolean fastNonEqual(final InstanceIdentifier<?> other) {
157 public final String toString() {
158 return addToStringAttributes(Objects.toStringHelper(this)).toString();
162 * Add class-specific toString attributes.
164 * @param toStringHelper ToStringHelper instance
165 * @return ToStringHelper instance which was passed in
167 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
168 return toStringHelper.add("targetType", targetType).add("path", Iterables.toString(getPathArguments()));
172 * Return an instance identifier trimmed at the first occurrence of a
173 * specific component type.
175 * For example let's say an instance identifier was built like so,
177 * identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
180 * And you wanted to obtain the Instance identifier which represented Nodes you would do it like so,
183 * identifier.firstIdentifierOf(Nodes.class)
186 * @param type component type
187 * @return trimmed instance identifier, or null if the component type
190 public final <I extends DataObject> InstanceIdentifier<I> firstIdentifierOf(final Class<I> type) {
192 for (final PathArgument a : getPathArguments()) {
193 if (type.equals(a.getType())) {
194 @SuppressWarnings("unchecked")
195 final InstanceIdentifier<I> ret = (InstanceIdentifier<I>) internalCreate(Iterables.limit(getPathArguments(), i));
206 * Return the key associated with the first component of specified type in
209 * @param listItem component type
210 * @param listKey component key type
211 * @return key associated with the component, or null if the component type
214 public final <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K firstKeyOf(final Class<N> listItem, final Class<K> listKey) {
215 for (final PathArgument i : getPathArguments()) {
216 if (listItem.equals(i.getType())) {
217 @SuppressWarnings("unchecked")
218 final K ret = ((IdentifiableItem<N, K>)i).getKey();
227 * Check whether an identifier is contained in this identifier. This is a strict subtree check, which requires all
228 * PathArguments to match exactly, e.g.
231 * The contains method checks if the other identifier is fully contained within the current identifier. It does this
232 * by looking at only the types of the path arguments and not by comparing the path arguments themselves.
234 * To illustrate here is an example which explains the working of this API.
236 * Let's say you have two instance identifiers as follows,
238 * this = /nodes/node/openflow:1
239 * other = /nodes/node/openflow:2
241 * then this.contains(other) will return false.
247 public final boolean contains(final InstanceIdentifier<? extends DataObject> other) {
248 Preconditions.checkNotNull(other, "other should not be null");
250 final Iterator<?> lit = pathArguments.iterator();
251 final Iterator<?> oit = other.pathArguments.iterator();
253 while (lit.hasNext()) {
254 if (!oit.hasNext()) {
258 if (!lit.next().equals(oit.next())) {
267 * Check whether this instance identifier contains the other identifier after wildcard expansion. This is similar
268 * to {@link #contains(InstanceIdentifier)}, with the exception that a wildcards are assumed to match the their
269 * non-wildcarded PathArgument counterpart.
271 * @param other Identifier which should be checked for inclusion.
272 * @return @true if this identifier contains the other object
274 public final boolean containsWildcarded(final InstanceIdentifier<?> other) {
275 Preconditions.checkNotNull(other, "other should not be null");
277 final Iterator<PathArgument> lit = pathArguments.iterator();
278 final Iterator<PathArgument> oit = other.pathArguments.iterator();
280 while (lit.hasNext()) {
281 if (!oit.hasNext()) {
285 final PathArgument la = lit.next();
286 final PathArgument oa = oit.next();
288 if (!la.getType().equals(oa.getType())) {
291 if (la instanceof IdentifiableItem<?, ?> && oa instanceof IdentifiableItem<?, ?> && !la.equals(oa)) {
300 * Create a builder rooted at this key.
302 * @return A builder instance
304 public InstanceIdentifierBuilder<T> builder() {
305 return new InstanceIdentifierBuilderImpl<T>(new Item<T>(targetType), pathArguments, hash, isWildcarded());
308 private InstanceIdentifier<?> childIdentifier(final PathArgument arg) {
309 return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)), HashCodeBuilder.nextHashCode(hash, arg), isWildcarded());
312 @SuppressWarnings("unchecked")
313 public final <N extends ChildOf<? super T>> InstanceIdentifier<N> child(final Class<N> container) {
314 final PathArgument arg = new Item<>(container);
315 return (InstanceIdentifier<N>) childIdentifier(arg);
318 @SuppressWarnings("unchecked")
319 public final <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> InstanceIdentifier<N> child(
320 final Class<N> listItem, final K listKey) {
321 final PathArgument arg = new IdentifiableItem<>(listItem, listKey);
322 return (InstanceIdentifier<N>) childIdentifier(arg);
325 @SuppressWarnings("unchecked")
326 public final <N extends DataObject & Augmentation<? super T>> InstanceIdentifier<N> augmentation(
327 final Class<N> container) {
328 final PathArgument arg = new Item<>(container);
329 return (InstanceIdentifier<N>) childIdentifier(arg);
333 private List<PathArgument> legacyCache;
336 * @deprecated Use {@link #getPathArguments()} instead.
339 public final List<PathArgument> getPath() {
340 if (legacyCache == null) {
341 legacyCache = ImmutableList.<PathArgument>copyOf(getPathArguments());
348 * Create a new InstanceIdentifierBuilder given a base InstanceIdentifier
354 * @deprecated Use {@link #builder()} instead.
357 public static <T extends DataObject> InstanceIdentifierBuilder<T> builder(final InstanceIdentifier<T> base) {
358 return base.builder();
362 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container
368 public static <T extends ChildOf<? extends DataRoot>> InstanceIdentifierBuilder<T> builder(final Class<T> container) {
369 return new InstanceIdentifierBuilderImpl<T>().addNode(container);
373 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an IdentifiableItem
381 public static <N extends Identifiable<K> & ChildOf<? extends DataRoot>, K extends Identifier<N>> InstanceIdentifierBuilder<N> builder(
382 final Class<N> listItem, final K listKey) {
383 return new InstanceIdentifierBuilderImpl<N>().addNode(listItem, listKey);
387 * Create an instance identifier for a very specific object type. This method
388 * implements {@link #create(Iterable)} semantics, except it is used by internal
389 * callers, which have assured that the argument is an immutable Iterable.
392 * @param pathArguments The path to a specific node in the data tree
393 * @return InstanceIdentifier instance
394 * @throws IllegalArgumentException if pathArguments is empty or
395 * contains a null element.
397 private static InstanceIdentifier<?> internalCreate(final Iterable<PathArgument> pathArguments) {
398 final Iterator<? extends PathArgument> it = Preconditions.checkNotNull(pathArguments, "pathArguments may not be null").iterator();
399 final HashCodeBuilder<PathArgument> hashBuilder = new HashCodeBuilder<>();
400 boolean wildcard = false;
401 PathArgument a = null;
403 while (it.hasNext()) {
405 Preconditions.checkArgument(a != null, "pathArguments may not contain null elements");
407 // TODO: sanity check ChildOf<>;
408 hashBuilder.addArgument(a);
410 if (Identifiable.class.isAssignableFrom(a.getType()) && !(a instanceof IdentifiableItem<?, ?>)) {
414 Preconditions.checkArgument(a != null, "pathArguments may not be empty");
416 return trustedCreate(a, pathArguments, hashBuilder.toInstance(), wildcard);
420 * Create an instance identifier for a very specific object type.
424 * List<PathArgument> path = Arrays.asList(new Item(Nodes.class))
425 * new InstanceIdentifier(path);
428 * @param pathArguments The path to a specific node in the data tree
429 * @return InstanceIdentifier instance
430 * @throws IllegalArgumentException if pathArguments is empty or
431 * contains a null element.
433 public static InstanceIdentifier<?> create(final Iterable<? extends PathArgument> pathArguments) {
434 if (pathArguments instanceof ImmutableCollection<?>) {
435 @SuppressWarnings("unchecked")
436 final Iterable<PathArgument> immutableArguments = (Iterable<PathArgument>) pathArguments;
437 return internalCreate(immutableArguments);
439 return internalCreate(ImmutableList.copyOf(pathArguments));
444 * Create an instance identifier for a very specific object type.
448 * new InstanceIdentifier(Nodes.class)
450 * would create an InstanceIdentifier for an object of type Nodes
452 * @param type The type of the object which this instance identifier represents
453 * @return InstanceIdentifier instance
455 @SuppressWarnings("unchecked")
456 public static <T extends DataObject> InstanceIdentifier<T> create(final Class<T> type) {
457 return (InstanceIdentifier<T>) create(Collections.<PathArgument> singletonList(new Item<>(type)));
461 * Return the key associated with the last component of the specified identifier.
463 * @param id instance identifier
464 * @return key associated with the last component
466 public static <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K keyOf(final InstanceIdentifier<N> id) {
467 @SuppressWarnings("unchecked")
468 final K ret = ((KeyedInstanceIdentifier<N, K>)id).getKey();
472 @SuppressWarnings({ "unchecked", "rawtypes" })
473 static InstanceIdentifier<?> trustedCreate(final PathArgument arg, final Iterable<PathArgument> pathArguments, final int hash, boolean wildcarded) {
474 if (Identifiable.class.isAssignableFrom(arg.getType()) && !(wildcarded)) {
475 Identifier<?> key = null;
476 if (arg instanceof IdentifiableItem<?, ?>) {
477 key = ((IdentifiableItem<?, ?>)arg).key;
482 return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key);
484 return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
489 * Path argument of {@link InstanceIdentifier}.
491 * Interface which implementations are used as path components of the
492 * path in overall data tree.
494 public interface PathArgument extends Comparable<PathArgument> {
495 Class<? extends DataObject> getType();
498 private static abstract class AbstractPathArgument<T extends DataObject> implements PathArgument {
499 private final Class<T> type;
501 protected AbstractPathArgument(final Class<T> type) {
502 this.type = Preconditions.checkNotNull(type, "Type may not be null.");
506 public final Class<T> getType() {
511 public int hashCode() {
512 return type.hashCode();
516 public boolean equals(final Object obj) {
523 if (getClass() != obj.getClass()) {
526 final AbstractPathArgument<?> other = (AbstractPathArgument<?>) obj;
527 return type.equals(other.type);
531 public int compareTo(PathArgument arg) {
532 return type.getCanonicalName().compareTo(arg.getType().getCanonicalName());
537 * An Item represents an object that probably is only one of it's kind. For example a Nodes object is only one of
538 * a kind. In YANG terms this would probably represent a container.
542 public static final class Item<T extends DataObject> extends AbstractPathArgument<T> {
543 public Item(final Class<T> type) {
548 public String toString() {
549 return getType().getName();
554 * An IdentifiableItem represents a object that is usually present in a collection and can be identified uniquely
555 * by a key. In YANG terms this would probably represent an item in a list.
557 * @param <I> An object that is identifiable by an identifier
558 * @param <T> The identifier of the object
560 public static final class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>> extends AbstractPathArgument<I> {
563 public IdentifiableItem(final Class<I> type, final T key) {
565 this.key = Preconditions.checkNotNull(key, "Key may not be null.");
573 public boolean equals(final Object obj) {
574 return super.equals(obj) && key.equals(((IdentifiableItem<?, ?>) obj).getKey());
578 public int hashCode() {
579 return super.hashCode() * 31 + key.hashCode();
583 public String toString() {
584 return getType().getName() + "[key=" + key + "]";
589 public interface InstanceIdentifierBuilder<T extends DataObject> extends Builder<InstanceIdentifier<T>> {
591 * Append the specified container as a child of the current InstanceIdentifier referenced by the builder.
593 * This method should be used when you want to build an instance identifier by appending top-level
598 * InstanceIdentifier.builder().child(Nodes.class).build();
602 * NOTE :- The above example is only for illustration purposes InstanceIdentifier.builder() has been deprecated
603 * and should not be used. Use InstanceIdentifier.builder(Nodes.class) instead
609 <N extends ChildOf<? super T>> InstanceIdentifierBuilder<N> child(
613 * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder.
615 * This method should be used when you want to build an instance identifier by appending a specific list element
624 <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> InstanceIdentifierBuilder<N> child(
625 Class<N> listItem, K listKey);
628 * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
635 <N extends DataObject & Augmentation<? super T>> InstanceIdentifierBuilder<N> augmentation(
639 * Build the instance identifier.
643 InstanceIdentifier<T> build();