2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
5 * and is available at http://www.eclipse.org/legal/epl-v10.html
7 package org.opendaylight.yangtools.yang.data.api;
9 import com.google.common.base.Optional;
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.collect.ImmutableSet;
13 import com.google.common.collect.Iterables;
14 import java.io.Serializable;
15 import java.lang.reflect.Array;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.Iterator;
19 import java.util.List;
21 import java.util.Map.Entry;
22 import java.util.Objects;
24 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
25 import javax.annotation.Nonnull;
26 import javax.annotation.Nullable;
27 import org.opendaylight.yangtools.concepts.Builder;
28 import org.opendaylight.yangtools.concepts.Immutable;
29 import org.opendaylight.yangtools.concepts.Path;
30 import org.opendaylight.yangtools.util.HashCodeBuilder;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.QNameModule;
33 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
36 * Unique identifier of a particular node instance in the data tree.
39 * Java representation of YANG Built-in type <code>instance-identifier</code>,
40 * which conceptually is XPath expression minimized to uniquely identify element
41 * in data tree which conforms to constraints maintained by YANG Model,
42 * effectively this makes Instance Identifier a path to element in data tree.
44 * Constraints put in YANG specification on instance-identifier allowed it to be
45 * effectively represented in Java and it's evaluation does not require
46 * full-blown XPath processor.
48 * <h3>Path Arguments</h3>
49 * Path to the node represented in instance identifier consists of
50 * {@link PathArgument} which carries necessary information to uniquely identify
51 * node on particular level in the subtree.
54 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
55 * <code>0..1</code> in particular subtree in data tree.</li>
56 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item),
57 * which has cardinality <code>0..n</code>.</li>
58 * <li>{@link NodeWithValue} - Identifier of instance <code>leaf</code> node or
59 * <code>leaf-list</code> node.</li>
60 * <li>{@link AugmentationIdentifier} - Identifier of instance of
61 * <code>augmentation</code> node.</li>
65 * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
67 public abstract class YangInstanceIdentifier extends CollectionPathArguments implements Path<YangInstanceIdentifier>, Immutable, Serializable {
69 * An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual
70 * root of the YANG namespace.
72 public static final YangInstanceIdentifier EMPTY = FixedYangInstanceIdentifier.EMPTY_INSTANCE;
74 private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, String> TOSTRINGCACHE_UPDATER =
75 AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, String.class, "toStringCache");
76 private static final long serialVersionUID = 4L;
78 private final int hash;
79 private transient volatile String toStringCache = null;
81 // Package-private to prevent outside subclassing
82 YangInstanceIdentifier(final int hash) {
86 @Nonnull abstract YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
87 @Nonnull abstract Collection<PathArgument> tryPathArguments();
88 @Nonnull abstract Collection<PathArgument> tryReversePathArguments();
91 * Check if this instance identifier has empty path arguments, e.g. it is
92 * empty and corresponds to {@link #EMPTY}.
94 * @return True if this instance identifier is empty, false otherwise.
96 public abstract boolean isEmpty();
99 * Return the conceptual parent {@link YangInstanceIdentifier}, which has
100 * one item less in {@link #getPathArguments()}.
102 * @return Parent {@link YangInstanceIdentifier}, or null if this is object is {@link #EMPTY}.
104 @Nullable public abstract YangInstanceIdentifier getParent();
107 * Returns a list of path arguments.
109 * @deprecated Use {@link #getPathArguments()} instead.
110 * @return Immutable list of path arguments.
113 public final List<PathArgument> getPath() {
114 return getPathArguments();
118 * Returns an ordered iteration of path arguments.
120 * @return Immutable iteration of path arguments.
123 public abstract List<PathArgument> getPathArguments();
126 * Returns an iterable of path arguments in reverse order. This is useful
127 * when walking up a tree organized this way.
129 * @return Immutable iterable of path arguments in reverse order.
132 public abstract List<PathArgument> getReversePathArguments();
135 * Returns the last PathArgument. This is equivalent of iterating
136 * to the last element of the iterable returned by {@link #getPathArguments()}.
138 * @return The last past argument, or null if there are no PathArguments.
140 public abstract PathArgument getLastPathArgument();
142 public static YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
143 if (Iterables.isEmpty(path)) {
147 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
148 for (PathArgument a : path) {
152 return FixedYangInstanceIdentifier.create(path, hash.build());
155 public static YangInstanceIdentifier create(final PathArgument... path) {
156 // We are forcing a copy, since we cannot trust the user
157 return create(Arrays.asList(path));
161 public final int hashCode() {
163 * The caching is safe, since the object contract requires
164 * immutability of the object and all objects referenced from this
166 * Used lists, maps are immutable. Path Arguments (elements) are also
167 * immutable, since the PathArgument contract requires immutability.
172 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
173 return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
177 public boolean equals(final Object obj) {
181 if (!(obj instanceof YangInstanceIdentifier)) {
184 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
185 if (this.hashCode() != obj.hashCode()) {
189 return pathArgumentsEqual(other);
193 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments
195 * @param name QName of {@link NodeIdentifier}
196 * @return Instance Identifier with additional path argument added to the end.
198 public final YangInstanceIdentifier node(final QName name) {
199 return node(new NodeIdentifier(name));
204 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments
206 * @param arg Path argument which should be added to the end
207 * @return Instance Identifier with additional path argument added to the end.
209 public final YangInstanceIdentifier node(final PathArgument arg) {
210 return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
214 * Get the relative path from an ancestor. This method attempts to perform
215 * the reverse of concatenating a base (ancestor) and a path.
218 * Ancestor against which the relative path should be calculated
219 * @return This object's relative path from parent, or Optional.absent() if
220 * the specified parent is not in fact an ancestor of this object.
222 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
223 final Iterator<?> lit = getPathArguments().iterator();
224 final Iterator<?> oit = ancestor.getPathArguments().iterator();
227 while (oit.hasNext()) {
228 // Ancestor is not really an ancestor
229 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
230 return Optional.absent();
237 return Optional.of(this);
239 if (!lit.hasNext()) {
240 return Optional.of(EMPTY);
243 return Optional.of(createRelativeIdentifier(common));
246 private static int hashCode(final Object value) {
251 if (value.getClass().equals(byte[].class)) {
252 return Arrays.hashCode((byte[]) value);
255 if (value.getClass().isArray()) {
257 int length = Array.getLength(value);
258 for (int i = 0; i < length; i++) {
259 hash += Objects.hashCode(Array.get(value, i));
265 return Objects.hashCode(value);
268 // Static factories & helpers
272 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied QName
274 * @param name QName of first node identifier
275 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
277 public static YangInstanceIdentifier of(final QName name) {
278 return create(new NodeIdentifier(name));
283 * Returns new builder for InstanceIdentifier with empty path arguments.
285 * @return new builder for InstanceIdentifier with empty path arguments.
287 public static InstanceIdentifierBuilder builder() {
288 return new YangInstanceIdentifierBuilder();
293 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
295 * @param origin Instace Identifier from which path arguments are copied.
296 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
298 public static InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
299 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
303 * Path argument / component of InstanceIdentifier
305 * Path argument uniquely identifies node in data tree on particular
308 * This interface itself is used as common parent for actual
309 * path arguments types and should not be implemented by user code.
311 * Path arguments SHOULD contain only minimum of information
312 * required to uniquely identify node on particular subtree level.
314 * For actual path arguments types see:
316 * <li>{@link NodeIdentifier} - Identifier of container or leaf
317 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
318 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
319 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
322 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
324 * If applicable returns unique QName of data node as defined in YANG
327 * This method may return null, if the corresponding schema node, does
328 * not have QName associated, such as in cases of augmentations.
335 * Return the string representation of this object for use in context
336 * provided by a previous object. This method can be implemented in
337 * terms of {@link #toString()}, but implementations are encourage to
338 * reuse any context already emitted by the previous object.
340 * @param previous Previous path argument
341 * @return String representation
343 String toRelativeString(PathArgument previous);
346 private static abstract class AbstractPathArgument implements PathArgument {
347 private static final long serialVersionUID = -4546547994250849340L;
348 private final QName nodeType;
349 private transient int hashValue;
350 private volatile transient boolean hashGuard = false;
352 protected AbstractPathArgument(final QName nodeType) {
353 this.nodeType = Preconditions.checkNotNull(nodeType);
357 public final QName getNodeType() {
362 public int compareTo(final PathArgument o) {
363 return nodeType.compareTo(o.getNodeType());
366 protected int hashCodeImpl() {
367 return 31 + getNodeType().hashCode();
371 public final int hashCode() {
373 hashValue = hashCodeImpl();
381 public boolean equals(final Object obj) {
385 if (obj == null || this.getClass() != obj.getClass()) {
389 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
393 public String toString() {
394 return getNodeType().toString();
398 public String toRelativeString(final PathArgument previous) {
399 if (previous instanceof AbstractPathArgument) {
400 final QNameModule mod = ((AbstractPathArgument)previous).getNodeType().getModule();
401 if (getNodeType().getModule().equals(mod)) {
402 return getNodeType().getLocalName();
406 return getNodeType().toString();
411 * Fluent Builder of Instance Identifier instances
413 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
415 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
417 * @param nodeType QName of {@link NodeIdentifier} which will be added
418 * @return this builder
420 InstanceIdentifierBuilder node(QName nodeType);
423 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting instance identifier.
425 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
426 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
427 * @return this builder
429 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
432 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
434 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
435 * @param key QName of key which will be added
436 * @param value value of key which will be added
437 * @return this builder
439 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
443 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder
445 * @return {@link YangInstanceIdentifier}
448 YangInstanceIdentifier build();
451 * @deprecated use #build()
454 YangInstanceIdentifier toInstance();
458 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
459 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
461 public static final class NodeIdentifier extends AbstractPathArgument {
462 private static final long serialVersionUID = -2255888212390871347L;
464 public NodeIdentifier(final QName node) {
470 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
473 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
474 private static final long serialVersionUID = -4787195606494761540L;
476 private final Map<QName, Object> keyValues;
478 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
480 this.keyValues = ImmutableMap.copyOf(keyValues);
483 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
484 this(node, ImmutableMap.of(key, value));
487 public Map<QName, Object> getKeyValues() {
492 protected int hashCodeImpl() {
493 final int prime = 31;
494 int result = super.hashCodeImpl();
495 result = prime * result;
497 for (Entry<QName, Object> entry : keyValues.entrySet()) {
498 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
504 public boolean equals(final Object obj) {
505 if (!super.equals(obj)) {
509 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
510 if (keyValues.size() != otherKeyValues.size()) {
514 for (Entry<QName, Object> entry : keyValues.entrySet()) {
515 if (!otherKeyValues.containsKey(entry.getKey())
516 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
526 public String toString() {
527 return super.toString() + '[' + keyValues + ']';
531 public String toRelativeString(final PathArgument previous) {
532 return super.toRelativeString(previous) + '[' + keyValues + ']';
537 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
540 public static final class NodeWithValue extends AbstractPathArgument {
541 private static final long serialVersionUID = -3637456085341738431L;
543 private final Object value;
545 public NodeWithValue(final QName node, final Object value) {
550 public Object getValue() {
555 protected int hashCodeImpl() {
556 final int prime = 31;
557 int result = super.hashCodeImpl();
558 result = prime * result + ((value == null) ? 0 : YangInstanceIdentifier.hashCode(value));
563 public boolean equals(final Object obj) {
564 if (!super.equals(obj)) {
567 final NodeWithValue other = (NodeWithValue) obj;
568 return Objects.deepEquals(value, other.value);
572 public String toString() {
573 return super.toString() + '[' + value + ']';
577 public String toRelativeString(final PathArgument previous) {
578 return super.toRelativeString(previous) + '[' + value + ']';
583 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} node in
584 * particular subtree.
586 * Augmentation is uniquely identified by set of all possible child nodes.
588 * to identify instance of augmentation,
589 * since RFC6020 states that <code>augment</code> that augment
590 * statement must not add multiple nodes from same namespace
591 * / module to the target node.
594 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
596 public static final class AugmentationIdentifier implements PathArgument {
597 private static final long serialVersionUID = -8122335594681936939L;
598 private final ImmutableSet<QName> childNames;
601 public QName getNodeType() {
602 // This should rather throw exception than return always null
603 throw new UnsupportedOperationException("Augmentation node has no QName");
608 * Construct new augmentation identifier using supplied set of possible
612 * Set of possible child nodes.
614 public AugmentationIdentifier(final Set<QName> childNames) {
615 this.childNames = ImmutableSet.copyOf(childNames);
619 * Returns set of all possible child nodes
621 * @return set of all possible child nodes.
623 public Set<QName> getPossibleChildNames() {
628 public String toString() {
629 final StringBuilder sb = new StringBuilder("AugmentationIdentifier{");
630 sb.append("childNames=").append(childNames).append('}');
631 return sb.toString();
635 public String toRelativeString(final PathArgument previous) {
640 public boolean equals(final Object o) {
644 if (!(o instanceof AugmentationIdentifier)) {
648 AugmentationIdentifier that = (AugmentationIdentifier) o;
649 return childNames.equals(that.childNames);
653 public int hashCode() {
654 return childNames.hashCode();
658 public int compareTo(final PathArgument o) {
659 if (!(o instanceof AugmentationIdentifier)) {
662 AugmentationIdentifier other = (AugmentationIdentifier) o;
663 Set<QName> otherChildNames = other.getPossibleChildNames();
664 int thisSize = childNames.size();
665 int otherSize = otherChildNames.size();
666 if (thisSize == otherSize) {
667 Iterator<QName> otherIterator = otherChildNames.iterator();
668 for (QName name : childNames) {
669 int c = name.compareTo(otherIterator.next());
675 } else if (thisSize < otherSize) {
684 public final boolean contains(final YangInstanceIdentifier other) {
685 Preconditions.checkArgument(other != null, "other should not be null");
687 final Iterator<?> lit = getPathArguments().iterator();
688 final Iterator<?> oit = other.getPathArguments().iterator();
690 while (lit.hasNext()) {
691 if (!oit.hasNext()) {
695 if (!lit.next().equals(oit.next())) {
704 public final String toString() {
706 * The toStringCache is safe, since the object contract requires
707 * immutability of the object and all objects referenced from this
709 * Used lists, maps are immutable. Path Arguments (elements) are also
710 * immutable, since the PathArgument contract requires immutability.
711 * The cache is thread-safe - if multiple computations occurs at the
712 * same time, cache will be overwritten with same result.
714 String ret = toStringCache;
716 final StringBuilder builder = new StringBuilder("/");
717 PathArgument prev = null;
718 for (PathArgument argument : getPathArguments()) {
722 builder.append(argument.toRelativeString(prev));
726 ret = builder.toString();
727 TOSTRINGCACHE_UPDATER.lazySet(this, ret);