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 object is {@link #EMPTY}.
119 @Nullable public abstract YangInstanceIdentifier getParent();
122 * Return the ancestor {@link YangInstanceIdentifier} with a particular depth, e.g. number of path arguments.
124 * @param depth Ancestor depth
125 * @return Ancestor {@link YangInstanceIdentifier}
126 * @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
128 @Nonnull public abstract YangInstanceIdentifier getAncestor(int depth);
131 * Returns an ordered iteration of path arguments.
133 * @return Immutable iteration of path arguments.
135 public abstract List<PathArgument> getPathArguments();
138 * Returns an iterable of path arguments in reverse order. This is useful
139 * when walking up a tree organized this way.
141 * @return Immutable iterable of path arguments in reverse order.
143 public abstract List<PathArgument> getReversePathArguments();
146 * Returns the last PathArgument. This is equivalent of iterating
147 * to the last element of the iterable returned by {@link #getPathArguments()}.
149 * @return The last past argument, or null if there are no PathArguments.
151 public abstract PathArgument getLastPathArgument();
153 public static YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
154 if (Iterables.isEmpty(path)) {
158 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
159 for (PathArgument a : path) {
163 return FixedYangInstanceIdentifier.create(path, hash.build());
166 public static YangInstanceIdentifier create(final PathArgument... path) {
167 // We are forcing a copy, since we cannot trust the user
168 return create(Arrays.asList(path));
172 public final int hashCode() {
174 * The caching is safe, since the object contract requires
175 * immutability of the object and all objects referenced from this
177 * Used lists, maps are immutable. Path Arguments (elements) are also
178 * immutable, since the PathArgument contract requires immutability.
183 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
184 return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
188 public boolean equals(final Object obj) {
192 if (!(obj instanceof YangInstanceIdentifier)) {
195 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
196 if (this.hashCode() != obj.hashCode()) {
200 return pathArgumentsEqual(other);
204 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments
206 * @param name QName of {@link NodeIdentifier}
207 * @return Instance Identifier with additional path argument added to the end.
209 public final YangInstanceIdentifier node(final QName name) {
210 return node(new NodeIdentifier(name));
215 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments
217 * @param arg Path argument which should be added to the end
218 * @return Instance Identifier with additional path argument added to the end.
220 public final YangInstanceIdentifier node(final PathArgument arg) {
221 return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
225 * Get the relative path from an ancestor. This method attempts to perform
226 * the reverse of concatenating a base (ancestor) and a path.
229 * Ancestor against which the relative path should be calculated
230 * @return This object's relative path from parent, or Optional.absent() if
231 * the specified parent is not in fact an ancestor of this object.
233 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
234 final Iterator<?> lit = getPathArguments().iterator();
235 final Iterator<?> oit = ancestor.getPathArguments().iterator();
238 while (oit.hasNext()) {
239 // Ancestor is not really an ancestor
240 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
241 return Optional.absent();
248 return Optional.of(this);
250 if (!lit.hasNext()) {
251 return Optional.of(EMPTY);
254 return Optional.of(createRelativeIdentifier(common));
258 public final boolean contains(final YangInstanceIdentifier other) {
259 Preconditions.checkArgument(other != null, "other should not be null");
261 final Iterator<?> lit = getPathArguments().iterator();
262 final Iterator<?> oit = other.getPathArguments().iterator();
264 while (lit.hasNext()) {
265 if (!oit.hasNext()) {
269 if (!lit.next().equals(oit.next())) {
278 public final String toString() {
280 * The toStringCache is safe, since the object contract requires
281 * immutability of the object and all objects referenced from this
283 * Used lists, maps are immutable. Path Arguments (elements) are also
284 * immutable, since the PathArgument contract requires immutability.
285 * The cache is thread-safe - if multiple computations occurs at the
286 * same time, cache will be overwritten with same result.
288 String ret = toStringCache;
290 final StringBuilder builder = new StringBuilder("/");
291 PathArgument prev = null;
292 for (PathArgument argument : getPathArguments()) {
296 builder.append(argument.toRelativeString(prev));
300 ret = builder.toString();
301 TOSTRINGCACHE_UPDATER.lazySet(this, ret);
306 private static int hashCode(final Object value) {
311 if (byte[].class.equals(value.getClass())) {
312 return Arrays.hashCode((byte[]) value);
315 if (value.getClass().isArray()) {
317 int length = Array.getLength(value);
318 for (int i = 0; i < length; i++) {
319 hash += Objects.hashCode(Array.get(value, i));
325 return Objects.hashCode(value);
328 // Static factories & helpers
331 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied QName
333 * @param name QName of first node identifier
334 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
336 public static YangInstanceIdentifier of(final QName name) {
337 return create(new NodeIdentifier(name));
341 * Returns new builder for InstanceIdentifier with empty path arguments.
343 * @return new builder for InstanceIdentifier with empty path arguments.
345 public static InstanceIdentifierBuilder builder() {
346 return new YangInstanceIdentifierBuilder();
351 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
353 * @param origin InstanceIdentifier from which path arguments are copied.
354 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
356 public static InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
357 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
361 * Path argument / component of InstanceIdentifier
363 * Path argument uniquely identifies node in data tree on particular
366 * This interface itself is used as common parent for actual
367 * path arguments types and should not be implemented by user code.
369 * Path arguments SHOULD contain only minimum of information
370 * required to uniquely identify node on particular subtree level.
372 * For actual path arguments types see:
374 * <li>{@link NodeIdentifier} - Identifier of container or leaf
375 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
376 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
377 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
380 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
382 * If applicable returns unique QName of data node as defined in YANG
385 * This method may return null, if the corresponding schema node, does
386 * not have QName associated, such as in cases of augmentations.
393 * Return the string representation of this object for use in context
394 * provided by a previous object. This method can be implemented in
395 * terms of {@link #toString()}, but implementations are encourage to
396 * reuse any context already emitted by the previous object.
398 * @param previous Previous path argument
399 * @return String representation
401 String toRelativeString(PathArgument previous);
404 private static abstract class AbstractPathArgument implements PathArgument {
405 private static final long serialVersionUID = -4546547994250849340L;
406 private final QName nodeType;
407 private transient int hashValue;
408 private volatile transient boolean hashGuard = false;
410 protected AbstractPathArgument(final QName nodeType) {
411 this.nodeType = Preconditions.checkNotNull(nodeType);
415 public final QName getNodeType() {
420 public int compareTo(final PathArgument o) {
421 return nodeType.compareTo(o.getNodeType());
424 protected int hashCodeImpl() {
425 return 31 + getNodeType().hashCode();
429 public final int hashCode() {
431 hashValue = hashCodeImpl();
439 public boolean equals(final Object obj) {
443 if (obj == null || this.getClass() != obj.getClass()) {
447 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
451 public String toString() {
452 return getNodeType().toString();
456 public String toRelativeString(final PathArgument previous) {
457 if (previous instanceof AbstractPathArgument) {
458 final QNameModule mod = ((AbstractPathArgument)previous).getNodeType().getModule();
459 if (getNodeType().getModule().equals(mod)) {
460 return getNodeType().getLocalName();
464 return getNodeType().toString();
469 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
470 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
472 public static final class NodeIdentifier extends AbstractPathArgument {
473 private static final long serialVersionUID = -2255888212390871347L;
474 private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
475 .build(new CacheLoader<QName, NodeIdentifier>() {
477 public NodeIdentifier load(final QName key) {
478 return new NodeIdentifier(key);
482 public NodeIdentifier(final QName node) {
487 * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
488 * instance cache, resulting in object reuse for equal inputs.
490 * @param node Node's QName
491 * @return A {@link NodeIdentifier}
493 public static NodeIdentifier create(final QName node) {
494 return CACHE.getUnchecked(node);
499 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
502 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
503 private static final long serialVersionUID = -4787195606494761540L;
505 private final Map<QName, Object> keyValues;
507 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
509 // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
510 this.keyValues = ImmutableOffsetMap.copyOf(keyValues);
513 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
514 this(node, SharedSingletonMap.of(key, value));
517 public Map<QName, Object> getKeyValues() {
522 protected int hashCodeImpl() {
523 final int prime = 31;
524 int result = super.hashCodeImpl();
525 result = prime * result;
527 for (Entry<QName, Object> entry : keyValues.entrySet()) {
528 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
534 public boolean equals(final Object obj) {
535 if (!super.equals(obj)) {
539 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
541 // TODO: benchmark to see if just calling equals() on the two maps is not faster
542 if (keyValues == otherKeyValues) {
545 if (keyValues.size() != otherKeyValues.size()) {
549 for (Entry<QName, Object> entry : keyValues.entrySet()) {
550 if (!otherKeyValues.containsKey(entry.getKey())
551 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
561 public String toString() {
562 return super.toString() + '[' + keyValues + ']';
566 public String toRelativeString(final PathArgument previous) {
567 return super.toRelativeString(previous) + '[' + keyValues + ']';
572 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
575 public static final class NodeWithValue extends AbstractPathArgument {
576 private static final long serialVersionUID = -3637456085341738431L;
578 private final Object value;
580 public NodeWithValue(final QName node, final Object value) {
585 public Object getValue() {
590 protected int hashCodeImpl() {
591 final int prime = 31;
592 int result = super.hashCodeImpl();
593 result = prime * result + ((value == null) ? 0 : YangInstanceIdentifier.hashCode(value));
598 public boolean equals(final Object obj) {
599 if (!super.equals(obj)) {
602 final NodeWithValue other = (NodeWithValue) obj;
603 return Objects.deepEquals(value, other.value);
607 public String toString() {
608 return super.toString() + '[' + value + ']';
612 public String toRelativeString(final PathArgument previous) {
613 return super.toRelativeString(previous) + '[' + value + ']';
618 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} node in
619 * particular subtree.
621 * Augmentation is uniquely identified by set of all possible child nodes.
623 * to identify instance of augmentation,
624 * since RFC6020 states that <code>augment</code> that augment
625 * statement must not add multiple nodes from same namespace
626 * / module to the target node.
629 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
631 public static final class AugmentationIdentifier implements PathArgument {
632 private static final long serialVersionUID = -8122335594681936939L;
633 private final ImmutableSet<QName> childNames;
636 public QName getNodeType() {
637 // This should rather throw exception than return always null
638 throw new UnsupportedOperationException("Augmentation node has no QName");
643 * Construct new augmentation identifier using supplied set of possible
647 * Set of possible child nodes.
649 public AugmentationIdentifier(final Set<QName> childNames) {
650 this.childNames = ImmutableSet.copyOf(childNames);
654 * Returns set of all possible child nodes
656 * @return set of all possible child nodes.
658 public Set<QName> getPossibleChildNames() {
663 public String toString() {
664 final StringBuilder sb = new StringBuilder("AugmentationIdentifier{");
665 sb.append("childNames=").append(childNames).append('}');
666 return sb.toString();
670 public String toRelativeString(final PathArgument previous) {
675 public boolean equals(final Object o) {
679 if (!(o instanceof AugmentationIdentifier)) {
683 AugmentationIdentifier that = (AugmentationIdentifier) o;
684 return childNames.equals(that.childNames);
688 public int hashCode() {
689 return childNames.hashCode();
693 public int compareTo(final PathArgument o) {
694 if (!(o instanceof AugmentationIdentifier)) {
697 AugmentationIdentifier other = (AugmentationIdentifier) o;
698 Set<QName> otherChildNames = other.getPossibleChildNames();
699 int thisSize = childNames.size();
700 int otherSize = otherChildNames.size();
701 if (thisSize == otherSize) {
702 Iterator<QName> otherIterator = otherChildNames.iterator();
703 for (QName name : childNames) {
704 int c = name.compareTo(otherIterator.next());
710 } else if (thisSize < otherSize) {
719 * Fluent Builder of Instance Identifier instances
721 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
723 * Adds a {@link PathArgument} to to path arguments of resulting instance identifier.
725 * @param arg A {@link PathArgument} to be added
726 * @return this builder
728 InstanceIdentifierBuilder node(PathArgument arg);
731 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
733 * @param nodeType QName of {@link NodeIdentifier} which will be added
734 * @return this builder
736 InstanceIdentifierBuilder node(QName nodeType);
739 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting instance identifier.
741 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
742 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
743 * @return this builder
745 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
748 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
750 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
751 * @param key QName of key which will be added
752 * @param value value of key which will be added
753 * @return this builder
755 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
759 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder
761 * @return {@link YangInstanceIdentifier}
764 YangInstanceIdentifier build();
767 * @deprecated use #build()
770 YangInstanceIdentifier toInstance();