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 java.io.Serializable;
25 import java.lang.invoke.MethodHandles;
26 import java.lang.invoke.VarHandle;
27 import java.lang.reflect.Array;
28 import java.util.AbstractMap.SimpleImmutableEntry;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.Collection;
32 import java.util.Deque;
33 import java.util.Iterator;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Objects;
38 import java.util.Optional;
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.HierarchicalIdentifier;
44 import org.opendaylight.yangtools.concepts.Immutable;
45 import org.opendaylight.yangtools.concepts.Mutable;
46 import org.opendaylight.yangtools.util.ImmutableOffsetMap;
47 import org.opendaylight.yangtools.util.SingletonSet;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.common.QNameModule;
50 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
53 * Unique identifier of a particular node instance in the data tree.
56 * Java representation of YANG Built-in type {@code instance-identifier}, which conceptually is XPath expression
57 * minimized to uniquely identify element in data tree which conforms to constraints maintained by YANG Model,
58 * effectively this makes Instance Identifier a path to element in data tree.
61 * Constraints put in YANG specification on instance-identifier allowed it to be effectively represented in Java and its
62 * evaluation does not require a full-blown XPath processor.
64 * <h2>Path Arguments</h2>
65 * Path to the node represented in instance identifier consists of {@link PathArgument} which carries necessary
66 * information to uniquely identify node on particular level in the subtree.
69 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality {@code 0..1} in particular subtree in data
71 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item), which has cardinality {@code 0..n}</li>
72 * <li>{@link NodeWithValue} - Identifier of instance {@code leaf} node or {@code leaf-list} node</li>
73 * <li>{@link AugmentationIdentifier} - Identifier of instance of {@code augmentation} node</li>
76 * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
78 public abstract sealed class YangInstanceIdentifier implements HierarchicalIdentifier<YangInstanceIdentifier>
79 permits FixedYangInstanceIdentifier, StackedYangInstanceIdentifier {
81 private static final long serialVersionUID = 4L;
82 private static final VarHandle TO_STRING_CACHE;
83 private static final VarHandle HASH;
86 final var lookup = MethodHandles.lookup();
88 HASH = lookup.findVarHandle(YangInstanceIdentifier.class, "hash", int.class);
89 TO_STRING_CACHE = lookup.findVarHandle(YangInstanceIdentifier.class, "toStringCache", String.class);
90 } catch (NoSuchFieldException | IllegalAccessException e) {
91 throw new ExceptionInInitializerError(e);
95 @SuppressWarnings("unused")
97 @SuppressWarnings("unused")
98 private transient String toStringCache = null;
100 YangInstanceIdentifier() {
101 // Package-private to prevent outside subclassing
105 * Return An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual root of the YANG
108 * @return An empty YangInstanceIdentifier
110 public static @NonNull YangInstanceIdentifier empty() {
111 return FixedYangInstanceIdentifier.EMPTY_INSTANCE;
114 abstract @NonNull YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
116 abstract @Nullable List<PathArgument> tryPathArguments();
118 abstract @Nullable List<PathArgument> tryReversePathArguments();
121 * Check if this instance identifier has empty path arguments, e.g. it is
122 * empty and corresponds to {@link #empty()}.
124 * @return True if this instance identifier is empty, false otherwise.
126 public abstract boolean isEmpty();
129 * Return an optimized version of this identifier, useful when the identifier
130 * will be used very frequently.
132 * @return A optimized equivalent instance.
134 public abstract @NonNull YangInstanceIdentifier toOptimized();
137 * Return the conceptual parent {@link YangInstanceIdentifier}, which has
138 * one item less in {@link #getPathArguments()}.
140 * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #empty()}.
142 public abstract @Nullable YangInstanceIdentifier getParent();
145 * Return the conceptual parent {@link YangInstanceIdentifier}, which has one item less in
146 * {@link #getPathArguments()}.
148 * @return Parent {@link YangInstanceIdentifier}
149 * @throws VerifyException if this object is {@link #empty()}.
151 public abstract @NonNull YangInstanceIdentifier coerceParent();
154 * Return the ancestor {@link YangInstanceIdentifier} with a particular depth, e.g. number of path arguments.
156 * @param depth Ancestor depth
157 * @return Ancestor {@link YangInstanceIdentifier}
158 * @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
160 public abstract @NonNull YangInstanceIdentifier getAncestor(int depth);
163 * Returns an ordered iteration of path arguments.
165 * @return Immutable iteration of path arguments.
167 public abstract @NonNull List<PathArgument> getPathArguments();
170 * Returns an iterable of path arguments in reverse order. This is useful
171 * when walking up a tree organized this way.
173 * @return Immutable iterable of path arguments in reverse order.
175 public abstract @NonNull List<PathArgument> getReversePathArguments();
178 * Returns the last PathArgument. This is equivalent of iterating
179 * to the last element of the iterable returned by {@link #getPathArguments()}.
181 * @return The last past argument, or null if there are no PathArguments.
183 public abstract PathArgument getLastPathArgument();
185 public static @NonNull YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
186 return Iterables.isEmpty(path) ? empty() : new FixedYangInstanceIdentifier(ImmutableList.copyOf(path));
189 public static @NonNull YangInstanceIdentifier create(final PathArgument pathArgument) {
190 return new FixedYangInstanceIdentifier(ImmutableList.of(pathArgument));
193 public static @NonNull YangInstanceIdentifier create(final PathArgument... path) {
194 // We are forcing a copy, since we cannot trust the user
195 return create(Arrays.asList(path));
199 * Create a {@link YangInstanceIdentifier} by taking a snapshot of provided path and iterating it backwards.
201 * @param pathTowardsRoot Path towards root
202 * @return A {@link YangInstanceIdentifier} instance
203 * @throws NullPointerException if {@code pathTowardsRoot} or any of its members is null
205 public static @NonNull YangInstanceIdentifier createReverse(final Deque<PathArgument> pathTowardsRoot) {
206 final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
207 pathTowardsRoot.size());
208 pathTowardsRoot.descendingIterator().forEachRemaining(builder::add);
209 return YangInstanceIdentifier.create(builder.build());
213 * Create a {@link YangInstanceIdentifier} by walking specified stack backwards and extracting path components
216 * @param stackTowardsRoot Stack towards root,
217 * @return A {@link YangInstanceIdentifier} instance
218 * @throws NullPointerException if {@code pathTowardsRoot} is null
220 public static <T> @NonNull YangInstanceIdentifier createReverse(final Deque<? extends T> stackTowardsRoot,
221 final Function<T, PathArgument> function) {
222 final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
223 stackTowardsRoot.size());
224 final Iterator<? extends T> it = stackTowardsRoot.descendingIterator();
225 while (it.hasNext()) {
226 builder.add(function.apply(it.next()));
228 return YangInstanceIdentifier.create(builder.build());
231 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
232 return getPathArguments().equals(other.getPathArguments());
236 public final boolean equals(final Object obj) {
237 return this == obj || obj instanceof YangInstanceIdentifier other && pathArgumentsEqual(other);
241 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments.
243 * @param name QName of {@link NodeIdentifier}
244 * @return Instance Identifier with additional path argument added to the end.
246 public final @NonNull YangInstanceIdentifier node(final QName name) {
247 return node(new NodeIdentifier(name));
251 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments.
253 * @param arg Path argument which should be added to the end
254 * @return Instance Identifier with additional path argument added to the end.
256 public final @NonNull YangInstanceIdentifier node(final PathArgument arg) {
257 return new StackedYangInstanceIdentifier(this, arg);
261 * Get the relative path from an ancestor. This method attempts to perform
262 * the reverse of concatenating a base (ancestor) and a path.
265 * Ancestor against which the relative path should be calculated
266 * @return This object's relative path from parent, or Optional.absent() if
267 * the specified parent is not in fact an ancestor of this object.
269 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
270 if (this == ancestor) {
271 return Optional.of(empty());
273 if (ancestor.isEmpty()) {
274 return Optional.of(this);
277 final Iterator<PathArgument> lit = getPathArguments().iterator();
278 final Iterator<PathArgument> oit = ancestor.getPathArguments().iterator();
281 while (oit.hasNext()) {
282 // Ancestor is not really an ancestor
283 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
284 return Optional.empty();
291 return Optional.of(this);
293 if (!lit.hasNext()) {
294 return Optional.of(empty());
297 return Optional.of(createRelativeIdentifier(common));
301 public final boolean contains(final YangInstanceIdentifier other) {
306 checkArgument(other != null, "other should not be null");
307 final Iterator<PathArgument> lit = getPathArguments().iterator();
308 final Iterator<PathArgument> oit = other.getPathArguments().iterator();
310 while (lit.hasNext()) {
311 if (!oit.hasNext()) {
315 if (!lit.next().equals(oit.next())) {
324 public final String toString() {
326 * The toStringCache is safe, since the object contract requires
327 * immutability of the object and all objects referenced from this
329 * Used lists, maps are immutable. Path Arguments (elements) are also
330 * immutable, since the PathArgument contract requires immutability.
331 * The cache is thread-safe - if multiple computations occurs at the
332 * same time, cache will be overwritten with same result.
334 final String ret = (String) TO_STRING_CACHE.getAcquire(this);
335 return ret != null ? ret : loadToString();
338 private String loadToString() {
339 final StringBuilder builder = new StringBuilder("/");
340 PathArgument prev = null;
341 for (PathArgument argument : getPathArguments()) {
345 builder.append(argument.toRelativeString(prev));
349 final String ret = builder.toString();
350 final String witness = (String) TO_STRING_CACHE.compareAndExchangeRelease(this, null, ret);
351 return witness == null ? ret : witness;
355 public final int hashCode() {
357 * The caching is safe, since the object contract requires
358 * immutability of the object and all objects referenced from this
360 * Used lists, maps are immutable. Path Arguments (elements) are also
361 * immutable, since the PathArgument contract requires immutability.
363 final int local = (int) HASH.getAcquire(this);
364 return local != 0 ? local : loadHashCode();
367 private static int hashCode(final Object value) {
372 if (byte[].class.equals(value.getClass())) {
373 return Arrays.hashCode((byte[]) value);
376 if (value.getClass().isArray()) {
378 int length = Array.getLength(value);
379 for (int i = 0; i < length; i++) {
380 hash += Objects.hashCode(Array.get(value, i));
386 return Objects.hashCode(value);
389 private int loadHashCode() {
390 final int computed = computeHashCode();
391 HASH.setRelease(this, computed);
395 abstract int computeHashCode();
398 final Object writeReplace() {
399 return new YIDv1(this);
402 // Static factories & helpers
405 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied
408 * @param name QName of first node identifier
409 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
411 public static @NonNull YangInstanceIdentifier of(final QName name) {
412 return create(new NodeIdentifier(name));
416 * Returns new builder for InstanceIdentifier with empty path arguments.
418 * @return new builder for InstanceIdentifier with empty path arguments.
420 public static @NonNull InstanceIdentifierBuilder builder() {
421 return new YangInstanceIdentifierBuilder();
425 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
427 * @param origin InstanceIdentifier from which path arguments are copied.
428 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
430 public static @NonNull InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
431 return new YangInstanceIdentifierBuilder(origin.getPathArguments());
435 * Path argument / component of InstanceIdentifier.
436 * Path argument uniquely identifies node in data tree on particular
440 * This interface itself is used as common parent for actual
441 * path arguments types and should not be implemented by user code.
444 * Path arguments SHOULD contain only minimum of information
445 * required to uniquely identify node on particular subtree level.
448 * For actual path arguments types see:
450 * <li>{@link NodeIdentifier} - Identifier of container or leaf
451 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
452 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
453 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
456 public sealed interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable
457 permits AbstractPathArgument, AugmentationIdentifier {
459 * Returns unique QName of data node as defined in YANG Schema, if available.
462 * @throws UnsupportedOperationException if node type is not applicable, for example in case of an augmentation.
464 @NonNull QName getNodeType();
467 * Return the string representation of this object for use in context
468 * provided by a previous object. This method can be implemented in
469 * terms of {@link #toString()}, but implementations are encourage to
470 * reuse any context already emitted by the previous object.
472 * @param previous Previous path argument
473 * @return String representation
475 @NonNull String toRelativeString(PathArgument previous);
478 private abstract static sealed class AbstractPathArgument implements PathArgument {
479 private static final long serialVersionUID = -4546547994250849340L;
480 private final @NonNull QName nodeType;
481 private transient volatile int hashValue;
483 protected AbstractPathArgument(final QName nodeType) {
484 this.nodeType = requireNonNull(nodeType);
488 public final QName getNodeType() {
493 @SuppressWarnings("checkstyle:parameterName")
494 public int compareTo(final PathArgument o) {
495 return nodeType.compareTo(o.getNodeType());
498 protected int hashCodeImpl() {
499 return nodeType.hashCode();
503 public final int hashCode() {
505 return (local = hashValue) != 0 ? local : (hashValue = hashCodeImpl());
509 public boolean equals(final Object obj) {
513 if (obj == null || this.getClass() != obj.getClass()) {
517 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
521 public String toString() {
522 return getNodeType().toString();
526 public String toRelativeString(final PathArgument previous) {
527 if (previous instanceof AbstractPathArgument) {
528 final QNameModule mod = previous.getNodeType().getModule();
529 if (getNodeType().getModule().equals(mod)) {
530 return getNodeType().getLocalName();
534 return getNodeType().toString();
537 abstract Object writeReplace();
541 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
542 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
544 public static final class NodeIdentifier extends AbstractPathArgument {
545 private static final long serialVersionUID = -2255888212390871347L;
546 private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
547 .build(new CacheLoader<QName, NodeIdentifier>() {
549 public NodeIdentifier load(final QName key) {
550 return new NodeIdentifier(key);
554 public NodeIdentifier(final QName node) {
559 * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
560 * instance cache, resulting in object reuse for equal inputs.
562 * @param node Node's QName
563 * @return A {@link NodeIdentifier}
565 public static @NonNull NodeIdentifier create(final QName node) {
566 return CACHE.getUnchecked(node);
570 Object writeReplace() {
571 return new NIv1(this);
576 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
579 public abstract static sealed class NodeIdentifierWithPredicates extends AbstractPathArgument {
581 public static final class Singleton extends NodeIdentifierWithPredicates {
582 private static final long serialVersionUID = 1L;
584 private final @NonNull QName key;
585 private final @NonNull Object value;
587 Singleton(final QName node, final QName key, final Object value) {
589 this.key = requireNonNull(key);
590 this.value = requireNonNull(value);
594 public SingletonSet<Entry<QName, Object>> entrySet() {
595 return SingletonSet.of(singleEntry());
599 public SingletonSet<QName> keySet() {
600 return SingletonSet.of(key);
604 public boolean containsKey(final QName qname) {
605 return key.equals(requireNonNull(qname));
609 public SingletonSet<Object> values() {
610 return SingletonSet.of(value);
619 public ImmutableMap<QName, Object> asMap() {
620 return ImmutableMap.of(key, value);
624 * Return the single entry contained in this object. This is equivalent to
625 * {@code entrySet().iterator().next()}.
627 * @return A single entry.
629 public @NonNull Entry<QName, Object> singleEntry() {
630 return new SimpleImmutableEntry<>(key, value);
634 boolean equalMapping(final NodeIdentifierWithPredicates other) {
635 final Singleton single = (Singleton) other;
636 return key.equals(single.key) && Objects.deepEquals(value, single.value);
640 Object keyValue(final QName qname) {
641 return key.equals(qname) ? value : null;
645 private static final class Regular extends NodeIdentifierWithPredicates {
646 private static final long serialVersionUID = 1L;
648 private final @NonNull Map<QName, Object> keyValues;
650 Regular(final QName node, final Map<QName, Object> keyValues) {
652 this.keyValues = requireNonNull(keyValues);
656 public Set<Entry<QName, Object>> entrySet() {
657 return keyValues.entrySet();
661 public Set<QName> keySet() {
662 return keyValues.keySet();
666 public boolean containsKey(final QName qname) {
667 return keyValues.containsKey(requireNonNull(qname));
671 public Collection<Object> values() {
672 return keyValues.values();
677 return keyValues.size();
681 public Map<QName, Object> asMap() {
686 Object keyValue(final QName qname) {
687 return keyValues.get(qname);
691 boolean equalMapping(final NodeIdentifierWithPredicates other) {
692 final Map<QName, Object> otherKeyValues = ((Regular) other).keyValues;
693 // TODO: benchmark to see if just calling equals() on the two maps is not faster
694 if (keyValues == otherKeyValues) {
697 if (keyValues.size() != otherKeyValues.size()) {
701 for (Entry<QName, Object> entry : entrySet()) {
702 final Object otherValue = otherKeyValues.get(entry.getKey());
703 if (otherValue == null || !Objects.deepEquals(entry.getValue(), otherValue)) {
712 private static final long serialVersionUID = -4787195606494761540L;
714 NodeIdentifierWithPredicates(final QName node) {
718 public static @NonNull NodeIdentifierWithPredicates of(final QName node) {
719 return new Regular(node, ImmutableMap.of());
722 public static @NonNull NodeIdentifierWithPredicates of(final QName node, final QName key, final Object value) {
723 return new Singleton(node, key, value);
726 public static @NonNull NodeIdentifierWithPredicates of(final QName node, final Entry<QName, Object> entry) {
727 return of(node, entry.getKey(), entry.getValue());
730 public static @NonNull NodeIdentifierWithPredicates of(final QName node, final Map<QName, Object> keyValues) {
731 return keyValues.size() == 1 ? of(keyValues, node)
732 // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
733 : new Regular(node, ImmutableOffsetMap.unorderedCopyOf(keyValues));
736 public static @NonNull NodeIdentifierWithPredicates of(final QName node,
737 final ImmutableOffsetMap<QName, Object> keyValues) {
738 return keyValues.size() == 1 ? of(keyValues, node) : new Regular(node, keyValues);
741 private static @NonNull NodeIdentifierWithPredicates of(final Map<QName, Object> keyValues, final QName node) {
742 return of(node, keyValues.entrySet().iterator().next());
746 * Return the set of predicates keys and values. Keys are guaranteeed to be unique.
748 * @return Predicate set.
750 public abstract @NonNull Set<Entry<QName, Object>> entrySet();
753 * Return the predicate key in the iteration order of {@link #entrySet()}.
755 * @return Predicate values.
757 public abstract @NonNull Set<QName> keySet();
760 * Determine whether a particular predicate key is present.
762 * @param key Predicate key
763 * @return True if the predicate is present, false otherwise
764 * @throws NullPointerException if {@code key} is null
766 public abstract boolean containsKey(QName key);
769 * Return the predicate values in the iteration order of {@link #entrySet()}.
771 * @return Predicate values.
773 public abstract @NonNull Collection<Object> values();
776 public final @Nullable Object getValue(final QName key) {
777 return keyValue(requireNonNull(key));
781 public final <T> @Nullable T getValue(final QName key, final Class<T> valueClass) {
782 return valueClass.cast(getValue(key));
786 * Return the number of predicates present.
788 * @return The number of predicates present.
790 public abstract int size();
793 * A Map-like view of this identifier's predicates. The view is expected to be stable and effectively-immutable.
795 * @return Map of predicates.
798 public abstract @NonNull Map<QName, Object> asMap();
801 protected final int hashCodeImpl() {
802 int result = 31 * super.hashCodeImpl();
803 for (Entry<QName, Object> entry : entrySet()) {
804 result += entry.getKey().hashCode() + YangInstanceIdentifier.hashCode(entry.getValue());
810 @SuppressWarnings("checkstyle:equalsHashCode")
811 public final boolean equals(final Object obj) {
812 return super.equals(obj) && equalMapping((NodeIdentifierWithPredicates) obj);
815 abstract boolean equalMapping(NodeIdentifierWithPredicates other);
817 abstract @Nullable Object keyValue(@NonNull QName qname);
820 public final String toString() {
821 return super.toString() + '[' + asMap() + ']';
825 public final String toRelativeString(final PathArgument previous) {
826 return super.toRelativeString(previous) + '[' + asMap() + ']';
830 final Object writeReplace() {
831 return new NIPv2(this);
836 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
839 public static final class NodeWithValue<T> extends AbstractPathArgument {
840 private static final long serialVersionUID = -3637456085341738431L;
842 private final @NonNull T value;
844 public NodeWithValue(final QName node, final T value) {
846 this.value = requireNonNull(value);
849 public @NonNull T getValue() {
854 protected int hashCodeImpl() {
855 return 31 * super.hashCodeImpl() + YangInstanceIdentifier.hashCode(value);
859 @SuppressWarnings("checkstyle:equalsHashCode")
860 public boolean equals(final Object obj) {
861 if (!super.equals(obj)) {
864 final NodeWithValue<?> other = (NodeWithValue<?>) obj;
865 return Objects.deepEquals(value, other.value);
869 public String toString() {
870 return super.toString() + '[' + value + ']';
874 public String toRelativeString(final PathArgument previous) {
875 return super.toRelativeString(previous) + '[' + value + ']';
879 Object writeReplace() {
880 return new NIVv1(this);
885 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode}
886 * node in particular subtree.
889 * Augmentation is uniquely identified by set of all possible child nodes.
891 * to identify instance of augmentation,
892 * since RFC6020 states that <code>augment</code> that augment
893 * statement must not add multiple nodes from same namespace
894 * / module to the target node.
896 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
898 public static final class AugmentationIdentifier implements PathArgument {
899 private static final long serialVersionUID = -8122335594681936939L;
901 private static final LoadingCache<ImmutableSet<QName>, AugmentationIdentifier> CACHE = CacheBuilder.newBuilder()
902 .weakValues().build(new CacheLoader<ImmutableSet<QName>, AugmentationIdentifier>() {
904 public AugmentationIdentifier load(final ImmutableSet<QName> key) {
905 return new AugmentationIdentifier(key);
909 private final @NonNull ImmutableSet<QName> childNames;
912 public QName getNodeType() {
913 // This should rather throw exception than return always null
914 throw new UnsupportedOperationException("Augmentation node has no QName");
918 * Construct new augmentation identifier using supplied set of possible
922 * Set of possible child nodes.
924 public AugmentationIdentifier(final ImmutableSet<QName> childNames) {
925 this.childNames = requireNonNull(childNames);
929 * Construct new augmentation identifier using supplied set of possible
933 * Set of possible child nodes.
935 public AugmentationIdentifier(final Set<QName> childNames) {
936 this.childNames = ImmutableSet.copyOf(childNames);
940 * Return an AugmentationIdentifier for a particular set of QNames. Unlike the constructor, this factory method
941 * uses a global instance cache, resulting in object reuse for equal inputs.
943 * @param childNames Set of possible child nodes
944 * @return An {@link AugmentationIdentifier}
946 public static @NonNull AugmentationIdentifier create(final ImmutableSet<QName> childNames) {
947 return CACHE.getUnchecked(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 Set<QName> childNames) {
958 final AugmentationIdentifier existing = CACHE.getIfPresent(childNames);
959 return existing != null ? existing : create(ImmutableSet.copyOf(childNames));
963 * Returns set of all possible child nodes.
965 * @return set of all possible child nodes.
967 public @NonNull Set<QName> getPossibleChildNames() {
972 public String toString() {
973 return "AugmentationIdentifier{" + "childNames=" + childNames + '}';
977 public String toRelativeString(final PathArgument previous) {
982 public boolean equals(final Object obj) {
983 return this == obj || obj instanceof AugmentationIdentifier other && childNames.equals(other.childNames);
987 public int hashCode() {
988 return childNames.hashCode();
992 @SuppressWarnings("checkstyle:parameterName")
993 public int compareTo(final PathArgument o) {
994 if (!(o instanceof AugmentationIdentifier other)) {
997 Set<QName> otherChildNames = other.getPossibleChildNames();
998 int thisSize = childNames.size();
999 int otherSize = otherChildNames.size();
1000 if (thisSize == otherSize) {
1001 // Quick Set-based comparison
1002 if (childNames.equals(otherChildNames)) {
1006 // We already know the sets are not equal, but have equal size, hence the sets differ in their elements,
1007 // but potentially share a common set of elements. The most consistent way of comparing them is using
1008 // total ordering defined by QName's compareTo. Hence convert both sets to lists ordered
1009 // by QName.compareTo() and decide on the first differing element.
1010 final List<QName> diff = new ArrayList<>(Sets.symmetricDifference(childNames, otherChildNames));
1011 verify(!diff.isEmpty(), "Augmentation identifiers %s and %s report no difference", this, o);
1012 diff.sort(QName::compareTo);
1013 return childNames.contains(diff.get(0)) ? -1 : 1;
1014 } else if (thisSize < otherSize) {
1021 private Object writeReplace() {
1022 return new AIv1(this);
1027 * Fluent Builder of Instance Identifier instances.
1029 public interface InstanceIdentifierBuilder extends Mutable {
1031 * Adds a {@link PathArgument} to path arguments of resulting instance identifier.
1033 * @param arg A {@link PathArgument} to be added
1034 * @return this builder
1036 @NonNull InstanceIdentifierBuilder node(PathArgument arg);
1039 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
1041 * @param nodeType QName of {@link NodeIdentifier} which will be added
1042 * @return this builder
1044 @NonNull InstanceIdentifierBuilder node(QName nodeType);
1047 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting
1048 * instance identifier.
1050 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
1051 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
1052 * @return this builder
1054 @NonNull InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
1057 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
1059 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
1060 * @param key QName of key which will be added
1061 * @param value value of key which will be added
1062 * @return this builder
1064 @NonNull InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
1067 * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
1069 * @param args {@link PathArgument}s to be added
1070 * @return this builder
1071 * @throws NullPointerException if any of the arguments is null
1073 @NonNull InstanceIdentifierBuilder append(Collection<? extends PathArgument> args);
1076 * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
1078 * @param args {@link PathArgument}s to be added
1079 * @return this builder
1080 * @throws NullPointerException if any of the arguments is null
1082 default @NonNull InstanceIdentifierBuilder append(final PathArgument... args) {
1083 return append(Arrays.asList(args));
1087 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder.
1089 * @return {@link YangInstanceIdentifier}
1091 @NonNull YangInstanceIdentifier build();