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.
51 * Constraints put in YANG specification on instance-identifier allowed it to be
52 * effectively represented in Java and it's evaluation does not require
53 * full-blown XPath processor.
56 * <h3>Path Arguments</h3>
57 * Path to the node represented in instance identifier consists of
58 * {@link PathArgument} which carries necessary information to uniquely identify
59 * node on particular level in the subtree.
62 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
63 * <code>0..1</code> in particular subtree in data tree.</li>
64 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item),
65 * which has cardinality <code>0..n</code>.</li>
66 * <li>{@link NodeWithValue} - Identifier of instance <code>leaf</code> node or
67 * <code>leaf-list</code> node.</li>
68 * <li>{@link AugmentationIdentifier} - Identifier of instance of
69 * <code>augmentation</code> node.</li>
72 * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
74 public abstract class YangInstanceIdentifier implements Path<YangInstanceIdentifier>, Immutable, Serializable {
76 * An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual
77 * root of the YANG namespace.
79 public static final YangInstanceIdentifier EMPTY = FixedYangInstanceIdentifier.EMPTY_INSTANCE;
81 private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, String> TOSTRINGCACHE_UPDATER =
82 AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, String.class, "toStringCache");
83 private static final long serialVersionUID = 4L;
85 private final int hash;
86 private transient volatile String toStringCache = null;
88 // Package-private to prevent outside subclassing
89 YangInstanceIdentifier(final int hash) {
93 @Nonnull abstract YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
95 @Nonnull abstract Collection<PathArgument> tryPathArguments();
97 @Nonnull abstract Collection<PathArgument> tryReversePathArguments();
100 * Check if this instance identifier has empty path arguments, e.g. it is
101 * empty and corresponds to {@link #EMPTY}.
103 * @return True if this instance identifier is empty, false otherwise.
105 public abstract boolean isEmpty();
108 * Return an optimized version of this identifier, useful when the identifier
109 * will be used very frequently.
111 * @return A optimized equivalent instance.
114 public abstract YangInstanceIdentifier toOptimized();
117 * Return the conceptual parent {@link YangInstanceIdentifier}, which has
118 * one item less in {@link #getPathArguments()}.
120 * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #EMPTY}.
122 @Nullable public abstract YangInstanceIdentifier getParent();
125 * Return the ancestor {@link YangInstanceIdentifier} with a particular depth, e.g. number of path arguments.
127 * @param depth Ancestor depth
128 * @return Ancestor {@link YangInstanceIdentifier}
129 * @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
131 @Nonnull public abstract YangInstanceIdentifier getAncestor(int depth);
134 * Returns an ordered iteration of path arguments.
136 * @return Immutable iteration of path arguments.
138 public abstract List<PathArgument> getPathArguments();
141 * Returns an iterable of path arguments in reverse order. This is useful
142 * when walking up a tree organized this way.
144 * @return Immutable iterable of path arguments in reverse order.
146 public abstract List<PathArgument> getReversePathArguments();
149 * Returns the last PathArgument. This is equivalent of iterating
150 * to the last element of the iterable returned by {@link #getPathArguments()}.
152 * @return The last past argument, or null if there are no PathArguments.
154 public abstract PathArgument getLastPathArgument();
156 public static YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
157 if (Iterables.isEmpty(path)) {
161 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
162 for (PathArgument a : path) {
166 return FixedYangInstanceIdentifier.create(path, hash.build());
169 public static YangInstanceIdentifier create(final PathArgument... path) {
170 // We are forcing a copy, since we cannot trust the user
171 return create(Arrays.asList(path));
174 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
175 return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
179 public boolean equals(final Object obj) {
183 if (!(obj instanceof YangInstanceIdentifier)) {
186 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
187 if (this.hashCode() != obj.hashCode()) {
191 return pathArgumentsEqual(other);
195 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments.
197 * @param name QName of {@link NodeIdentifier}
198 * @return Instance Identifier with additional path argument added to the end.
200 public final YangInstanceIdentifier node(final QName name) {
201 return node(new NodeIdentifier(name));
205 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments.
207 * @param arg Path argument which should be added to the end
208 * @return Instance Identifier with additional path argument added to the end.
210 public final YangInstanceIdentifier node(final PathArgument arg) {
211 return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
215 * Get the relative path from an ancestor. This method attempts to perform
216 * the reverse of concatenating a base (ancestor) and a path.
219 * Ancestor against which the relative path should be calculated
220 * @return This object's relative path from parent, or Optional.absent() if
221 * the specified parent is not in fact an ancestor of this object.
223 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
224 if (this == ancestor) {
225 return Optional.of(EMPTY);
227 if (ancestor.isEmpty()) {
228 return Optional.of(this);
231 final Iterator<?> lit = getPathArguments().iterator();
232 final Iterator<?> oit = ancestor.getPathArguments().iterator();
235 while (oit.hasNext()) {
236 // Ancestor is not really an ancestor
237 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
238 return Optional.absent();
245 return Optional.of(this);
247 if (!lit.hasNext()) {
248 return Optional.of(EMPTY);
251 return Optional.of(createRelativeIdentifier(common));
255 public final boolean contains(@Nonnull final YangInstanceIdentifier other) {
260 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);
307 public final int hashCode() {
309 * The caching is safe, since the object contract requires
310 * immutability of the object and all objects referenced from this
312 * Used lists, maps are immutable. Path Arguments (elements) are also
313 * immutable, since the PathArgument contract requires immutability.
318 private static int hashCode(final Object value) {
323 if (byte[].class.equals(value.getClass())) {
324 return Arrays.hashCode((byte[]) value);
327 if (value.getClass().isArray()) {
329 int length = Array.getLength(value);
330 for (int i = 0; i < length; i++) {
331 hash += Objects.hashCode(Array.get(value, i));
337 return Objects.hashCode(value);
340 // Static factories & helpers
343 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied
346 * @param name QName of first node identifier
347 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
349 public static YangInstanceIdentifier of(final QName name) {
350 return create(new NodeIdentifier(name));
354 * Returns new builder for InstanceIdentifier with empty path arguments.
356 * @return new builder for InstanceIdentifier with empty path arguments.
358 public static InstanceIdentifierBuilder builder() {
359 return new YangInstanceIdentifierBuilder();
363 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
365 * @param origin InstanceIdentifier from which path arguments are copied.
366 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
368 public static InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
369 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
373 * Path argument / component of InstanceIdentifier.
374 * Path argument uniquely identifies node in data tree on particular
378 * This interface itself is used as common parent for actual
379 * path arguments types and should not be implemented by user code.
382 * Path arguments SHOULD contain only minimum of information
383 * required to uniquely identify node on particular subtree level.
386 * For actual path arguments types see:
388 * <li>{@link NodeIdentifier} - Identifier of container or leaf
389 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
390 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
391 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
394 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
396 * If applicable returns unique QName of data node as defined in YANG
400 * This method may return null, if the corresponding schema node, does
401 * not have QName associated, such as in cases of augmentations.
408 * Return the string representation of this object for use in context
409 * provided by a previous object. This method can be implemented in
410 * terms of {@link #toString()}, but implementations are encourage to
411 * reuse any context already emitted by the previous object.
413 * @param previous Previous path argument
414 * @return String representation
416 String toRelativeString(PathArgument previous);
419 private abstract static class AbstractPathArgument implements PathArgument {
420 private static final long serialVersionUID = -4546547994250849340L;
421 private final QName nodeType;
422 private transient int hashValue;
423 private transient volatile boolean hashGuard = false;
425 protected AbstractPathArgument(final QName nodeType) {
426 this.nodeType = Preconditions.checkNotNull(nodeType);
430 public final QName getNodeType() {
435 @SuppressWarnings("checkstyle:parameterName")
436 public int compareTo(@Nonnull final PathArgument o) {
437 return nodeType.compareTo(o.getNodeType());
440 protected int hashCodeImpl() {
441 return 31 + getNodeType().hashCode();
445 public final int hashCode() {
447 hashValue = hashCodeImpl();
455 public boolean equals(final Object obj) {
459 if (obj == null || this.getClass() != obj.getClass()) {
463 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
467 public String toString() {
468 return getNodeType().toString();
472 public String toRelativeString(final PathArgument previous) {
473 if (previous instanceof AbstractPathArgument) {
474 final QNameModule mod = previous.getNodeType().getModule();
475 if (getNodeType().getModule().equals(mod)) {
476 return getNodeType().getLocalName();
480 return getNodeType().toString();
485 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
486 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
488 public static final class NodeIdentifier extends AbstractPathArgument {
489 private static final long serialVersionUID = -2255888212390871347L;
490 private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
491 .build(new CacheLoader<QName, NodeIdentifier>() {
493 public NodeIdentifier load(@Nonnull final QName key) {
494 return new NodeIdentifier(key);
498 public NodeIdentifier(final QName node) {
503 * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
504 * instance cache, resulting in object reuse for equal inputs.
506 * @param node Node's QName
507 * @return A {@link NodeIdentifier}
509 public static NodeIdentifier create(final QName node) {
510 return CACHE.getUnchecked(node);
515 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
518 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
519 private static final long serialVersionUID = -4787195606494761540L;
521 private final Map<QName, Object> keyValues;
523 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
525 // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
526 this.keyValues = ImmutableOffsetMap.unorderedCopyOf(keyValues);
529 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
531 this.keyValues = SharedSingletonMap.unorderedOf(key, value);
534 public Map<QName, Object> getKeyValues() {
539 protected int hashCodeImpl() {
540 final int prime = 31;
541 int result = super.hashCodeImpl();
542 result = prime * result;
544 for (Entry<QName, Object> entry : keyValues.entrySet()) {
545 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
551 public boolean equals(final Object obj) {
552 if (!super.equals(obj)) {
556 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
558 // TODO: benchmark to see if just calling equals() on the two maps is not faster
559 if (keyValues == otherKeyValues) {
562 if (keyValues.size() != otherKeyValues.size()) {
566 for (Entry<QName, Object> entry : keyValues.entrySet()) {
567 if (!otherKeyValues.containsKey(entry.getKey())
568 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
578 public String toString() {
579 return super.toString() + '[' + keyValues + ']';
583 public String toRelativeString(final PathArgument previous) {
584 return super.toRelativeString(previous) + '[' + keyValues + ']';
589 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
592 public static final class NodeWithValue<T> extends AbstractPathArgument {
593 private static final long serialVersionUID = -3637456085341738431L;
595 private final T value;
597 public NodeWithValue(final QName node, final T value) {
602 public T getValue() {
607 protected int hashCodeImpl() {
608 final int prime = 31;
609 int result = super.hashCodeImpl();
610 result = prime * result + YangInstanceIdentifier.hashCode(value);
615 public boolean equals(final Object obj) {
616 if (!super.equals(obj)) {
619 final NodeWithValue<?> other = (NodeWithValue<?>) obj;
620 return Objects.deepEquals(value, other.value);
624 public String toString() {
625 return super.toString() + '[' + value + ']';
629 public String toRelativeString(final PathArgument previous) {
630 return super.toRelativeString(previous) + '[' + value + ']';
635 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode}
636 * node in particular subtree.
639 * Augmentation is uniquely identified by set of all possible child nodes.
641 * to identify instance of augmentation,
642 * since RFC6020 states that <code>augment</code> that augment
643 * statement must not add multiple nodes from same namespace
644 * / module to the target node.
646 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
648 public static final class AugmentationIdentifier implements PathArgument {
649 private static final long serialVersionUID = -8122335594681936939L;
650 private final ImmutableSet<QName> childNames;
653 public QName getNodeType() {
654 // This should rather throw exception than return always null
655 throw new UnsupportedOperationException("Augmentation node has no QName");
659 * Construct new augmentation identifier using supplied set of possible
663 * Set of possible child nodes.
665 public AugmentationIdentifier(final Set<QName> childNames) {
666 this.childNames = ImmutableSet.copyOf(childNames);
670 * Returns set of all possible child nodes.
672 * @return set of all possible child nodes.
674 public Set<QName> getPossibleChildNames() {
679 public String toString() {
680 return "AugmentationIdentifier{" + "childNames=" + childNames + '}';
684 public String toRelativeString(final PathArgument previous) {
689 public boolean equals(final Object obj) {
693 if (!(obj instanceof AugmentationIdentifier)) {
697 AugmentationIdentifier that = (AugmentationIdentifier) obj;
698 return childNames.equals(that.childNames);
702 public int hashCode() {
703 return childNames.hashCode();
707 @SuppressWarnings("checkstyle:parameterName")
708 public int compareTo(@Nonnull final PathArgument o) {
709 if (!(o instanceof AugmentationIdentifier)) {
712 AugmentationIdentifier other = (AugmentationIdentifier) o;
713 Set<QName> otherChildNames = other.getPossibleChildNames();
714 int thisSize = childNames.size();
715 int otherSize = otherChildNames.size();
716 if (thisSize == otherSize) {
717 Iterator<QName> otherIterator = otherChildNames.iterator();
718 for (QName name : childNames) {
719 int child = name.compareTo(otherIterator.next());
725 } else if (thisSize < otherSize) {
734 * Fluent Builder of Instance Identifier instances.
736 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
738 * Adds a {@link PathArgument} to to path arguments of resulting instance identifier.
740 * @param arg A {@link PathArgument} to be added
741 * @return this builder
743 InstanceIdentifierBuilder node(PathArgument arg);
746 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
748 * @param nodeType QName of {@link NodeIdentifier} which will be added
749 * @return this builder
751 InstanceIdentifierBuilder node(QName nodeType);
754 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting
755 * instance identifier.
757 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
758 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
759 * @return this builder
761 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
764 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
766 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
767 * @param key QName of key which will be added
768 * @param value value of key which will be added
769 * @return this builder
771 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
774 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder.
776 * @return {@link YangInstanceIdentifier}
779 YangInstanceIdentifier build();