2 * Copyright (c) 2014 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.data.api;
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.collect.Iterables;
16 import java.io.Serializable;
17 import java.lang.reflect.Array;
18 import java.util.Arrays;
19 import java.util.Collection;
20 import java.util.Iterator;
21 import java.util.List;
23 import java.util.Map.Entry;
24 import java.util.Objects;
26 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
27 import javax.annotation.Nonnull;
28 import javax.annotation.Nullable;
29 import org.opendaylight.yangtools.concepts.Builder;
30 import org.opendaylight.yangtools.concepts.Immutable;
31 import org.opendaylight.yangtools.concepts.Path;
32 import org.opendaylight.yangtools.util.HashCodeBuilder;
33 import org.opendaylight.yangtools.util.ImmutableOffsetMap;
34 import org.opendaylight.yangtools.yang.common.QName;
35 import org.opendaylight.yangtools.yang.common.QNameModule;
36 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
39 * Unique identifier of a particular node instance in the data tree.
42 * Java representation of YANG Built-in type <code>instance-identifier</code>,
43 * which conceptually is XPath expression minimized to uniquely identify element
44 * in data tree which conforms to constraints maintained by YANG Model,
45 * effectively this makes Instance Identifier a path to element in data tree.
47 * Constraints put in YANG specification on instance-identifier allowed it to be
48 * effectively represented in Java and it's evaluation does not require
49 * full-blown XPath processor.
51 * <h3>Path Arguments</h3>
52 * Path to the node represented in instance identifier consists of
53 * {@link PathArgument} which carries necessary information to uniquely identify
54 * node on particular level in the subtree.
57 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
58 * <code>0..1</code> in particular subtree in data tree.</li>
59 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item),
60 * which has cardinality <code>0..n</code>.</li>
61 * <li>{@link NodeWithValue} - Identifier of instance <code>leaf</code> node or
62 * <code>leaf-list</code> node.</li>
63 * <li>{@link AugmentationIdentifier} - Identifier of instance of
64 * <code>augmentation</code> node.</li>
68 * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
70 public abstract class YangInstanceIdentifier implements Path<YangInstanceIdentifier>, Immutable, Serializable {
72 * An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual
73 * root of the YANG namespace.
75 public static final YangInstanceIdentifier EMPTY = FixedYangInstanceIdentifier.EMPTY_INSTANCE;
77 private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, String> TOSTRINGCACHE_UPDATER =
78 AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, String.class, "toStringCache");
79 private static final long serialVersionUID = 4L;
81 private final int hash;
82 private transient volatile String toStringCache = null;
84 // Package-private to prevent outside subclassing
85 YangInstanceIdentifier(final int hash) {
89 @Nonnull abstract YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
90 @Nonnull abstract Collection<PathArgument> tryPathArguments();
91 @Nonnull abstract Collection<PathArgument> tryReversePathArguments();
94 * Check if this instance identifier has empty path arguments, e.g. it is
95 * empty and corresponds to {@link #EMPTY}.
97 * @return True if this instance identifier is empty, false otherwise.
99 public abstract boolean isEmpty();
102 * Return an optimized version of this identifier, useful when the identifier
103 * will be used very frequently.
105 * @return A optimized equivalent instance.
108 public abstract YangInstanceIdentifier toOptimized();
111 * Return the conceptual parent {@link YangInstanceIdentifier}, which has
112 * one item less in {@link #getPathArguments()}.
114 * @return Parent {@link YangInstanceIdentifier}, or null if this is object is {@link #EMPTY}.
116 @Nullable public abstract YangInstanceIdentifier getParent();
119 * Returns an ordered iteration of path arguments.
121 * @return Immutable iteration of path arguments.
123 public abstract List<PathArgument> getPathArguments();
126 * Returns an iterable of path arguments in reverse order. This is useful
127 * when walking up a tree organized this way.
129 * @return Immutable iterable of path arguments in reverse order.
131 public abstract List<PathArgument> getReversePathArguments();
134 * Returns the last PathArgument. This is equivalent of iterating
135 * to the last element of the iterable returned by {@link #getPathArguments()}.
137 * @return The last past argument, or null if there are no PathArguments.
139 public abstract PathArgument getLastPathArgument();
141 public static YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
142 if (Iterables.isEmpty(path)) {
146 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
147 for (PathArgument a : path) {
151 return FixedYangInstanceIdentifier.create(path, hash.build());
154 public static YangInstanceIdentifier create(final PathArgument... path) {
155 // We are forcing a copy, since we cannot trust the user
156 return create(Arrays.asList(path));
160 public final int hashCode() {
162 * The caching is safe, since the object contract requires
163 * immutability of the object and all objects referenced from this
165 * Used lists, maps are immutable. Path Arguments (elements) are also
166 * immutable, since the PathArgument contract requires immutability.
171 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
172 return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
176 public boolean equals(final Object obj) {
180 if (!(obj instanceof YangInstanceIdentifier)) {
183 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
184 if (this.hashCode() != obj.hashCode()) {
188 return pathArgumentsEqual(other);
192 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments
194 * @param name QName of {@link NodeIdentifier}
195 * @return Instance Identifier with additional path argument added to the end.
197 public final YangInstanceIdentifier node(final QName name) {
198 return node(new NodeIdentifier(name));
203 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments
205 * @param arg Path argument which should be added to the end
206 * @return Instance Identifier with additional path argument added to the end.
208 public final YangInstanceIdentifier node(final PathArgument arg) {
209 return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
213 * Get the relative path from an ancestor. This method attempts to perform
214 * the reverse of concatenating a base (ancestor) and a path.
217 * Ancestor against which the relative path should be calculated
218 * @return This object's relative path from parent, or Optional.absent() if
219 * the specified parent is not in fact an ancestor of this object.
221 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
222 final Iterator<?> lit = getPathArguments().iterator();
223 final Iterator<?> oit = ancestor.getPathArguments().iterator();
226 while (oit.hasNext()) {
227 // Ancestor is not really an ancestor
228 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
229 return Optional.absent();
236 return Optional.of(this);
238 if (!lit.hasNext()) {
239 return Optional.of(EMPTY);
242 return Optional.of(createRelativeIdentifier(common));
246 public final boolean contains(final YangInstanceIdentifier other) {
247 Preconditions.checkArgument(other != null, "other should not be null");
249 final Iterator<?> lit = getPathArguments().iterator();
250 final Iterator<?> oit = other.getPathArguments().iterator();
252 while (lit.hasNext()) {
253 if (!oit.hasNext()) {
257 if (!lit.next().equals(oit.next())) {
266 public final String toString() {
268 * The toStringCache is safe, since the object contract requires
269 * immutability of the object and all objects referenced from this
271 * Used lists, maps are immutable. Path Arguments (elements) are also
272 * immutable, since the PathArgument contract requires immutability.
273 * The cache is thread-safe - if multiple computations occurs at the
274 * same time, cache will be overwritten with same result.
276 String ret = toStringCache;
278 final StringBuilder builder = new StringBuilder("/");
279 PathArgument prev = null;
280 for (PathArgument argument : getPathArguments()) {
284 builder.append(argument.toRelativeString(prev));
288 ret = builder.toString();
289 TOSTRINGCACHE_UPDATER.lazySet(this, ret);
294 private static int hashCode(final Object value) {
299 if (byte[].class.equals(value.getClass())) {
300 return Arrays.hashCode((byte[]) value);
303 if (value.getClass().isArray()) {
305 int length = Array.getLength(value);
306 for (int i = 0; i < length; i++) {
307 hash += Objects.hashCode(Array.get(value, i));
313 return Objects.hashCode(value);
316 // Static factories & helpers
319 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied QName
321 * @param name QName of first node identifier
322 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
324 public static YangInstanceIdentifier of(final QName name) {
325 return create(new NodeIdentifier(name));
329 * Returns new builder for InstanceIdentifier with empty path arguments.
331 * @return new builder for InstanceIdentifier with empty path arguments.
333 public static InstanceIdentifierBuilder builder() {
334 return new YangInstanceIdentifierBuilder();
339 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
341 * @param origin InstanceIdentifier from which path arguments are copied.
342 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
344 public static InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
345 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
349 * Path argument / component of InstanceIdentifier
351 * Path argument uniquely identifies node in data tree on particular
354 * This interface itself is used as common parent for actual
355 * path arguments types and should not be implemented by user code.
357 * Path arguments SHOULD contain only minimum of information
358 * required to uniquely identify node on particular subtree level.
360 * For actual path arguments types see:
362 * <li>{@link NodeIdentifier} - Identifier of container or leaf
363 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
364 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
365 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
368 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
370 * If applicable returns unique QName of data node as defined in YANG
373 * This method may return null, if the corresponding schema node, does
374 * not have QName associated, such as in cases of augmentations.
381 * Return the string representation of this object for use in context
382 * provided by a previous object. This method can be implemented in
383 * terms of {@link #toString()}, but implementations are encourage to
384 * reuse any context already emitted by the previous object.
386 * @param previous Previous path argument
387 * @return String representation
389 String toRelativeString(PathArgument previous);
392 private static abstract class AbstractPathArgument implements PathArgument {
393 private static final long serialVersionUID = -4546547994250849340L;
394 private final QName nodeType;
395 private transient int hashValue;
396 private volatile transient boolean hashGuard = false;
398 protected AbstractPathArgument(final QName nodeType) {
399 this.nodeType = Preconditions.checkNotNull(nodeType);
403 public final QName getNodeType() {
408 public int compareTo(final PathArgument o) {
409 return nodeType.compareTo(o.getNodeType());
412 protected int hashCodeImpl() {
413 return 31 + getNodeType().hashCode();
417 public final int hashCode() {
419 hashValue = hashCodeImpl();
427 public boolean equals(final Object obj) {
431 if (obj == null || this.getClass() != obj.getClass()) {
435 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
439 public String toString() {
440 return getNodeType().toString();
444 public String toRelativeString(final PathArgument previous) {
445 if (previous instanceof AbstractPathArgument) {
446 final QNameModule mod = ((AbstractPathArgument)previous).getNodeType().getModule();
447 if (getNodeType().getModule().equals(mod)) {
448 return getNodeType().getLocalName();
452 return getNodeType().toString();
457 * Fluent Builder of Instance Identifier instances
459 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
461 * Adds a {@link PathArgument} to to path arguments of resulting instance identifier.
463 * @param arg A {@link PathArgument} to be added
464 * @return this builder
466 InstanceIdentifierBuilder node(PathArgument arg);
469 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
471 * @param nodeType QName of {@link NodeIdentifier} which will be added
472 * @return this builder
474 InstanceIdentifierBuilder node(QName nodeType);
477 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting instance identifier.
479 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
480 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
481 * @return this builder
483 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
486 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
488 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
489 * @param key QName of key which will be added
490 * @param value value of key which will be added
491 * @return this builder
493 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
497 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder
499 * @return {@link YangInstanceIdentifier}
502 YangInstanceIdentifier build();
505 * @deprecated use #build()
508 YangInstanceIdentifier toInstance();
512 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
513 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
515 public static final class NodeIdentifier extends AbstractPathArgument {
516 private static final long serialVersionUID = -2255888212390871347L;
518 public NodeIdentifier(final QName node) {
524 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
527 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
528 private static final long serialVersionUID = -4787195606494761540L;
530 private final Map<QName, Object> keyValues;
532 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
534 // Retains ImmutableMap for maps with size() <= 1. For larger sizes uses a shared key set.
535 this.keyValues = ImmutableOffsetMap.copyOf(keyValues);
538 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
539 this(node, ImmutableMap.of(key, value));
542 public Map<QName, Object> getKeyValues() {
547 protected int hashCodeImpl() {
548 final int prime = 31;
549 int result = super.hashCodeImpl();
550 result = prime * result;
552 for (Entry<QName, Object> entry : keyValues.entrySet()) {
553 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
559 public boolean equals(final Object obj) {
560 if (!super.equals(obj)) {
564 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
566 // TODO: benchmark to see if just calling equals() on the two maps is not faster
567 if (keyValues == otherKeyValues) {
570 if (keyValues.size() != otherKeyValues.size()) {
574 for (Entry<QName, Object> entry : keyValues.entrySet()) {
575 if (!otherKeyValues.containsKey(entry.getKey())
576 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
586 public String toString() {
587 return super.toString() + '[' + keyValues + ']';
591 public String toRelativeString(final PathArgument previous) {
592 return super.toRelativeString(previous) + '[' + keyValues + ']';
597 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
600 public static final class NodeWithValue extends AbstractPathArgument {
601 private static final long serialVersionUID = -3637456085341738431L;
603 private final Object value;
605 public NodeWithValue(final QName node, final Object value) {
610 public Object getValue() {
615 protected int hashCodeImpl() {
616 final int prime = 31;
617 int result = super.hashCodeImpl();
618 result = prime * result + ((value == null) ? 0 : YangInstanceIdentifier.hashCode(value));
623 public boolean equals(final Object obj) {
624 if (!super.equals(obj)) {
627 final NodeWithValue other = (NodeWithValue) obj;
628 return Objects.deepEquals(value, other.value);
632 public String toString() {
633 return super.toString() + '[' + value + ']';
637 public String toRelativeString(final PathArgument previous) {
638 return super.toRelativeString(previous) + '[' + value + ']';
643 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} node in
644 * particular subtree.
646 * Augmentation is uniquely identified by set of all possible child nodes.
648 * to identify instance of augmentation,
649 * since RFC6020 states that <code>augment</code> that augment
650 * statement must not add multiple nodes from same namespace
651 * / module to the target node.
654 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
656 public static final class AugmentationIdentifier implements PathArgument {
657 private static final long serialVersionUID = -8122335594681936939L;
658 private final ImmutableSet<QName> childNames;
661 public QName getNodeType() {
662 // This should rather throw exception than return always null
663 throw new UnsupportedOperationException("Augmentation node has no QName");
668 * Construct new augmentation identifier using supplied set of possible
672 * Set of possible child nodes.
674 public AugmentationIdentifier(final Set<QName> childNames) {
675 this.childNames = ImmutableSet.copyOf(childNames);
679 * Returns set of all possible child nodes
681 * @return set of all possible child nodes.
683 public Set<QName> getPossibleChildNames() {
688 public String toString() {
689 final StringBuilder sb = new StringBuilder("AugmentationIdentifier{");
690 sb.append("childNames=").append(childNames).append('}');
691 return sb.toString();
695 public String toRelativeString(final PathArgument previous) {
700 public boolean equals(final Object o) {
704 if (!(o instanceof AugmentationIdentifier)) {
708 AugmentationIdentifier that = (AugmentationIdentifier) o;
709 return childNames.equals(that.childNames);
713 public int hashCode() {
714 return childNames.hashCode();
718 public int compareTo(final PathArgument o) {
719 if (!(o instanceof AugmentationIdentifier)) {
722 AugmentationIdentifier other = (AugmentationIdentifier) o;
723 Set<QName> otherChildNames = other.getPossibleChildNames();
724 int thisSize = childNames.size();
725 int otherSize = otherChildNames.size();
726 if (thisSize == otherSize) {
727 Iterator<QName> otherIterator = otherChildNames.iterator();
728 for (QName name : childNames) {
729 int c = name.compareTo(otherIterator.next());
735 } else if (thisSize < otherSize) {