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;
17 import java.util.Collections;
18 import java.util.Iterator;
19 import java.util.List;
21 import org.opendaylight.yangtools.concepts.Builder;
22 import org.opendaylight.yangtools.concepts.Immutable;
23 import org.opendaylight.yangtools.concepts.Path;
24 import org.opendaylight.yangtools.util.HashCodeBuilder;
28 * This instance identifier uniquely identifies a specific DataObject in the data tree modeled by YANG.
30 * For Example let's say you were trying to refer to a node in inventory which was modeled in YANG as follows,
33 * module opendaylight-inventory {
39 * ext:context-instance "node-context";
48 * You could create an instance identifier as follows to get to a node with id "openflow:1"
50 * InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
52 * This would be the same as using a path like so, "/nodes/node/openflow:1" to refer to the openflow:1 node
55 public class InstanceIdentifier<T extends DataObject> implements Path<InstanceIdentifier<? extends DataObject>>, Immutable {
57 * Protected to differentiate internal and external access. Internal
58 * access is required never to modify the contents. References passed
59 * to outside entities have to be wrapped in an unmodifiable view.
61 protected final Iterable<PathArgument> pathArguments;
62 private final Class<T> targetType;
63 private final boolean wildcarded;
64 private final int hash;
66 InstanceIdentifier(final Class<T> type, final Iterable<PathArgument> pathArguments, final boolean wildcarded, final int hash) {
67 this.pathArguments = Preconditions.checkNotNull(pathArguments);
68 this.targetType = Preconditions.checkNotNull(type);
69 this.wildcarded = wildcarded;
74 * Return the type of data which this InstanceIdentifier identifies.
78 public final Class<T> getTargetType() {
83 * Return the path argument chain which makes up this instance identifier.
85 * @return Path argument chain. Immutable and does not contain nulls.
87 public final Iterable<PathArgument> getPathArguments() {
88 return Iterables.unmodifiableIterable(pathArguments);
92 * Check whether an instance identifier contains any wildcards. A wildcard
93 * is an path argument which has a null key.
95 * @return @true if any of the path arguments has a null key.
97 public final boolean isWildcarded() {
102 public final int hashCode() {
107 public final boolean equals(final Object obj) {
114 if (getClass() != obj.getClass()) {
118 final InstanceIdentifier<?> other = (InstanceIdentifier<?>) obj;
119 if (pathArguments == other.pathArguments) {
124 * We could now just go and compare the pathArguments, but that
125 * can be potentially expensive. Let's try to avoid that by
126 * checking various things that we have cached from pathArguments
127 * and trying to prove the identifiers are *not* equal.
129 if (hash != other.hash) {
132 if (wildcarded != other.wildcarded) {
135 if (targetType != other.targetType) {
138 if (fastNonEqual(other)) {
142 // Everything checks out so far, so we have to do a full equals
143 return Iterables.elementsEqual(pathArguments, other.pathArguments);
147 * Perform class-specific fast checks for non-equality. This allows
148 * subclasses to avoid iterating over the pathArguments by performing
149 * quick checks on their specific fields.
151 * @param other The other identifier, guaranteed to be the same class
152 * @return @true if the other identifier cannot be equal to this one.
154 protected boolean fastNonEqual(final InstanceIdentifier<?> other) {
159 public final String toString() {
160 return addToStringAttributes(Objects.toStringHelper(this)).toString();
164 * Add class-specific toString attributes.
166 * @param toStringHelper ToStringHelper instance
167 * @return ToStringHelper instance which was passed in
169 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
170 return toStringHelper.add("targetType", targetType).add("path", Iterables.toString(getPathArguments()));
174 * Return an instance identifier trimmed at the first occurrence of a
175 * specific component type.
177 * For example let's say an instance identifier was built like so,
179 * identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
182 * And you wanted to obtain the Instance identifier which represented Nodes you would do it like so,
185 * identifier.firstIdentifierOf(Nodes.class)
188 * @param type component type
189 * @return trimmed instance identifier, or null if the component type
192 public final <I extends DataObject> InstanceIdentifier<I> firstIdentifierOf(final Class<I> type) {
194 for (final PathArgument a : getPathArguments()) {
195 if (type.equals(a.getType())) {
196 @SuppressWarnings("unchecked")
197 final InstanceIdentifier<I> ret = (InstanceIdentifier<I>) internalCreate(Iterables.limit(getPathArguments(), i));
208 * Return the key associated with the first component of specified type in
211 * @param listItem component type
212 * @param listKey component key type
213 * @return key associated with the component, or null if the component type
216 public final <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K firstKeyOf(final Class<N> listItem, final Class<K> listKey) {
217 for (final PathArgument i : getPathArguments()) {
218 if (listItem.equals(i.getType())) {
219 @SuppressWarnings("unchecked")
220 final K ret = ((IdentifiableItem<N, K>)i).getKey();
229 * Check whether an identifier is contained in this identifier. This is a strict subtree check, which requires all
230 * PathArguments to match exactly, e.g.
233 * The contains method checks if the other identifier is fully contained within the current identifier. It does this
234 * by looking at only the types of the path arguments and not by comparing the path arguments themselves.
236 * To illustrate here is an example which explains the working of this API.
238 * Let's say you have two instance identifiers as follows,
240 * this = /nodes/node/openflow:1
241 * other = /nodes/node/openflow:2
243 * then this.contains(other) will return false.
249 public final boolean contains(final InstanceIdentifier<? extends DataObject> other) {
250 Preconditions.checkNotNull(other, "other should not be null");
252 final Iterator<?> lit = pathArguments.iterator();
253 final Iterator<?> oit = other.pathArguments.iterator();
255 while (lit.hasNext()) {
256 if (!oit.hasNext()) {
260 if (!lit.next().equals(oit.next())) {
269 * Check whether this instance identifier contains the other identifier after wildcard expansion. This is similar
270 * to {@link #contains(InstanceIdentifier)}, with the exception that a wildcards are assumed to match the their
271 * non-wildcarded PathArgument counterpart.
273 * @param other Identifier which should be checked for inclusion.
274 * @return @true if this identifier contains the other object
276 public final boolean containsWildcarded(final InstanceIdentifier<?> other) {
277 Preconditions.checkNotNull(other, "other should not be null");
279 final Iterator<PathArgument> lit = pathArguments.iterator();
280 final Iterator<PathArgument> oit = other.pathArguments.iterator();
282 while (lit.hasNext()) {
283 if (!oit.hasNext()) {
287 final PathArgument la = lit.next();
288 final PathArgument oa = oit.next();
290 if (!la.getType().equals(oa.getType())) {
293 if (la instanceof IdentifiableItem<?, ?> && oa instanceof IdentifiableItem<?, ?> && !la.equals(oa)) {
302 * Create a builder rooted at this key.
304 * @return A builder instance
306 public InstanceIdentifierBuilder<T> builder() {
307 return new InstanceIdentifierBuilderImpl<T>(new Item<T>(targetType), pathArguments, hash, isWildcarded());
310 private InstanceIdentifier<?> childIdentifier(final PathArgument arg) {
311 return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)), HashCodeBuilder.nextHashCode(hash, arg), isWildcarded());
314 @SuppressWarnings("unchecked")
315 public final <N extends ChildOf<? super T>> InstanceIdentifier<N> child(final Class<N> container) {
316 final PathArgument arg = new Item<>(container);
317 return (InstanceIdentifier<N>) childIdentifier(arg);
320 @SuppressWarnings("unchecked")
321 public final <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> KeyedInstanceIdentifier<N, K> child(
322 final Class<N> listItem, final K listKey) {
323 final PathArgument arg = new IdentifiableItem<>(listItem, listKey);
324 return (KeyedInstanceIdentifier<N, K>) childIdentifier(arg);
327 @SuppressWarnings("unchecked")
328 public final <N extends DataObject & Augmentation<? super T>> InstanceIdentifier<N> augmentation(
329 final Class<N> container) {
330 final PathArgument arg = new Item<>(container);
331 return (InstanceIdentifier<N>) childIdentifier(arg);
335 private List<PathArgument> legacyCache;
338 * @deprecated Use {@link #getPathArguments()} instead.
341 public final List<PathArgument> getPath() {
342 if (legacyCache == null) {
343 legacyCache = ImmutableList.<PathArgument>copyOf(getPathArguments());
350 * Create a new InstanceIdentifierBuilder given a base InstanceIdentifier
356 * @deprecated Use {@link #builder()} instead.
359 public static <T extends DataObject> InstanceIdentifierBuilder<T> builder(final InstanceIdentifier<T> base) {
360 return base.builder();
364 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container
370 public static <T extends ChildOf<? extends DataRoot>> InstanceIdentifierBuilder<T> builder(final Class<T> container) {
371 return new InstanceIdentifierBuilderImpl<T>().addNode(container);
375 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an IdentifiableItem
383 public static <N extends Identifiable<K> & ChildOf<? extends DataRoot>, K extends Identifier<N>> InstanceIdentifierBuilder<N> builder(
384 final Class<N> listItem, final K listKey) {
385 return new InstanceIdentifierBuilderImpl<N>().addNode(listItem, listKey);
389 * Create an instance identifier for a very specific object type. This method
390 * implements {@link #create(Iterable)} semantics, except it is used by internal
391 * callers, which have assured that the argument is an immutable Iterable.
394 * @param pathArguments The path to a specific node in the data tree
395 * @return InstanceIdentifier instance
396 * @throws IllegalArgumentException if pathArguments is empty or
397 * contains a null element.
399 private static InstanceIdentifier<?> internalCreate(final Iterable<PathArgument> pathArguments) {
400 final Iterator<? extends PathArgument> it = Preconditions.checkNotNull(pathArguments, "pathArguments may not be null").iterator();
401 final HashCodeBuilder<PathArgument> hashBuilder = new HashCodeBuilder<>();
402 boolean wildcard = false;
403 PathArgument a = null;
405 while (it.hasNext()) {
407 Preconditions.checkArgument(a != null, "pathArguments may not contain null elements");
409 // TODO: sanity check ChildOf<>;
410 hashBuilder.addArgument(a);
412 if (Identifiable.class.isAssignableFrom(a.getType()) && !(a instanceof IdentifiableItem<?, ?>)) {
416 Preconditions.checkArgument(a != null, "pathArguments may not be empty");
418 return trustedCreate(a, pathArguments, hashBuilder.toInstance(), wildcard);
422 * Create an instance identifier for a very specific object type.
426 * List<PathArgument> path = Arrays.asList(new Item(Nodes.class))
427 * new InstanceIdentifier(path);
430 * @param pathArguments The path to a specific node in the data tree
431 * @return InstanceIdentifier instance
432 * @throws IllegalArgumentException if pathArguments is empty or
433 * contains a null element.
435 public static InstanceIdentifier<?> create(final Iterable<? extends PathArgument> pathArguments) {
436 if (pathArguments instanceof ImmutableCollection<?>) {
437 @SuppressWarnings("unchecked")
438 final Iterable<PathArgument> immutableArguments = (Iterable<PathArgument>) pathArguments;
439 return internalCreate(immutableArguments);
441 return internalCreate(ImmutableList.copyOf(pathArguments));
446 * Create an instance identifier for a very specific object type.
450 * new InstanceIdentifier(Nodes.class)
452 * would create an InstanceIdentifier for an object of type Nodes
454 * @param type The type of the object which this instance identifier represents
455 * @return InstanceIdentifier instance
457 @SuppressWarnings("unchecked")
458 public static <T extends DataObject> InstanceIdentifier<T> create(final Class<T> type) {
459 return (InstanceIdentifier<T>) create(Collections.<PathArgument> singletonList(new Item<>(type)));
463 * Return the key associated with the last component of the specified identifier.
465 * @param id instance identifier
466 * @return key associated with the last component
468 public static <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K keyOf(final InstanceIdentifier<N> id) {
469 @SuppressWarnings("unchecked")
470 final K ret = ((KeyedInstanceIdentifier<N, K>)id).getKey();
474 @SuppressWarnings({ "unchecked", "rawtypes" })
475 static InstanceIdentifier<?> trustedCreate(final PathArgument arg, final Iterable<PathArgument> pathArguments, final int hash, boolean wildcarded) {
476 if (Identifiable.class.isAssignableFrom(arg.getType()) && !(wildcarded)) {
477 Identifier<?> key = null;
478 if (arg instanceof IdentifiableItem<?, ?>) {
479 key = ((IdentifiableItem<?, ?>)arg).key;
484 return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key);
486 return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
491 * Path argument of {@link InstanceIdentifier}.
493 * Interface which implementations are used as path components of the
494 * path in overall data tree.
496 public interface PathArgument extends Comparable<PathArgument> {
497 Class<? extends DataObject> getType();
500 private static abstract class AbstractPathArgument<T extends DataObject> implements PathArgument {
501 private final Class<T> type;
503 protected AbstractPathArgument(final Class<T> type) {
504 this.type = Preconditions.checkNotNull(type, "Type may not be null.");
508 public final Class<T> getType() {
513 public int hashCode() {
514 return type.hashCode();
518 public boolean equals(final Object obj) {
525 if (getClass() != obj.getClass()) {
528 final AbstractPathArgument<?> other = (AbstractPathArgument<?>) obj;
529 return type.equals(other.type);
533 public int compareTo(final PathArgument arg) {
534 return type.getCanonicalName().compareTo(arg.getType().getCanonicalName());
539 * An Item represents an object that probably is only one of it's kind. For example a Nodes object is only one of
540 * a kind. In YANG terms this would probably represent a container.
544 public static final class Item<T extends DataObject> extends AbstractPathArgument<T> {
545 public Item(final Class<T> type) {
550 public String toString() {
551 return getType().getName();
556 * An IdentifiableItem represents a object that is usually present in a collection and can be identified uniquely
557 * by a key. In YANG terms this would probably represent an item in a list.
559 * @param <I> An object that is identifiable by an identifier
560 * @param <T> The identifier of the object
562 public static final class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>> extends AbstractPathArgument<I> {
565 public IdentifiableItem(final Class<I> type, final T key) {
567 this.key = Preconditions.checkNotNull(key, "Key may not be null.");
575 public boolean equals(final Object obj) {
576 return super.equals(obj) && key.equals(((IdentifiableItem<?, ?>) obj).getKey());
580 public int hashCode() {
581 return super.hashCode() * 31 + key.hashCode();
585 public String toString() {
586 return getType().getName() + "[key=" + key + "]";
591 public interface InstanceIdentifierBuilder<T extends DataObject> extends Builder<InstanceIdentifier<T>> {
593 * Append the specified container as a child of the current InstanceIdentifier referenced by the builder.
595 * This method should be used when you want to build an instance identifier by appending top-level
600 * InstanceIdentifier.builder().child(Nodes.class).build();
604 * NOTE :- The above example is only for illustration purposes InstanceIdentifier.builder() has been deprecated
605 * and should not be used. Use InstanceIdentifier.builder(Nodes.class) instead
611 <N extends ChildOf<? super T>> InstanceIdentifierBuilder<N> child(
615 * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder.
617 * This method should be used when you want to build an instance identifier by appending a specific list element
626 <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> InstanceIdentifierBuilder<N> child(
627 Class<N> listItem, K listKey);
630 * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
637 <N extends DataObject & Augmentation<? super T>> InstanceIdentifierBuilder<N> augmentation(
641 * Build the instance identifier.
645 InstanceIdentifier<T> build();