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.ImmutableList;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.ImmutableSet;
14 import com.google.common.collect.Iterables;
15 import com.google.common.collect.Lists;
17 import java.io.Serializable;
18 import java.lang.reflect.Array;
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.Collections;
22 import java.util.Iterator;
23 import java.util.List;
25 import java.util.Map.Entry;
26 import java.util.Objects;
29 import org.opendaylight.yangtools.concepts.Builder;
30 import org.opendaylight.yangtools.concepts.Immutable;
31 import org.opendaylight.yangtools.concepts.Path;
32 import org.opendaylight.yangtools.util.HashCodeBuilder;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
38 * Unique identifier of a particular node instance in the data tree.
41 * Java representation of YANG Built-in type <code>instance-identifier</code>,
42 * which conceptually is XPath expression minimized to uniquely identify element
43 * in data tree which conforms to constraints maintained by YANG Model,
44 * effectively this makes Instance Identifier a path to element in data tree.
46 * Constraints put in YANG specification on instance-identifier allowed it to be
47 * effectively represented in Java and it's evaluation does not require
48 * full-blown XPath processor.
50 * <h3>Path Arguments</h3>
51 * Path to the node represented in instance identifier consists of
52 * {@link PathArgument} which carries necessary information to uniquely identify
53 * node on particular level in the subtree.
56 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
57 * <code>0..1</code> in particular subtree in data tree.</li>
58 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item),
59 * which has cardinality <code>0..n</code>.</li>
60 * <li>{@link NodeWithValue} - Identifier of instance <code>leaf</code> node or
61 * <code>leaf-list</code> node.</li>
62 * <li>{@link AugmentationIdentifier} - Identifier of instance of
63 * <code>augmentation</code> node.</li>
67 * @see http://tools.ietf.org/html/rfc6020#section-9.13
69 public final class YangInstanceIdentifier implements Path<YangInstanceIdentifier>, Immutable, Serializable {
70 private static final YangInstanceIdentifier EMPTY = trustedCreate(Collections.<PathArgument>emptyList());
72 private static final long serialVersionUID = 2L;
73 private final Iterable<PathArgument> pathArguments;
74 private final int hash;
76 private transient volatile ImmutableList<PathArgument> legacyPath = null;
77 private transient volatile String toStringCache = null;
79 private final ImmutableList<PathArgument> getLegacyPath() {
80 // Temporary variable saves a volatile read
81 ImmutableList<PathArgument> ret = legacyPath;
84 // We could have used a synchronized block, but let's just not bother
85 ret = ImmutableList.copyOf(pathArguments);
94 * Returns a list of path arguments.
96 * @deprecated Use {@link #getPathArguments()} instead.
97 * @return Immutable list of path arguments.
100 public List<PathArgument> getPath() {
101 return getLegacyPath();
105 * Returns an ordered iteration of path arguments.
107 * @return Immutable iteration of path arguments.
109 public Iterable<PathArgument> getPathArguments() {
110 return pathArguments;
114 * Returns an iterable of path arguments in reverse order. This is useful
115 * when walking up a tree organized this way.
117 * @return Immutable iterable of path arguments in reverse order.
119 public Iterable<PathArgument> getReversePathArguments() {
120 return getLegacyPath().reverse();
124 * Returns the last PathArgument. This is equivalent of iterating
125 * to the last element of the iterable returned by {@link #getPathArguments()}.
127 * @return The last past argument, or null if there are no PathArguments.
129 public PathArgument getLastPathArgument() {
130 return Iterables.getFirst(getReversePathArguments(), null);
133 private YangInstanceIdentifier(final Iterable<PathArgument> path, final int hash) {
134 this.pathArguments = Preconditions.checkNotNull(path, "path must not be null.");
138 private static final YangInstanceIdentifier trustedCreate(final Iterable<PathArgument> path) {
139 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
140 for (PathArgument a : path) {
144 return new YangInstanceIdentifier(path, hash.toInstance());
147 public static final YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
148 if (Iterables.isEmpty(path)) {
152 return trustedCreate(ImmutableList.copyOf(path));
155 public static final 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 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.
173 public boolean equals(final Object obj) {
180 if (getClass() != obj.getClass()) {
183 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
184 if (this.hashCode() != obj.hashCode()) {
187 return Iterables.elementsEqual(pathArguments, other.pathArguments);
191 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments
193 * @param name QName of {@link NodeIdentifier}
194 * @return Instance Identifier with additional path argument added to the end.
196 public YangInstanceIdentifier node(final QName name) {
197 return node(new NodeIdentifier(name));
202 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments
204 * @param arg Path argument which should be added to the end
205 * @return Instance Identifier with additional path argument added to the end.
207 public YangInstanceIdentifier node(final PathArgument arg) {
208 return new YangInstanceIdentifier(Iterables.concat(pathArguments, Collections.singleton(arg)), HashCodeBuilder.nextHashCode(hash, arg));
212 * Get the relative path from an ancestor. This method attempts to perform
213 * the reverse of concatenating a base (ancestor) and a path.
216 * Ancestor against which the relative path should be calculated
217 * @return This object's relative path from parent, or Optional.absent() if
218 * the specified parent is not in fact an ancestor of this object.
220 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
221 final Iterator<?> lit = pathArguments.iterator();
222 final Iterator<?> oit = ancestor.pathArguments.iterator();
225 while (oit.hasNext()) {
226 // Ancestor is not really an ancestor
227 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
228 return Optional.absent();
235 return Optional.of(this);
237 if (!lit.hasNext()) {
238 return Optional.of(EMPTY);
240 return Optional.of(trustedCreate(Iterables.skip(pathArguments, common)));
243 private static int hashCode(final Object value) {
248 if (value.getClass().equals(byte[].class)) {
249 return Arrays.hashCode((byte[]) value);
252 if (value.getClass().isArray()) {
254 int length = Array.getLength(value);
255 for (int i = 0; i < length; i++) {
256 hash += Objects.hashCode(Array.get(value, i));
262 return Objects.hashCode(value);
265 // Static factories & helpers
269 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied QName
271 * @param name QName of first node identifier
272 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
274 public static YangInstanceIdentifier of(final QName name) {
275 return create(new NodeIdentifier(name));
280 * Returns new builder for InstanceIdentifier with empty path arguments.
282 * @return new builder for InstanceIdentifier with empty path arguments.
284 static public InstanceIdentifierBuilder builder() {
285 return new BuilderImpl();
290 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
292 * @param origin Instace Identifier from which path arguments are copied.
293 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
295 static public InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
296 return new BuilderImpl(origin.getPathArguments(), origin.hashCode());
300 * Returns new builder for InstanceIdentifier with first path argument set to {@link NodeIdentifier}.
302 * @param node QName of first {@link NodeIdentifier} path argument.
303 * @return new builder for InstanceIdentifier with first path argument set to {@link NodeIdentifier}.
305 * @deprecated Either use {@link #node(QName)} or instantiate an intermediate builder.
308 public static InstanceIdentifierBuilder builder(final QName node) {
309 return builder().node(node);
313 * Path argument / component of InstanceIdentifier
315 * Path argument uniquely identifies node in data tree on particular
318 * This interface itself is used as common parent for actual
319 * path arguments types and should not be implemented by user code.
321 * Path arguments SHOULD contain only minimum of information
322 * required to uniquely identify node on particular subtree level.
324 * For actual path arguments types see:
326 * <li>{@link NodeIdentifier} - Identifier of container or leaf
327 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
328 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
329 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
332 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
334 * If applicable returns unique QName of data node as defined in YANG
337 * This method may return null, if the corresponding schema node, does
338 * not have QName associated, such as in cases of augmentations.
345 * Return the string representation of this object for use in context
346 * provided by a previous object. This method can be implemented in
347 * terms of {@link #toString()}, but implementations are encourage to
348 * reuse any context already emitted by the previous object.
350 * @param previous Previous path argument
351 * @return String representation
353 String toRelativeString(PathArgument previous);
356 private static abstract class AbstractPathArgument implements PathArgument {
357 private static final long serialVersionUID = -4546547994250849340L;
358 private final QName nodeType;
359 private volatile transient Integer hash = null;
361 protected AbstractPathArgument(final QName nodeType) {
362 this.nodeType = Preconditions.checkNotNull(nodeType);
366 public final QName getNodeType() {
371 public int compareTo(final PathArgument o) {
372 return nodeType.compareTo(o.getNodeType());
375 protected int hashCodeImpl() {
376 return 31 + getNodeType().hashCode();
380 public final int hashCode() {
383 synchronized (this) {
386 ret = hashCodeImpl();
396 public boolean equals(final Object obj) {
400 if (obj == null || this.getClass() != obj.getClass()) {
404 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
408 public String toString() {
409 return getNodeType().toString();
413 public String toRelativeString(final PathArgument previous) {
414 if (previous instanceof AbstractPathArgument) {
415 final QNameModule mod = ((AbstractPathArgument)previous).getNodeType().getModule();
416 if (getNodeType().getModule().equals(mod)) {
417 return getNodeType().getLocalName();
421 return getNodeType().toString();
427 * Fluent Builder of Instance Identifier instances
432 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
434 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
436 * @param nodeType QName of {@link NodeIdentifier} which will be added
437 * @return this builder
439 InstanceIdentifierBuilder node(QName nodeType);
442 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting instance identifier.
444 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
445 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
446 * @return this builder
448 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
451 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
453 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
454 * @param key QName of key which will be added
455 * @param value value of key which will be added
456 * @return this builder
458 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
462 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder
464 * @return {@link YangInstanceIdentifier}
466 YangInstanceIdentifier build();
470 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
471 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
473 public static final class NodeIdentifier extends AbstractPathArgument {
474 private static final long serialVersionUID = -2255888212390871347L;
476 public NodeIdentifier(final QName node) {
482 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
485 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
486 private static final long serialVersionUID = -4787195606494761540L;
488 private final Map<QName, Object> keyValues;
490 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
492 this.keyValues = ImmutableMap.copyOf(keyValues);
495 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
496 this(node, ImmutableMap.of(key, value));
499 public Map<QName, Object> getKeyValues() {
504 protected int hashCodeImpl() {
505 final int prime = 31;
506 int result = super.hashCodeImpl();
507 result = prime * result;
509 for (Entry<QName, Object> entry : keyValues.entrySet()) {
510 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
516 public boolean equals(final Object obj) {
517 if (!super.equals(obj)) {
521 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
522 if (keyValues.size() != otherKeyValues.size()) {
526 for (Entry<QName, Object> entry : keyValues.entrySet()) {
527 if (!otherKeyValues.containsKey(entry.getKey())
528 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
538 public String toString() {
539 return super.toString() + '[' + keyValues + ']';
543 public String toRelativeString(final PathArgument previous) {
544 return super.toRelativeString(previous) + '[' + keyValues + ']';
549 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
552 public static final class NodeWithValue extends AbstractPathArgument {
553 private static final long serialVersionUID = -3637456085341738431L;
555 private final Object value;
557 public NodeWithValue(final QName node, final Object value) {
562 public Object getValue() {
567 protected int hashCodeImpl() {
568 final int prime = 31;
569 int result = super.hashCodeImpl();
570 result = prime * result + ((value == null) ? 0 : YangInstanceIdentifier.hashCode(value));
575 public boolean equals(final Object obj) {
576 if (!super.equals(obj)) {
579 final NodeWithValue other = (NodeWithValue) obj;
580 return Objects.deepEquals(value, other.value);
584 public String toString() {
585 return super.toString() + '[' + value + ']';
589 public String toRelativeString(final PathArgument previous) {
590 return super.toRelativeString(previous) + '[' + value + ']';
595 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} node in
596 * particular subtree.
598 * Augmentation is uniquely identified by set of all possible child nodes.
600 * to identify instance of augmentation,
601 * since RFC6020 states that <code>augment</code> that augment
602 * statement must not add multiple nodes from same namespace
603 * / module to the target node.
606 * @see http://tools.ietf.org/html/rfc6020#section-7.15
608 public static final class AugmentationIdentifier implements PathArgument {
609 private static final long serialVersionUID = -8122335594681936939L;
610 private final ImmutableSet<QName> childNames;
613 public QName getNodeType() {
614 // This should rather throw exception than return always null
615 throw new UnsupportedOperationException("Augmentation node has no QName");
620 * Construct new augmentation identifier using supplied set of possible
624 * Set of possible child nodes.
626 public AugmentationIdentifier(final Set<QName> childNames) {
627 this.childNames = ImmutableSet.copyOf(childNames);
631 * Augmentation node has no QName
634 * {@link AugmentationIdentifier#AugmentationIdentifier(Set)}
638 public AugmentationIdentifier(final QName nodeType, final Set<QName> childNames) {
643 * Returns set of all possible child nodes
645 * @return set of all possible child nodes.
647 public Set<QName> getPossibleChildNames() {
652 public String toString() {
653 final StringBuffer sb = new StringBuffer("AugmentationIdentifier{");
654 sb.append("childNames=").append(childNames).append('}');
655 return sb.toString();
659 public String toRelativeString(final PathArgument previous) {
664 public boolean equals(final Object o) {
668 if (!(o instanceof AugmentationIdentifier)) {
672 AugmentationIdentifier that = (AugmentationIdentifier) o;
673 return childNames.equals(that.childNames);
677 public int hashCode() {
678 return childNames.hashCode();
682 public int compareTo(final PathArgument o) {
683 if (!(o instanceof AugmentationIdentifier)) {
686 AugmentationIdentifier other = (AugmentationIdentifier) o;
687 Set<QName> otherChildNames = other.getPossibleChildNames();
688 int thisSize = childNames.size();
689 int otherSize = otherChildNames.size();
690 if (thisSize == otherSize) {
691 Iterator<QName> otherIterator = otherChildNames.iterator();
692 for (QName name : childNames) {
693 int c = name.compareTo(otherIterator.next());
699 } else if (thisSize < otherSize) {
707 private static class BuilderImpl implements InstanceIdentifierBuilder {
708 private final HashCodeBuilder<PathArgument> hash;
709 private final List<PathArgument> path;
711 public BuilderImpl() {
712 this.hash = new HashCodeBuilder<>();
713 this.path = new ArrayList<>();
716 public BuilderImpl(final Iterable<PathArgument> prefix, final int hash) {
717 this.path = Lists.newArrayList(prefix);
718 this.hash = new HashCodeBuilder<>(hash);
722 public InstanceIdentifierBuilder node(final QName nodeType) {
723 final PathArgument arg = new NodeIdentifier(nodeType);
725 hash.addArgument(arg);
730 public InstanceIdentifierBuilder nodeWithKey(final QName nodeType, final QName key, final Object value) {
731 final PathArgument arg = new NodeIdentifierWithPredicates(nodeType, key, value);
733 hash.addArgument(arg);
738 public InstanceIdentifierBuilder nodeWithKey(final QName nodeType, final Map<QName, Object> keyValues) {
739 final PathArgument arg = new NodeIdentifierWithPredicates(nodeType, keyValues);
741 hash.addArgument(arg);
747 public YangInstanceIdentifier toInstance() {
752 public YangInstanceIdentifier build() {
753 return new YangInstanceIdentifier(ImmutableList.copyOf(path), hash.toInstance());
758 public boolean contains(final YangInstanceIdentifier other) {
759 Preconditions.checkArgument(other != null, "other should not be null");
761 final Iterator<?> lit = pathArguments.iterator();
762 final Iterator<?> oit = other.pathArguments.iterator();
764 while (lit.hasNext()) {
765 if (!oit.hasNext()) {
769 if (!lit.next().equals(oit.next())) {
778 public String toString() {
780 * The toStringCache is safe, since the object contract requires
781 * immutability of the object and all objects referenced from this
783 * Used lists, maps are immutable. Path Arguments (elements) are also
784 * immutable, since the PathArgument contract requires immutability.
785 * The cache is thread-safe - if multiple computations occurs at the
786 * same time, cache will be overwritten with same result.
788 String ret = toStringCache;
790 synchronized (this) {
793 final StringBuilder builder = new StringBuilder("/");
794 PathArgument prev = null;
795 for (PathArgument argument : getPathArguments()) {
799 builder.append(argument.toRelativeString(prev));
803 ret = builder.toString();