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;
16 import java.io.IOException;
17 import java.io.ObjectInputStream;
18 import java.io.ObjectOutputStream;
19 import java.io.Serializable;
20 import java.lang.reflect.Array;
21 import java.lang.reflect.Field;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Collections;
25 import java.util.Iterator;
26 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.Objects;
31 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
32 import org.opendaylight.yangtools.concepts.Builder;
33 import org.opendaylight.yangtools.concepts.Immutable;
34 import org.opendaylight.yangtools.concepts.Path;
35 import org.opendaylight.yangtools.util.HashCodeBuilder;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.common.QNameModule;
38 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
41 * Unique identifier of a particular node instance in the data tree.
44 * Java representation of YANG Built-in type <code>instance-identifier</code>,
45 * which conceptually is XPath expression minimized to uniquely identify element
46 * in data tree which conforms to constraints maintained by YANG Model,
47 * effectively this makes Instance Identifier a path to element in data tree.
49 * Constraints put in YANG specification on instance-identifier allowed it to be
50 * effectively represented in Java and it's evaluation does not require
51 * full-blown XPath processor.
53 * <h3>Path Arguments</h3>
54 * Path to the node represented in instance identifier consists of
55 * {@link PathArgument} which carries necessary information to uniquely identify
56 * node on particular level in the subtree.
59 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
60 * <code>0..1</code> in particular subtree in data tree.</li>
61 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item),
62 * which has cardinality <code>0..n</code>.</li>
63 * <li>{@link NodeWithValue} - Identifier of instance <code>leaf</code> node or
64 * <code>leaf-list</code> node.</li>
65 * <li>{@link AugmentationIdentifier} - Identifier of instance of
66 * <code>augmentation</code> node.</li>
70 * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
72 public final class YangInstanceIdentifier implements Path<YangInstanceIdentifier>, Immutable, Serializable {
73 @SuppressWarnings("rawtypes")
74 private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, ImmutableList> LEGACYPATH_UPDATER =
75 AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, ImmutableList.class, "legacyPath");
76 private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, String> TOSTRINGCACHE_UPDATER =
77 AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, String.class, "toStringCache");
78 private static final YangInstanceIdentifier EMPTY = trustedCreate(Collections.<PathArgument>emptyList());
79 private static final Field PATHARGUMENTS_FIELD;
81 private static final long serialVersionUID = 3L;
82 private transient final Iterable<PathArgument> pathArguments;
83 private final int hash;
85 private volatile ImmutableList<PathArgument> legacyPath = null;
86 private transient volatile String toStringCache = null;
91 f = YangInstanceIdentifier.class.getDeclaredField("pathArguments");
92 } catch (NoSuchFieldException | SecurityException e) {
93 throw new ExceptionInInitializerError(e);
95 f.setAccessible(true);
97 PATHARGUMENTS_FIELD = f;
100 private final ImmutableList<PathArgument> getLegacyPath() {
101 // Temporary variable saves a volatile read
102 ImmutableList<PathArgument> ret = legacyPath;
104 // We could have used a synchronized block, but the window is quite
105 // small and worst that can happen is duplicate object construction.
106 ret = ImmutableList.copyOf(pathArguments);
107 LEGACYPATH_UPDATER.lazySet(this, ret);
114 * Returns a list of path arguments.
116 * @deprecated Use {@link #getPathArguments()} instead.
117 * @return Immutable list of path arguments.
120 public List<PathArgument> getPath() {
121 return getLegacyPath();
125 * Returns an ordered iteration of path arguments.
127 * @return Immutable iteration of path arguments.
129 public Iterable<PathArgument> getPathArguments() {
130 return pathArguments;
134 * Returns an iterable of path arguments in reverse order. This is useful
135 * when walking up a tree organized this way.
137 * @return Immutable iterable of path arguments in reverse order.
139 public Iterable<PathArgument> getReversePathArguments() {
140 return getLegacyPath().reverse();
144 * Returns the last PathArgument. This is equivalent of iterating
145 * to the last element of the iterable returned by {@link #getPathArguments()}.
147 * @return The last past argument, or null if there are no PathArguments.
149 public PathArgument getLastPathArgument() {
150 return Iterables.getFirst(getReversePathArguments(), null);
153 private YangInstanceIdentifier(final Iterable<PathArgument> path, final int hash) {
154 this.pathArguments = Preconditions.checkNotNull(path, "path must not be null.");
158 private static final YangInstanceIdentifier trustedCreate(final Iterable<PathArgument> path) {
159 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
160 for (PathArgument a : path) {
164 return new YangInstanceIdentifier(path, hash.toInstance());
167 public static final YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
168 if (Iterables.isEmpty(path)) {
172 return trustedCreate(ImmutableList.copyOf(path));
175 public static final YangInstanceIdentifier create(final PathArgument... path) {
176 // We are forcing a copy, since we cannot trust the user
177 return create(Arrays.asList(path));
181 public int hashCode() {
183 * The caching is safe, since the object contract requires
184 * immutability of the object and all objects referenced from this
186 * Used lists, maps are immutable. Path Arguments (elements) are also
187 * immutable, since the PathArgument contract requires immutability.
193 public boolean equals(final Object obj) {
200 if (getClass() != obj.getClass()) {
203 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
204 if (this.hashCode() != obj.hashCode()) {
207 return Iterables.elementsEqual(pathArguments, other.pathArguments);
211 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments
213 * @param name QName of {@link NodeIdentifier}
214 * @return Instance Identifier with additional path argument added to the end.
216 public YangInstanceIdentifier node(final QName name) {
217 return node(new NodeIdentifier(name));
222 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments
224 * @param arg Path argument which should be added to the end
225 * @return Instance Identifier with additional path argument added to the end.
227 public YangInstanceIdentifier node(final PathArgument arg) {
228 return new YangInstanceIdentifier(Iterables.concat(pathArguments, Collections.singleton(arg)), HashCodeBuilder.nextHashCode(hash, arg));
232 * Get the relative path from an ancestor. This method attempts to perform
233 * the reverse of concatenating a base (ancestor) and a path.
236 * Ancestor against which the relative path should be calculated
237 * @return This object's relative path from parent, or Optional.absent() if
238 * the specified parent is not in fact an ancestor of this object.
240 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
241 final Iterator<?> lit = pathArguments.iterator();
242 final Iterator<?> oit = ancestor.pathArguments.iterator();
245 while (oit.hasNext()) {
246 // Ancestor is not really an ancestor
247 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
248 return Optional.absent();
255 return Optional.of(this);
257 if (!lit.hasNext()) {
258 return Optional.of(EMPTY);
260 return Optional.of(trustedCreate(Iterables.skip(pathArguments, common)));
263 private static int hashCode(final Object value) {
268 if (value.getClass().equals(byte[].class)) {
269 return Arrays.hashCode((byte[]) value);
272 if (value.getClass().isArray()) {
274 int length = Array.getLength(value);
275 for (int i = 0; i < length; i++) {
276 hash += Objects.hashCode(Array.get(value, i));
282 return Objects.hashCode(value);
285 // Static factories & helpers
289 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied QName
291 * @param name QName of first node identifier
292 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
294 public static YangInstanceIdentifier of(final QName name) {
295 return create(new NodeIdentifier(name));
300 * Returns new builder for InstanceIdentifier with empty path arguments.
302 * @return new builder for InstanceIdentifier with empty path arguments.
304 static public InstanceIdentifierBuilder builder() {
305 return new BuilderImpl();
310 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
312 * @param origin Instace Identifier from which path arguments are copied.
313 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
315 static public InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
316 return new BuilderImpl(origin.getPathArguments(), origin.hashCode());
320 * Returns new builder for InstanceIdentifier with first path argument set to {@link NodeIdentifier}.
322 * @param node QName of first {@link NodeIdentifier} path argument.
323 * @return new builder for InstanceIdentifier with first path argument set to {@link NodeIdentifier}.
325 * @deprecated Either use {@link #node(QName)} or instantiate an intermediate builder.
328 public static InstanceIdentifierBuilder builder(final QName node) {
329 return builder().node(node);
333 * Path argument / component of InstanceIdentifier
335 * Path argument uniquely identifies node in data tree on particular
338 * This interface itself is used as common parent for actual
339 * path arguments types and should not be implemented by user code.
341 * Path arguments SHOULD contain only minimum of information
342 * required to uniquely identify node on particular subtree level.
344 * For actual path arguments types see:
346 * <li>{@link NodeIdentifier} - Identifier of container or leaf
347 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
348 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
349 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
352 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
354 * If applicable returns unique QName of data node as defined in YANG
357 * This method may return null, if the corresponding schema node, does
358 * not have QName associated, such as in cases of augmentations.
365 * Return the string representation of this object for use in context
366 * provided by a previous object. This method can be implemented in
367 * terms of {@link #toString()}, but implementations are encourage to
368 * reuse any context already emitted by the previous object.
370 * @param previous Previous path argument
371 * @return String representation
373 String toRelativeString(PathArgument previous);
376 private static abstract class AbstractPathArgument implements PathArgument {
377 private static final AtomicReferenceFieldUpdater<AbstractPathArgument, Integer> HASH_UPDATER =
378 AtomicReferenceFieldUpdater.newUpdater(AbstractPathArgument.class, Integer.class, "hash");
379 private static final long serialVersionUID = -4546547994250849340L;
380 private final QName nodeType;
381 private volatile transient Integer hash = null;
383 protected AbstractPathArgument(final QName nodeType) {
384 this.nodeType = Preconditions.checkNotNull(nodeType);
388 public final QName getNodeType() {
393 public int compareTo(final PathArgument o) {
394 return nodeType.compareTo(o.getNodeType());
397 protected int hashCodeImpl() {
398 return 31 + getNodeType().hashCode();
402 public final int hashCode() {
405 ret = hashCodeImpl();
406 HASH_UPDATER.lazySet(this, ret);
413 public boolean equals(final Object obj) {
417 if (obj == null || this.getClass() != obj.getClass()) {
421 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
425 public String toString() {
426 return getNodeType().toString();
430 public String toRelativeString(final PathArgument previous) {
431 if (previous instanceof AbstractPathArgument) {
432 final QNameModule mod = ((AbstractPathArgument)previous).getNodeType().getModule();
433 if (getNodeType().getModule().equals(mod)) {
434 return getNodeType().getLocalName();
438 return getNodeType().toString();
444 * Fluent Builder of Instance Identifier instances
449 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
451 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
453 * @param nodeType QName of {@link NodeIdentifier} which will be added
454 * @return this builder
456 InstanceIdentifierBuilder node(QName nodeType);
459 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting instance identifier.
461 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
462 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
463 * @return this builder
465 InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
468 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
470 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
471 * @param key QName of key which will be added
472 * @param value value of key which will be added
473 * @return this builder
475 InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
479 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder
481 * @return {@link YangInstanceIdentifier}
483 YangInstanceIdentifier build();
487 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
488 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
490 public static final class NodeIdentifier extends AbstractPathArgument {
491 private static final long serialVersionUID = -2255888212390871347L;
493 public NodeIdentifier(final QName node) {
499 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
502 public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
503 private static final long serialVersionUID = -4787195606494761540L;
505 private final Map<QName, Object> keyValues;
507 public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
509 this.keyValues = ImmutableMap.copyOf(keyValues);
512 public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
513 this(node, ImmutableMap.of(key, value));
516 public Map<QName, Object> getKeyValues() {
521 protected int hashCodeImpl() {
522 final int prime = 31;
523 int result = super.hashCodeImpl();
524 result = prime * result;
526 for (Entry<QName, Object> entry : keyValues.entrySet()) {
527 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
533 public boolean equals(final Object obj) {
534 if (!super.equals(obj)) {
538 final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
539 if (keyValues.size() != otherKeyValues.size()) {
543 for (Entry<QName, Object> entry : keyValues.entrySet()) {
544 if (!otherKeyValues.containsKey(entry.getKey())
545 || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
555 public String toString() {
556 return super.toString() + '[' + keyValues + ']';
560 public String toRelativeString(final PathArgument previous) {
561 return super.toRelativeString(previous) + '[' + keyValues + ']';
566 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
569 public static final class NodeWithValue extends AbstractPathArgument {
570 private static final long serialVersionUID = -3637456085341738431L;
572 private final Object value;
574 public NodeWithValue(final QName node, final Object value) {
579 public Object getValue() {
584 protected int hashCodeImpl() {
585 final int prime = 31;
586 int result = super.hashCodeImpl();
587 result = prime * result + ((value == null) ? 0 : YangInstanceIdentifier.hashCode(value));
592 public boolean equals(final Object obj) {
593 if (!super.equals(obj)) {
596 final NodeWithValue other = (NodeWithValue) obj;
597 return Objects.deepEquals(value, other.value);
601 public String toString() {
602 return super.toString() + '[' + value + ']';
606 public String toRelativeString(final PathArgument previous) {
607 return super.toRelativeString(previous) + '[' + value + ']';
612 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} node in
613 * particular subtree.
615 * Augmentation is uniquely identified by set of all possible child nodes.
617 * to identify instance of augmentation,
618 * since RFC6020 states that <code>augment</code> that augment
619 * statement must not add multiple nodes from same namespace
620 * / module to the target node.
623 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
625 public static final class AugmentationIdentifier implements PathArgument {
626 private static final long serialVersionUID = -8122335594681936939L;
627 private final ImmutableSet<QName> childNames;
630 public QName getNodeType() {
631 // This should rather throw exception than return always null
632 throw new UnsupportedOperationException("Augmentation node has no QName");
637 * Construct new augmentation identifier using supplied set of possible
641 * Set of possible child nodes.
643 public AugmentationIdentifier(final Set<QName> childNames) {
644 this.childNames = ImmutableSet.copyOf(childNames);
648 * Augmentation node has no QName
650 * @deprecated Use {@link #AugmentationIdentifier(Set)} instead.
653 public AugmentationIdentifier(final QName nodeType, final Set<QName> childNames) {
658 * Returns set of all possible child nodes
660 * @return set of all possible child nodes.
662 public Set<QName> getPossibleChildNames() {
667 public String toString() {
668 final StringBuffer sb = new StringBuffer("AugmentationIdentifier{");
669 sb.append("childNames=").append(childNames).append('}');
670 return sb.toString();
674 public String toRelativeString(final PathArgument previous) {
679 public boolean equals(final Object o) {
683 if (!(o instanceof AugmentationIdentifier)) {
687 AugmentationIdentifier that = (AugmentationIdentifier) o;
688 return childNames.equals(that.childNames);
692 public int hashCode() {
693 return childNames.hashCode();
697 public int compareTo(final PathArgument o) {
698 if (!(o instanceof AugmentationIdentifier)) {
701 AugmentationIdentifier other = (AugmentationIdentifier) o;
702 Set<QName> otherChildNames = other.getPossibleChildNames();
703 int thisSize = childNames.size();
704 int otherSize = otherChildNames.size();
705 if (thisSize == otherSize) {
706 Iterator<QName> otherIterator = otherChildNames.iterator();
707 for (QName name : childNames) {
708 int c = name.compareTo(otherIterator.next());
714 } else if (thisSize < otherSize) {
722 private static class BuilderImpl implements InstanceIdentifierBuilder {
723 private final HashCodeBuilder<PathArgument> hash;
724 private final List<PathArgument> path;
726 public BuilderImpl() {
727 this.hash = new HashCodeBuilder<>();
728 this.path = new ArrayList<>();
731 public BuilderImpl(final Iterable<PathArgument> prefix, final int hash) {
732 this.path = Lists.newArrayList(prefix);
733 this.hash = new HashCodeBuilder<>(hash);
737 public InstanceIdentifierBuilder node(final QName nodeType) {
738 final PathArgument arg = new NodeIdentifier(nodeType);
740 hash.addArgument(arg);
745 public InstanceIdentifierBuilder nodeWithKey(final QName nodeType, final QName key, final Object value) {
746 final PathArgument arg = new NodeIdentifierWithPredicates(nodeType, key, value);
748 hash.addArgument(arg);
753 public InstanceIdentifierBuilder nodeWithKey(final QName nodeType, final Map<QName, Object> keyValues) {
754 final PathArgument arg = new NodeIdentifierWithPredicates(nodeType, keyValues);
756 hash.addArgument(arg);
762 public YangInstanceIdentifier toInstance() {
767 public YangInstanceIdentifier build() {
768 return new YangInstanceIdentifier(ImmutableList.copyOf(path), hash.toInstance());
773 public boolean contains(final YangInstanceIdentifier other) {
774 Preconditions.checkArgument(other != null, "other should not be null");
776 final Iterator<?> lit = pathArguments.iterator();
777 final Iterator<?> oit = other.pathArguments.iterator();
779 while (lit.hasNext()) {
780 if (!oit.hasNext()) {
784 if (!lit.next().equals(oit.next())) {
793 public String toString() {
795 * The toStringCache is safe, since the object contract requires
796 * immutability of the object and all objects referenced from this
798 * Used lists, maps are immutable. Path Arguments (elements) are also
799 * immutable, since the PathArgument contract requires immutability.
800 * The cache is thread-safe - if multiple computations occurs at the
801 * same time, cache will be overwritten with same result.
803 String ret = toStringCache;
805 final StringBuilder builder = new StringBuilder("/");
806 PathArgument prev = null;
807 for (PathArgument argument : getPathArguments()) {
811 builder.append(argument.toRelativeString(prev));
815 ret = builder.toString();
816 TOSTRINGCACHE_UPDATER.lazySet(this, ret);
821 private void readObject(final ObjectInputStream inputStream) throws IOException, ClassNotFoundException {
822 inputStream.defaultReadObject();
825 PATHARGUMENTS_FIELD.set(this, legacyPath);
826 } catch (IllegalArgumentException | IllegalAccessException e) {
827 throw new IOException(e);
831 private void writeObject(final ObjectOutputStream outputStream) throws IOException {
833 * This may look strange, but what we are doing here is side-stepping the fact
834 * that pathArguments is not generally serializable. We are forcing instantiation
835 * of the legacy path, which is an ImmutableList (thus Serializable) and write
836 * it out. The read path does the opposite -- it reads the legacyPath and then
837 * uses invocation API to set the field.
840 outputStream.defaultWriteObject();