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 if (this == ancestor) {
237 return Optional.of(EMPTY);
239 if (ancestor.isEmpty()) {
240 return Optional.of(this);
243 final Iterator<?> lit = getPathArguments().iterator();
244 final Iterator<?> oit = ancestor.getPathArguments().iterator();
247 while (oit.hasNext()) {
248 // Ancestor is not really an ancestor
249 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
250 return Optional.absent();
257 return Optional.of(this);
259 if (!lit.hasNext()) {
260 return Optional.of(EMPTY);
263 return Optional.of(createRelativeIdentifier(common));
267 public final boolean contains(final YangInstanceIdentifier other) {
272 Preconditions.checkArgument(other != null, "other should not be null");
273 final Iterator<?> lit = getPathArguments().iterator();
274 final Iterator<?> oit = other.getPathArguments().iterator();
276 while (lit.hasNext()) {
277 if (!oit.hasNext()) {
281 if (!lit.next().equals(oit.next())) {
290 public final String toString() {
292 * The toStringCache is safe, since the object contract requires
293 * immutability of the object and all objects referenced from this
295 * Used lists, maps are immutable. Path Arguments (elements) are also
296 * immutable, since the PathArgument contract requires immutability.
297 * The cache is thread-safe - if multiple computations occurs at the
298 * same time, cache will be overwritten with same result.
300 String ret = toStringCache;
302 final StringBuilder builder = new StringBuilder("/");
303 PathArgument prev = null;
304 for (PathArgument argument : getPathArguments()) {
308 builder.append(argument.toRelativeString(prev));
312 ret = builder.toString();
313 TOSTRINGCACHE_UPDATER.lazySet(this, ret);
318 private static int hashCode(final Object value) {
323 if (byte[].class.equals(value.getClass())) {
324 return Arrays.hashCode((byte[]) value);
327 if (value.getClass().isArray()) {
329 int length = Array.getLength(value);
330 for (int i = 0; i < length; i++) {
331 hash += Objects.hashCode(Array.get(value, i));
337 return Objects.hashCode(value);
340 // Static factories & helpers
343 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied QName
345 * @param name QName of first node identifier
346 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
348 public static YangInstanceIdentifier of(final QName name) {
349 return create(new NodeIdentifier(name));
353 * Returns new builder for InstanceIdentifier with empty path arguments.
355 * @return new builder for InstanceIdentifier with empty path arguments.
357 public static InstanceIdentifierBuilder builder() {
358 return new YangInstanceIdentifierBuilder();
363 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
365 * @param origin InstanceIdentifier from which path arguments are copied.
366 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
368 public static InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
369 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
373 * Path argument / component of InstanceIdentifier
375 * Path argument uniquely identifies node in data tree on particular
378 * This interface itself is used as common parent for actual
379 * path arguments types and should not be implemented by user code.
381 * Path arguments SHOULD contain only minimum of information
382 * required to uniquely identify node on particular subtree level.
384 * For actual path arguments types see:
386 * <li>{@link NodeIdentifier} - Identifier of container or leaf
387 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
388 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
389 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
392 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
394 * If applicable returns unique QName of data node as defined in YANG
397 * This method may return null, if the corresponding schema node, does
398 * not have QName associated, such as in cases of augmentations.
405 * Return the string representation of this object for use in context
406 * provided by a previous object. This method can be implemented in
407 * terms of {@link #toString()}, but implementations are encourage to
408 * reuse any context already emitted by the previous object.
410 * @param previous Previous path argument
411 * @return String representation
413 String toRelativeString(PathArgument previous);
416 private static abstract class AbstractPathArgument implements PathArgument {
417 private static final long serialVersionUID = -4546547994250849340L;
418 private final QName nodeType;
419 private transient int hashValue;
420 private transient volatile boolean hashGuard = false;
422 protected AbstractPathArgument(final QName nodeType) {
423 this.nodeType = Preconditions.checkNotNull(nodeType);
427 public final QName getNodeType() {
432 public int compareTo(final PathArgument o) {
433 return nodeType.compareTo(o.getNodeType());
436 protected int hashCodeImpl() {
437 return 31 + getNodeType().hashCode();
441 public final int hashCode() {
443 hashValue = hashCodeImpl();
451 public boolean equals(final Object obj) {
455 if (obj == null || this.getClass() != obj.getClass()) {
459 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
463 public String toString() {
464 return getNodeType().toString();
468 public String toRelativeString(final PathArgument previous) {
469 if (previous instanceof AbstractPathArgument) {
470 final QNameModule mod = previous.getNodeType().getModule();
471 if (getNodeType().getModule().equals(mod)) {
472 return getNodeType().getLocalName();
476 return getNodeType().toString();
481 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
482 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
484 public static final class NodeIdentifier extends AbstractPathArgument {
485 private static final long serialVersionUID = -2255888212390871347L;
486 private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
487 .build(new CacheLoader<QName, NodeIdentifier>() {
489 public NodeIdentifier load(final QName key) {
490 return new NodeIdentifier(key);
494 public NodeIdentifier(final QName node) {
499 * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
500 * instance cache, resulting in object reuse for equal inputs.
502 * @param node Node's QName
503 * @return A {@link NodeIdentifier}
505 public static NodeIdentifier create(final QName node) {
506 return CACHE.getUnchecked(node);
511 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
514 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
515 private static final long serialVersionUID = -4787195606494761540L;
517 private final Map<QName, Object> keyValues;
519 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
521 // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
522 this.keyValues = ImmutableOffsetMap.unorderedCopyOf(keyValues);
525 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
527 this.keyValues = SharedSingletonMap.unorderedOf(key, value);
530 public Map<QName, Object> getKeyValues() {
535 protected int hashCodeImpl() {
536 final int prime = 31;
537 int result = super.hashCodeImpl();
538 result = prime * result;
540 for (Entry<QName, Object> entry : keyValues.entrySet()) {
541 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
547 public boolean equals(final Object obj) {
548 if (!super.equals(obj)) {
552 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
554 // TODO: benchmark to see if just calling equals() on the two maps is not faster
555 if (keyValues == otherKeyValues) {
558 if (keyValues.size() != otherKeyValues.size()) {
562 for (Entry<QName, Object> entry : keyValues.entrySet()) {
563 if (!otherKeyValues.containsKey(entry.getKey())
564 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
574 public String toString() {
575 return super.toString() + '[' + keyValues + ']';
579 public String toRelativeString(final PathArgument previous) {
580 return super.toRelativeString(previous) + '[' + keyValues + ']';
585 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
588 public static final class NodeWithValue<T> extends AbstractPathArgument {
589 private static final long serialVersionUID = -3637456085341738431L;
591 private final T value;
593 public NodeWithValue(final QName node, final T value) {
598 public T getValue() {
603 protected int hashCodeImpl() {
604 final int prime = 31;
605 int result = super.hashCodeImpl();
606 result = prime * result + YangInstanceIdentifier.hashCode(value);
611 public boolean equals(final Object obj) {
612 if (!super.equals(obj)) {
615 final NodeWithValue<?> other = (NodeWithValue<?>) obj;
616 return Objects.deepEquals(value, other.value);
620 public String toString() {
621 return super.toString() + '[' + value + ']';
625 public String toRelativeString(final PathArgument previous) {
626 return super.toRelativeString(previous) + '[' + value + ']';
631 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} node in
632 * particular subtree.
634 * Augmentation is uniquely identified by set of all possible child nodes.
636 * to identify instance of augmentation,
637 * since RFC6020 states that <code>augment</code> that augment
638 * statement must not add multiple nodes from same namespace
639 * / module to the target node.
642 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
644 public static final class AugmentationIdentifier implements PathArgument {
645 private static final long serialVersionUID = -8122335594681936939L;
646 private final ImmutableSet<QName> childNames;
649 public QName getNodeType() {
650 // This should rather throw exception than return always null
651 throw new UnsupportedOperationException("Augmentation node has no QName");
656 * Construct new augmentation identifier using supplied set of possible
660 * Set of possible child nodes.
662 public AugmentationIdentifier(final Set<QName> childNames) {
663 this.childNames = ImmutableSet.copyOf(childNames);
667 * Returns set of all possible child nodes
669 * @return set of all possible child nodes.
671 public Set<QName> getPossibleChildNames() {
676 public String toString() {
677 return "AugmentationIdentifier{" + "childNames=" + childNames + '}';
681 public String toRelativeString(final PathArgument previous) {
686 public boolean equals(final Object o) {
690 if (!(o instanceof AugmentationIdentifier)) {
694 AugmentationIdentifier that = (AugmentationIdentifier) o;
695 return childNames.equals(that.childNames);
699 public int hashCode() {
700 return childNames.hashCode();
704 public int compareTo(final PathArgument o) {
705 if (!(o instanceof AugmentationIdentifier)) {
708 AugmentationIdentifier other = (AugmentationIdentifier) o;
709 Set<QName> otherChildNames = other.getPossibleChildNames();
710 int thisSize = childNames.size();
711 int otherSize = otherChildNames.size();
712 if (thisSize == otherSize) {
713 Iterator<QName> otherIterator = otherChildNames.iterator();
714 for (QName name : childNames) {
715 int c = name.compareTo(otherIterator.next());
721 } else if (thisSize < otherSize) {
730 * Fluent Builder of Instance Identifier instances
732 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
734 * Adds a {@link PathArgument} to to path arguments of resulting instance identifier.
736 * @param arg A {@link PathArgument} to be added
737 * @return this builder
739 InstanceIdentifierBuilder node(PathArgument arg);
742 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
744 * @param nodeType QName of {@link NodeIdentifier} which will be added
745 * @return this builder
747 InstanceIdentifierBuilder node(QName nodeType);
750 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting instance identifier.
752 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
753 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
754 * @return this builder
756 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
759 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
761 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
762 * @param key QName of key which will be added
763 * @param value value of key which will be added
764 * @return this builder
766 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
770 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder
772 * @return {@link YangInstanceIdentifier}
775 YangInstanceIdentifier build();