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.HashCodeBuilder;
47 import org.opendaylight.yangtools.util.ImmutableOffsetMap;
48 import org.opendaylight.yangtools.util.SingletonSet;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.common.QNameModule;
51 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
54 * Unique identifier of a particular node instance in the data tree.
57 * Java representation of YANG Built-in type {@code instance-identifier}, which conceptually is XPath expression
58 * minimized to uniquely identify element in data tree which conforms to constraints maintained by YANG Model,
59 * effectively this makes Instance Identifier a path to element in data tree.
62 * Constraints put in YANG specification on instance-identifier allowed it to be effectively represented in Java and its
63 * evaluation does not require a full-blown XPath processor.
65 * <h2>Path Arguments</h2>
66 * Path to the node represented in instance identifier consists of {@link PathArgument} which carries necessary
67 * information to uniquely identify node on particular level in the subtree.
70 * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality {@code 0..1} in particular subtree in data
72 * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item), which has cardinality {@code 0..n}</li>
73 * <li>{@link NodeWithValue} - Identifier of instance {@code leaf} node or {@code leaf-list} node</li>
74 * <li>{@link AugmentationIdentifier} - Identifier of instance of {@code augmentation} node</li>
77 * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
79 // FIXME: 7.0.0: this concept needs to be moved to yang-common, as parser components need the ability to refer
80 // to data nodes -- most notably XPath expressions and {@code default} statement arguments need to be able
81 // to represent these.
82 public abstract class YangInstanceIdentifier implements HierarchicalIdentifier<YangInstanceIdentifier> {
83 private static final long serialVersionUID = 4L;
84 private static final VarHandle TO_STRING_CACHE;
88 TO_STRING_CACHE = MethodHandles.lookup().findVarHandle(YangInstanceIdentifier.class, "toStringCache",
90 } catch (NoSuchFieldException | IllegalAccessException e) {
91 throw new ExceptionInInitializerError(e);
96 private final int hash;
97 @SuppressWarnings("unused")
98 private transient String toStringCache = null;
100 // Package-private to prevent outside subclassing
101 YangInstanceIdentifier(final int hash) {
106 * Return An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual root of the YANG
109 * @return An empty YangInstanceIdentifier
111 public static @NonNull YangInstanceIdentifier empty() {
112 return FixedYangInstanceIdentifier.EMPTY_INSTANCE;
115 abstract @NonNull YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
117 abstract @Nullable Collection<PathArgument> tryPathArguments();
119 abstract @Nullable Collection<PathArgument> tryReversePathArguments();
122 * Check if this instance identifier has empty path arguments, e.g. it is
123 * empty and corresponds to {@link #empty()}.
125 * @return True if this instance identifier is empty, false otherwise.
127 public abstract boolean isEmpty();
130 * Return an optimized version of this identifier, useful when the identifier
131 * will be used very frequently.
133 * @return A optimized equivalent instance.
135 public abstract @NonNull YangInstanceIdentifier toOptimized();
138 * Return the conceptual parent {@link YangInstanceIdentifier}, which has
139 * one item less in {@link #getPathArguments()}.
141 * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #empty()}.
143 public abstract @Nullable YangInstanceIdentifier getParent();
146 * Return the conceptual parent {@link YangInstanceIdentifier}, which has one item less in
147 * {@link #getPathArguments()}.
149 * @return Parent {@link YangInstanceIdentifier}
150 * @throws VerifyException if this object is {@link #empty()}.
152 public abstract @NonNull YangInstanceIdentifier coerceParent();
155 * Return the ancestor {@link YangInstanceIdentifier} with a particular depth, e.g. number of path arguments.
157 * @param depth Ancestor depth
158 * @return Ancestor {@link YangInstanceIdentifier}
159 * @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
161 public abstract @NonNull YangInstanceIdentifier getAncestor(int depth);
164 * Returns an ordered iteration of path arguments.
166 * @return Immutable iteration of path arguments.
168 public abstract @NonNull List<PathArgument> getPathArguments();
171 * Returns an iterable of path arguments in reverse order. This is useful
172 * when walking up a tree organized this way.
174 * @return Immutable iterable of path arguments in reverse order.
176 public abstract @NonNull List<PathArgument> getReversePathArguments();
179 * Returns the last PathArgument. This is equivalent of iterating
180 * to the last element of the iterable returned by {@link #getPathArguments()}.
182 * @return The last past argument, or null if there are no PathArguments.
184 public abstract PathArgument getLastPathArgument();
186 public static @NonNull YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
187 if (Iterables.isEmpty(path)) {
191 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
192 for (PathArgument a : path) {
196 return FixedYangInstanceIdentifier.create(path, hash.build());
199 public static @NonNull YangInstanceIdentifier create(final PathArgument pathArgument) {
200 return new FixedYangInstanceIdentifier(ImmutableList.of(pathArgument),
201 HashCodeBuilder.nextHashCode(1, pathArgument));
204 public static @NonNull YangInstanceIdentifier create(final PathArgument... path) {
205 // We are forcing a copy, since we cannot trust the user
206 return create(Arrays.asList(path));
210 * Create a {@link YangInstanceIdentifier} by taking a snapshot of provided path and iterating it backwards.
212 * @param pathTowardsRoot Path towards root
213 * @return A {@link YangInstanceIdentifier} instance
214 * @throws NullPointerException if {@code pathTowardsRoot} or any of its members is null
216 public static @NonNull YangInstanceIdentifier createReverse(final Deque<PathArgument> pathTowardsRoot) {
217 final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
218 pathTowardsRoot.size());
219 pathTowardsRoot.descendingIterator().forEachRemaining(builder::add);
220 return YangInstanceIdentifier.create(builder.build());
224 * Create a {@link YangInstanceIdentifier} by walking specified stack backwards and extracting path components
227 * @param stackTowardsRoot Stack towards root,
228 * @return A {@link YangInstanceIdentifier} instance
229 * @throws NullPointerException if {@code pathTowardsRoot} is null
231 public static <T> @NonNull YangInstanceIdentifier createReverse(final Deque<? extends T> stackTowardsRoot,
232 final Function<T, PathArgument> function) {
233 final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
234 stackTowardsRoot.size());
235 final Iterator<? extends T> it = stackTowardsRoot.descendingIterator();
236 while (it.hasNext()) {
237 builder.add(function.apply(it.next()));
239 return YangInstanceIdentifier.create(builder.build());
242 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
243 return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
247 public boolean equals(final Object obj) {
251 if (!(obj instanceof YangInstanceIdentifier)) {
254 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
255 if (this.hashCode() != obj.hashCode()) {
259 return pathArgumentsEqual(other);
263 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments.
265 * @param name QName of {@link NodeIdentifier}
266 * @return Instance Identifier with additional path argument added to the end.
268 public final @NonNull YangInstanceIdentifier node(final QName name) {
269 return node(new NodeIdentifier(name));
273 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments.
275 * @param arg Path argument which should be added to the end
276 * @return Instance Identifier with additional path argument added to the end.
278 public final @NonNull YangInstanceIdentifier node(final PathArgument arg) {
279 return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
283 * Get the relative path from an ancestor. This method attempts to perform
284 * the reverse of concatenating a base (ancestor) and a path.
287 * Ancestor against which the relative path should be calculated
288 * @return This object's relative path from parent, or Optional.absent() if
289 * the specified parent is not in fact an ancestor of this object.
291 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
292 if (this == ancestor) {
293 return Optional.of(empty());
295 if (ancestor.isEmpty()) {
296 return Optional.of(this);
299 final Iterator<PathArgument> lit = getPathArguments().iterator();
300 final Iterator<PathArgument> oit = ancestor.getPathArguments().iterator();
303 while (oit.hasNext()) {
304 // Ancestor is not really an ancestor
305 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
306 return Optional.empty();
313 return Optional.of(this);
315 if (!lit.hasNext()) {
316 return Optional.of(empty());
319 return Optional.of(createRelativeIdentifier(common));
323 public final boolean contains(final YangInstanceIdentifier other) {
328 checkArgument(other != null, "other should not be null");
329 final Iterator<PathArgument> lit = getPathArguments().iterator();
330 final Iterator<PathArgument> oit = other.getPathArguments().iterator();
332 while (lit.hasNext()) {
333 if (!oit.hasNext()) {
337 if (!lit.next().equals(oit.next())) {
346 public final String toString() {
348 * The toStringCache is safe, since the object contract requires
349 * immutability of the object and all objects referenced from this
351 * Used lists, maps are immutable. Path Arguments (elements) are also
352 * immutable, since the PathArgument contract requires immutability.
353 * The cache is thread-safe - if multiple computations occurs at the
354 * same time, cache will be overwritten with same result.
356 final String ret = (String) TO_STRING_CACHE.getAcquire(this);
357 return ret != null ? ret : loadToString();
360 private String loadToString() {
361 final StringBuilder builder = new StringBuilder("/");
362 PathArgument prev = null;
363 for (PathArgument argument : getPathArguments()) {
367 builder.append(argument.toRelativeString(prev));
371 final String ret = builder.toString();
372 final String witness = (String) TO_STRING_CACHE.compareAndExchangeRelease(this, null, ret);
373 return witness == null ? ret : witness;
377 public final int hashCode() {
379 * The caching is safe, since the object contract requires
380 * immutability of the object and all objects referenced from this
382 * Used lists, maps are immutable. Path Arguments (elements) are also
383 * immutable, since the PathArgument contract requires immutability.
388 private static int hashCode(final Object value) {
393 if (byte[].class.equals(value.getClass())) {
394 return Arrays.hashCode((byte[]) value);
397 if (value.getClass().isArray()) {
399 int length = Array.getLength(value);
400 for (int i = 0; i < length; i++) {
401 hash += Objects.hashCode(Array.get(value, i));
407 return Objects.hashCode(value);
410 final Object writeReplace() {
411 return new YIDv1(this);
414 // Static factories & helpers
417 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied
420 * @param name QName of first node identifier
421 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
423 public static @NonNull YangInstanceIdentifier of(final QName name) {
424 return create(new NodeIdentifier(name));
428 * Returns new builder for InstanceIdentifier with empty path arguments.
430 * @return new builder for InstanceIdentifier with empty path arguments.
432 public static @NonNull InstanceIdentifierBuilder builder() {
433 return new YangInstanceIdentifierBuilder();
437 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
439 * @param origin InstanceIdentifier from which path arguments are copied.
440 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
442 public static @NonNull InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
443 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
447 * Path argument / component of InstanceIdentifier.
448 * Path argument uniquely identifies node in data tree on particular
452 * This interface itself is used as common parent for actual
453 * path arguments types and should not be implemented by user code.
456 * Path arguments SHOULD contain only minimum of information
457 * required to uniquely identify node on particular subtree level.
460 * For actual path arguments types see:
462 * <li>{@link NodeIdentifier} - Identifier of container or leaf
463 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
464 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
465 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
468 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
470 * Returns unique QName of data node as defined in YANG Schema, if available.
473 * @throws UnsupportedOperationException if node type is not applicable, for example in case of an augmentation.
475 @NonNull QName getNodeType();
478 * Return the string representation of this object for use in context
479 * provided by a previous object. This method can be implemented in
480 * terms of {@link #toString()}, but implementations are encourage to
481 * reuse any context already emitted by the previous object.
483 * @param previous Previous path argument
484 * @return String representation
486 @NonNull String toRelativeString(PathArgument previous);
489 private abstract static class AbstractPathArgument implements PathArgument {
490 private static final long serialVersionUID = -4546547994250849340L;
491 private final @NonNull QName nodeType;
492 private transient volatile int hashValue;
494 protected AbstractPathArgument(final QName nodeType) {
495 this.nodeType = requireNonNull(nodeType);
499 public final QName getNodeType() {
504 @SuppressWarnings("checkstyle:parameterName")
505 public int compareTo(final PathArgument o) {
506 return nodeType.compareTo(o.getNodeType());
509 protected int hashCodeImpl() {
510 return nodeType.hashCode();
514 public final int hashCode() {
516 return (local = hashValue) != 0 ? local : (hashValue = hashCodeImpl());
520 public boolean equals(final Object obj) {
524 if (obj == null || this.getClass() != obj.getClass()) {
528 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
532 public String toString() {
533 return getNodeType().toString();
537 public String toRelativeString(final PathArgument previous) {
538 if (previous instanceof AbstractPathArgument) {
539 final QNameModule mod = previous.getNodeType().getModule();
540 if (getNodeType().getModule().equals(mod)) {
541 return getNodeType().getLocalName();
545 return getNodeType().toString();
548 abstract Object writeReplace();
552 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
553 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
555 public static final class NodeIdentifier extends AbstractPathArgument {
556 private static final long serialVersionUID = -2255888212390871347L;
557 private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
558 .build(new CacheLoader<QName, NodeIdentifier>() {
560 public NodeIdentifier load(final QName key) {
561 return new NodeIdentifier(key);
565 public NodeIdentifier(final QName node) {
570 * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
571 * instance cache, resulting in object reuse for equal inputs.
573 * @param node Node's QName
574 * @return A {@link NodeIdentifier}
576 public static @NonNull NodeIdentifier create(final QName node) {
577 return CACHE.getUnchecked(node);
581 Object writeReplace() {
582 return new NIv1(this);
587 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
590 public abstract static class NodeIdentifierWithPredicates extends AbstractPathArgument {
592 public static final class Singleton extends NodeIdentifierWithPredicates {
593 private static final long serialVersionUID = 1L;
595 private final @NonNull QName key;
596 private final @NonNull Object value;
598 Singleton(final QName node, final QName key, final Object value) {
600 this.key = requireNonNull(key);
601 this.value = requireNonNull(value);
605 public SingletonSet<Entry<QName, Object>> entrySet() {
606 return SingletonSet.of(singleEntry());
610 public SingletonSet<QName> keySet() {
611 return SingletonSet.of(key);
615 public boolean containsKey(final QName qname) {
616 return key.equals(requireNonNull(qname));
620 public SingletonSet<Object> values() {
621 return SingletonSet.of(value);
630 public ImmutableMap<QName, Object> asMap() {
631 return ImmutableMap.of(key, value);
635 * Return the single entry contained in this object. This is equivalent to
636 * {@code entrySet().iterator().next()}.
638 * @return A single entry.
640 public @NonNull Entry<QName, Object> singleEntry() {
641 return new SimpleImmutableEntry<>(key, value);
645 boolean equalMapping(final NodeIdentifierWithPredicates other) {
646 final Singleton single = (Singleton) other;
647 return key.equals(single.key) && Objects.deepEquals(value, single.value);
651 Object keyValue(final QName qname) {
652 return key.equals(qname) ? value : null;
656 private static final class Regular extends NodeIdentifierWithPredicates {
657 private static final long serialVersionUID = 1L;
659 private final @NonNull Map<QName, Object> keyValues;
661 Regular(final QName node, final Map<QName, Object> keyValues) {
663 this.keyValues = requireNonNull(keyValues);
667 public Set<Entry<QName, Object>> entrySet() {
668 return keyValues.entrySet();
672 public Set<QName> keySet() {
673 return keyValues.keySet();
677 public boolean containsKey(final QName qname) {
678 return keyValues.containsKey(requireNonNull(qname));
682 public Collection<Object> values() {
683 return keyValues.values();
688 return keyValues.size();
692 public Map<QName, Object> asMap() {
697 Object keyValue(final QName qname) {
698 return keyValues.get(qname);
702 boolean equalMapping(final NodeIdentifierWithPredicates other) {
703 final Map<QName, Object> otherKeyValues = ((Regular) other).keyValues;
704 // TODO: benchmark to see if just calling equals() on the two maps is not faster
705 if (keyValues == otherKeyValues) {
708 if (keyValues.size() != otherKeyValues.size()) {
712 for (Entry<QName, Object> entry : entrySet()) {
713 final Object otherValue = otherKeyValues.get(entry.getKey());
714 if (otherValue == null || !Objects.deepEquals(entry.getValue(), otherValue)) {
723 private static final long serialVersionUID = -4787195606494761540L;
725 NodeIdentifierWithPredicates(final QName node) {
729 public static @NonNull NodeIdentifierWithPredicates of(final QName node) {
730 return new Regular(node, ImmutableMap.of());
733 public static @NonNull NodeIdentifierWithPredicates of(final QName node, final QName key, final Object value) {
734 return new Singleton(node, key, value);
737 public static @NonNull NodeIdentifierWithPredicates of(final QName node, final Entry<QName, Object> entry) {
738 return of(node, entry.getKey(), entry.getValue());
741 public static @NonNull NodeIdentifierWithPredicates of(final QName node, final Map<QName, Object> keyValues) {
742 return keyValues.size() == 1 ? of(keyValues, node)
743 // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
744 : new Regular(node, ImmutableOffsetMap.unorderedCopyOf(keyValues));
747 public static @NonNull NodeIdentifierWithPredicates of(final QName node,
748 final ImmutableOffsetMap<QName, Object> keyValues) {
749 return keyValues.size() == 1 ? of(keyValues, node) : new Regular(node, keyValues);
752 private static @NonNull NodeIdentifierWithPredicates of(final Map<QName, Object> keyValues, final QName node) {
753 return of(node, keyValues.entrySet().iterator().next());
757 * Return the set of predicates keys and values. Keys are guaranteeed to be unique.
759 * @return Predicate set.
761 public abstract @NonNull Set<Entry<QName, Object>> entrySet();
764 * Return the predicate key in the iteration order of {@link #entrySet()}.
766 * @return Predicate values.
768 public abstract @NonNull Set<QName> keySet();
771 * Determine whether a particular predicate key is present.
773 * @param key Predicate key
774 * @return True if the predicate is present, false otherwise
775 * @throws NullPointerException if {@code key} is null
777 public abstract boolean containsKey(QName key);
780 * Return the predicate values in the iteration order of {@link #entrySet()}.
782 * @return Predicate values.
784 public abstract @NonNull Collection<Object> values();
787 public final @Nullable Object getValue(final QName key) {
788 return keyValue(requireNonNull(key));
792 public final <T> @Nullable T getValue(final QName key, final Class<T> valueClass) {
793 return valueClass.cast(getValue(key));
797 * Return the number of predicates present.
799 * @return The number of predicates present.
801 public abstract int size();
804 * A Map-like view of this identifier's predicates. The view is expected to be stable and effectively-immutable.
806 * @return Map of predicates.
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 @NonNull T value;
855 public NodeWithValue(final QName node, final T value) {
857 this.value = requireNonNull(value);
860 public @NonNull 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 Mutable {
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}
1111 @NonNull YangInstanceIdentifier build();