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.
50 * Constraints put in YANG specification on instance-identifier allowed it to be
51 * effectively represented in Java and it's evaluation does not require
52 * full-blown XPath processor.
54 * <h3>Path Arguments</h3>
55 * Path to the node represented in instance identifier consists of
56 * {@link PathArgument} which carries necessary information to uniquely identify
57 * node on particular level in the subtree.
60 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
61 * <code>0..1</code> in particular subtree in data tree.</li>
62 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item),
63 * which has cardinality <code>0..n</code>.</li>
64 * <li>{@link NodeWithValue} - Identifier of instance <code>leaf</code> node or
65 * <code>leaf-list</code> node.</li>
66 * <li>{@link AugmentationIdentifier} - Identifier of instance of
67 * <code>augmentation</code> node.</li>
71 * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
73 public abstract class YangInstanceIdentifier implements Path<YangInstanceIdentifier>, Immutable, Serializable {
75 * An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual
76 * root of the YANG namespace.
78 public static final YangInstanceIdentifier EMPTY = FixedYangInstanceIdentifier.EMPTY_INSTANCE;
80 private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, String> TOSTRINGCACHE_UPDATER =
81 AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, String.class, "toStringCache");
82 private static final long serialVersionUID = 4L;
84 private final int hash;
85 private transient volatile String toStringCache = null;
87 // Package-private to prevent outside subclassing
88 YangInstanceIdentifier(final int hash) {
92 @Nonnull abstract YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
93 @Nonnull abstract Collection<PathArgument> tryPathArguments();
94 @Nonnull abstract Collection<PathArgument> tryReversePathArguments();
97 * Check if this instance identifier has empty path arguments, e.g. it is
98 * empty and corresponds to {@link #EMPTY}.
100 * @return True if this instance identifier is empty, false otherwise.
102 public abstract boolean isEmpty();
105 * Return an optimized version of this identifier, useful when the identifier
106 * will be used very frequently.
108 * @return A optimized equivalent instance.
111 public abstract YangInstanceIdentifier toOptimized();
114 * Return the conceptual parent {@link YangInstanceIdentifier}, which has
115 * one item less in {@link #getPathArguments()}.
117 * @return Parent {@link YangInstanceIdentifier}, or null if this is object is {@link #EMPTY}.
119 @Nullable public abstract YangInstanceIdentifier getParent();
122 * Returns an ordered iteration of path arguments.
124 * @return Immutable iteration of path arguments.
126 public abstract List<PathArgument> getPathArguments();
129 * Returns an iterable of path arguments in reverse order. This is useful
130 * when walking up a tree organized this way.
132 * @return Immutable iterable of path arguments in reverse order.
134 public abstract List<PathArgument> getReversePathArguments();
137 * Returns the last PathArgument. This is equivalent of iterating
138 * to the last element of the iterable returned by {@link #getPathArguments()}.
140 * @return The last past argument, or null if there are no PathArguments.
142 public abstract PathArgument getLastPathArgument();
144 public static YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
145 if (Iterables.isEmpty(path)) {
149 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
150 for (PathArgument a : path) {
154 return FixedYangInstanceIdentifier.create(path, hash.build());
157 public static YangInstanceIdentifier create(final PathArgument... path) {
158 // We are forcing a copy, since we cannot trust the user
159 return create(Arrays.asList(path));
163 public final int hashCode() {
165 * The caching is safe, since the object contract requires
166 * immutability of the object and all objects referenced from this
168 * Used lists, maps are immutable. Path Arguments (elements) are also
169 * immutable, since the PathArgument contract requires immutability.
174 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
175 return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
179 public boolean equals(final Object obj) {
183 if (!(obj instanceof YangInstanceIdentifier)) {
186 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
187 if (this.hashCode() != obj.hashCode()) {
191 return pathArgumentsEqual(other);
195 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments
197 * @param name QName of {@link NodeIdentifier}
198 * @return Instance Identifier with additional path argument added to the end.
200 public final YangInstanceIdentifier node(final QName name) {
201 return node(new NodeIdentifier(name));
206 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments
208 * @param arg Path argument which should be added to the end
209 * @return Instance Identifier with additional path argument added to the end.
211 public final YangInstanceIdentifier node(final PathArgument arg) {
212 return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
216 * Get the relative path from an ancestor. This method attempts to perform
217 * the reverse of concatenating a base (ancestor) and a path.
220 * Ancestor against which the relative path should be calculated
221 * @return This object's relative path from parent, or Optional.absent() if
222 * the specified parent is not in fact an ancestor of this object.
224 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
225 final Iterator<?> lit = getPathArguments().iterator();
226 final Iterator<?> oit = ancestor.getPathArguments().iterator();
229 while (oit.hasNext()) {
230 // Ancestor is not really an ancestor
231 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
232 return Optional.absent();
239 return Optional.of(this);
241 if (!lit.hasNext()) {
242 return Optional.of(EMPTY);
245 return Optional.of(createRelativeIdentifier(common));
249 public final boolean contains(final YangInstanceIdentifier other) {
250 Preconditions.checkArgument(other != null, "other should not be null");
252 final Iterator<?> lit = getPathArguments().iterator();
253 final Iterator<?> oit = other.getPathArguments().iterator();
255 while (lit.hasNext()) {
256 if (!oit.hasNext()) {
260 if (!lit.next().equals(oit.next())) {
269 public final String toString() {
271 * The toStringCache is safe, since the object contract requires
272 * immutability of the object and all objects referenced from this
274 * Used lists, maps are immutable. Path Arguments (elements) are also
275 * immutable, since the PathArgument contract requires immutability.
276 * The cache is thread-safe - if multiple computations occurs at the
277 * same time, cache will be overwritten with same result.
279 String ret = toStringCache;
281 final StringBuilder builder = new StringBuilder("/");
282 PathArgument prev = null;
283 for (PathArgument argument : getPathArguments()) {
287 builder.append(argument.toRelativeString(prev));
291 ret = builder.toString();
292 TOSTRINGCACHE_UPDATER.lazySet(this, ret);
297 private static int hashCode(final Object value) {
302 if (byte[].class.equals(value.getClass())) {
303 return Arrays.hashCode((byte[]) value);
306 if (value.getClass().isArray()) {
308 int length = Array.getLength(value);
309 for (int i = 0; i < length; i++) {
310 hash += Objects.hashCode(Array.get(value, i));
316 return Objects.hashCode(value);
319 // Static factories & helpers
322 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied QName
324 * @param name QName of first node identifier
325 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
327 public static YangInstanceIdentifier of(final QName name) {
328 return create(new NodeIdentifier(name));
332 * Returns new builder for InstanceIdentifier with empty path arguments.
334 * @return new builder for InstanceIdentifier with empty path arguments.
336 public static InstanceIdentifierBuilder builder() {
337 return new YangInstanceIdentifierBuilder();
342 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
344 * @param origin InstanceIdentifier from which path arguments are copied.
345 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
347 public static InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
348 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
352 * Path argument / component of InstanceIdentifier
354 * Path argument uniquely identifies node in data tree on particular
357 * This interface itself is used as common parent for actual
358 * path arguments types and should not be implemented by user code.
360 * Path arguments SHOULD contain only minimum of information
361 * required to uniquely identify node on particular subtree level.
363 * For actual path arguments types see:
365 * <li>{@link NodeIdentifier} - Identifier of container or leaf
366 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
367 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
368 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
371 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
373 * If applicable returns unique QName of data node as defined in YANG
376 * This method may return null, if the corresponding schema node, does
377 * not have QName associated, such as in cases of augmentations.
384 * Return the string representation of this object for use in context
385 * provided by a previous object. This method can be implemented in
386 * terms of {@link #toString()}, but implementations are encourage to
387 * reuse any context already emitted by the previous object.
389 * @param previous Previous path argument
390 * @return String representation
392 String toRelativeString(PathArgument previous);
395 private static abstract class AbstractPathArgument implements PathArgument {
396 private static final long serialVersionUID = -4546547994250849340L;
397 private final QName nodeType;
398 private transient int hashValue;
399 private volatile transient boolean hashGuard = false;
401 protected AbstractPathArgument(final QName nodeType) {
402 this.nodeType = Preconditions.checkNotNull(nodeType);
406 public final QName getNodeType() {
411 public int compareTo(final PathArgument o) {
412 return nodeType.compareTo(o.getNodeType());
415 protected int hashCodeImpl() {
416 return 31 + getNodeType().hashCode();
420 public final int hashCode() {
422 hashValue = hashCodeImpl();
430 public boolean equals(final Object obj) {
434 if (obj == null || this.getClass() != obj.getClass()) {
438 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
442 public String toString() {
443 return getNodeType().toString();
447 public String toRelativeString(final PathArgument previous) {
448 if (previous instanceof AbstractPathArgument) {
449 final QNameModule mod = ((AbstractPathArgument)previous).getNodeType().getModule();
450 if (getNodeType().getModule().equals(mod)) {
451 return getNodeType().getLocalName();
455 return getNodeType().toString();
460 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
461 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
463 public static final class NodeIdentifier extends AbstractPathArgument {
464 private static final long serialVersionUID = -2255888212390871347L;
465 private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
466 .build(new CacheLoader<QName, NodeIdentifier>() {
468 public NodeIdentifier load(final QName key) {
469 return new NodeIdentifier(key);
473 public NodeIdentifier(final QName node) {
478 * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
479 * instance cache, resulting in object reuse for equal inputs.
481 * @param node Node's QName
482 * @return A {@link NodeIdentifier}
484 public static NodeIdentifier create(final QName node) {
485 return CACHE.getUnchecked(node);
490 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
493 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
494 private static final long serialVersionUID = -4787195606494761540L;
496 private final Map<QName, Object> keyValues;
498 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
500 // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
501 this.keyValues = ImmutableOffsetMap.copyOf(keyValues);
504 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
505 this(node, SharedSingletonMap.of(key, value));
508 public Map<QName, Object> getKeyValues() {
513 protected int hashCodeImpl() {
514 final int prime = 31;
515 int result = super.hashCodeImpl();
516 result = prime * result;
518 for (Entry<QName, Object> entry : keyValues.entrySet()) {
519 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
525 public boolean equals(final Object obj) {
526 if (!super.equals(obj)) {
530 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
532 // TODO: benchmark to see if just calling equals() on the two maps is not faster
533 if (keyValues == otherKeyValues) {
536 if (keyValues.size() != otherKeyValues.size()) {
540 for (Entry<QName, Object> entry : keyValues.entrySet()) {
541 if (!otherKeyValues.containsKey(entry.getKey())
542 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
552 public String toString() {
553 return super.toString() + '[' + keyValues + ']';
557 public String toRelativeString(final PathArgument previous) {
558 return super.toRelativeString(previous) + '[' + keyValues + ']';
563 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
566 public static final class NodeWithValue extends AbstractPathArgument {
567 private static final long serialVersionUID = -3637456085341738431L;
569 private final Object value;
571 public NodeWithValue(final QName node, final Object value) {
576 public Object getValue() {
581 protected int hashCodeImpl() {
582 final int prime = 31;
583 int result = super.hashCodeImpl();
584 result = prime * result + ((value == null) ? 0 : YangInstanceIdentifier.hashCode(value));
589 public boolean equals(final Object obj) {
590 if (!super.equals(obj)) {
593 final NodeWithValue other = (NodeWithValue) obj;
594 return Objects.deepEquals(value, other.value);
598 public String toString() {
599 return super.toString() + '[' + value + ']';
603 public String toRelativeString(final PathArgument previous) {
604 return super.toRelativeString(previous) + '[' + value + ']';
609 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} node in
610 * particular subtree.
612 * Augmentation is uniquely identified by set of all possible child nodes.
614 * to identify instance of augmentation,
615 * since RFC6020 states that <code>augment</code> that augment
616 * statement must not add multiple nodes from same namespace
617 * / module to the target node.
620 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
622 public static final class AugmentationIdentifier implements PathArgument {
623 private static final long serialVersionUID = -8122335594681936939L;
624 private final ImmutableSet<QName> childNames;
627 public QName getNodeType() {
628 // This should rather throw exception than return always null
629 throw new UnsupportedOperationException("Augmentation node has no QName");
634 * Construct new augmentation identifier using supplied set of possible
638 * Set of possible child nodes.
640 public AugmentationIdentifier(final Set<QName> childNames) {
641 this.childNames = ImmutableSet.copyOf(childNames);
645 * Returns set of all possible child nodes
647 * @return set of all possible child nodes.
649 public Set<QName> getPossibleChildNames() {
654 public String toString() {
655 final StringBuilder sb = new StringBuilder("AugmentationIdentifier{");
656 sb.append("childNames=").append(childNames).append('}');
657 return sb.toString();
661 public String toRelativeString(final PathArgument previous) {
666 public boolean equals(final Object o) {
670 if (!(o instanceof AugmentationIdentifier)) {
674 AugmentationIdentifier that = (AugmentationIdentifier) o;
675 return childNames.equals(that.childNames);
679 public int hashCode() {
680 return childNames.hashCode();
684 public int compareTo(final PathArgument o) {
685 if (!(o instanceof AugmentationIdentifier)) {
688 AugmentationIdentifier other = (AugmentationIdentifier) o;
689 Set<QName> otherChildNames = other.getPossibleChildNames();
690 int thisSize = childNames.size();
691 int otherSize = otherChildNames.size();
692 if (thisSize == otherSize) {
693 Iterator<QName> otherIterator = otherChildNames.iterator();
694 for (QName name : childNames) {
695 int c = name.compareTo(otherIterator.next());
701 } else if (thisSize < otherSize) {
710 * Fluent Builder of Instance Identifier instances
712 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
714 * Adds a {@link PathArgument} to to path arguments of resulting instance identifier.
716 * @param arg A {@link PathArgument} to be added
717 * @return this builder
719 InstanceIdentifierBuilder node(PathArgument arg);
722 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
724 * @param nodeType QName of {@link NodeIdentifier} which will be added
725 * @return this builder
727 InstanceIdentifierBuilder node(QName nodeType);
730 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting instance identifier.
732 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
733 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
734 * @return this builder
736 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
739 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
741 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
742 * @param key QName of key which will be added
743 * @param value value of key which will be added
744 * @return this builder
746 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
750 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder
752 * @return {@link YangInstanceIdentifier}
755 YangInstanceIdentifier build();
758 * @deprecated use #build()
761 YangInstanceIdentifier toInstance();