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.data.api.schema.LeafSetEntryNode;
37 * Unique identifier of a partical node instance in the data tree.
40 * Java representation of YANG Built-in type <code>instance-identifier</code>,
41 * which conceptually is XPath expression minimised to uniquely identify element
42 * in data tree which conforms to constraints maintained by YANG Model,
43 * effectively this makes Instance Identifier a path to element in data tree.
45 * Constraints put in YANG specification on instance-identifier allowed it to be
46 * effectively represented in Java and it's evaluation does not require
47 * full-blown XPath processor.
49 * <h3>Path Arguments</h3>
50 * Path to the node represented in instance identifier consists of
51 * {@link PathArgument} which carries necessary information to uniquely identify
52 * node on particular level in the subtree.
55 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
56 * <code>0..1</code> in particular subtree in data tree.</li>
57 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item),
58 * which has cardinality <code>0..n</code>.</li>
59 * <li>{@link NodeWithValue} - Identifier of instance <code>leaf</code> node or
60 * <code>leaf-list</code> node.</li>
61 * <li>{@link AugmentationIdentifier} - Identifier of instance of
62 * <code>augmentation</code> node.</li>
66 * @see http://tools.ietf.org/html/rfc6020#section-9.13
68 public final class InstanceIdentifier implements Path<InstanceIdentifier>, Immutable, Serializable {
69 private static final InstanceIdentifier EMPTY = trustedCreate(Collections.<PathArgument>emptyList());
71 private static final long serialVersionUID = 2L;
72 private final Iterable<PathArgument> pathArguments;
73 private final int hash;
75 private transient ImmutableList<PathArgument> legacyPath = null;
76 private transient String toStringCache = null;
78 private final ImmutableList<PathArgument> getLegacyPath() {
79 if (legacyPath == null) {
81 if (legacyPath == null) {
82 legacyPath = ImmutableList.copyOf(pathArguments);
91 * Returns a list of path arguments.
93 * @deprecated Use {@link #getPathArguments()} instead.
94 * @return Immutable list of path arguments.
97 public List<PathArgument> getPath() {
98 return getLegacyPath();
102 * Returns an ordered iteration of path arguments.
104 * @return Immutable iteration of path arguments.
106 public Iterable<PathArgument> getPathArguments() {
107 return pathArguments;
111 * Returns an iterable of path arguments in reverse order. This is useful
112 * when walking up a tree organized this way.
114 * @return Immutable iterable of path arguments in reverse order.
116 public Iterable<PathArgument> getReversePathArguments() {
117 return getLegacyPath().reverse();
121 * Returns the last PathArgument. This is equivalent of iterating
122 * to the last element of the iterable returned by {@link #getPathArguments()}.
124 * @return The last past argument, or null if there are no PathArguments.
126 public PathArgument getLastPathArgument() {
127 return Iterables.getFirst(getReversePathArguments(), null);
130 private InstanceIdentifier(final Iterable<PathArgument> path, final int hash) {
131 this.pathArguments = Preconditions.checkNotNull(path, "path must not be null.");
135 private static final InstanceIdentifier trustedCreate(final Iterable<PathArgument> path) {
136 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
137 for (PathArgument a : path) {
141 return new InstanceIdentifier(path, hash.toInstance());
144 public static final InstanceIdentifier create(final Iterable<? extends PathArgument> path) {
145 if (Iterables.isEmpty(path)) {
149 return trustedCreate(ImmutableList.copyOf(path));
152 public static final InstanceIdentifier create(final PathArgument... path) {
153 // We are forcing a copy, since we cannot trust the user
154 return create(Arrays.asList(path));
158 public int hashCode() {
160 * The caching is safe, since the object contract requires
161 * immutability of the object and all objects referenced from this
163 * Used lists, maps are immutable. Path Arguments (elements) are also
164 * immutable, since the PathArgument contract requires immutability.
170 public boolean equals(final Object obj) {
177 if (getClass() != obj.getClass()) {
180 InstanceIdentifier other = (InstanceIdentifier) obj;
181 if (this.hashCode() != obj.hashCode()) {
184 return Iterables.elementsEqual(pathArguments, other.pathArguments);
188 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments
190 * @param name QName of {@link NodeIdentifier}
191 * @return Instance Identifier with additional path argument added to the end.
193 public InstanceIdentifier node(final QName name) {
194 return node(new NodeIdentifier(name));
199 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments
201 * @param arg Path argument which should be added to the end
202 * @return Instance Identifier with additional path argument added to the end.
204 public InstanceIdentifier node(final PathArgument arg) {
205 return new InstanceIdentifier(Iterables.concat(pathArguments, Collections.singleton(arg)), HashCodeBuilder.nextHashCode(hash, arg));
209 * Get the relative path from an ancestor. This method attempts to perform
210 * the reverse of concatenating a base (ancestor) and a path.
213 * Ancestor against which the relative path should be calculated
214 * @return This object's relative path from parent, or Optional.absent() if
215 * the specified parent is not in fact an ancestor of this object.
217 public Optional<InstanceIdentifier> relativeTo(final InstanceIdentifier ancestor) {
218 final Iterator<?> lit = pathArguments.iterator();
219 final Iterator<?> oit = ancestor.pathArguments.iterator();
222 while (oit.hasNext()) {
223 // Ancestor is not really an ancestor
224 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
225 return Optional.absent();
232 return Optional.of(this);
234 if (!lit.hasNext()) {
235 return Optional.of(EMPTY);
237 return Optional.of(trustedCreate(Iterables.skip(pathArguments, 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 InstanceIdentifier 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 static public InstanceIdentifierBuilder builder() {
282 return new BuilderImpl();
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 static public InstanceIdentifierBuilder builder(final InstanceIdentifier origin) {
293 return new BuilderImpl(origin.getPathArguments(), origin.hashCode());
297 * Returns new builder for InstanceIdentifier with first path argument set to {@link NodeIdentifier}.
299 * @param node QName of first {@link NodeIdentifier} path argument.
300 * @return new builder for InstanceIdentifier with first path argument set to {@link NodeIdentifier}.
302 * @deprecated Either use {@link #node(QName)} or instantiate an intermediate builder.
305 public static InstanceIdentifierBuilder builder(final QName node) {
306 return builder().node(node);
310 * Path argument / component of InstanceIdentifier
312 * Path argument uniquelly identifies node in data tree on particular
315 * This interface itself is used as common parent for actual
316 * path arguments types and should not be implemented by user code.
318 * Path arguments SHOULD contain only minimum of information
319 * required to uniquely identify node on particular subtree level.
321 * For actual path arguments types see:
323 * <li>{@link NodeIdentifier} - Identifier of container or leaf
324 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
325 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
326 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
329 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
331 * If applicable returns unique QName of data node as defined in YANG
334 * This method may return null, if the corresponding schema node, does
335 * not have QName associated, such as in cases of augmentations.
342 private static abstract class AbstractPathArgument implements PathArgument {
343 private static final long serialVersionUID = -4546547994250849340L;
344 private final QName nodeType;
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());
361 public int hashCode() {
362 return 31 + getNodeType().hashCode();
366 public boolean equals(final Object obj) {
370 if (obj == null || this.getClass() != obj.getClass()) {
374 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
378 public String toString() {
379 return getNodeType().toString();
385 * Fluent Builder of Instance Identifier instances
390 public interface InstanceIdentifierBuilder extends Builder<InstanceIdentifier> {
392 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
394 * @param nodeType QName of {@link NodeIdentifier} which will be added
395 * @return this builder
397 InstanceIdentifierBuilder node(QName nodeType);
400 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting instance identifier.
402 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
403 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
404 * @return this builder
406 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
409 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
411 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
412 * @param key QName of key which will be added
413 * @param value value of key which will be added
414 * @return this builder
416 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
420 * Builds an {@link InstanceIdentifier} with path arguments from this builder
422 * @return {@link InstanceIdentifier}
424 InstanceIdentifier build();
428 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
429 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
431 public static final class NodeIdentifier extends AbstractPathArgument {
432 private static final long serialVersionUID = -2255888212390871347L;
434 public NodeIdentifier(final QName node) {
440 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
443 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
444 private static final long serialVersionUID = -4787195606494761540L;
446 private final Map<QName, Object> keyValues;
448 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
450 this.keyValues = ImmutableMap.copyOf(keyValues);
453 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
454 this(node, ImmutableMap.of(key, value));
457 public Map<QName, Object> getKeyValues() {
462 public int hashCode() {
463 final int prime = 31;
464 int result = super.hashCode();
465 result = prime * result;
467 for (Entry<QName, Object> entry : keyValues.entrySet()) {
468 result += Objects.hashCode(entry.getKey()) + InstanceIdentifier.hashCode(entry.getValue());
474 public boolean equals(final Object obj) {
475 if (!super.equals(obj)) {
479 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
480 if (keyValues.size() != otherKeyValues.size()) {
484 for (Entry<QName, Object> entry : keyValues.entrySet()) {
485 if (!otherKeyValues.containsKey(entry.getKey())
486 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
496 public String toString() {
497 return super.toString() + '[' + keyValues + ']';
502 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
505 public static final class NodeWithValue extends AbstractPathArgument {
506 private static final long serialVersionUID = -3637456085341738431L;
508 private final Object value;
510 public NodeWithValue(final QName node, final Object value) {
515 public Object getValue() {
520 public int hashCode() {
521 final int prime = 31;
522 int result = super.hashCode();
523 result = prime * result + ((value == null) ? 0 : InstanceIdentifier.hashCode(value));
528 public boolean equals(final Object obj) {
529 if (!super.equals(obj)) {
532 final NodeWithValue other = (NodeWithValue) obj;
533 return Objects.deepEquals(value, other.value);
537 public String toString() {
538 return super.toString() + '[' + value + ']';
543 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} node in
544 * particular subtree.
546 * Augmentation is uniquely identified by set of all possible child nodes.
548 * to identify instance of augmentation,
549 * since RFC6020 states that <code>augment</code> that augment
550 * statement must not add multiple nodes from same namespace
551 * / module to the target node.
554 * @see http://tools.ietf.org/html/rfc6020#section-7.15
556 public static final class AugmentationIdentifier implements PathArgument {
557 private static final long serialVersionUID = -8122335594681936939L;
558 private final ImmutableSet<QName> childNames;
561 public QName getNodeType() {
562 // This should rather throw exception than return always null
563 throw new UnsupportedOperationException("Augmentation node has no QName");
568 * Construct new augmentation identifier using supplied set of possible
572 * Set of possible child nodes.
574 public AugmentationIdentifier(final Set<QName> childNames) {
575 this.childNames = ImmutableSet.copyOf(childNames);
579 * Augmentation node has no QName
582 * {@link AugmentationIdentifier#AugmentationIdentifier(Set)}
586 public AugmentationIdentifier(final QName nodeType, final Set<QName> childNames) {
592 * Returns set of all possible child nodes
594 * @return set of all possible child nodes.
596 public Set<QName> getPossibleChildNames() {
601 public String toString() {
602 final StringBuffer sb = new StringBuffer("AugmentationIdentifier{");
603 sb.append("childNames=").append(childNames).append('}');
604 return sb.toString();
608 public boolean equals(final Object o) {
612 if (!(o instanceof AugmentationIdentifier)) {
616 AugmentationIdentifier that = (AugmentationIdentifier) o;
617 return childNames.equals(that.childNames);
621 public int hashCode() {
622 return childNames.hashCode();
626 public int compareTo(final PathArgument o) {
627 if (!(o instanceof AugmentationIdentifier)) {
630 AugmentationIdentifier other = (AugmentationIdentifier) o;
631 Set<QName> otherChildNames = other.getPossibleChildNames();
632 int thisSize = childNames.size();
633 int otherSize = otherChildNames.size();
634 if (thisSize == otherSize) {
635 Iterator<QName> otherIterator = otherChildNames.iterator();
636 for (QName name : childNames) {
637 int c = name.compareTo(otherIterator.next());
643 } else if (thisSize < otherSize) {
651 private static class BuilderImpl implements InstanceIdentifierBuilder {
652 private final HashCodeBuilder<PathArgument> hash;
653 private final List<PathArgument> path;
655 public BuilderImpl() {
656 this.hash = new HashCodeBuilder<>();
657 this.path = new ArrayList<>();
660 public BuilderImpl(final Iterable<PathArgument> prefix, final int hash) {
661 this.path = Lists.newArrayList(prefix);
662 this.hash = new HashCodeBuilder<>(hash);
666 public InstanceIdentifierBuilder node(final QName nodeType) {
667 final PathArgument arg = new NodeIdentifier(nodeType);
669 hash.addArgument(arg);
674 public InstanceIdentifierBuilder nodeWithKey(final QName nodeType, final QName key, final Object value) {
675 final PathArgument arg = new NodeIdentifierWithPredicates(nodeType, key, value);
677 hash.addArgument(arg);
682 public InstanceIdentifierBuilder nodeWithKey(final QName nodeType, final Map<QName, Object> keyValues) {
683 final PathArgument arg = new NodeIdentifierWithPredicates(nodeType, keyValues);
685 hash.addArgument(arg);
691 public InstanceIdentifier toInstance() {
696 public InstanceIdentifier build() {
697 return new InstanceIdentifier(ImmutableList.copyOf(path), hash.toInstance());
702 public boolean contains(final InstanceIdentifier other) {
703 Preconditions.checkArgument(other != null, "other should not be null");
705 final Iterator<?> lit = pathArguments.iterator();
706 final Iterator<?> oit = other.pathArguments.iterator();
708 while (lit.hasNext()) {
709 if (!oit.hasNext()) {
713 if (!lit.next().equals(oit.next())) {
722 public String toString() {
724 * The toStringCache is safe, since the object contract requires
725 * immutability of the object and all objects referenced from this
727 * Used lists, maps are immutable. Path Arguments (elements) are also
728 * immutable, since the PathArgument contract requires immutability.
729 * The cache is thread-safe - if multiple computations occurs at the
730 * same time, cache will be overwritten with same result.
732 if (toStringCache != null) {
733 return toStringCache;
736 final StringBuilder builder = new StringBuilder('/');
737 boolean first = true;
738 for (PathArgument argument : getPathArguments()) {
744 builder.append(argument.toString());
747 toStringCache = builder.toString();
748 return toStringCache;