2 * Copyright (c) 2017 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
9 package org.opendaylight.mdsal.binding.javav2.spec.base;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.MoreObjects;
15 import com.google.common.base.MoreObjects.ToStringHelper;
16 import com.google.common.base.Preconditions;
17 import com.google.common.collect.ImmutableCollection;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.Iterables;
20 import java.io.IOException;
21 import java.io.Serializable;
22 import java.lang.reflect.Field;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.Iterator;
26 import java.util.List;
27 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation;
28 import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode;
29 import org.opendaylight.yangtools.concepts.Identifiable;
30 import org.opendaylight.yangtools.concepts.Immutable;
31 import org.opendaylight.yangtools.concepts.Path;
32 import org.opendaylight.yangtools.util.HashCodeBuilder;
36 * This instance identifier uniquely identifies a specific TreeNode in the data tree modeled by
39 * For Example let's say you were trying to refer to a node in inventory which was modeled in YANG
43 * module opendaylight-inventory {
49 * ext:context-instance "node-context";
58 * You could create an instance identifier as follows to get to a node with id "openflow:1"
60 * InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new
61 * NodeId("openflow:1")).build();
63 * This would be the same as using a path like so, "/nodes/node/openflow:1" to refer to the
68 public class InstanceIdentifier<T extends TreeNode> implements Path<InstanceIdentifier<? extends TreeNode>>, Immutable,
70 private static final Field PATHARGUMENTS_FIELD;
71 private static final long serialVersionUID = 2L;
73 * Protected to differentiate internal and external access. Internal
74 * access is required never to modify the contents. References passed
75 * to outside entities have to be wrapped in an unmodifiable view.
77 protected transient final Iterable<TreeArgument> pathArguments;
78 private final Class<T> targetType;
79 private final boolean wildcarded;
80 private final int hash;
85 f = InstanceIdentifier.class.getDeclaredField("pathArguments");
86 } catch (NoSuchFieldException | SecurityException e) {
87 throw new ExceptionInInitializerError(e);
89 f.setAccessible(true);
90 PATHARGUMENTS_FIELD = f;
93 InstanceIdentifier(final Class<T> type, final Iterable<TreeArgument> pathArguments, final boolean wildcarded, final int hash) {
94 this.pathArguments = requireNonNull(pathArguments);
95 this.targetType = requireNonNull(type);
96 this.wildcarded = wildcarded;
101 * Return the type of data which this InstanceIdentifier identifies.
103 * @return Target type
105 public final Class<T> getTargetType() {
110 * Return the path argument chain which makes up this instance identifier.
112 * @return Path argument chain. Immutable and does not contain nulls.
114 public final Iterable<TreeArgument> getPathArguments() {
115 return Iterables.unmodifiableIterable(pathArguments);
119 * Check whether an instance identifier contains any wildcards. A wildcard
120 * is an path argument which has a null key.
122 * @return true if any of the path arguments has a null key.
124 public final boolean isWildcarded() {
129 public final int hashCode() {
134 public final boolean equals(final Object obj) {
141 if (getClass() != obj.getClass()) {
145 final InstanceIdentifier<?> other = (InstanceIdentifier<?>) obj;
146 if (pathArguments == other.pathArguments) {
151 * We could now just go and compare the pathArguments, but that
152 * can be potentially expensive. Let's try to avoid that by
153 * checking various things that we have cached from pathArguments
154 * and trying to prove the identifiers are *not* equal.
156 if (hash != other.hash) {
159 if (wildcarded != other.wildcarded) {
162 if (targetType != other.targetType) {
165 if (fastNonEqual(other)) {
169 // Everything checks out so far, so we have to do a full equals
170 return Iterables.elementsEqual(pathArguments, other.pathArguments);
174 * Perform class-specific fast checks for non-equality. This allows
175 * subclasses to avoid iterating over the pathArguments by performing
176 * quick checks on their specific fields.
178 * @param other The other identifier, guaranteed to be the same class
179 * @return true if the other identifier cannot be equal to this one.
181 protected boolean fastNonEqual(final InstanceIdentifier<?> other) {
186 public final String toString() {
187 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
191 * Add class-specific toString attributes.
193 * @param toStringHelper ToStringHelper instance
194 * @return ToStringHelper instance which was passed in
196 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
197 return toStringHelper.add("targetType", targetType).add("path", Iterables.toString(pathArguments));
201 * Return an instance identifier trimmed at the first occurrence of a
202 * specific component type.
204 * For example let's say an instance identifier was built like so,
206 * identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
209 * And you wanted to obtain the Instance identifier which represented Nodes you would do it like so,
212 * identifier.firstIdentifierOf(Nodes.class)
215 * @param type component type
216 * @return trimmed instance identifier, or null if the component type
219 public final <I extends TreeNode> InstanceIdentifier<I> firstIdentifierOf(final Class<I> type) {
221 for (final TreeArgument a : pathArguments) {
222 if (type.equals(a.getType())) {
223 @SuppressWarnings("unchecked")
224 final InstanceIdentifier<I> ret = (InstanceIdentifier<I>) internalCreate(Iterables.limit(pathArguments, i));
235 * Return the key associated with the first component of specified type in
238 * @param listItem component type
239 * @param listKey component key type
240 * @return key associated with the component, or null if the component type
243 * @deprecated Use {@link #firstKeyOf(Class)} instead.
246 public final <N extends TreeNode, K> K firstKeyOf(final Class<N> listItem,
247 final Class<K> listKey) {
248 return firstKeyOf(listItem);
252 * Return the key associated with the first component of specified type in
255 * @param listItem component type
256 * @return key associated with the component, or null if the component type
260 public final <N extends TreeNode, K> K firstKeyOf(final Class<N> listItem) {
261 for (final TreeArgument i : pathArguments) {
262 if (listItem.equals(i.getType())) {
263 @SuppressWarnings("unchecked")
264 final K ret = ((IdentifiableItem<N, K>)i).getKey();
273 * Check whether an identifier is contained in this identifier. This is a strict subtree check, which requires all
274 * PathArguments to match exactly, e.g.
277 * The contains method checks if the other identifier is fully contained within the current identifier. It does this
278 * by looking at only the types of the path arguments and not by comparing the path arguments themselves.
280 * To illustrate here is an example which explains the working of this API.
282 * Let's say you have two instance identifiers as follows,
284 * this = /nodes/node/openflow:1
285 * other = /nodes/node/openflow:2
287 * then this.contains(other) will return false.
293 public final boolean contains(final InstanceIdentifier<? extends TreeNode> other) {
294 requireNonNull(other, "other should not be null");
296 final Iterator<?> lit = pathArguments.iterator();
297 final Iterator<?> oit = other.pathArguments.iterator();
299 while (lit.hasNext()) {
300 if (!oit.hasNext()) {
304 if (!lit.next().equals(oit.next())) {
313 * Check whether this instance identifier contains the other identifier after wildcard expansion. This is similar
314 * to {@link #contains(InstanceIdentifier)}, with the exception that a wildcards are assumed to match the their
315 * non-wildcarded PathArgument counterpart.
317 * @param other Identifier which should be checked for inclusion.
318 * @return true if this identifier contains the other object
320 public final boolean containsWildcarded(final InstanceIdentifier<?> other) {
321 requireNonNull(other, "other should not be null");
323 final Iterator<TreeArgument> lit = pathArguments.iterator();
324 final Iterator<TreeArgument> oit = other.pathArguments.iterator();
326 while (lit.hasNext()) {
327 if (!oit.hasNext()) {
331 final TreeArgument la = lit.next();
332 final TreeArgument oa = oit.next();
334 if (!la.getType().equals(oa.getType())) {
337 if (la instanceof IdentifiableItem<?, ?> && oa instanceof IdentifiableItem<?, ?> && !la.equals(oa)) {
346 * Create a builder rooted at this key.
348 * @return A builder instance
350 public InstanceIdentifierBuilder<T> builder() {
351 return new InstanceIdentifierBuilderImpl<T>(new Item<T>(targetType), pathArguments, hash, isWildcarded());
354 private InstanceIdentifier<?> childIdentifier(final TreeArgument arg) {
355 return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)), HashCodeBuilder.nextHashCode(hash, arg), isWildcarded());
358 @SuppressWarnings("unchecked")
359 public final <N extends TreeChildNode<? super T, ?>> InstanceIdentifier<N> child(final Class<N> container) {
360 final TreeArgument arg = new Item<>(container);
361 return (InstanceIdentifier<N>) childIdentifier(arg);
364 @SuppressWarnings("unchecked")
365 public final <N extends TreeChildNode<? super T, ?>, K> KeyedInstanceIdentifier<N, K> child(
366 final Class<N> listItem, final K listKey) {
367 final TreeArgument arg = new IdentifiableItem<>(listItem, listKey);
368 return (KeyedInstanceIdentifier<N, K>) childIdentifier(arg);
371 @SuppressWarnings("unchecked")
372 public final <N extends TreeNode & Augmentation<? super T>> InstanceIdentifier<N> augmentation(
373 final Class<N> container) {
374 final TreeArgument arg = new Item<>(container);
375 return (InstanceIdentifier<N>) childIdentifier(arg);
379 private List<TreeArgument> legacyCache;
382 * @deprecated Use {@link #getPathArguments()} instead.
385 public final List<TreeArgument> getPath() {
386 if (legacyCache == null) {
387 legacyCache = ImmutableList.copyOf(pathArguments);
394 * Create a new InstanceIdentifierBuilder given a base InstanceIdentifier
400 * @deprecated Use {@link #builder()} instead.
403 public static <T extends TreeNode> InstanceIdentifierBuilder<T> builder(final InstanceIdentifier<T> base) {
404 return base.builder();
408 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container
414 public static <T extends TreeChildNode<? extends TreeRoot, ?>> InstanceIdentifierBuilder<T> builder(
415 final Class<T> container) {
416 return new InstanceIdentifierBuilderImpl<T>().addNode(container);
420 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an IdentifiableItem
429 public static <N extends TreeChildNode<? extends TreeRoot, ?>, K> InstanceIdentifierBuilder<N> builder(
430 final Class<N> listItem, final K listKey) {
431 return new InstanceIdentifierBuilderImpl<N>().addNode(listItem, listKey);
435 * Create an instance identifier for a very specific object type. This method
436 * implements {@link #create(Iterable)} semantics, except it is used by internal
437 * callers, which have assured that the argument is an immutable Iterable.
440 * @param pathArguments The path to a specific node in the data tree
441 * @return InstanceIdentifier instance
442 * @throws IllegalArgumentException if pathArguments is empty or
443 * contains a null element.
445 private static InstanceIdentifier<?> internalCreate(final Iterable<TreeArgument> pathArguments) {
446 final Iterator<? extends TreeArgument> it = requireNonNull(pathArguments, "pathArguments may not be null").iterator();
447 final HashCodeBuilder<TreeArgument> hashBuilder = new HashCodeBuilder<>();
448 boolean wildcard = false;
449 TreeArgument a = null;
451 while (it.hasNext()) {
453 Preconditions.checkArgument(a != null, "pathArguments may not contain null elements");
455 // TODO: sanity check ChildTreeNode<>;
456 hashBuilder.addArgument(a);
458 if (Identifiable.class.isAssignableFrom(a.getType()) && !(a instanceof IdentifiableItem<?, ?>)) {
462 Preconditions.checkArgument(a != null, "pathArguments may not be empty");
464 return trustedCreate(a, pathArguments, hashBuilder.build(), wildcard);
468 * Create an instance identifier for a very specific object type.
472 * List<PathArgument> path = Arrays.asList(new Item(Nodes.class))
473 * new InstanceIdentifier(path);
476 * @param pathArguments The path to a specific node in the data tree
477 * @return InstanceIdentifier instance
478 * @throws IllegalArgumentException if pathArguments is empty or
479 * contains a null element.
481 public static InstanceIdentifier<?> create(final Iterable<? extends TreeArgument> pathArguments) {
482 if (pathArguments instanceof ImmutableCollection<?>) {
483 @SuppressWarnings("unchecked")
484 final Iterable<TreeArgument> immutableArguments = (Iterable<TreeArgument>) pathArguments;
485 return internalCreate(immutableArguments);
487 return internalCreate(ImmutableList.copyOf(pathArguments));
492 * Create an instance identifier for a very specific object type.
496 * new InstanceIdentifier(Nodes.class)
498 * would create an InstanceIdentifier for an object of type Nodes
500 * @param type The type of the object which this instance identifier represents
501 * @return InstanceIdentifier instance
503 @SuppressWarnings("unchecked")
504 public static <T extends TreeNode> InstanceIdentifier<T> create(final Class<T> type) {
505 return (InstanceIdentifier<T>) create(Collections.<TreeArgument> singletonList(new Item<>(type)));
509 * Return the key associated with the last component of the specified identifier.
511 * @param id instance identifier
512 * @return key associated with the last component
513 * @throws IllegalArgumentException if the supplied identifier type cannot have a key.
514 * @throws NullPointerException if id is null.
517 public static <N extends TreeNode, K> K keyOf(
518 final InstanceIdentifier<N> id) {
520 Preconditions.checkArgument(id instanceof KeyedInstanceIdentifier, "%s does not have a key", id);
522 @SuppressWarnings("unchecked")
523 final K ret = ((KeyedInstanceIdentifier<N, K>)id).getKey();
527 @SuppressWarnings({ "unchecked", "rawtypes" })
528 static InstanceIdentifier<?> trustedCreate(final TreeArgument arg, final Iterable<TreeArgument> pathArguments, final int hash, boolean wildcarded) {
529 if (Identifiable.class.isAssignableFrom(arg.getType()) && !(wildcarded)) {
531 if (arg instanceof IdentifiableItem<?, ?>) {
532 key = ((IdentifiableItem<?, ?>) arg).getKey();
537 return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key);
539 return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
543 private void writeObject(final java.io.ObjectOutputStream out) throws IOException {
544 out.defaultWriteObject();
545 out.writeInt(Iterables.size(pathArguments));
546 for (Object o : pathArguments) {
551 private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
552 in.defaultReadObject();
554 final int size = in.readInt();
555 final List<TreeArgument> args = new ArrayList<>(size);
556 for (int i = 0; i < size; ++i) {
557 args.add((TreeArgument) in.readObject());
561 PATHARGUMENTS_FIELD.set(this, ImmutableList.copyOf(args));
562 } catch (IllegalArgumentException | IllegalAccessException e) {
563 throw new IOException(e);