2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.yang.data.api;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.annotations.Beta;
15 import com.google.common.base.VerifyException;
16 import com.google.common.cache.CacheBuilder;
17 import com.google.common.cache.CacheLoader;
18 import com.google.common.cache.LoadingCache;
19 import com.google.common.collect.ImmutableList;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.ImmutableSet;
22 import com.google.common.collect.Iterables;
23 import com.google.common.collect.Sets;
24 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
25 import java.io.Serializable;
26 import java.lang.reflect.Array;
27 import java.util.AbstractMap.SimpleImmutableEntry;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.Deque;
32 import java.util.Iterator;
33 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.Objects;
37 import java.util.Optional;
39 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
40 import java.util.function.Function;
41 import org.eclipse.jdt.annotation.NonNull;
42 import org.eclipse.jdt.annotation.Nullable;
43 import org.opendaylight.yangtools.concepts.Builder;
44 import org.opendaylight.yangtools.concepts.Immutable;
45 import org.opendaylight.yangtools.concepts.Path;
46 import org.opendaylight.yangtools.util.HashCodeBuilder;
47 import org.opendaylight.yangtools.util.ImmutableOffsetMap;
48 import org.opendaylight.yangtools.util.SharedSingletonMap;
49 import org.opendaylight.yangtools.util.SingletonSet;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.common.QNameModule;
52 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
55 * Unique identifier of a particular node instance in the data tree.
58 * Java representation of YANG Built-in type {@code instance-identifier}, which conceptually is XPath expression
59 * minimized to uniquely identify element in data tree which conforms to constraints maintained by YANG Model,
60 * effectively this makes Instance Identifier a path to element in data tree.
63 * Constraints put in YANG specification on instance-identifier allowed it to be effectively represented in Java and its
64 * evaluation does not require a full-blown XPath processor.
66 * <h2>Path Arguments</h2>
67 * Path to the node represented in instance identifier consists of {@link PathArgument} which carries necessary
68 * information to uniquely identify node on particular level in the subtree.
71 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality {@code 0..1} in particular subtree in data
73 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item), which has cardinality {@code 0..n}</li>
74 * <li>{@link NodeWithValue} - Identifier of instance {@code leaf} node or {@code leaf-list} node</li>
75 * <li>{@link AugmentationIdentifier} - Identifier of instance of {@code augmentation} node</li>
78 * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
80 // FIXME: 6.0.0: this concept needs to be moved to yang-common, as parser components need the ability to refer
81 // to data nodes -- most notably XPath expressions and {@code default} statement arguments need to be able
82 // to represent these.
83 public abstract class YangInstanceIdentifier implements Path<YangInstanceIdentifier>, Immutable, Serializable {
84 private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, String> TOSTRINGCACHE_UPDATER =
85 AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, String.class, "toStringCache");
86 private static final long serialVersionUID = 4L;
88 private final int hash;
89 private transient volatile String toStringCache = null;
91 // Package-private to prevent outside subclassing
92 YangInstanceIdentifier(final int hash) {
97 * Return An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual root of the YANG
100 * @return An empty YangInstanceIdentifier
102 public static @NonNull YangInstanceIdentifier empty() {
103 return FixedYangInstanceIdentifier.EMPTY_INSTANCE;
106 abstract @NonNull YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
108 abstract @Nullable Collection<PathArgument> tryPathArguments();
110 abstract @Nullable Collection<PathArgument> tryReversePathArguments();
113 * Check if this instance identifier has empty path arguments, e.g. it is
114 * empty and corresponds to {@link #empty()}.
116 * @return True if this instance identifier is empty, false otherwise.
118 public abstract boolean isEmpty();
121 * Return an optimized version of this identifier, useful when the identifier
122 * will be used very frequently.
124 * @return A optimized equivalent instance.
126 public abstract @NonNull YangInstanceIdentifier toOptimized();
129 * Return the conceptual parent {@link YangInstanceIdentifier}, which has
130 * one item less in {@link #getPathArguments()}.
132 * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #empty()}.
134 public abstract @Nullable YangInstanceIdentifier getParent();
137 * Return the conceptual parent {@link YangInstanceIdentifier}, which has one item less in
138 * {@link #getPathArguments()}.
140 * @return Parent {@link YangInstanceIdentifier}
141 * @throws VerifyException if this object is {@link #empty()}.
143 public abstract @NonNull YangInstanceIdentifier coerceParent();
146 * Return the ancestor {@link YangInstanceIdentifier} with a particular depth, e.g. number of path arguments.
148 * @param depth Ancestor depth
149 * @return Ancestor {@link YangInstanceIdentifier}
150 * @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
152 public abstract @NonNull YangInstanceIdentifier getAncestor(int depth);
155 * Returns an ordered iteration of path arguments.
157 * @return Immutable iteration of path arguments.
159 public abstract @NonNull List<PathArgument> getPathArguments();
162 * Returns an iterable of path arguments in reverse order. This is useful
163 * when walking up a tree organized this way.
165 * @return Immutable iterable of path arguments in reverse order.
167 public abstract @NonNull List<PathArgument> getReversePathArguments();
170 * Returns the last PathArgument. This is equivalent of iterating
171 * to the last element of the iterable returned by {@link #getPathArguments()}.
173 * @return The last past argument, or null if there are no PathArguments.
175 public abstract PathArgument getLastPathArgument();
177 public static @NonNull YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
178 if (Iterables.isEmpty(path)) {
182 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
183 for (PathArgument a : path) {
187 return FixedYangInstanceIdentifier.create(path, hash.build());
190 public static @NonNull YangInstanceIdentifier create(final PathArgument pathArgument) {
191 return new FixedYangInstanceIdentifier(ImmutableList.of(pathArgument),
192 HashCodeBuilder.nextHashCode(1, pathArgument));
195 public static @NonNull YangInstanceIdentifier create(final PathArgument... path) {
196 // We are forcing a copy, since we cannot trust the user
197 return create(Arrays.asList(path));
201 * Create a {@link YangInstanceIdentifier} by taking a snapshot of provided path and iterating it backwards.
203 * @param pathTowardsRoot Path towards root
204 * @return A {@link YangInstanceIdentifier} instance
205 * @throws NullPointerException if {@code pathTowardsRoot} or any of its members is null
207 public static @NonNull YangInstanceIdentifier createReverse(final Deque<PathArgument> pathTowardsRoot) {
208 final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
209 pathTowardsRoot.size());
210 pathTowardsRoot.descendingIterator().forEachRemaining(builder::add);
211 return YangInstanceIdentifier.create(builder.build());
215 * Create a {@link YangInstanceIdentifier} by walking specified stack backwards and extracting path components
218 * @param stackTowardsRoot Stack towards root,
219 * @return A {@link YangInstanceIdentifier} instance
220 * @throws NullPointerException if {@code pathTowardsRoot} is null
222 public static <T> @NonNull YangInstanceIdentifier createReverse(final Deque<? extends T> stackTowardsRoot,
223 final Function<T, PathArgument> function) {
224 final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
225 stackTowardsRoot.size());
226 final Iterator<? extends T> it = stackTowardsRoot.descendingIterator();
227 while (it.hasNext()) {
228 builder.add(function.apply(it.next()));
230 return YangInstanceIdentifier.create(builder.build());
233 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
234 return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
238 public boolean equals(final Object obj) {
242 if (!(obj instanceof YangInstanceIdentifier)) {
245 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
246 if (this.hashCode() != obj.hashCode()) {
250 return pathArgumentsEqual(other);
254 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments.
256 * @param name QName of {@link NodeIdentifier}
257 * @return Instance Identifier with additional path argument added to the end.
259 public final @NonNull YangInstanceIdentifier node(final QName name) {
260 return node(new NodeIdentifier(name));
264 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments.
266 * @param arg Path argument which should be added to the end
267 * @return Instance Identifier with additional path argument added to the end.
269 public final @NonNull YangInstanceIdentifier node(final PathArgument arg) {
270 return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
274 * Get the relative path from an ancestor. This method attempts to perform
275 * the reverse of concatenating a base (ancestor) and a path.
278 * Ancestor against which the relative path should be calculated
279 * @return This object's relative path from parent, or Optional.absent() if
280 * the specified parent is not in fact an ancestor of this object.
282 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
283 if (this == ancestor) {
284 return Optional.of(empty());
286 if (ancestor.isEmpty()) {
287 return Optional.of(this);
290 final Iterator<PathArgument> lit = getPathArguments().iterator();
291 final Iterator<PathArgument> oit = ancestor.getPathArguments().iterator();
294 while (oit.hasNext()) {
295 // Ancestor is not really an ancestor
296 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
297 return Optional.empty();
304 return Optional.of(this);
306 if (!lit.hasNext()) {
307 return Optional.of(empty());
310 return Optional.of(createRelativeIdentifier(common));
314 public final boolean contains(final YangInstanceIdentifier other) {
319 checkArgument(other != null, "other should not be null");
320 final Iterator<PathArgument> lit = getPathArguments().iterator();
321 final Iterator<PathArgument> oit = other.getPathArguments().iterator();
323 while (lit.hasNext()) {
324 if (!oit.hasNext()) {
328 if (!lit.next().equals(oit.next())) {
337 public final String toString() {
339 * The toStringCache is safe, since the object contract requires
340 * immutability of the object and all objects referenced from this
342 * Used lists, maps are immutable. Path Arguments (elements) are also
343 * immutable, since the PathArgument contract requires immutability.
344 * The cache is thread-safe - if multiple computations occurs at the
345 * same time, cache will be overwritten with same result.
347 String ret = toStringCache;
349 final StringBuilder builder = new StringBuilder("/");
350 PathArgument prev = null;
351 for (PathArgument argument : getPathArguments()) {
355 builder.append(argument.toRelativeString(prev));
359 ret = builder.toString();
360 TOSTRINGCACHE_UPDATER.lazySet(this, ret);
366 public final int hashCode() {
368 * The caching is safe, since the object contract requires
369 * immutability of the object and all objects referenced from this
371 * Used lists, maps are immutable. Path Arguments (elements) are also
372 * immutable, since the PathArgument contract requires immutability.
377 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
378 justification = "https://github.com/spotbugs/spotbugs/issues/811")
379 private static int hashCode(final Object value) {
384 if (byte[].class.equals(value.getClass())) {
385 return Arrays.hashCode((byte[]) value);
388 if (value.getClass().isArray()) {
390 int length = Array.getLength(value);
391 for (int i = 0; i < length; i++) {
392 hash += Objects.hashCode(Array.get(value, i));
398 return Objects.hashCode(value);
401 final Object writeReplace() {
402 return new YIDv1(this);
405 // Static factories & helpers
408 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied
411 * @param name QName of first node identifier
412 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
414 public static @NonNull YangInstanceIdentifier of(final QName name) {
415 return create(new NodeIdentifier(name));
419 * Returns new builder for InstanceIdentifier with empty path arguments.
421 * @return new builder for InstanceIdentifier with empty path arguments.
423 public static @NonNull InstanceIdentifierBuilder builder() {
424 return new YangInstanceIdentifierBuilder();
428 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
430 * @param origin InstanceIdentifier from which path arguments are copied.
431 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
433 public static @NonNull InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
434 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
438 * Path argument / component of InstanceIdentifier.
439 * Path argument uniquely identifies node in data tree on particular
443 * This interface itself is used as common parent for actual
444 * path arguments types and should not be implemented by user code.
447 * Path arguments SHOULD contain only minimum of information
448 * required to uniquely identify node on particular subtree level.
451 * For actual path arguments types see:
453 * <li>{@link NodeIdentifier} - Identifier of container or leaf
454 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
455 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
456 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
459 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
461 * Returns unique QName of data node as defined in YANG Schema, if available.
464 * @throws UnsupportedOperationException if node type is not applicable, for example in case of an augmentation.
466 @NonNull QName getNodeType();
469 * Return the string representation of this object for use in context
470 * provided by a previous object. This method can be implemented in
471 * terms of {@link #toString()}, but implementations are encourage to
472 * reuse any context already emitted by the previous object.
474 * @param previous Previous path argument
475 * @return String representation
477 @NonNull String toRelativeString(PathArgument previous);
480 private abstract static class AbstractPathArgument implements PathArgument {
481 private static final long serialVersionUID = -4546547994250849340L;
482 private final @NonNull QName nodeType;
483 private transient volatile int hashValue;
485 protected AbstractPathArgument(final QName nodeType) {
486 this.nodeType = requireNonNull(nodeType);
490 public final QName getNodeType() {
495 @SuppressWarnings("checkstyle:parameterName")
496 public int compareTo(final PathArgument o) {
497 return nodeType.compareTo(o.getNodeType());
500 protected int hashCodeImpl() {
501 return nodeType.hashCode();
505 public final int hashCode() {
507 return (local = hashValue) != 0 ? local : (hashValue = hashCodeImpl());
511 public boolean equals(final Object obj) {
515 if (obj == null || this.getClass() != obj.getClass()) {
519 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
523 public String toString() {
524 return getNodeType().toString();
528 public String toRelativeString(final PathArgument previous) {
529 if (previous instanceof AbstractPathArgument) {
530 final QNameModule mod = previous.getNodeType().getModule();
531 if (getNodeType().getModule().equals(mod)) {
532 return getNodeType().getLocalName();
536 return getNodeType().toString();
539 abstract Object writeReplace();
543 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
544 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
546 public static final class NodeIdentifier extends AbstractPathArgument {
547 private static final long serialVersionUID = -2255888212390871347L;
548 private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
549 .build(new CacheLoader<QName, NodeIdentifier>() {
551 public NodeIdentifier load(final QName key) {
552 return new NodeIdentifier(key);
556 public NodeIdentifier(final QName node) {
561 * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
562 * instance cache, resulting in object reuse for equal inputs.
564 * @param node Node's QName
565 * @return A {@link NodeIdentifier}
567 public static @NonNull NodeIdentifier create(final QName node) {
568 return CACHE.getUnchecked(node);
572 Object writeReplace() {
573 return new NIv1(this);
578 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
581 public abstract static class NodeIdentifierWithPredicates extends AbstractPathArgument {
583 public static final class Singleton extends NodeIdentifierWithPredicates {
584 private static final long serialVersionUID = 1L;
586 private final @NonNull QName key;
587 private final @NonNull Object value;
589 Singleton(final QName node, final QName key, final Object value) {
591 this.key = requireNonNull(key);
592 this.value = requireNonNull(value);
596 public SingletonSet<Entry<QName, Object>> entrySet() {
597 return SingletonSet.of(singleEntry());
601 public SingletonSet<QName> keySet() {
602 return SingletonSet.of(key);
606 public boolean containsKey(final QName qname) {
607 return key.equals(requireNonNull(qname));
611 public SingletonSet<Object> values() {
612 return SingletonSet.of(value);
621 public ImmutableMap<QName, Object> asMap() {
622 return ImmutableMap.of(key, value);
626 * Return the single entry contained in this object. This is equivalent to
627 * {@code entrySet().iterator().next()}.
629 * @return A single entry.
631 public @NonNull Entry<QName, Object> singleEntry() {
632 return new SimpleImmutableEntry<>(key, value);
636 boolean equalMapping(final NodeIdentifierWithPredicates other) {
637 final Singleton single = (Singleton) other;
638 return key.equals(single.key) && Objects.deepEquals(value, single.value);
642 Object keyValue(final QName qname) {
643 return key.equals(qname) ? value : null;
647 private static final class Regular extends NodeIdentifierWithPredicates {
648 private static final long serialVersionUID = 1L;
650 private final @NonNull Map<QName, Object> keyValues;
652 Regular(final QName node, final Map<QName, Object> keyValues) {
654 this.keyValues = requireNonNull(keyValues);
658 public Set<Entry<QName, Object>> entrySet() {
659 return keyValues.entrySet();
663 public Set<QName> keySet() {
664 return keyValues.keySet();
668 public boolean containsKey(final QName qname) {
669 return keyValues.containsKey(requireNonNull(qname));
673 public Collection<Object> values() {
674 return keyValues.values();
679 return keyValues.size();
683 public Map<QName, Object> asMap() {
688 Object keyValue(final QName qname) {
689 return keyValues.get(qname);
693 boolean equalMapping(final NodeIdentifierWithPredicates other) {
694 final Map<QName, Object> otherKeyValues = ((Regular) other).keyValues;
695 // TODO: benchmark to see if just calling equals() on the two maps is not faster
696 if (keyValues == otherKeyValues) {
699 if (keyValues.size() != otherKeyValues.size()) {
703 for (Entry<QName, Object> entry : entrySet()) {
704 final Object otherValue = otherKeyValues.get(entry.getKey());
705 if (otherValue == null || !Objects.deepEquals(entry.getValue(), otherValue)) {
714 private static final long serialVersionUID = -4787195606494761540L;
716 NodeIdentifierWithPredicates(final QName node) {
720 public static @NonNull NodeIdentifierWithPredicates of(final QName node) {
721 return new Regular(node, ImmutableMap.of());
724 public static @NonNull NodeIdentifierWithPredicates of(final QName node, final QName key, final Object value) {
725 return new Singleton(node, key, value);
728 public static @NonNull NodeIdentifierWithPredicates of(final QName node, final Entry<QName, Object> entry) {
729 return of(node, entry.getKey(), entry.getValue());
732 public static @NonNull NodeIdentifierWithPredicates of(final QName node, final Map<QName, Object> keyValues) {
733 return keyValues.size() == 1 ? of(keyValues, node)
734 // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
735 : new Regular(node, ImmutableOffsetMap.unorderedCopyOf(keyValues));
738 public static @NonNull NodeIdentifierWithPredicates of(final QName node,
739 final ImmutableOffsetMap<QName, Object> keyValues) {
740 return keyValues.size() == 1 ? of(keyValues, node) : new Regular(node, keyValues);
744 public static @NonNull NodeIdentifierWithPredicates of(final QName node,
745 final SharedSingletonMap<QName, Object> keyValues) {
746 return of(node, keyValues.getEntry());
749 private static @NonNull NodeIdentifierWithPredicates of(final Map<QName, Object> keyValues, final QName node) {
750 return of(node, keyValues.entrySet().iterator().next());
754 * Return the set of predicates keys and values. Keys are guaranteeed to be unique.
756 * @return Predicate set.
758 public abstract @NonNull Set<Entry<QName, Object>> entrySet();
761 * Return the predicate key in the iteration order of {@link #entrySet()}.
763 * @return Predicate values.
765 public abstract @NonNull Set<QName> keySet();
768 * Determine whether a particular predicate key is present.
770 * @param key Predicate key
771 * @return True if the predicate is present, false otherwise
772 * @throws NullPointerException if {@code key} is null
774 public abstract boolean containsKey(QName key);
777 * Return the predicate values in the iteration order of {@link #entrySet()}.
779 * @return Predicate values.
781 public abstract @NonNull Collection<Object> values();
784 public final @Nullable Object getValue(final QName key) {
785 return keyValue(requireNonNull(key));
789 public final <T> @Nullable T getValue(final QName key, final Class<T> valueClass) {
790 return valueClass.cast(getValue(key));
794 * Return the number of predicates present.
796 * @return The number of predicates present.
798 public abstract int size();
801 * A Map-like view of this identifier's predicates. The view is expected to be stable and effectively-immutable.
803 * @return Map of predicates.
804 * @deprecated This method in a provisional one. It can be used in the code base, but users requiring it should
805 * contact <a href="mailto:yangtools-dev@lists.opendaylight.org">yangtools-dev</a> for migration
806 * guidelines. Callers are strongly encouraged to explore {@link #entrySet()}, {@link #size()},
807 * {@link #values()} and {@link #keySet()} as an alternative.
809 public abstract @NonNull Map<QName, Object> asMap();
812 protected final int hashCodeImpl() {
813 int result = 31 * super.hashCodeImpl();
814 for (Entry<QName, Object> entry : entrySet()) {
815 result += entry.getKey().hashCode() + YangInstanceIdentifier.hashCode(entry.getValue());
821 @SuppressWarnings("checkstyle:equalsHashCode")
822 public final boolean equals(final Object obj) {
823 return super.equals(obj) && equalMapping((NodeIdentifierWithPredicates) obj);
826 abstract boolean equalMapping(NodeIdentifierWithPredicates other);
828 abstract @Nullable Object keyValue(@NonNull QName qname);
831 public final String toString() {
832 return super.toString() + '[' + asMap() + ']';
836 public final String toRelativeString(final PathArgument previous) {
837 return super.toRelativeString(previous) + '[' + asMap() + ']';
841 final Object writeReplace() {
842 return new NIPv2(this);
847 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
850 public static final class NodeWithValue<T> extends AbstractPathArgument {
851 private static final long serialVersionUID = -3637456085341738431L;
853 private final T value;
855 public NodeWithValue(final QName node, final T value) {
860 public T getValue() {
865 protected int hashCodeImpl() {
866 return 31 * super.hashCodeImpl() + YangInstanceIdentifier.hashCode(value);
870 @SuppressWarnings("checkstyle:equalsHashCode")
871 public boolean equals(final Object obj) {
872 if (!super.equals(obj)) {
875 final NodeWithValue<?> other = (NodeWithValue<?>) obj;
876 return Objects.deepEquals(value, other.value);
880 public String toString() {
881 return super.toString() + '[' + value + ']';
885 public String toRelativeString(final PathArgument previous) {
886 return super.toRelativeString(previous) + '[' + value + ']';
890 Object writeReplace() {
891 return new NIVv1(this);
896 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode}
897 * node in particular subtree.
900 * Augmentation is uniquely identified by set of all possible child nodes.
902 * to identify instance of augmentation,
903 * since RFC6020 states that <code>augment</code> that augment
904 * statement must not add multiple nodes from same namespace
905 * / module to the target node.
907 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
909 public static final class AugmentationIdentifier implements PathArgument {
910 private static final long serialVersionUID = -8122335594681936939L;
912 private static final LoadingCache<ImmutableSet<QName>, AugmentationIdentifier> CACHE = CacheBuilder.newBuilder()
913 .weakValues().build(new CacheLoader<ImmutableSet<QName>, AugmentationIdentifier>() {
915 public AugmentationIdentifier load(final ImmutableSet<QName> key) {
916 return new AugmentationIdentifier(key);
920 private final @NonNull ImmutableSet<QName> childNames;
923 public QName getNodeType() {
924 // This should rather throw exception than return always null
925 throw new UnsupportedOperationException("Augmentation node has no QName");
929 * Construct new augmentation identifier using supplied set of possible
933 * Set of possible child nodes.
935 public AugmentationIdentifier(final ImmutableSet<QName> childNames) {
936 this.childNames = requireNonNull(childNames);
940 * Construct new augmentation identifier using supplied set of possible
944 * Set of possible child nodes.
946 public AugmentationIdentifier(final Set<QName> childNames) {
947 this.childNames = ImmutableSet.copyOf(childNames);
951 * Return an AugmentationIdentifier for a particular set of QNames. Unlike the constructor, this factory method
952 * uses a global instance cache, resulting in object reuse for equal inputs.
954 * @param childNames Set of possible child nodes
955 * @return An {@link AugmentationIdentifier}
957 public static @NonNull AugmentationIdentifier create(final ImmutableSet<QName> childNames) {
958 return CACHE.getUnchecked(childNames);
962 * Return an AugmentationIdentifier for a particular set of QNames. Unlike the constructor, this factory method
963 * uses a global instance cache, resulting in object reuse for equal inputs.
965 * @param childNames Set of possible child nodes
966 * @return An {@link AugmentationIdentifier}
968 public static @NonNull AugmentationIdentifier create(final Set<QName> childNames) {
969 final AugmentationIdentifier existing = CACHE.getIfPresent(childNames);
970 return existing != null ? existing : create(ImmutableSet.copyOf(childNames));
974 * Returns set of all possible child nodes.
976 * @return set of all possible child nodes.
978 public @NonNull Set<QName> getPossibleChildNames() {
983 public String toString() {
984 return "AugmentationIdentifier{" + "childNames=" + childNames + '}';
988 public String toRelativeString(final PathArgument previous) {
993 public boolean equals(final Object obj) {
997 if (!(obj instanceof AugmentationIdentifier)) {
1001 AugmentationIdentifier that = (AugmentationIdentifier) obj;
1002 return childNames.equals(that.childNames);
1006 public int hashCode() {
1007 return childNames.hashCode();
1011 @SuppressWarnings("checkstyle:parameterName")
1012 public int compareTo(final PathArgument o) {
1013 if (!(o instanceof AugmentationIdentifier)) {
1016 AugmentationIdentifier other = (AugmentationIdentifier) o;
1017 Set<QName> otherChildNames = other.getPossibleChildNames();
1018 int thisSize = childNames.size();
1019 int otherSize = otherChildNames.size();
1020 if (thisSize == otherSize) {
1021 // Quick Set-based comparison
1022 if (childNames.equals(otherChildNames)) {
1026 // We already know the sets are not equal, but have equal size, hence the sets differ in their elements,
1027 // but potentially share a common set of elements. The most consistent way of comparing them is using
1028 // total ordering defined by QName's compareTo. Hence convert both sets to lists ordered
1029 // by QName.compareTo() and decide on the first differing element.
1030 final List<QName> diff = new ArrayList<>(Sets.symmetricDifference(childNames, otherChildNames));
1031 verify(!diff.isEmpty(), "Augmentation identifiers %s and %s report no difference", this, o);
1032 diff.sort(QName::compareTo);
1033 return childNames.contains(diff.get(0)) ? -1 : 1;
1034 } else if (thisSize < otherSize) {
1041 private Object writeReplace() {
1042 return new AIv1(this);
1047 * Fluent Builder of Instance Identifier instances.
1049 public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
1051 * Adds a {@link PathArgument} to path arguments of resulting instance identifier.
1053 * @param arg A {@link PathArgument} to be added
1054 * @return this builder
1056 @NonNull InstanceIdentifierBuilder node(PathArgument arg);
1059 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
1061 * @param nodeType QName of {@link NodeIdentifier} which will be added
1062 * @return this builder
1064 @NonNull InstanceIdentifierBuilder node(QName nodeType);
1067 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting
1068 * instance identifier.
1070 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
1071 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
1072 * @return this builder
1074 @NonNull InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
1077 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
1079 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
1080 * @param key QName of key which will be added
1081 * @param value value of key which will be added
1082 * @return this builder
1084 @NonNull InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
1087 * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
1089 * @param args {@link PathArgument}s to be added
1090 * @return this builder
1091 * @throws NullPointerException if any of the arguments is null
1093 @NonNull InstanceIdentifierBuilder append(Collection<? extends PathArgument> args);
1096 * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
1098 * @param args {@link PathArgument}s to be added
1099 * @return this builder
1100 * @throws NullPointerException if any of the arguments is null
1102 default @NonNull InstanceIdentifierBuilder append(final PathArgument... args) {
1103 return append(Arrays.asList(args));
1107 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder.
1109 * @return {@link YangInstanceIdentifier}
1112 YangInstanceIdentifier build();