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.Verify.verify;
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
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;
32 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
33 import javax.annotation.Nonnull;
34 import javax.annotation.Nullable;
35 import org.opendaylight.yangtools.concepts.Builder;
36 import org.opendaylight.yangtools.concepts.Immutable;
37 import org.opendaylight.yangtools.concepts.Path;
38 import org.opendaylight.yangtools.util.HashCodeBuilder;
39 import org.opendaylight.yangtools.util.ImmutableOffsetMap;
40 import org.opendaylight.yangtools.util.SharedSingletonMap;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.common.QNameModule;
43 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
46 * Unique identifier of a particular node instance in the data tree.
49 * Java representation of YANG Built-in type <code>instance-identifier</code>,
50 * which conceptually is XPath expression minimized to uniquely identify element
51 * in data tree which conforms to constraints maintained by YANG Model,
52 * effectively this makes Instance Identifier a path to element in data tree.
55 * Constraints put in YANG specification on instance-identifier allowed it to be
56 * effectively represented in Java and it's evaluation does not require
57 * full-blown XPath processor.
60 * <h3>Path Arguments</h3>
61 * Path to the node represented in instance identifier consists of
62 * {@link PathArgument} which carries necessary information to uniquely identify
63 * node on particular level in the subtree.
66 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
67 * <code>0..1</code> in particular subtree in data tree.</li>
68 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item),
69 * which has cardinality <code>0..n</code>.</li>
70 * <li>{@link NodeWithValue} - Identifier of instance <code>leaf</code> node or
71 * <code>leaf-list</code> node.</li>
72 * <li>{@link AugmentationIdentifier} - Identifier of instance of
73 * <code>augmentation</code> node.</li>
76 * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
78 public abstract class YangInstanceIdentifier implements Path<YangInstanceIdentifier>, Immutable, Serializable {
80 * An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual
81 * root of the YANG namespace.
83 public static final YangInstanceIdentifier EMPTY = FixedYangInstanceIdentifier.EMPTY_INSTANCE;
85 private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, String> TOSTRINGCACHE_UPDATER =
86 AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, String.class, "toStringCache");
87 private static final long serialVersionUID = 4L;
89 private final int hash;
90 private transient volatile String toStringCache = null;
92 // Package-private to prevent outside subclassing
93 YangInstanceIdentifier(final int hash) {
97 @Nonnull abstract YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
99 @Nonnull abstract Collection<PathArgument> tryPathArguments();
101 @Nonnull abstract Collection<PathArgument> tryReversePathArguments();
104 * Check if this instance identifier has empty path arguments, e.g. it is
105 * empty and corresponds to {@link #EMPTY}.
107 * @return True if this instance identifier is empty, false otherwise.
109 public abstract boolean isEmpty();
112 * Return an optimized version of this identifier, useful when the identifier
113 * will be used very frequently.
115 * @return A optimized equivalent instance.
118 public abstract YangInstanceIdentifier toOptimized();
121 * Return the conceptual parent {@link YangInstanceIdentifier}, which has
122 * one item less in {@link #getPathArguments()}.
124 * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #EMPTY}.
126 @Nullable public abstract YangInstanceIdentifier getParent();
129 * Return the ancestor {@link YangInstanceIdentifier} with a particular depth, e.g. number of path arguments.
131 * @param depth Ancestor depth
132 * @return Ancestor {@link YangInstanceIdentifier}
133 * @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
135 @Nonnull public abstract YangInstanceIdentifier getAncestor(int depth);
138 * Returns an ordered iteration of path arguments.
140 * @return Immutable iteration of path arguments.
142 public abstract List<PathArgument> getPathArguments();
145 * Returns an iterable of path arguments in reverse order. This is useful
146 * when walking up a tree organized this way.
148 * @return Immutable iterable of path arguments in reverse order.
150 public abstract List<PathArgument> getReversePathArguments();
153 * Returns the last PathArgument. This is equivalent of iterating
154 * to the last element of the iterable returned by {@link #getPathArguments()}.
156 * @return The last past argument, or null if there are no PathArguments.
158 public abstract PathArgument getLastPathArgument();
160 public static YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
161 if (Iterables.isEmpty(path)) {
165 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
166 for (PathArgument a : path) {
170 return FixedYangInstanceIdentifier.create(path, hash.build());
173 public static YangInstanceIdentifier create(final PathArgument... path) {
174 // We are forcing a copy, since we cannot trust the user
175 return create(Arrays.asList(path));
178 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
179 return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
183 public boolean equals(final Object obj) {
187 if (!(obj instanceof YangInstanceIdentifier)) {
190 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
191 if (this.hashCode() != obj.hashCode()) {
195 return pathArgumentsEqual(other);
199 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments.
201 * @param name QName of {@link NodeIdentifier}
202 * @return Instance Identifier with additional path argument added to the end.
204 public final YangInstanceIdentifier node(final QName name) {
205 return node(new NodeIdentifier(name));
209 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments.
211 * @param arg Path argument which should be added to the end
212 * @return Instance Identifier with additional path argument added to the end.
214 public final YangInstanceIdentifier node(final PathArgument arg) {
215 return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
219 * Get the relative path from an ancestor. This method attempts to perform
220 * the reverse of concatenating a base (ancestor) and a path.
223 * Ancestor against which the relative path should be calculated
224 * @return This object's relative path from parent, or Optional.absent() if
225 * the specified parent is not in fact an ancestor of this object.
227 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
228 if (this == ancestor) {
229 return Optional.of(EMPTY);
231 if (ancestor.isEmpty()) {
232 return Optional.of(this);
235 final Iterator<PathArgument> lit = getPathArguments().iterator();
236 final Iterator<PathArgument> oit = ancestor.getPathArguments().iterator();
239 while (oit.hasNext()) {
240 // Ancestor is not really an ancestor
241 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
242 return Optional.absent();
249 return Optional.of(this);
251 if (!lit.hasNext()) {
252 return Optional.of(EMPTY);
255 return Optional.of(createRelativeIdentifier(common));
259 public final boolean contains(@Nonnull final YangInstanceIdentifier other) {
264 Preconditions.checkArgument(other != null, "other should not be null");
265 final Iterator<PathArgument> lit = getPathArguments().iterator();
266 final Iterator<PathArgument> oit = other.getPathArguments().iterator();
268 while (lit.hasNext()) {
269 if (!oit.hasNext()) {
273 if (!lit.next().equals(oit.next())) {
282 public final String toString() {
284 * The toStringCache is safe, since the object contract requires
285 * immutability of the object and all objects referenced from this
287 * Used lists, maps are immutable. Path Arguments (elements) are also
288 * immutable, since the PathArgument contract requires immutability.
289 * The cache is thread-safe - if multiple computations occurs at the
290 * same time, cache will be overwritten with same result.
292 String ret = toStringCache;
294 final StringBuilder builder = new StringBuilder("/");
295 PathArgument prev = null;
296 for (PathArgument argument : getPathArguments()) {
300 builder.append(argument.toRelativeString(prev));
304 ret = builder.toString();
305 TOSTRINGCACHE_UPDATER.lazySet(this, ret);
311 public final int hashCode() {
313 * The caching is safe, since the object contract requires
314 * immutability of the object and all objects referenced from this
316 * Used lists, maps are immutable. Path Arguments (elements) are also
317 * immutable, since the PathArgument contract requires immutability.
322 private static int hashCode(final Object value) {
327 if (byte[].class.equals(value.getClass())) {
328 return Arrays.hashCode((byte[]) value);
331 if (value.getClass().isArray()) {
333 int length = Array.getLength(value);
334 for (int i = 0; i < length; i++) {
335 hash += Objects.hashCode(Array.get(value, i));
341 return Objects.hashCode(value);
344 // Static factories & helpers
347 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied
350 * @param name QName of first node identifier
351 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
353 public static YangInstanceIdentifier of(final QName name) {
354 return create(new NodeIdentifier(name));
358 * Returns new builder for InstanceIdentifier with empty path arguments.
360 * @return new builder for InstanceIdentifier with empty path arguments.
362 public static InstanceIdentifierBuilder builder() {
363 return new YangInstanceIdentifierBuilder();
367 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
369 * @param origin InstanceIdentifier from which path arguments are copied.
370 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
372 public static InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
373 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
377 * Path argument / component of InstanceIdentifier.
378 * Path argument uniquely identifies node in data tree on particular
382 * This interface itself is used as common parent for actual
383 * path arguments types and should not be implemented by user code.
386 * Path arguments SHOULD contain only minimum of information
387 * required to uniquely identify node on particular subtree level.
390 * For actual path arguments types see:
392 * <li>{@link NodeIdentifier} - Identifier of container or leaf
393 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
394 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
395 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
398 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
400 * If applicable returns unique QName of data node as defined in YANG
404 * This method may return null, if the corresponding schema node, does
405 * not have QName associated, such as in cases of augmentations.
412 * Return the string representation of this object for use in context
413 * provided by a previous object. This method can be implemented in
414 * terms of {@link #toString()}, but implementations are encourage to
415 * reuse any context already emitted by the previous object.
417 * @param previous Previous path argument
418 * @return String representation
420 String toRelativeString(PathArgument previous);
423 private abstract static class AbstractPathArgument implements PathArgument {
424 private static final long serialVersionUID = -4546547994250849340L;
425 private final QName nodeType;
426 private transient int hashValue;
427 private transient volatile boolean hashGuard = false;
429 protected AbstractPathArgument(final QName nodeType) {
430 this.nodeType = Preconditions.checkNotNull(nodeType);
434 public final QName getNodeType() {
439 @SuppressWarnings("checkstyle:parameterName")
440 public int compareTo(@Nonnull final PathArgument o) {
441 return nodeType.compareTo(o.getNodeType());
444 protected int hashCodeImpl() {
445 return 31 + getNodeType().hashCode();
449 public final int hashCode() {
451 hashValue = hashCodeImpl();
459 public boolean equals(final Object obj) {
463 if (obj == null || this.getClass() != obj.getClass()) {
467 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
471 public String toString() {
472 return getNodeType().toString();
476 public String toRelativeString(final PathArgument previous) {
477 if (previous instanceof AbstractPathArgument) {
478 final QNameModule mod = previous.getNodeType().getModule();
479 if (getNodeType().getModule().equals(mod)) {
480 return getNodeType().getLocalName();
484 return getNodeType().toString();
489 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
490 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
492 public static final class NodeIdentifier extends AbstractPathArgument {
493 private static final long serialVersionUID = -2255888212390871347L;
494 private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
495 .build(new CacheLoader<QName, NodeIdentifier>() {
497 public NodeIdentifier load(@Nonnull final QName key) {
498 return new NodeIdentifier(key);
502 public NodeIdentifier(final QName node) {
507 * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
508 * instance cache, resulting in object reuse for equal inputs.
510 * @param node Node's QName
511 * @return A {@link NodeIdentifier}
513 public static NodeIdentifier create(final QName node) {
514 return CACHE.getUnchecked(node);
519 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
522 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
523 private static final long serialVersionUID = -4787195606494761540L;
525 private final Map<QName, Object> keyValues;
527 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
529 // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
530 this.keyValues = ImmutableOffsetMap.unorderedCopyOf(keyValues);
533 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
535 this.keyValues = SharedSingletonMap.unorderedOf(key, value);
538 public Map<QName, Object> getKeyValues() {
543 protected int hashCodeImpl() {
544 final int prime = 31;
545 int result = super.hashCodeImpl();
546 result = prime * result;
548 for (Entry<QName, Object> entry : keyValues.entrySet()) {
549 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
555 @SuppressWarnings("checkstyle:equalsHashCode")
556 public boolean equals(final Object obj) {
557 if (!super.equals(obj)) {
561 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
563 // TODO: benchmark to see if just calling equals() on the two maps is not faster
564 if (keyValues == otherKeyValues) {
567 if (keyValues.size() != otherKeyValues.size()) {
571 for (Entry<QName, Object> entry : keyValues.entrySet()) {
572 if (!otherKeyValues.containsKey(entry.getKey())
573 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
583 public String toString() {
584 return super.toString() + '[' + keyValues + ']';
588 public String toRelativeString(final PathArgument previous) {
589 return super.toRelativeString(previous) + '[' + keyValues + ']';
594 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
597 public static final class NodeWithValue<T> extends AbstractPathArgument {
598 private static final long serialVersionUID = -3637456085341738431L;
600 private final T value;
602 public NodeWithValue(final QName node, final T value) {
607 public T getValue() {
612 protected int hashCodeImpl() {
613 final int prime = 31;
614 int result = super.hashCodeImpl();
615 result = prime * result + YangInstanceIdentifier.hashCode(value);
620 @SuppressWarnings("checkstyle:equalsHashCode")
621 public boolean equals(final Object obj) {
622 if (!super.equals(obj)) {
625 final NodeWithValue<?> other = (NodeWithValue<?>) obj;
626 return Objects.deepEquals(value, other.value);
630 public String toString() {
631 return super.toString() + '[' + value + ']';
635 public String toRelativeString(final PathArgument previous) {
636 return super.toRelativeString(previous) + '[' + value + ']';
641 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode}
642 * node in particular subtree.
645 * Augmentation is uniquely identified by set of all possible child nodes.
647 * to identify instance of augmentation,
648 * since RFC6020 states that <code>augment</code> that augment
649 * statement must not add multiple nodes from same namespace
650 * / module to the target node.
652 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
654 public static final class AugmentationIdentifier implements PathArgument {
655 private static final long serialVersionUID = -8122335594681936939L;
656 private final ImmutableSet<QName> childNames;
659 public QName getNodeType() {
660 // This should rather throw exception than return always null
661 throw new UnsupportedOperationException("Augmentation node has no QName");
665 * Construct new augmentation identifier using supplied set of possible
669 * Set of possible child nodes.
671 public AugmentationIdentifier(final Set<QName> childNames) {
672 this.childNames = ImmutableSet.copyOf(childNames);
676 * Returns set of all possible child nodes.
678 * @return set of all possible child nodes.
680 public Set<QName> getPossibleChildNames() {
685 public String toString() {
686 return "AugmentationIdentifier{" + "childNames=" + childNames + '}';
690 public String toRelativeString(final PathArgument previous) {
695 public boolean equals(final Object obj) {
699 if (!(obj instanceof AugmentationIdentifier)) {
703 AugmentationIdentifier that = (AugmentationIdentifier) obj;
704 return childNames.equals(that.childNames);
708 public int hashCode() {
709 return childNames.hashCode();
713 @SuppressWarnings("checkstyle:parameterName")
714 public int compareTo(@Nonnull final PathArgument o) {
715 if (!(o instanceof AugmentationIdentifier)) {
718 AugmentationIdentifier other = (AugmentationIdentifier) o;
719 Set<QName> otherChildNames = other.getPossibleChildNames();
720 int thisSize = childNames.size();
721 int otherSize = otherChildNames.size();
722 if (thisSize == otherSize) {
723 // Quick Set-based comparison
724 if (childNames.equals(otherChildNames)) {
728 // We already know the sets are not equal, but have equal size, hence the sets differ in their elements,
729 // but potentially share a common set of elements. The most consistent way of comparing them is using
730 // total ordering defined by QName's compareTo. Hence convert both sets to lists ordered
731 // by QName.compareTo() and decide on the first differing element.
732 final List<QName> diff = new ArrayList<>(Sets.symmetricDifference(childNames, otherChildNames));
733 verify(!diff.isEmpty(), "Augmentation identifiers %s and %s report no difference", this, o);
734 diff.sort(QName::compareTo);
735 return childNames.contains(diff.get(0)) ? -1 : 1;
736 } else if (thisSize < otherSize) {
745 * Fluent Builder of Instance Identifier instances.
747 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
749 * Adds a {@link PathArgument} to path arguments of resulting instance identifier.
751 * @param arg A {@link PathArgument} to be added
752 * @return this builder
754 InstanceIdentifierBuilder node(PathArgument arg);
757 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
759 * @param nodeType QName of {@link NodeIdentifier} which will be added
760 * @return this builder
762 InstanceIdentifierBuilder node(QName nodeType);
765 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting
766 * instance identifier.
768 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
769 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
770 * @return this builder
772 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
775 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
777 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
778 * @param key QName of key which will be added
779 * @param value value of key which will be added
780 * @return this builder
782 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
785 * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
787 * @param args {@link PathArgument}s to be added
788 * @return this builder
789 * @throws NullPointerException if any of the arguments is null
792 InstanceIdentifierBuilder append(Collection<? extends PathArgument> args);
795 * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
797 * @param args {@link PathArgument}s to be added
798 * @return this builder
799 * @throws NullPointerException if any of the arguments is null
802 default InstanceIdentifierBuilder append(final PathArgument... args) {
803 return append(Arrays.asList(args));
807 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder.
809 * @return {@link YangInstanceIdentifier}
812 YangInstanceIdentifier build();