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 static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import com.google.common.collect.ImmutableCollection;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.Iterables;
18 import java.io.IOException;
19 import java.io.Serializable;
20 import java.lang.reflect.Field;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.Iterator;
24 import java.util.List;
25 import org.opendaylight.yangtools.concepts.Builder;
26 import org.opendaylight.yangtools.concepts.Immutable;
27 import org.opendaylight.yangtools.concepts.Path;
28 import org.opendaylight.yangtools.util.HashCodeBuilder;
31 * This instance identifier uniquely identifies a specific DataObject in the data tree modeled by YANG.
34 * For Example let's say you were trying to refer to a node in inventory which was modeled in YANG as follows,
38 * module opendaylight-inventory {
44 * ext:context-instance "node-context";
54 * You can create an instance identifier as follows to get to a node with id "openflow:1": {@code
55 * InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
59 * This would be the same as using a path like so, "/nodes/node/openflow:1" to refer to the openflow:1 node
61 public class InstanceIdentifier<T extends DataObject> implements Path<InstanceIdentifier<? extends DataObject>>,
62 Immutable, Serializable {
63 private static final Field PATHARGUMENTS_FIELD;
64 private static final long serialVersionUID = 2L;
66 * Protected to differentiate internal and external access. Internal
67 * access is required never to modify the contents. References passed
68 * to outside entities have to be wrapped in an unmodifiable view.
70 protected final transient Iterable<PathArgument> pathArguments;
71 private final Class<T> targetType;
72 private final boolean wildcarded;
73 private final int hash;
78 f = InstanceIdentifier.class.getDeclaredField("pathArguments");
79 } catch (NoSuchFieldException | SecurityException e) {
80 throw new ExceptionInInitializerError(e);
82 f.setAccessible(true);
83 PATHARGUMENTS_FIELD = f;
86 InstanceIdentifier(final Class<T> type, final Iterable<PathArgument> pathArguments, final boolean wildcarded,
88 this.pathArguments = requireNonNull(pathArguments);
89 this.targetType = requireNonNull(type);
90 this.wildcarded = wildcarded;
95 * Return the type of data which this InstanceIdentifier identifies.
99 public final Class<T> getTargetType() {
104 * Return the path argument chain which makes up this instance identifier.
106 * @return Path argument chain. Immutable and does not contain nulls.
108 public final Iterable<PathArgument> getPathArguments() {
109 return Iterables.unmodifiableIterable(pathArguments);
113 * Check whether an instance identifier contains any wildcards. A wildcard is an path argument which has a null key.
115 * @return true if any of the path arguments has a null key.
117 public final boolean isWildcarded() {
122 public final int hashCode() {
127 public final boolean equals(final Object obj) {
134 if (getClass() != obj.getClass()) {
138 final InstanceIdentifier<?> other = (InstanceIdentifier<?>) obj;
139 if (pathArguments == other.pathArguments) {
144 * We could now just go and compare the pathArguments, but that
145 * can be potentially expensive. Let's try to avoid that by
146 * checking various things that we have cached from pathArguments
147 * and trying to prove the identifiers are *not* equal.
149 if (hash != other.hash) {
152 if (wildcarded != other.wildcarded) {
155 if (targetType != other.targetType) {
158 if (fastNonEqual(other)) {
162 // Everything checks out so far, so we have to do a full equals
163 return Iterables.elementsEqual(pathArguments, other.pathArguments);
167 * Perform class-specific fast checks for non-equality. This allows subclasses to avoid iterating over the
168 * pathArguments by performing quick checks on their specific fields.
170 * @param other The other identifier, guaranteed to be the same class
171 * @return true if the other identifier cannot be equal to this one.
173 protected boolean fastNonEqual(final InstanceIdentifier<?> other) {
178 public final String toString() {
179 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
183 * Add class-specific toString attributes.
185 * @param toStringHelper ToStringHelper instance
186 * @return ToStringHelper instance which was passed in
188 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
189 return toStringHelper.add("targetType", targetType).add("path", Iterables.toString(pathArguments));
193 * Return an instance identifier trimmed at the first occurrence of a specific component type.
196 * For example let's say an instance identifier was built like so,
198 * identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class,
199 * new NodeKey(new NodeId("openflow:1")).build();
203 * And you wanted to obtain the Instance identifier which represented Nodes you would do it like so,
207 * identifier.firstIdentifierOf(Nodes.class)
210 * @param type component type
211 * @return trimmed instance identifier, or null if the component type
214 public final <I extends DataObject> InstanceIdentifier<I> firstIdentifierOf(final Class<I> type) {
216 for (final PathArgument a : pathArguments) {
217 if (type.equals(a.getType())) {
218 @SuppressWarnings("unchecked")
219 final InstanceIdentifier<I> ret = (InstanceIdentifier<I>) internalCreate(
220 Iterables.limit(pathArguments, count));
231 * Return the key associated with the first component of specified type in
234 * @param listItem component type
235 * @param listKey component key type
236 * @return key associated with the component, or null if the component type
239 * @deprecated Use {@link #firstKeyOf(Class)} instead.
242 public final <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K firstKeyOf(final Class<N> listItem,
243 final Class<K> listKey) {
244 return firstKeyOf(listItem);
248 * Return the key associated with the first component of specified type in
251 * @param listItem component type
252 * @return key associated with the component, or null if the component type
255 public final <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K firstKeyOf(
256 final Class<N> listItem) {
257 for (final PathArgument i : pathArguments) {
258 if (listItem.equals(i.getType())) {
259 @SuppressWarnings("unchecked")
260 final K ret = ((IdentifiableItem<N, K>)i).getKey();
269 * Check whether an identifier is contained in this identifier. This is a strict subtree check, which requires all
270 * PathArguments to match exactly.
273 * The contains method checks if the other identifier is fully contained within the current identifier. It does this
274 * by looking at only the types of the path arguments and not by comparing the path arguments themselves.
277 * To illustrate here is an example which explains the working of this API. Let's say you have two instance
278 * identifiers as follows:
280 * this = /nodes/node/openflow:1
281 * other = /nodes/node/openflow:2
283 * then this.contains(other) will return false.
285 * @param other Potentially-container instance identifier
286 * @return True if the specified identifier is contained in this identifier.
289 public final boolean contains(final InstanceIdentifier<? extends DataObject> other) {
290 requireNonNull(other, "other should not be null");
292 final Iterator<?> lit = pathArguments.iterator();
293 final Iterator<?> oit = other.pathArguments.iterator();
295 while (lit.hasNext()) {
296 if (!oit.hasNext()) {
300 if (!lit.next().equals(oit.next())) {
309 * Check whether this instance identifier contains the other identifier after wildcard expansion. This is similar
310 * to {@link #contains(InstanceIdentifier)}, with the exception that a wildcards are assumed to match the their
311 * non-wildcarded PathArgument counterpart.
313 * @param other Identifier which should be checked for inclusion.
314 * @return true if this identifier contains the other object
316 public final boolean containsWildcarded(final InstanceIdentifier<?> other) {
317 requireNonNull(other, "other should not be null");
319 final Iterator<PathArgument> lit = pathArguments.iterator();
320 final Iterator<PathArgument> oit = other.pathArguments.iterator();
322 while (lit.hasNext()) {
323 if (!oit.hasNext()) {
327 final PathArgument la = lit.next();
328 final PathArgument oa = oit.next();
330 if (!la.getType().equals(oa.getType())) {
333 if (la instanceof IdentifiableItem<?, ?> && oa instanceof IdentifiableItem<?, ?> && !la.equals(oa)) {
341 private <N extends DataObject> InstanceIdentifier<N> childIdentifier(final AbstractPathArgument<N> arg) {
342 return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)),
343 HashCodeBuilder.nextHashCode(hash, arg), isWildcarded());
347 * Create an InstanceIdentifier for a child container. This method is a more efficient equivalent to
348 * {@code builder().child(container).build()}.
350 * @param container Container to append
351 * @param <N> Container type
352 * @return An InstanceIdentifier.
353 * @throws NullPointerException if {@code container} is null
355 public final <N extends ChildOf<? super T>> InstanceIdentifier<N> child(final Class<N> container) {
356 return childIdentifier(new Item<>(container));
360 * Create an InstanceIdentifier for a child list item. This method is a more efficient equivalent to
361 * {@code builder().child(listItem, listKey).build()}.
363 * @param listItem List to append
364 * @param listKey List key
365 * @param <N> List type
366 * @param <K> Key type
367 * @return An InstanceIdentifier.
368 * @throws NullPointerException if any argument is null
370 @SuppressWarnings("unchecked")
371 public final <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> KeyedInstanceIdentifier<N, K>
372 child(final Class<N> listItem, final K listKey) {
373 return (KeyedInstanceIdentifier<N, K>) childIdentifier(new IdentifiableItem<>(listItem, listKey));
377 * Create an InstanceIdentifier for a child augmentation. This method is a more efficient equivalent to
378 * {@code builder().augmentation(container).build()}.
380 * @param container Container to append
381 * @param <N> Container type
382 * @return An InstanceIdentifier.
383 * @throws NullPointerException if {@code container} is null
385 public final <N extends DataObject & Augmentation<? super T>> InstanceIdentifier<N> augmentation(
386 final Class<N> container) {
387 return childIdentifier(new Item<>(container));
391 private List<PathArgument> legacyCache;
394 * Return the path as a list.
396 * @deprecated Use {@link #getPathArguments()} instead.
399 public final List<PathArgument> getPath() {
400 if (legacyCache == null) {
401 legacyCache = ImmutableList.<PathArgument>copyOf(pathArguments);
408 * Create a builder rooted at this key.
410 * @return A builder instance
412 public InstanceIdentifierBuilder<T> builder() {
413 return new InstanceIdentifierBuilderImpl<>(new Item<>(targetType), pathArguments, hash, isWildcarded());
417 * Create a new InstanceIdentifierBuilder given a base InstanceIdentifier.
419 * @deprecated Use {@link #builder()} instead.
422 public static <T extends DataObject> InstanceIdentifierBuilder<T> builder(final InstanceIdentifier<T> base) {
423 return base.builder();
427 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container.
429 * @param container Base container
430 * @param <T> Type of the container
431 * @return A new {@link InstanceIdentifierBuilder}
432 * @throws NullPointerException if {@code container} is null
434 public static <T extends ChildOf<? extends DataRoot>> InstanceIdentifierBuilder<T> builder(
435 final Class<T> container) {
436 return new InstanceIdentifierBuilderImpl<T>().addNode(container);
440 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an
441 * {@link IdentifiableItem}.
443 * @param listItem list item class
444 * @param listKey key value
445 * @param <N> List type
446 * @param <K> List key
447 * @return A new {@link InstanceIdentifierBuilder}
448 * @throws NullPointerException if any argument is null
450 public static <N extends Identifiable<K> & ChildOf<? extends DataRoot>,
451 K extends Identifier<N>> InstanceIdentifierBuilder<N> builder(final Class<N> listItem, final K listKey) {
452 return new InstanceIdentifierBuilderImpl<N>().addNode(listItem, listKey);
456 * Create an instance identifier for a very specific object type. This method implements {@link #create(Iterable)}
457 * semantics, except it is used by internal callers, which have assured that the argument is an immutable Iterable.
459 * @param pathArguments The path to a specific node in the data tree
460 * @return InstanceIdentifier instance
461 * @throws IllegalArgumentException if pathArguments is empty or contains a null element.
462 * @throws NullPointerException if {@code pathArguments} is null
464 private static InstanceIdentifier<?> internalCreate(final Iterable<PathArgument> pathArguments) {
465 final Iterator<? extends PathArgument> it = requireNonNull(pathArguments, "pathArguments may not be null")
467 final HashCodeBuilder<PathArgument> hashBuilder = new HashCodeBuilder<>();
468 boolean wildcard = false;
469 PathArgument arg = null;
471 while (it.hasNext()) {
473 checkArgument(arg != null, "pathArguments may not contain null elements");
475 // TODO: sanity check ChildOf<>;
476 hashBuilder.addArgument(arg);
478 if (Identifiable.class.isAssignableFrom(arg.getType()) && !(arg instanceof IdentifiableItem<?, ?>)) {
482 checkArgument(arg != null, "pathArguments may not be empty");
484 return trustedCreate(arg, pathArguments, hashBuilder.build(), wildcard);
488 * Create an instance identifier for a very specific object type.
493 * List<PathArgument> path = Arrays.asList(new Item(Nodes.class))
494 * new InstanceIdentifier(path);
497 * @param pathArguments The path to a specific node in the data tree
498 * @return InstanceIdentifier instance
499 * @throws IllegalArgumentException if pathArguments is empty or
500 * contains a null element.
502 public static InstanceIdentifier<?> create(final Iterable<? extends PathArgument> pathArguments) {
503 if (pathArguments instanceof ImmutableCollection<?>) {
504 @SuppressWarnings("unchecked")
505 final Iterable<PathArgument> immutableArguments = (Iterable<PathArgument>) pathArguments;
506 return internalCreate(immutableArguments);
509 return internalCreate(ImmutableList.copyOf(pathArguments));
513 * Create an instance identifier for a very specific object type.
518 * new InstanceIdentifier(Nodes.class)
520 * would create an InstanceIdentifier for an object of type Nodes
522 * @param type The type of the object which this instance identifier represents
523 * @return InstanceIdentifier instance
525 @SuppressWarnings("unchecked")
526 public static <T extends DataObject> InstanceIdentifier<T> create(final Class<T> type) {
527 return (InstanceIdentifier<T>) create(Collections.singletonList(new Item<>(type)));
531 * Return the key associated with the last component of the specified identifier.
533 * @param id instance identifier
534 * @return key associated with the last component
535 * @throws IllegalArgumentException if the supplied identifier type cannot have a key.
536 * @throws NullPointerException if id is null.
538 public static <N extends Identifiable<K> & DataObject, K extends Identifier<N>> K keyOf(
539 final InstanceIdentifier<N> id) {
541 checkArgument(id instanceof KeyedInstanceIdentifier, "%s does not have a key", id);
543 @SuppressWarnings("unchecked")
544 final K ret = ((KeyedInstanceIdentifier<N, K>)id).getKey();
548 @SuppressWarnings({ "unchecked", "rawtypes" })
549 static <N extends DataObject> InstanceIdentifier<N> trustedCreate(final PathArgument arg,
550 final Iterable<PathArgument> pathArguments, final int hash, boolean wildcarded) {
551 if (Identifiable.class.isAssignableFrom(arg.getType()) && !wildcarded) {
552 Identifier<?> key = null;
553 if (arg instanceof IdentifiableItem<?, ?>) {
554 key = ((IdentifiableItem<?, ?>)arg).key;
559 return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key);
562 return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
566 * Path argument of {@link InstanceIdentifier}. Interface which implementations are used as path components of the
567 * path in overall data tree.
569 public interface PathArgument extends Comparable<PathArgument> {
571 * Return the data object type backing this PathArgument.
573 * @return Data object type.
575 Class<? extends DataObject> getType();
578 private abstract static class AbstractPathArgument<T extends DataObject> implements PathArgument, Serializable {
579 private static final long serialVersionUID = 1L;
580 private final Class<T> type;
582 protected AbstractPathArgument(final Class<T> type) {
583 this.type = requireNonNull(type, "Type may not be null.");
587 public final Class<T> getType() {
592 public int hashCode() {
593 return type.hashCode();
597 public boolean equals(final Object obj) {
604 if (getClass() != obj.getClass()) {
607 final AbstractPathArgument<?> other = (AbstractPathArgument<?>) obj;
608 return type.equals(other.type);
612 public int compareTo(final PathArgument arg) {
613 return type.getCanonicalName().compareTo(arg.getType().getCanonicalName());
618 * An Item represents an object that probably is only one of it's kind. For example a Nodes object is only one of
619 * a kind. In YANG terms this would probably represent a container.
621 * @param <T> Item type
623 public static final class Item<T extends DataObject> extends AbstractPathArgument<T> {
624 private static final long serialVersionUID = 1L;
626 public Item(final Class<T> type) {
631 public String toString() {
632 return getType().getName();
637 * An IdentifiableItem represents a object that is usually present in a collection and can be identified uniquely
638 * by a key. In YANG terms this would probably represent an item in a list.
640 * @param <I> An object that is identifiable by an identifier
641 * @param <T> The identifier of the object
643 public static final class IdentifiableItem<I extends Identifiable<T> & DataObject, T extends Identifier<I>>
644 extends AbstractPathArgument<I> {
645 private static final long serialVersionUID = 1L;
648 public IdentifiableItem(final Class<I> type, final T key) {
650 this.key = requireNonNull(key, "Key may not be null.");
654 * Return the data object type backing this PathArgument.
656 * @return Data object type.
663 public boolean equals(final Object obj) {
664 return super.equals(obj) && key.equals(((IdentifiableItem<?, ?>) obj).getKey());
668 public int hashCode() {
669 return super.hashCode() * 31 + key.hashCode();
673 public String toString() {
674 return getType().getName() + "[key=" + key + "]";
678 public interface InstanceIdentifierBuilder<T extends DataObject> extends Builder<InstanceIdentifier<T>> {
680 * Append the specified container as a child of the current InstanceIdentifier referenced by the builder.
682 * This method should be used when you want to build an instance identifier by appending top-level
687 * InstanceIdentifier.builder().child(Nodes.class).build();
690 * NOTE :- The above example is only for illustration purposes InstanceIdentifier.builder() has been deprecated
691 * and should not be used. Use InstanceIdentifier.builder(Nodes.class) instead
693 * @param container Container to append
694 * @param <N> Container type
695 * @return this builder
696 * @throws NullPointerException if {@code container} is null
698 <N extends ChildOf<? super T>> InstanceIdentifierBuilder<N> child(Class<N> container);
701 * Append the specified listItem as a child of the current InstanceIdentifier referenced by the builder.
703 * This method should be used when you want to build an instance identifier by appending a specific list element
706 * @param listItem List to append
707 * @param listKey List key
708 * @param <N> List type
709 * @param <K> Key type
710 * @return this builder
711 * @throws NullPointerException if any argument is null
713 <N extends Identifiable<K> & ChildOf<? super T>, K extends Identifier<N>> InstanceIdentifierBuilder<N> child(
714 Class<N> listItem, K listKey);
717 * Build an identifier which refers to a specific augmentation of the current InstanceIdentifier referenced by
720 * @param container augmentation class
721 * @param <N> augmentation type
722 * @return this builder
723 * @throws NullPointerException if {@code container} is null
725 <N extends DataObject & Augmentation<? super T>> InstanceIdentifierBuilder<N> augmentation(Class<N> container);
728 * Build the instance identifier.
730 * @return Resulting instance identifier.
733 InstanceIdentifier<T> build();
736 private void writeObject(final java.io.ObjectOutputStream out) throws IOException {
737 out.defaultWriteObject();
738 out.writeInt(Iterables.size(pathArguments));
739 for (Object o : pathArguments) {
744 private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
745 in.defaultReadObject();
747 final int size = in.readInt();
748 final List<PathArgument> args = new ArrayList<>(size);
749 for (int i = 0; i < size; ++i) {
750 args.add((PathArgument) in.readObject());
754 PATHARGUMENTS_FIELD.set(this, ImmutableList.copyOf(args));
755 } catch (IllegalArgumentException | IllegalAccessException e) {
756 throw new IOException(e);