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 // FIXME: 3.0.0: this concept needs to be moved to yang-common, as parser components need the ability to refer
80 // to data nodes -- most notably XPath expressions and {@code default} statement arguments need to be able
81 // to represent these.
82 public abstract class YangInstanceIdentifier implements Path<YangInstanceIdentifier>, Immutable, Serializable {
84 * An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual
85 * root of the YANG namespace.
87 public static final YangInstanceIdentifier EMPTY = FixedYangInstanceIdentifier.EMPTY_INSTANCE;
89 private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, String> TOSTRINGCACHE_UPDATER =
90 AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, String.class, "toStringCache");
91 private static final long serialVersionUID = 4L;
93 private final int hash;
94 private transient volatile String toStringCache = null;
96 // Package-private to prevent outside subclassing
97 YangInstanceIdentifier(final int hash) {
101 @Nonnull abstract YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
103 @Nonnull abstract Collection<PathArgument> tryPathArguments();
105 @Nonnull abstract Collection<PathArgument> tryReversePathArguments();
108 * Check if this instance identifier has empty path arguments, e.g. it is
109 * empty and corresponds to {@link #EMPTY}.
111 * @return True if this instance identifier is empty, false otherwise.
113 public abstract boolean isEmpty();
116 * Return an optimized version of this identifier, useful when the identifier
117 * will be used very frequently.
119 * @return A optimized equivalent instance.
122 public abstract YangInstanceIdentifier toOptimized();
125 * Return the conceptual parent {@link YangInstanceIdentifier}, which has
126 * one item less in {@link #getPathArguments()}.
128 * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #EMPTY}.
130 @Nullable public abstract YangInstanceIdentifier getParent();
133 * Return the ancestor {@link YangInstanceIdentifier} with a particular depth, e.g. number of path arguments.
135 * @param depth Ancestor depth
136 * @return Ancestor {@link YangInstanceIdentifier}
137 * @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
139 @Nonnull public abstract YangInstanceIdentifier getAncestor(int depth);
142 * Returns an ordered iteration of path arguments.
144 * @return Immutable iteration of path arguments.
146 public abstract List<PathArgument> getPathArguments();
149 * Returns an iterable of path arguments in reverse order. This is useful
150 * when walking up a tree organized this way.
152 * @return Immutable iterable of path arguments in reverse order.
154 public abstract List<PathArgument> getReversePathArguments();
157 * Returns the last PathArgument. This is equivalent of iterating
158 * to the last element of the iterable returned by {@link #getPathArguments()}.
160 * @return The last past argument, or null if there are no PathArguments.
162 public abstract PathArgument getLastPathArgument();
164 public static YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
165 if (Iterables.isEmpty(path)) {
169 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
170 for (PathArgument a : path) {
174 return FixedYangInstanceIdentifier.create(path, hash.build());
177 public static YangInstanceIdentifier create(final PathArgument... path) {
178 // We are forcing a copy, since we cannot trust the user
179 return create(Arrays.asList(path));
182 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
183 return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
187 public boolean equals(final Object obj) {
191 if (!(obj instanceof YangInstanceIdentifier)) {
194 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
195 if (this.hashCode() != obj.hashCode()) {
199 return pathArgumentsEqual(other);
203 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments.
205 * @param name QName of {@link NodeIdentifier}
206 * @return Instance Identifier with additional path argument added to the end.
208 public final YangInstanceIdentifier node(final QName name) {
209 return node(new NodeIdentifier(name));
213 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments.
215 * @param arg Path argument which should be added to the end
216 * @return Instance Identifier with additional path argument added to the end.
218 public final YangInstanceIdentifier node(final PathArgument arg) {
219 return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
223 * Get the relative path from an ancestor. This method attempts to perform
224 * the reverse of concatenating a base (ancestor) and a path.
227 * Ancestor against which the relative path should be calculated
228 * @return This object's relative path from parent, or Optional.absent() if
229 * the specified parent is not in fact an ancestor of this object.
231 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
232 if (this == ancestor) {
233 return Optional.of(EMPTY);
235 if (ancestor.isEmpty()) {
236 return Optional.of(this);
239 final Iterator<PathArgument> lit = getPathArguments().iterator();
240 final Iterator<PathArgument> oit = ancestor.getPathArguments().iterator();
243 while (oit.hasNext()) {
244 // Ancestor is not really an ancestor
245 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
246 return Optional.empty();
253 return Optional.of(this);
255 if (!lit.hasNext()) {
256 return Optional.of(EMPTY);
259 return Optional.of(createRelativeIdentifier(common));
263 public final boolean contains(@Nonnull final YangInstanceIdentifier other) {
268 checkArgument(other != null, "other should not be null");
269 final Iterator<PathArgument> lit = getPathArguments().iterator();
270 final Iterator<PathArgument> oit = other.getPathArguments().iterator();
272 while (lit.hasNext()) {
273 if (!oit.hasNext()) {
277 if (!lit.next().equals(oit.next())) {
286 public final String toString() {
288 * The toStringCache is safe, since the object contract requires
289 * immutability of the object and all objects referenced from this
291 * Used lists, maps are immutable. Path Arguments (elements) are also
292 * immutable, since the PathArgument contract requires immutability.
293 * The cache is thread-safe - if multiple computations occurs at the
294 * same time, cache will be overwritten with same result.
296 String ret = toStringCache;
298 final StringBuilder builder = new StringBuilder("/");
299 PathArgument prev = null;
300 for (PathArgument argument : getPathArguments()) {
304 builder.append(argument.toRelativeString(prev));
308 ret = builder.toString();
309 TOSTRINGCACHE_UPDATER.lazySet(this, ret);
315 public final int hashCode() {
317 * The caching is safe, since the object contract requires
318 * immutability of the object and all objects referenced from this
320 * Used lists, maps are immutable. Path Arguments (elements) are also
321 * immutable, since the PathArgument contract requires immutability.
326 private static int hashCode(final Object value) {
331 if (byte[].class.equals(value.getClass())) {
332 return Arrays.hashCode((byte[]) value);
335 if (value.getClass().isArray()) {
337 int length = Array.getLength(value);
338 for (int i = 0; i < length; i++) {
339 hash += Objects.hashCode(Array.get(value, i));
345 return Objects.hashCode(value);
348 // Static factories & helpers
351 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied
354 * @param name QName of first node identifier
355 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
357 public static YangInstanceIdentifier of(final QName name) {
358 return create(new NodeIdentifier(name));
362 * Returns new builder for InstanceIdentifier with empty path arguments.
364 * @return new builder for InstanceIdentifier with empty path arguments.
366 public static InstanceIdentifierBuilder builder() {
367 return new YangInstanceIdentifierBuilder();
371 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
373 * @param origin InstanceIdentifier from which path arguments are copied.
374 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
376 public static InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
377 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
381 * Path argument / component of InstanceIdentifier.
382 * Path argument uniquely identifies node in data tree on particular
386 * This interface itself is used as common parent for actual
387 * path arguments types and should not be implemented by user code.
390 * Path arguments SHOULD contain only minimum of information
391 * required to uniquely identify node on particular subtree level.
394 * For actual path arguments types see:
396 * <li>{@link NodeIdentifier} - Identifier of container or leaf
397 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
398 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
399 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
402 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
404 * If applicable returns unique QName of data node as defined in YANG
408 * This method may return null, if the corresponding schema node, does
409 * not have QName associated, such as in cases of augmentations.
416 * Return the string representation of this object for use in context
417 * provided by a previous object. This method can be implemented in
418 * terms of {@link #toString()}, but implementations are encourage to
419 * reuse any context already emitted by the previous object.
421 * @param previous Previous path argument
422 * @return String representation
424 String toRelativeString(PathArgument previous);
427 private abstract static class AbstractPathArgument implements PathArgument {
428 private static final long serialVersionUID = -4546547994250849340L;
429 private final QName nodeType;
430 private transient int hashValue;
431 private transient volatile boolean hashGuard = false;
433 protected AbstractPathArgument(final QName nodeType) {
434 this.nodeType = requireNonNull(nodeType);
438 public final QName getNodeType() {
443 @SuppressWarnings("checkstyle:parameterName")
444 public int compareTo(@Nonnull final PathArgument o) {
445 return nodeType.compareTo(o.getNodeType());
448 protected int hashCodeImpl() {
449 return 31 + getNodeType().hashCode();
453 public final int hashCode() {
455 hashValue = hashCodeImpl();
463 public boolean equals(final Object obj) {
467 if (obj == null || this.getClass() != obj.getClass()) {
471 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
475 public String toString() {
476 return getNodeType().toString();
480 public String toRelativeString(final PathArgument previous) {
481 if (previous instanceof AbstractPathArgument) {
482 final QNameModule mod = previous.getNodeType().getModule();
483 if (getNodeType().getModule().equals(mod)) {
484 return getNodeType().getLocalName();
488 return getNodeType().toString();
493 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
494 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
496 public static final class NodeIdentifier extends AbstractPathArgument {
497 private static final long serialVersionUID = -2255888212390871347L;
498 private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
499 .build(new CacheLoader<QName, NodeIdentifier>() {
501 public NodeIdentifier load(@Nonnull final QName key) {
502 return new NodeIdentifier(key);
506 public NodeIdentifier(final QName node) {
511 * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
512 * instance cache, resulting in object reuse for equal inputs.
514 * @param node Node's QName
515 * @return A {@link NodeIdentifier}
517 public static NodeIdentifier create(final QName node) {
518 return CACHE.getUnchecked(node);
523 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
526 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
527 private static final long serialVersionUID = -4787195606494761540L;
529 private final Map<QName, Object> keyValues;
531 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
533 // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
534 this.keyValues = ImmutableOffsetMap.unorderedCopyOf(keyValues);
537 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
539 this.keyValues = SharedSingletonMap.unorderedOf(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 @SuppressWarnings("checkstyle:equalsHashCode")
560 public boolean equals(final Object obj) {
561 if (!super.equals(obj)) {
565 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
567 // TODO: benchmark to see if just calling equals() on the two maps is not faster
568 if (keyValues == otherKeyValues) {
571 if (keyValues.size() != otherKeyValues.size()) {
575 for (Entry<QName, Object> entry : keyValues.entrySet()) {
576 if (!otherKeyValues.containsKey(entry.getKey())
577 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
587 public String toString() {
588 return super.toString() + '[' + keyValues + ']';
592 public String toRelativeString(final PathArgument previous) {
593 return super.toRelativeString(previous) + '[' + keyValues + ']';
598 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
601 public static final class NodeWithValue<T> extends AbstractPathArgument {
602 private static final long serialVersionUID = -3637456085341738431L;
604 private final T value;
606 public NodeWithValue(final QName node, final T value) {
611 public T getValue() {
616 protected int hashCodeImpl() {
617 final int prime = 31;
618 int result = super.hashCodeImpl();
619 result = prime * result + YangInstanceIdentifier.hashCode(value);
624 @SuppressWarnings("checkstyle:equalsHashCode")
625 public boolean equals(final Object obj) {
626 if (!super.equals(obj)) {
629 final NodeWithValue<?> other = (NodeWithValue<?>) obj;
630 return Objects.deepEquals(value, other.value);
634 public String toString() {
635 return super.toString() + '[' + value + ']';
639 public String toRelativeString(final PathArgument previous) {
640 return super.toRelativeString(previous) + '[' + value + ']';
645 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode}
646 * node in particular subtree.
649 * Augmentation is uniquely identified by set of all possible child nodes.
651 * to identify instance of augmentation,
652 * since RFC6020 states that <code>augment</code> that augment
653 * statement must not add multiple nodes from same namespace
654 * / module to the target node.
656 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
658 public static final class AugmentationIdentifier implements PathArgument {
659 private static final long serialVersionUID = -8122335594681936939L;
660 private final ImmutableSet<QName> childNames;
663 public QName getNodeType() {
664 // This should rather throw exception than return always null
665 throw new UnsupportedOperationException("Augmentation node has no QName");
669 * Construct new augmentation identifier using supplied set of possible
673 * Set of possible child nodes.
675 public AugmentationIdentifier(final Set<QName> childNames) {
676 this.childNames = ImmutableSet.copyOf(childNames);
680 * Returns set of all possible child nodes.
682 * @return set of all possible child nodes.
684 public Set<QName> getPossibleChildNames() {
689 public String toString() {
690 return "AugmentationIdentifier{" + "childNames=" + childNames + '}';
694 public String toRelativeString(final PathArgument previous) {
699 public boolean equals(final Object obj) {
703 if (!(obj instanceof AugmentationIdentifier)) {
707 AugmentationIdentifier that = (AugmentationIdentifier) obj;
708 return childNames.equals(that.childNames);
712 public int hashCode() {
713 return childNames.hashCode();
717 @SuppressWarnings("checkstyle:parameterName")
718 public int compareTo(@Nonnull 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 // Quick Set-based comparison
728 if (childNames.equals(otherChildNames)) {
732 // We already know the sets are not equal, but have equal size, hence the sets differ in their elements,
733 // but potentially share a common set of elements. The most consistent way of comparing them is using
734 // total ordering defined by QName's compareTo. Hence convert both sets to lists ordered
735 // by QName.compareTo() and decide on the first differing element.
736 final List<QName> diff = new ArrayList<>(Sets.symmetricDifference(childNames, otherChildNames));
737 verify(!diff.isEmpty(), "Augmentation identifiers %s and %s report no difference", this, o);
738 diff.sort(QName::compareTo);
739 return childNames.contains(diff.get(0)) ? -1 : 1;
740 } else if (thisSize < otherSize) {
749 * Fluent Builder of Instance Identifier instances.
751 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
753 * Adds a {@link PathArgument} to path arguments of resulting instance identifier.
755 * @param arg A {@link PathArgument} to be added
756 * @return this builder
758 InstanceIdentifierBuilder node(PathArgument arg);
761 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
763 * @param nodeType QName of {@link NodeIdentifier} which will be added
764 * @return this builder
766 InstanceIdentifierBuilder node(QName nodeType);
769 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting
770 * instance identifier.
772 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
773 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
774 * @return this builder
776 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
779 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
781 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
782 * @param key QName of key which will be added
783 * @param value value of key which will be added
784 * @return this builder
786 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
789 * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
791 * @param args {@link PathArgument}s to be added
792 * @return this builder
793 * @throws NullPointerException if any of the arguments is null
796 InstanceIdentifierBuilder append(Collection<? extends PathArgument> args);
799 * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
801 * @param args {@link PathArgument}s to be added
802 * @return this builder
803 * @throws NullPointerException if any of the arguments is null
806 default InstanceIdentifierBuilder append(final PathArgument... args) {
807 return append(Arrays.asList(args));
811 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder.
813 * @return {@link YangInstanceIdentifier}
816 YangInstanceIdentifier build();