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.cache.CacheBuilder;
14 import com.google.common.cache.CacheLoader;
15 import com.google.common.cache.LoadingCache;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Iterables;
18 import java.io.Serializable;
19 import java.lang.reflect.Array;
20 import java.util.Arrays;
21 import java.util.Collection;
22 import java.util.Iterator;
23 import java.util.List;
25 import java.util.Map.Entry;
26 import java.util.Objects;
28 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
29 import javax.annotation.Nonnull;
30 import javax.annotation.Nullable;
31 import org.opendaylight.yangtools.concepts.Builder;
32 import org.opendaylight.yangtools.concepts.Immutable;
33 import org.opendaylight.yangtools.concepts.Path;
34 import org.opendaylight.yangtools.util.HashCodeBuilder;
35 import org.opendaylight.yangtools.util.ImmutableOffsetMap;
36 import org.opendaylight.yangtools.util.SharedSingletonMap;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.common.QNameModule;
39 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
42 * Unique identifier of a particular node instance in the data tree.
45 * Java representation of YANG Built-in type <code>instance-identifier</code>,
46 * which conceptually is XPath expression minimized to uniquely identify element
47 * in data tree which conforms to constraints maintained by YANG Model,
48 * effectively this makes Instance Identifier a path to element in data tree.
51 * Constraints put in YANG specification on instance-identifier allowed it to be
52 * effectively represented in Java and it's evaluation does not require
53 * full-blown XPath processor.
55 * <h3>Path Arguments</h3>
57 * Path to the node represented in instance identifier consists of
58 * {@link PathArgument} which carries necessary information to uniquely identify
59 * node on particular level in the subtree.
62 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
63 * <code>0..1</code> in particular subtree in data tree.</li>
64 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item),
65 * which has cardinality <code>0..n</code>.</li>
66 * <li>{@link NodeWithValue} - Identifier of instance <code>leaf</code> node or
67 * <code>leaf-list</code> node.</li>
68 * <li>{@link AugmentationIdentifier} - Identifier of instance of
69 * <code>augmentation</code> node.</li>
73 * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
75 public abstract class YangInstanceIdentifier implements Path<YangInstanceIdentifier>, Immutable, Serializable {
77 * An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual
78 * root of the YANG namespace.
80 public static final YangInstanceIdentifier EMPTY = FixedYangInstanceIdentifier.EMPTY_INSTANCE;
82 private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, String> TOSTRINGCACHE_UPDATER =
83 AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, String.class, "toStringCache");
84 private static final long serialVersionUID = 4L;
86 private final int hash;
87 private transient volatile String toStringCache = null;
89 // Package-private to prevent outside subclassing
90 YangInstanceIdentifier(final int hash) {
94 @Nonnull abstract YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
95 @Nonnull abstract Collection<PathArgument> tryPathArguments();
96 @Nonnull abstract Collection<PathArgument> tryReversePathArguments();
99 * Check if this instance identifier has empty path arguments, e.g. it is
100 * empty and corresponds to {@link #EMPTY}.
102 * @return True if this instance identifier is empty, false otherwise.
104 public abstract boolean isEmpty();
107 * Return an optimized version of this identifier, useful when the identifier
108 * will be used very frequently.
110 * @return A optimized equivalent instance.
113 public abstract YangInstanceIdentifier toOptimized();
116 * Return the conceptual parent {@link YangInstanceIdentifier}, which has
117 * one item less in {@link #getPathArguments()}.
119 * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #EMPTY}.
121 @Nullable public abstract YangInstanceIdentifier getParent();
124 * Return the ancestor {@link YangInstanceIdentifier} with a particular depth, e.g. number of path arguments.
126 * @param depth Ancestor depth
127 * @return Ancestor {@link YangInstanceIdentifier}
128 * @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
130 @Nonnull public abstract YangInstanceIdentifier getAncestor(int depth);
133 * Returns an ordered iteration of path arguments.
135 * @return Immutable iteration of path arguments.
137 public abstract List<PathArgument> getPathArguments();
140 * Returns an iterable of path arguments in reverse order. This is useful
141 * when walking up a tree organized this way.
143 * @return Immutable iterable of path arguments in reverse order.
145 public abstract List<PathArgument> getReversePathArguments();
148 * Returns the last PathArgument. This is equivalent of iterating
149 * to the last element of the iterable returned by {@link #getPathArguments()}.
151 * @return The last past argument, or null if there are no PathArguments.
153 public abstract PathArgument getLastPathArgument();
155 public static YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
156 if (Iterables.isEmpty(path)) {
160 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
161 for (PathArgument a : path) {
165 return FixedYangInstanceIdentifier.create(path, hash.build());
168 public static YangInstanceIdentifier create(final PathArgument... path) {
169 // We are forcing a copy, since we cannot trust the user
170 return create(Arrays.asList(path));
174 public final int hashCode() {
176 * The caching is safe, since the object contract requires
177 * immutability of the object and all objects referenced from this
179 * Used lists, maps are immutable. Path Arguments (elements) are also
180 * immutable, since the PathArgument contract requires immutability.
185 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
186 return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
190 public boolean equals(final Object obj) {
194 if (!(obj instanceof YangInstanceIdentifier)) {
197 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
198 if (this.hashCode() != obj.hashCode()) {
202 return pathArgumentsEqual(other);
206 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments
208 * @param name QName of {@link NodeIdentifier}
209 * @return Instance Identifier with additional path argument added to the end.
211 public final YangInstanceIdentifier node(final QName name) {
212 return node(new NodeIdentifier(name));
217 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments
219 * @param arg Path argument which should be added to the end
220 * @return Instance Identifier with additional path argument added to the end.
222 public final YangInstanceIdentifier node(final PathArgument arg) {
223 return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
227 * Get the relative path from an ancestor. This method attempts to perform
228 * the reverse of concatenating a base (ancestor) and a path.
231 * Ancestor against which the relative path should be calculated
232 * @return This object's relative path from parent, or Optional.absent() if
233 * the specified parent is not in fact an ancestor of this object.
235 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
236 final Iterator<?> lit = getPathArguments().iterator();
237 final Iterator<?> oit = ancestor.getPathArguments().iterator();
240 while (oit.hasNext()) {
241 // Ancestor is not really an ancestor
242 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
243 return Optional.absent();
250 return Optional.of(this);
252 if (!lit.hasNext()) {
253 return Optional.of(EMPTY);
256 return Optional.of(createRelativeIdentifier(common));
260 public final boolean contains(final YangInstanceIdentifier other) {
261 Preconditions.checkArgument(other != null, "other should not be null");
263 final Iterator<?> lit = getPathArguments().iterator();
264 final Iterator<?> oit = other.getPathArguments().iterator();
266 while (lit.hasNext()) {
267 if (!oit.hasNext()) {
271 if (!lit.next().equals(oit.next())) {
280 public final String toString() {
282 * The toStringCache is safe, since the object contract requires
283 * immutability of the object and all objects referenced from this
285 * Used lists, maps are immutable. Path Arguments (elements) are also
286 * immutable, since the PathArgument contract requires immutability.
287 * The cache is thread-safe - if multiple computations occurs at the
288 * same time, cache will be overwritten with same result.
290 String ret = toStringCache;
292 final StringBuilder builder = new StringBuilder("/");
293 PathArgument prev = null;
294 for (PathArgument argument : getPathArguments()) {
298 builder.append(argument.toRelativeString(prev));
302 ret = builder.toString();
303 TOSTRINGCACHE_UPDATER.lazySet(this, ret);
308 private static int hashCode(final Object value) {
313 if (byte[].class.equals(value.getClass())) {
314 return Arrays.hashCode((byte[]) value);
317 if (value.getClass().isArray()) {
319 int length = Array.getLength(value);
320 for (int i = 0; i < length; i++) {
321 hash += Objects.hashCode(Array.get(value, i));
327 return Objects.hashCode(value);
330 // Static factories & helpers
333 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied QName
335 * @param name QName of first node identifier
336 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
338 public static YangInstanceIdentifier of(final QName name) {
339 return create(new NodeIdentifier(name));
343 * Returns new builder for InstanceIdentifier with empty path arguments.
345 * @return new builder for InstanceIdentifier with empty path arguments.
347 public static InstanceIdentifierBuilder builder() {
348 return new YangInstanceIdentifierBuilder();
353 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
355 * @param origin InstanceIdentifier from which path arguments are copied.
356 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
358 public static InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
359 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
363 * Path argument / component of InstanceIdentifier
365 * Path argument uniquely identifies node in data tree on particular
368 * This interface itself is used as common parent for actual
369 * path arguments types and should not be implemented by user code.
371 * Path arguments SHOULD contain only minimum of information
372 * required to uniquely identify node on particular subtree level.
374 * For actual path arguments types see:
376 * <li>{@link NodeIdentifier} - Identifier of container or leaf
377 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
378 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
379 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
382 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
384 * If applicable returns unique QName of data node as defined in YANG
387 * This method may return null, if the corresponding schema node, does
388 * not have QName associated, such as in cases of augmentations.
395 * Return the string representation of this object for use in context
396 * provided by a previous object. This method can be implemented in
397 * terms of {@link #toString()}, but implementations are encourage to
398 * reuse any context already emitted by the previous object.
400 * @param previous Previous path argument
401 * @return String representation
403 String toRelativeString(PathArgument previous);
406 private static abstract class AbstractPathArgument implements PathArgument {
407 private static final long serialVersionUID = -4546547994250849340L;
408 private final QName nodeType;
409 private transient int hashValue;
410 private transient volatile boolean hashGuard = false;
412 protected AbstractPathArgument(final QName nodeType) {
413 this.nodeType = Preconditions.checkNotNull(nodeType);
417 public final QName getNodeType() {
422 public int compareTo(final PathArgument o) {
423 return nodeType.compareTo(o.getNodeType());
426 protected int hashCodeImpl() {
427 return 31 + getNodeType().hashCode();
431 public final int hashCode() {
433 hashValue = hashCodeImpl();
441 public boolean equals(final Object obj) {
445 if (obj == null || this.getClass() != obj.getClass()) {
449 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
453 public String toString() {
454 return getNodeType().toString();
458 public String toRelativeString(final PathArgument previous) {
459 if (previous instanceof AbstractPathArgument) {
460 final QNameModule mod = ((AbstractPathArgument)previous).getNodeType().getModule();
461 if (getNodeType().getModule().equals(mod)) {
462 return getNodeType().getLocalName();
466 return getNodeType().toString();
471 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
472 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
474 public static final class NodeIdentifier extends AbstractPathArgument {
475 private static final long serialVersionUID = -2255888212390871347L;
476 private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
477 .build(new CacheLoader<QName, NodeIdentifier>() {
479 public NodeIdentifier load(final QName key) {
480 return new NodeIdentifier(key);
484 public NodeIdentifier(final QName node) {
489 * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
490 * instance cache, resulting in object reuse for equal inputs.
492 * @param node Node's QName
493 * @return A {@link NodeIdentifier}
495 public static NodeIdentifier create(final QName node) {
496 return CACHE.getUnchecked(node);
501 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
504 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
505 private static final long serialVersionUID = -4787195606494761540L;
507 private final Map<QName, Object> keyValues;
509 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
511 // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
512 this.keyValues = ImmutableOffsetMap.unorderedCopyOf(keyValues);
515 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
517 this.keyValues = SharedSingletonMap.unorderedOf(key, value);
520 public Map<QName, Object> getKeyValues() {
525 protected int hashCodeImpl() {
526 final int prime = 31;
527 int result = super.hashCodeImpl();
528 result = prime * result;
530 for (Entry<QName, Object> entry : keyValues.entrySet()) {
531 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
537 public boolean equals(final Object obj) {
538 if (!super.equals(obj)) {
542 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
544 // TODO: benchmark to see if just calling equals() on the two maps is not faster
545 if (keyValues == otherKeyValues) {
548 if (keyValues.size() != otherKeyValues.size()) {
552 for (Entry<QName, Object> entry : keyValues.entrySet()) {
553 if (!otherKeyValues.containsKey(entry.getKey())
554 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
564 public String toString() {
565 return super.toString() + '[' + keyValues + ']';
569 public String toRelativeString(final PathArgument previous) {
570 return super.toRelativeString(previous) + '[' + keyValues + ']';
575 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
578 public static final class NodeWithValue<T> extends AbstractPathArgument {
579 private static final long serialVersionUID = -3637456085341738431L;
581 private final T value;
583 public NodeWithValue(final QName node, final T value) {
588 public T getValue() {
593 protected int hashCodeImpl() {
594 final int prime = 31;
595 int result = super.hashCodeImpl();
596 result = prime * result + YangInstanceIdentifier.hashCode(value);
601 public boolean equals(final Object obj) {
602 if (!super.equals(obj)) {
605 final NodeWithValue<?> other = (NodeWithValue<?>) obj;
606 return Objects.deepEquals(value, other.value);
610 public String toString() {
611 return super.toString() + '[' + value + ']';
615 public String toRelativeString(final PathArgument previous) {
616 return super.toRelativeString(previous) + '[' + value + ']';
621 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} node in
622 * particular subtree.
624 * Augmentation is uniquely identified by set of all possible child nodes.
626 * to identify instance of augmentation,
627 * since RFC6020 states that <code>augment</code> that augment
628 * statement must not add multiple nodes from same namespace
629 * / module to the target node.
632 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
634 public static final class AugmentationIdentifier implements PathArgument {
635 private static final long serialVersionUID = -8122335594681936939L;
636 private final ImmutableSet<QName> childNames;
639 public QName getNodeType() {
640 // This should rather throw exception than return always null
641 throw new UnsupportedOperationException("Augmentation node has no QName");
646 * Construct new augmentation identifier using supplied set of possible
650 * Set of possible child nodes.
652 public AugmentationIdentifier(final Set<QName> childNames) {
653 this.childNames = ImmutableSet.copyOf(childNames);
657 * Returns set of all possible child nodes
659 * @return set of all possible child nodes.
661 public Set<QName> getPossibleChildNames() {
666 public String toString() {
667 final StringBuilder sb = new StringBuilder("AugmentationIdentifier{");
668 sb.append("childNames=").append(childNames).append('}');
669 return sb.toString();
673 public String toRelativeString(final PathArgument previous) {
678 public boolean equals(final Object o) {
682 if (!(o instanceof AugmentationIdentifier)) {
686 AugmentationIdentifier that = (AugmentationIdentifier) o;
687 return childNames.equals(that.childNames);
691 public int hashCode() {
692 return childNames.hashCode();
696 public int compareTo(final PathArgument o) {
697 if (!(o instanceof AugmentationIdentifier)) {
700 AugmentationIdentifier other = (AugmentationIdentifier) o;
701 Set<QName> otherChildNames = other.getPossibleChildNames();
702 int thisSize = childNames.size();
703 int otherSize = otherChildNames.size();
704 if (thisSize == otherSize) {
705 Iterator<QName> otherIterator = otherChildNames.iterator();
706 for (QName name : childNames) {
707 int c = name.compareTo(otherIterator.next());
713 } else if (thisSize < otherSize) {
722 * Fluent Builder of Instance Identifier instances
724 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
726 * Adds a {@link PathArgument} to to path arguments of resulting instance identifier.
728 * @param arg A {@link PathArgument} to be added
729 * @return this builder
731 InstanceIdentifierBuilder node(PathArgument arg);
734 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
736 * @param nodeType QName of {@link NodeIdentifier} which will be added
737 * @return this builder
739 InstanceIdentifierBuilder node(QName nodeType);
742 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting instance identifier.
744 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
745 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
746 * @return this builder
748 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
751 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
753 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
754 * @param key QName of key which will be added
755 * @param value value of key which will be added
756 * @return this builder
758 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
762 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder
764 * @return {@link YangInstanceIdentifier}
767 YangInstanceIdentifier build();