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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.annotations.Beta;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.cache.CacheLoader;
17 import com.google.common.cache.LoadingCache;
18 import com.google.common.collect.ImmutableSet;
19 import com.google.common.collect.Iterables;
20 import com.google.common.collect.Sets;
21 import java.io.Serializable;
22 import java.lang.reflect.Array;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Iterator;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.Objects;
31 import java.util.Optional;
33 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
34 import javax.annotation.Nonnull;
35 import javax.annotation.Nullable;
36 import org.opendaylight.yangtools.concepts.Builder;
37 import org.opendaylight.yangtools.concepts.Immutable;
38 import org.opendaylight.yangtools.concepts.Path;
39 import org.opendaylight.yangtools.util.HashCodeBuilder;
40 import org.opendaylight.yangtools.util.ImmutableOffsetMap;
41 import org.opendaylight.yangtools.util.SharedSingletonMap;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.common.QNameModule;
44 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
47 * Unique identifier of a particular node instance in the data tree.
50 * Java representation of YANG Built-in type <code>instance-identifier</code>,
51 * which conceptually is XPath expression minimized to uniquely identify element
52 * in data tree which conforms to constraints maintained by YANG Model,
53 * effectively this makes Instance Identifier a path to element in data tree.
56 * Constraints put in YANG specification on instance-identifier allowed it to be
57 * effectively represented in Java and it's evaluation does not require
58 * full-blown XPath processor.
61 * <h3>Path Arguments</h3>
62 * Path to the node represented in instance identifier consists of
63 * {@link PathArgument} which carries necessary information to uniquely identify
64 * node on particular level in the subtree.
67 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
68 * <code>0..1</code> in particular subtree in data tree.</li>
69 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item),
70 * which has cardinality <code>0..n</code>.</li>
71 * <li>{@link NodeWithValue} - Identifier of instance <code>leaf</code> node or
72 * <code>leaf-list</code> node.</li>
73 * <li>{@link AugmentationIdentifier} - Identifier of instance of
74 * <code>augmentation</code> node.</li>
77 * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
79 public abstract class YangInstanceIdentifier implements Path<YangInstanceIdentifier>, Immutable, Serializable {
81 * An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual
82 * root of the YANG namespace.
84 public static final YangInstanceIdentifier EMPTY = FixedYangInstanceIdentifier.EMPTY_INSTANCE;
86 private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, String> TOSTRINGCACHE_UPDATER =
87 AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, String.class, "toStringCache");
88 private static final long serialVersionUID = 4L;
90 private final int hash;
91 private transient volatile String toStringCache = null;
93 // Package-private to prevent outside subclassing
94 YangInstanceIdentifier(final int hash) {
98 @Nonnull abstract YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
100 @Nonnull abstract Collection<PathArgument> tryPathArguments();
102 @Nonnull abstract Collection<PathArgument> tryReversePathArguments();
105 * Check if this instance identifier has empty path arguments, e.g. it is
106 * empty and corresponds to {@link #EMPTY}.
108 * @return True if this instance identifier is empty, false otherwise.
110 public abstract boolean isEmpty();
113 * Return an optimized version of this identifier, useful when the identifier
114 * will be used very frequently.
116 * @return A optimized equivalent instance.
119 public abstract YangInstanceIdentifier toOptimized();
122 * Return the conceptual parent {@link YangInstanceIdentifier}, which has
123 * one item less in {@link #getPathArguments()}.
125 * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #EMPTY}.
127 @Nullable public abstract YangInstanceIdentifier getParent();
130 * Return the ancestor {@link YangInstanceIdentifier} with a particular depth, e.g. number of path arguments.
132 * @param depth Ancestor depth
133 * @return Ancestor {@link YangInstanceIdentifier}
134 * @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
136 @Nonnull public abstract YangInstanceIdentifier getAncestor(int depth);
139 * Returns an ordered iteration of path arguments.
141 * @return Immutable iteration of path arguments.
143 public abstract List<PathArgument> getPathArguments();
146 * Returns an iterable of path arguments in reverse order. This is useful
147 * when walking up a tree organized this way.
149 * @return Immutable iterable of path arguments in reverse order.
151 public abstract List<PathArgument> getReversePathArguments();
154 * Returns the last PathArgument. This is equivalent of iterating
155 * to the last element of the iterable returned by {@link #getPathArguments()}.
157 * @return The last past argument, or null if there are no PathArguments.
159 public abstract PathArgument getLastPathArgument();
161 public static YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
162 if (Iterables.isEmpty(path)) {
166 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
167 for (PathArgument a : path) {
171 return FixedYangInstanceIdentifier.create(path, hash.build());
174 public static YangInstanceIdentifier create(final PathArgument... path) {
175 // We are forcing a copy, since we cannot trust the user
176 return create(Arrays.asList(path));
179 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
180 return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
184 public boolean equals(final Object obj) {
188 if (!(obj instanceof YangInstanceIdentifier)) {
191 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
192 if (this.hashCode() != obj.hashCode()) {
196 return pathArgumentsEqual(other);
200 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments.
202 * @param name QName of {@link NodeIdentifier}
203 * @return Instance Identifier with additional path argument added to the end.
205 public final YangInstanceIdentifier node(final QName name) {
206 return node(new NodeIdentifier(name));
210 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments.
212 * @param arg Path argument which should be added to the end
213 * @return Instance Identifier with additional path argument added to the end.
215 public final YangInstanceIdentifier node(final PathArgument arg) {
216 return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
220 * Get the relative path from an ancestor. This method attempts to perform
221 * the reverse of concatenating a base (ancestor) and a path.
224 * Ancestor against which the relative path should be calculated
225 * @return This object's relative path from parent, or Optional.absent() if
226 * the specified parent is not in fact an ancestor of this object.
228 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
229 if (this == ancestor) {
230 return Optional.of(EMPTY);
232 if (ancestor.isEmpty()) {
233 return Optional.of(this);
236 final Iterator<PathArgument> lit = getPathArguments().iterator();
237 final Iterator<PathArgument> 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.empty();
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(@Nonnull final YangInstanceIdentifier other) {
265 checkArgument(other != null, "other should not be null");
266 final Iterator<PathArgument> lit = getPathArguments().iterator();
267 final Iterator<PathArgument> oit = other.getPathArguments().iterator();
269 while (lit.hasNext()) {
270 if (!oit.hasNext()) {
274 if (!lit.next().equals(oit.next())) {
283 public final String toString() {
285 * The toStringCache is safe, since the object contract requires
286 * immutability of the object and all objects referenced from this
288 * Used lists, maps are immutable. Path Arguments (elements) are also
289 * immutable, since the PathArgument contract requires immutability.
290 * The cache is thread-safe - if multiple computations occurs at the
291 * same time, cache will be overwritten with same result.
293 String ret = toStringCache;
295 final StringBuilder builder = new StringBuilder("/");
296 PathArgument prev = null;
297 for (PathArgument argument : getPathArguments()) {
301 builder.append(argument.toRelativeString(prev));
305 ret = builder.toString();
306 TOSTRINGCACHE_UPDATER.lazySet(this, ret);
312 public final int hashCode() {
314 * The caching is safe, since the object contract requires
315 * immutability of the object and all objects referenced from this
317 * Used lists, maps are immutable. Path Arguments (elements) are also
318 * immutable, since the PathArgument contract requires immutability.
323 private static int hashCode(final Object value) {
328 if (byte[].class.equals(value.getClass())) {
329 return Arrays.hashCode((byte[]) value);
332 if (value.getClass().isArray()) {
334 int length = Array.getLength(value);
335 for (int i = 0; i < length; i++) {
336 hash += Objects.hashCode(Array.get(value, i));
342 return Objects.hashCode(value);
345 // Static factories & helpers
348 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied
351 * @param name QName of first node identifier
352 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
354 public static YangInstanceIdentifier of(final QName name) {
355 return create(new NodeIdentifier(name));
359 * Returns new builder for InstanceIdentifier with empty path arguments.
361 * @return new builder for InstanceIdentifier with empty path arguments.
363 public static InstanceIdentifierBuilder builder() {
364 return new YangInstanceIdentifierBuilder();
368 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
370 * @param origin InstanceIdentifier from which path arguments are copied.
371 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
373 public static InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
374 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
378 * Path argument / component of InstanceIdentifier.
379 * Path argument uniquely identifies node in data tree on particular
383 * This interface itself is used as common parent for actual
384 * path arguments types and should not be implemented by user code.
387 * Path arguments SHOULD contain only minimum of information
388 * required to uniquely identify node on particular subtree level.
391 * For actual path arguments types see:
393 * <li>{@link NodeIdentifier} - Identifier of container or leaf
394 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
395 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
396 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
399 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
401 * If applicable returns unique QName of data node as defined in YANG
405 * This method may return null, if the corresponding schema node, does
406 * not have QName associated, such as in cases of augmentations.
413 * Return the string representation of this object for use in context
414 * provided by a previous object. This method can be implemented in
415 * terms of {@link #toString()}, but implementations are encourage to
416 * reuse any context already emitted by the previous object.
418 * @param previous Previous path argument
419 * @return String representation
421 String toRelativeString(PathArgument previous);
424 private abstract static class AbstractPathArgument implements PathArgument {
425 private static final long serialVersionUID = -4546547994250849340L;
426 private final QName nodeType;
427 private transient int hashValue;
428 private transient volatile boolean hashGuard = false;
430 protected AbstractPathArgument(final QName nodeType) {
431 this.nodeType = requireNonNull(nodeType);
435 public final QName getNodeType() {
440 @SuppressWarnings("checkstyle:parameterName")
441 public int compareTo(@Nonnull final PathArgument o) {
442 return nodeType.compareTo(o.getNodeType());
445 protected int hashCodeImpl() {
446 return 31 + getNodeType().hashCode();
450 public final int hashCode() {
452 hashValue = hashCodeImpl();
460 public boolean equals(final Object obj) {
464 if (obj == null || this.getClass() != obj.getClass()) {
468 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
472 public String toString() {
473 return getNodeType().toString();
477 public String toRelativeString(final PathArgument previous) {
478 if (previous instanceof AbstractPathArgument) {
479 final QNameModule mod = previous.getNodeType().getModule();
480 if (getNodeType().getModule().equals(mod)) {
481 return getNodeType().getLocalName();
485 return getNodeType().toString();
490 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
491 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
493 public static final class NodeIdentifier extends AbstractPathArgument {
494 private static final long serialVersionUID = -2255888212390871347L;
495 private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
496 .build(new CacheLoader<QName, NodeIdentifier>() {
498 public NodeIdentifier load(@Nonnull final QName key) {
499 return new NodeIdentifier(key);
503 public NodeIdentifier(final QName node) {
508 * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
509 * instance cache, resulting in object reuse for equal inputs.
511 * @param node Node's QName
512 * @return A {@link NodeIdentifier}
514 public static NodeIdentifier create(final QName node) {
515 return CACHE.getUnchecked(node);
520 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
523 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
524 private static final long serialVersionUID = -4787195606494761540L;
526 private final Map<QName, Object> keyValues;
528 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
530 // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
531 this.keyValues = ImmutableOffsetMap.unorderedCopyOf(keyValues);
534 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
536 this.keyValues = SharedSingletonMap.unorderedOf(key, value);
539 public Map<QName, Object> getKeyValues() {
544 protected int hashCodeImpl() {
545 final int prime = 31;
546 int result = super.hashCodeImpl();
547 result = prime * result;
549 for (Entry<QName, Object> entry : keyValues.entrySet()) {
550 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
556 @SuppressWarnings("checkstyle:equalsHashCode")
557 public boolean equals(final Object obj) {
558 if (!super.equals(obj)) {
562 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
564 // TODO: benchmark to see if just calling equals() on the two maps is not faster
565 if (keyValues == otherKeyValues) {
568 if (keyValues.size() != otherKeyValues.size()) {
572 for (Entry<QName, Object> entry : keyValues.entrySet()) {
573 if (!otherKeyValues.containsKey(entry.getKey())
574 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
584 public String toString() {
585 return super.toString() + '[' + keyValues + ']';
589 public String toRelativeString(final PathArgument previous) {
590 return super.toRelativeString(previous) + '[' + keyValues + ']';
595 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
598 public static final class NodeWithValue<T> extends AbstractPathArgument {
599 private static final long serialVersionUID = -3637456085341738431L;
601 private final T value;
603 public NodeWithValue(final QName node, final T value) {
608 public T getValue() {
613 protected int hashCodeImpl() {
614 final int prime = 31;
615 int result = super.hashCodeImpl();
616 result = prime * result + YangInstanceIdentifier.hashCode(value);
621 @SuppressWarnings("checkstyle:equalsHashCode")
622 public boolean equals(final Object obj) {
623 if (!super.equals(obj)) {
626 final NodeWithValue<?> other = (NodeWithValue<?>) obj;
627 return Objects.deepEquals(value, other.value);
631 public String toString() {
632 return super.toString() + '[' + value + ']';
636 public String toRelativeString(final PathArgument previous) {
637 return super.toRelativeString(previous) + '[' + value + ']';
642 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode}
643 * node in 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.
653 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
655 public static final class AugmentationIdentifier implements PathArgument {
656 private static final long serialVersionUID = -8122335594681936939L;
657 private final ImmutableSet<QName> childNames;
660 public QName getNodeType() {
661 // This should rather throw exception than return always null
662 throw new UnsupportedOperationException("Augmentation node has no QName");
666 * Construct new augmentation identifier using supplied set of possible
670 * Set of possible child nodes.
672 public AugmentationIdentifier(final Set<QName> childNames) {
673 this.childNames = ImmutableSet.copyOf(childNames);
677 * Returns set of all possible child nodes.
679 * @return set of all possible child nodes.
681 public Set<QName> getPossibleChildNames() {
686 public String toString() {
687 return "AugmentationIdentifier{" + "childNames=" + childNames + '}';
691 public String toRelativeString(final PathArgument previous) {
696 public boolean equals(final Object obj) {
700 if (!(obj instanceof AugmentationIdentifier)) {
704 AugmentationIdentifier that = (AugmentationIdentifier) obj;
705 return childNames.equals(that.childNames);
709 public int hashCode() {
710 return childNames.hashCode();
714 @SuppressWarnings("checkstyle:parameterName")
715 public int compareTo(@Nonnull final PathArgument o) {
716 if (!(o instanceof AugmentationIdentifier)) {
719 AugmentationIdentifier other = (AugmentationIdentifier) o;
720 Set<QName> otherChildNames = other.getPossibleChildNames();
721 int thisSize = childNames.size();
722 int otherSize = otherChildNames.size();
723 if (thisSize == otherSize) {
724 // Quick Set-based comparison
725 if (childNames.equals(otherChildNames)) {
729 // We already know the sets are not equal, but have equal size, hence the sets differ in their elements,
730 // but potentially share a common set of elements. The most consistent way of comparing them is using
731 // total ordering defined by QName's compareTo. Hence convert both sets to lists ordered
732 // by QName.compareTo() and decide on the first differing element.
733 final List<QName> diff = new ArrayList<>(Sets.symmetricDifference(childNames, otherChildNames));
734 verify(!diff.isEmpty(), "Augmentation identifiers %s and %s report no difference", this, o);
735 diff.sort(QName::compareTo);
736 return childNames.contains(diff.get(0)) ? -1 : 1;
737 } else if (thisSize < otherSize) {
746 * Fluent Builder of Instance Identifier instances.
748 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
750 * Adds a {@link PathArgument} to path arguments of resulting instance identifier.
752 * @param arg A {@link PathArgument} to be added
753 * @return this builder
755 InstanceIdentifierBuilder node(PathArgument arg);
758 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
760 * @param nodeType QName of {@link NodeIdentifier} which will be added
761 * @return this builder
763 InstanceIdentifierBuilder node(QName nodeType);
766 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting
767 * instance identifier.
769 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
770 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
771 * @return this builder
773 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
776 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
778 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
779 * @param key QName of key which will be added
780 * @param value value of key which will be added
781 * @return this builder
783 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
786 * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
788 * @param args {@link PathArgument}s to be added
789 * @return this builder
790 * @throws NullPointerException if any of the arguments is null
793 InstanceIdentifierBuilder append(Collection<? extends PathArgument> args);
796 * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
798 * @param args {@link PathArgument}s to be added
799 * @return this builder
800 * @throws NullPointerException if any of the arguments is null
803 default InstanceIdentifierBuilder append(final PathArgument... args) {
804 return append(Arrays.asList(args));
808 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder.
810 * @return {@link YangInstanceIdentifier}
813 YangInstanceIdentifier build();