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 com.google.common.annotations.Beta;
12 import com.google.common.base.MoreObjects;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.Preconditions;
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.mdsal.binding.javav2.spec.structural.Augmentation;
26 import org.opendaylight.mdsal.binding.javav2.spec.structural.TreeChildNode;
27 import org.opendaylight.yangtools.concepts.Identifiable;
28 import org.opendaylight.yangtools.concepts.Immutable;
29 import org.opendaylight.yangtools.concepts.Path;
30 import org.opendaylight.yangtools.util.HashCodeBuilder;
34 * This instance identifier uniquely identifies a specific TreeNode in the data tree modeled by
37 * For Example let's say you were trying to refer to a node in inventory which was modeled in YANG
41 * module opendaylight-inventory {
47 * ext:context-instance "node-context";
56 * You could create an instance identifier as follows to get to a node with id "openflow:1"
58 * InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new
59 * NodeId("openflow:1")).build();
61 * This would be the same as using a path like so, "/nodes/node/openflow:1" to refer to the
66 public class InstanceIdentifier<T extends TreeNode> implements Path<InstanceIdentifier<? extends TreeNode>>, Immutable,
68 private static final Field PATHARGUMENTS_FIELD;
69 private static final long serialVersionUID = 2L;
71 * Protected to differentiate internal and external access. Internal
72 * access is required never to modify the contents. References passed
73 * to outside entities have to be wrapped in an unmodifiable view.
75 protected transient final Iterable<TreeArgument> pathArguments;
76 private final Class<T> targetType;
77 private final boolean wildcarded;
78 private final int hash;
83 f = InstanceIdentifier.class.getDeclaredField("pathArguments");
84 } catch (NoSuchFieldException | SecurityException e) {
85 throw new ExceptionInInitializerError(e);
87 f.setAccessible(true);
88 PATHARGUMENTS_FIELD = f;
91 InstanceIdentifier(final Class<T> type, final Iterable<TreeArgument> pathArguments, final boolean wildcarded, final int hash) {
92 this.pathArguments = Preconditions.checkNotNull(pathArguments);
93 this.targetType = Preconditions.checkNotNull(type);
94 this.wildcarded = wildcarded;
99 * Return the type of data which this InstanceIdentifier identifies.
101 * @return Target type
103 public final Class<T> getTargetType() {
108 * Return the path argument chain which makes up this instance identifier.
110 * @return Path argument chain. Immutable and does not contain nulls.
112 public final Iterable<TreeArgument> getPathArguments() {
113 return Iterables.unmodifiableIterable(pathArguments);
117 * Check whether an instance identifier contains any wildcards. A wildcard
118 * is an path argument which has a null key.
120 * @return true if any of the path arguments has a null key.
122 public final boolean isWildcarded() {
127 public final int hashCode() {
132 public final boolean equals(final Object obj) {
139 if (getClass() != obj.getClass()) {
143 final InstanceIdentifier<?> other = (InstanceIdentifier<?>) obj;
144 if (pathArguments == other.pathArguments) {
149 * We could now just go and compare the pathArguments, but that
150 * can be potentially expensive. Let's try to avoid that by
151 * checking various things that we have cached from pathArguments
152 * and trying to prove the identifiers are *not* equal.
154 if (hash != other.hash) {
157 if (wildcarded != other.wildcarded) {
160 if (targetType != other.targetType) {
163 if (fastNonEqual(other)) {
167 // Everything checks out so far, so we have to do a full equals
168 return Iterables.elementsEqual(pathArguments, other.pathArguments);
172 * Perform class-specific fast checks for non-equality. This allows
173 * subclasses to avoid iterating over the pathArguments by performing
174 * quick checks on their specific fields.
176 * @param other The other identifier, guaranteed to be the same class
177 * @return true if the other identifier cannot be equal to this one.
179 protected boolean fastNonEqual(final InstanceIdentifier<?> other) {
184 public final String toString() {
185 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
189 * Add class-specific toString attributes.
191 * @param toStringHelper ToStringHelper instance
192 * @return ToStringHelper instance which was passed in
194 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
195 return toStringHelper.add("targetType", targetType).add("path", Iterables.toString(pathArguments));
199 * Return an instance identifier trimmed at the first occurrence of a
200 * specific component type.
202 * For example let's say an instance identifier was built like so,
204 * identifier = InstanceIdentifierBuilder.builder(Nodes.class).child(Node.class, new NodeKey(new NodeId("openflow:1")).build();
207 * And you wanted to obtain the Instance identifier which represented Nodes you would do it like so,
210 * identifier.firstIdentifierOf(Nodes.class)
213 * @param type component type
214 * @return trimmed instance identifier, or null if the component type
217 public final <I extends TreeNode> InstanceIdentifier<I> firstIdentifierOf(final Class<I> type) {
219 for (final TreeArgument a : pathArguments) {
220 if (type.equals(a.getType())) {
221 @SuppressWarnings("unchecked")
222 final InstanceIdentifier<I> ret = (InstanceIdentifier<I>) internalCreate(Iterables.limit(pathArguments, i));
233 * Return the key associated with the first component of specified type in
236 * @param listItem component type
237 * @param listKey component key type
238 * @return key associated with the component, or null if the component type
241 * @deprecated Use {@link #firstKeyOf(Class)} instead.
244 public final <N extends TreeNode, K> K firstKeyOf(final Class<N> listItem,
245 final Class<K> listKey) {
246 return firstKeyOf(listItem);
250 * Return the key associated with the first component of specified type in
253 * @param listItem component type
254 * @return key associated with the component, or null if the component type
258 public final <N extends TreeNode, K> K firstKeyOf(final Class<N> listItem) {
259 for (final TreeArgument i : pathArguments) {
260 if (listItem.equals(i.getType())) {
261 @SuppressWarnings("unchecked")
262 final K ret = ((IdentifiableItem<N, K>)i).getKey();
271 * Check whether an identifier is contained in this identifier. This is a strict subtree check, which requires all
272 * PathArguments to match exactly, e.g.
275 * The contains method checks if the other identifier is fully contained within the current identifier. It does this
276 * by looking at only the types of the path arguments and not by comparing the path arguments themselves.
278 * To illustrate here is an example which explains the working of this API.
280 * Let's say you have two instance identifiers as follows,
282 * this = /nodes/node/openflow:1
283 * other = /nodes/node/openflow:2
285 * then this.contains(other) will return false.
291 public final boolean contains(final InstanceIdentifier<? extends TreeNode> other) {
292 Preconditions.checkNotNull(other, "other should not be null");
294 final Iterator<?> lit = pathArguments.iterator();
295 final Iterator<?> oit = other.pathArguments.iterator();
297 while (lit.hasNext()) {
298 if (!oit.hasNext()) {
302 if (!lit.next().equals(oit.next())) {
311 * Check whether this instance identifier contains the other identifier after wildcard expansion. This is similar
312 * to {@link #contains(InstanceIdentifier)}, with the exception that a wildcards are assumed to match the their
313 * non-wildcarded PathArgument counterpart.
315 * @param other Identifier which should be checked for inclusion.
316 * @return true if this identifier contains the other object
318 public final boolean containsWildcarded(final InstanceIdentifier<?> other) {
319 Preconditions.checkNotNull(other, "other should not be null");
321 final Iterator<TreeArgument> lit = pathArguments.iterator();
322 final Iterator<TreeArgument> oit = other.pathArguments.iterator();
324 while (lit.hasNext()) {
325 if (!oit.hasNext()) {
329 final TreeArgument la = lit.next();
330 final TreeArgument oa = oit.next();
332 if (!la.getType().equals(oa.getType())) {
335 if (la instanceof IdentifiableItem<?, ?> && oa instanceof IdentifiableItem<?, ?> && !la.equals(oa)) {
344 * Create a builder rooted at this key.
346 * @return A builder instance
348 public InstanceIdentifierBuilder<T> builder() {
349 return new InstanceIdentifierBuilderImpl<T>(new Item<T>(targetType), pathArguments, hash, isWildcarded());
352 private InstanceIdentifier<?> childIdentifier(final TreeArgument arg) {
353 return trustedCreate(arg, Iterables.concat(pathArguments, Collections.singleton(arg)), HashCodeBuilder.nextHashCode(hash, arg), isWildcarded());
356 @SuppressWarnings("unchecked")
357 public final <N extends TreeChildNode<? super T, ?>> InstanceIdentifier<N> child(final Class<N> container) {
358 final TreeArgument arg = new Item<>(container);
359 return (InstanceIdentifier<N>) childIdentifier(arg);
362 @SuppressWarnings("unchecked")
363 public final <N extends TreeChildNode<? super T, ?>, K> KeyedInstanceIdentifier<N, K> child(
364 final Class<N> listItem, final K listKey) {
365 final TreeArgument arg = new IdentifiableItem<>(listItem, listKey);
366 return (KeyedInstanceIdentifier<N, K>) childIdentifier(arg);
369 @SuppressWarnings("unchecked")
370 public final <N extends TreeNode & Augmentation<? super T>> InstanceIdentifier<N> augmentation(
371 final Class<N> container) {
372 final TreeArgument arg = new Item<>(container);
373 return (InstanceIdentifier<N>) childIdentifier(arg);
377 private List<TreeArgument> legacyCache;
380 * @deprecated Use {@link #getPathArguments()} instead.
383 public final List<TreeArgument> getPath() {
384 if (legacyCache == null) {
385 legacyCache = ImmutableList.copyOf(pathArguments);
392 * Create a new InstanceIdentifierBuilder given a base InstanceIdentifier
398 * @deprecated Use {@link #builder()} instead.
401 public static <T extends TreeNode> InstanceIdentifierBuilder<T> builder(final InstanceIdentifier<T> base) {
402 return base.builder();
406 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier as specified by container
412 public static <T extends TreeChildNode<? extends TreeRoot, ?>> InstanceIdentifierBuilder<T> builder(
413 final Class<T> container) {
414 return new InstanceIdentifierBuilderImpl<T>().addNode(container);
418 * Create an InstanceIdentifierBuilder for a specific type of InstanceIdentifier which represents an IdentifiableItem
427 public static <N extends TreeChildNode<? extends TreeRoot, ?>, K> InstanceIdentifierBuilder<N> builder(
428 final Class<N> listItem, final K listKey) {
429 return new InstanceIdentifierBuilderImpl<N>().addNode(listItem, listKey);
433 * Create an instance identifier for a very specific object type. This method
434 * implements {@link #create(Iterable)} semantics, except it is used by internal
435 * callers, which have assured that the argument is an immutable Iterable.
438 * @param pathArguments The path to a specific node in the data tree
439 * @return InstanceIdentifier instance
440 * @throws IllegalArgumentException if pathArguments is empty or
441 * contains a null element.
443 private static InstanceIdentifier<?> internalCreate(final Iterable<TreeArgument> pathArguments) {
444 final Iterator<? extends TreeArgument> it = Preconditions.checkNotNull(pathArguments, "pathArguments may not be null").iterator();
445 final HashCodeBuilder<TreeArgument> hashBuilder = new HashCodeBuilder<>();
446 boolean wildcard = false;
447 TreeArgument a = null;
449 while (it.hasNext()) {
451 Preconditions.checkArgument(a != null, "pathArguments may not contain null elements");
453 // TODO: sanity check ChildTreeNode<>;
454 hashBuilder.addArgument(a);
456 if (Identifiable.class.isAssignableFrom(a.getType()) && !(a instanceof IdentifiableItem<?, ?>)) {
460 Preconditions.checkArgument(a != null, "pathArguments may not be empty");
462 return trustedCreate(a, pathArguments, hashBuilder.build(), wildcard);
466 * Create an instance identifier for a very specific object type.
470 * List<PathArgument> path = Arrays.asList(new Item(Nodes.class))
471 * new InstanceIdentifier(path);
474 * @param pathArguments The path to a specific node in the data tree
475 * @return InstanceIdentifier instance
476 * @throws IllegalArgumentException if pathArguments is empty or
477 * contains a null element.
479 public static InstanceIdentifier<?> create(final Iterable<? extends TreeArgument> pathArguments) {
480 if (pathArguments instanceof ImmutableCollection<?>) {
481 @SuppressWarnings("unchecked")
482 final Iterable<TreeArgument> immutableArguments = (Iterable<TreeArgument>) pathArguments;
483 return internalCreate(immutableArguments);
485 return internalCreate(ImmutableList.copyOf(pathArguments));
490 * Create an instance identifier for a very specific object type.
494 * new InstanceIdentifier(Nodes.class)
496 * would create an InstanceIdentifier for an object of type Nodes
498 * @param type The type of the object which this instance identifier represents
499 * @return InstanceIdentifier instance
501 @SuppressWarnings("unchecked")
502 public static <T extends TreeNode> InstanceIdentifier<T> create(final Class<T> type) {
503 return (InstanceIdentifier<T>) create(Collections.<TreeArgument> singletonList(new Item<>(type)));
507 * Return the key associated with the last component of the specified identifier.
509 * @param id instance identifier
510 * @return key associated with the last component
511 * @throws IllegalArgumentException if the supplied identifier type cannot have a key.
512 * @throws NullPointerException if id is null.
515 public static <N extends TreeNode, K> K keyOf(
516 final InstanceIdentifier<N> id) {
517 Preconditions.checkNotNull(id);
518 Preconditions.checkArgument(id instanceof KeyedInstanceIdentifier, "%s does not have a key", id);
520 @SuppressWarnings("unchecked")
521 final K ret = ((KeyedInstanceIdentifier<N, K>)id).getKey();
525 @SuppressWarnings({ "unchecked", "rawtypes" })
526 static InstanceIdentifier<?> trustedCreate(final TreeArgument arg, final Iterable<TreeArgument> pathArguments, final int hash, boolean wildcarded) {
527 if (Identifiable.class.isAssignableFrom(arg.getType()) && !(wildcarded)) {
529 if (arg instanceof IdentifiableItem<?, ?>) {
530 key = ((IdentifiableItem<?, ?>) arg).getKey();
535 return new KeyedInstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash, key);
537 return new InstanceIdentifier(arg.getType(), pathArguments, wildcarded, hash);
541 private void writeObject(final java.io.ObjectOutputStream out) throws IOException {
542 out.defaultWriteObject();
543 out.writeInt(Iterables.size(pathArguments));
544 for (Object o : pathArguments) {
549 private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
550 in.defaultReadObject();
552 final int size = in.readInt();
553 final List<TreeArgument> args = new ArrayList<>(size);
554 for (int i = 0; i < size; ++i) {
555 args.add((TreeArgument) in.readObject());
559 PATHARGUMENTS_FIELD.set(this, ImmutableList.copyOf(args));
560 } catch (IllegalArgumentException | IllegalAccessException e) {
561 throw new IOException(e);