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.Iterator;
18 import java.util.List;
20 import java.util.Map.Entry;
21 import java.util.Objects;
23 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
24 import javax.annotation.Nonnull;
25 import javax.annotation.Nullable;
26 import org.opendaylight.yangtools.concepts.Builder;
27 import org.opendaylight.yangtools.concepts.Immutable;
28 import org.opendaylight.yangtools.concepts.Path;
29 import org.opendaylight.yangtools.util.HashCodeBuilder;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.common.QNameModule;
32 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
35 * Unique identifier of a particular node instance in the data tree.
38 * Java representation of YANG Built-in type <code>instance-identifier</code>,
39 * which conceptually is XPath expression minimized to uniquely identify element
40 * in data tree which conforms to constraints maintained by YANG Model,
41 * effectively this makes Instance Identifier a path to element in data tree.
43 * Constraints put in YANG specification on instance-identifier allowed it to be
44 * effectively represented in Java and it's evaluation does not require
45 * full-blown XPath processor.
47 * <h3>Path Arguments</h3>
48 * Path to the node represented in instance identifier consists of
49 * {@link PathArgument} which carries necessary information to uniquely identify
50 * node on particular level in the subtree.
53 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
54 * <code>0..1</code> in particular subtree in data tree.</li>
55 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item),
56 * which has cardinality <code>0..n</code>.</li>
57 * <li>{@link NodeWithValue} - Identifier of instance <code>leaf</code> node or
58 * <code>leaf-list</code> node.</li>
59 * <li>{@link AugmentationIdentifier} - Identifier of instance of
60 * <code>augmentation</code> node.</li>
64 * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
66 public abstract class YangInstanceIdentifier implements Path<YangInstanceIdentifier>, Immutable, Serializable {
68 * An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual
69 * root of the YANG namespace.
71 public static final YangInstanceIdentifier EMPTY = FixedYangInstanceIdentifier.EMPTY_INSTANCE;
73 private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, String> TOSTRINGCACHE_UPDATER =
74 AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, String.class, "toStringCache");
75 private static final long serialVersionUID = 4L;
77 private final int hash;
78 private transient volatile String toStringCache = null;
80 // Package-private to prevent outside subclassing
81 YangInstanceIdentifier(final int hash) {
85 @Nonnull abstract YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
86 @Nonnull abstract Iterable<PathArgument> tryPathArguments();
89 * Check if this instance identifier has empty path arguments, e.g. it is
90 * empty and corresponds to {@link #EMPTY}.
92 * @return True if this instance identifier is empty, false otherwise.
94 public abstract boolean isEmpty();
97 * Return the conceptual parent {@link YangInstanceIdentifier}, which has
98 * one item less in {@link #getPathArguments()}.
100 * @return Parent {@link YangInstanceIdentifier}, or null if this is object is {@link #EMPTY}.
102 @Nullable public abstract YangInstanceIdentifier getParent();
105 * Returns a list of path arguments.
107 * @deprecated Use {@link #getPathArguments()} instead.
108 * @return Immutable list of path arguments.
111 public abstract List<PathArgument> getPath();
114 * Returns an ordered iteration of path arguments.
116 * @return Immutable iteration of path arguments.
118 public abstract Iterable<PathArgument> getPathArguments();
121 * Returns an iterable of path arguments in reverse order. This is useful
122 * when walking up a tree organized this way.
124 * @return Immutable iterable of path arguments in reverse order.
126 public abstract Iterable<PathArgument> getReversePathArguments();
129 * Returns the last PathArgument. This is equivalent of iterating
130 * to the last element of the iterable returned by {@link #getPathArguments()}.
132 * @return The last past argument, or null if there are no PathArguments.
134 public abstract PathArgument getLastPathArgument();
136 public static YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
137 if (Iterables.isEmpty(path)) {
141 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
142 for (PathArgument a : path) {
146 return FixedYangInstanceIdentifier.create(path, hash.build());
149 public static YangInstanceIdentifier create(final PathArgument... path) {
150 // We are forcing a copy, since we cannot trust the user
151 return create(Arrays.asList(path));
155 public final int hashCode() {
157 * The caching is safe, since the object contract requires
158 * immutability of the object and all objects referenced from this
160 * Used lists, maps are immutable. Path Arguments (elements) are also
161 * immutable, since the PathArgument contract requires immutability.
166 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
167 return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
171 public boolean equals(final Object obj) {
175 if (!(obj instanceof YangInstanceIdentifier)) {
178 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
179 if (this.hashCode() != obj.hashCode()) {
183 return pathArgumentsEqual(other);
187 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments
189 * @param name QName of {@link NodeIdentifier}
190 * @return Instance Identifier with additional path argument added to the end.
192 public final YangInstanceIdentifier node(final QName name) {
193 return node(new NodeIdentifier(name));
198 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments
200 * @param arg Path argument which should be added to the end
201 * @return Instance Identifier with additional path argument added to the end.
203 public final YangInstanceIdentifier node(final PathArgument arg) {
204 return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
208 * Get the relative path from an ancestor. This method attempts to perform
209 * the reverse of concatenating a base (ancestor) and a path.
212 * Ancestor against which the relative path should be calculated
213 * @return This object's relative path from parent, or Optional.absent() if
214 * the specified parent is not in fact an ancestor of this object.
216 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
217 final Iterator<?> lit = getPathArguments().iterator();
218 final Iterator<?> oit = ancestor.getPathArguments().iterator();
221 while (oit.hasNext()) {
222 // Ancestor is not really an ancestor
223 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
224 return Optional.absent();
231 return Optional.of(this);
233 if (!lit.hasNext()) {
234 return Optional.of(EMPTY);
237 return Optional.of(createRelativeIdentifier(common));
240 private static int hashCode(final Object value) {
245 if (value.getClass().equals(byte[].class)) {
246 return Arrays.hashCode((byte[]) value);
249 if (value.getClass().isArray()) {
251 int length = Array.getLength(value);
252 for (int i = 0; i < length; i++) {
253 hash += Objects.hashCode(Array.get(value, i));
259 return Objects.hashCode(value);
262 // Static factories & helpers
266 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied QName
268 * @param name QName of first node identifier
269 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
271 public static YangInstanceIdentifier of(final QName name) {
272 return create(new NodeIdentifier(name));
277 * Returns new builder for InstanceIdentifier with empty path arguments.
279 * @return new builder for InstanceIdentifier with empty path arguments.
281 public static InstanceIdentifierBuilder builder() {
282 return new YangInstanceIdentifierBuilder();
287 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
289 * @param origin Instace Identifier from which path arguments are copied.
290 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
292 public static InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
293 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
297 * Path argument / component of InstanceIdentifier
299 * Path argument uniquely identifies node in data tree on particular
302 * This interface itself is used as common parent for actual
303 * path arguments types and should not be implemented by user code.
305 * Path arguments SHOULD contain only minimum of information
306 * required to uniquely identify node on particular subtree level.
308 * For actual path arguments types see:
310 * <li>{@link NodeIdentifier} - Identifier of container or leaf
311 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
312 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
313 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
316 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
318 * If applicable returns unique QName of data node as defined in YANG
321 * This method may return null, if the corresponding schema node, does
322 * not have QName associated, such as in cases of augmentations.
329 * Return the string representation of this object for use in context
330 * provided by a previous object. This method can be implemented in
331 * terms of {@link #toString()}, but implementations are encourage to
332 * reuse any context already emitted by the previous object.
334 * @param previous Previous path argument
335 * @return String representation
337 String toRelativeString(PathArgument previous);
340 private static abstract class AbstractPathArgument implements PathArgument {
341 private static final long serialVersionUID = -4546547994250849340L;
342 private final QName nodeType;
343 private transient int hashValue;
344 private volatile transient boolean hashGuard = false;
346 protected AbstractPathArgument(final QName nodeType) {
347 this.nodeType = Preconditions.checkNotNull(nodeType);
351 public final QName getNodeType() {
356 public int compareTo(final PathArgument o) {
357 return nodeType.compareTo(o.getNodeType());
360 protected int hashCodeImpl() {
361 return 31 + getNodeType().hashCode();
365 public final int hashCode() {
367 hashValue = hashCodeImpl();
375 public boolean equals(final Object obj) {
379 if (obj == null || this.getClass() != obj.getClass()) {
383 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
387 public String toString() {
388 return getNodeType().toString();
392 public String toRelativeString(final PathArgument previous) {
393 if (previous instanceof AbstractPathArgument) {
394 final QNameModule mod = ((AbstractPathArgument)previous).getNodeType().getModule();
395 if (getNodeType().getModule().equals(mod)) {
396 return getNodeType().getLocalName();
400 return getNodeType().toString();
405 * Fluent Builder of Instance Identifier instances
407 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
409 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
411 * @param nodeType QName of {@link NodeIdentifier} which will be added
412 * @return this builder
414 InstanceIdentifierBuilder node(QName nodeType);
417 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting instance identifier.
419 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
420 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
421 * @return this builder
423 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
426 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
428 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
429 * @param key QName of key which will be added
430 * @param value value of key which will be added
431 * @return this builder
433 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
437 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder
439 * @return {@link YangInstanceIdentifier}
442 YangInstanceIdentifier build();
445 * @deprecated use #build()
448 YangInstanceIdentifier toInstance();
452 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
453 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
455 public static final class NodeIdentifier extends AbstractPathArgument {
456 private static final long serialVersionUID = -2255888212390871347L;
458 public NodeIdentifier(final QName node) {
464 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
467 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
468 private static final long serialVersionUID = -4787195606494761540L;
470 private final Map<QName, Object> keyValues;
472 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
474 this.keyValues = ImmutableMap.copyOf(keyValues);
477 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
478 this(node, ImmutableMap.of(key, value));
481 public Map<QName, Object> getKeyValues() {
486 protected int hashCodeImpl() {
487 final int prime = 31;
488 int result = super.hashCodeImpl();
489 result = prime * result;
491 for (Entry<QName, Object> entry : keyValues.entrySet()) {
492 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
498 public boolean equals(final Object obj) {
499 if (!super.equals(obj)) {
503 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
504 if (keyValues.size() != otherKeyValues.size()) {
508 for (Entry<QName, Object> entry : keyValues.entrySet()) {
509 if (!otherKeyValues.containsKey(entry.getKey())
510 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
520 public String toString() {
521 return super.toString() + '[' + keyValues + ']';
525 public String toRelativeString(final PathArgument previous) {
526 return super.toRelativeString(previous) + '[' + keyValues + ']';
531 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
534 public static final class NodeWithValue extends AbstractPathArgument {
535 private static final long serialVersionUID = -3637456085341738431L;
537 private final Object value;
539 public NodeWithValue(final QName node, final Object value) {
544 public Object getValue() {
549 protected int hashCodeImpl() {
550 final int prime = 31;
551 int result = super.hashCodeImpl();
552 result = prime * result + ((value == null) ? 0 : YangInstanceIdentifier.hashCode(value));
557 public boolean equals(final Object obj) {
558 if (!super.equals(obj)) {
561 final NodeWithValue other = (NodeWithValue) obj;
562 return Objects.deepEquals(value, other.value);
566 public String toString() {
567 return super.toString() + '[' + value + ']';
571 public String toRelativeString(final PathArgument previous) {
572 return super.toRelativeString(previous) + '[' + value + ']';
577 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} node in
578 * particular subtree.
580 * Augmentation is uniquely identified by set of all possible child nodes.
582 * to identify instance of augmentation,
583 * since RFC6020 states that <code>augment</code> that augment
584 * statement must not add multiple nodes from same namespace
585 * / module to the target node.
588 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
590 public static final class AugmentationIdentifier implements PathArgument {
591 private static final long serialVersionUID = -8122335594681936939L;
592 private final ImmutableSet<QName> childNames;
595 public QName getNodeType() {
596 // This should rather throw exception than return always null
597 throw new UnsupportedOperationException("Augmentation node has no QName");
602 * Construct new augmentation identifier using supplied set of possible
606 * Set of possible child nodes.
608 public AugmentationIdentifier(final Set<QName> childNames) {
609 this.childNames = ImmutableSet.copyOf(childNames);
613 * Returns set of all possible child nodes
615 * @return set of all possible child nodes.
617 public Set<QName> getPossibleChildNames() {
622 public String toString() {
623 final StringBuilder sb = new StringBuilder("AugmentationIdentifier{");
624 sb.append("childNames=").append(childNames).append('}');
625 return sb.toString();
629 public String toRelativeString(final PathArgument previous) {
634 public boolean equals(final Object o) {
638 if (!(o instanceof AugmentationIdentifier)) {
642 AugmentationIdentifier that = (AugmentationIdentifier) o;
643 return childNames.equals(that.childNames);
647 public int hashCode() {
648 return childNames.hashCode();
652 public int compareTo(final PathArgument o) {
653 if (!(o instanceof AugmentationIdentifier)) {
656 AugmentationIdentifier other = (AugmentationIdentifier) o;
657 Set<QName> otherChildNames = other.getPossibleChildNames();
658 int thisSize = childNames.size();
659 int otherSize = otherChildNames.size();
660 if (thisSize == otherSize) {
661 Iterator<QName> otherIterator = otherChildNames.iterator();
662 for (QName name : childNames) {
663 int c = name.compareTo(otherIterator.next());
669 } else if (thisSize < otherSize) {
678 public final boolean contains(final YangInstanceIdentifier other) {
679 Preconditions.checkArgument(other != null, "other should not be null");
681 final Iterator<?> lit = getPathArguments().iterator();
682 final Iterator<?> oit = other.getPathArguments().iterator();
684 while (lit.hasNext()) {
685 if (!oit.hasNext()) {
689 if (!lit.next().equals(oit.next())) {
698 public final String toString() {
700 * The toStringCache is safe, since the object contract requires
701 * immutability of the object and all objects referenced from this
703 * Used lists, maps are immutable. Path Arguments (elements) are also
704 * immutable, since the PathArgument contract requires immutability.
705 * The cache is thread-safe - if multiple computations occurs at the
706 * same time, cache will be overwritten with same result.
708 String ret = toStringCache;
710 final StringBuilder builder = new StringBuilder("/");
711 PathArgument prev = null;
712 for (PathArgument argument : getPathArguments()) {
716 builder.append(argument.toRelativeString(prev));
720 ret = builder.toString();
721 TOSTRINGCACHE_UPDATER.lazySet(this, ret);