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.invoke.MethodHandles;
27 import java.lang.invoke.VarHandle;
28 import java.lang.reflect.Array;
29 import java.util.AbstractMap.SimpleImmutableEntry;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Collection;
33 import java.util.Deque;
34 import java.util.Iterator;
35 import java.util.List;
37 import java.util.Map.Entry;
38 import java.util.Objects;
39 import java.util.Optional;
41 import java.util.function.Function;
42 import org.eclipse.jdt.annotation.NonNull;
43 import org.eclipse.jdt.annotation.Nullable;
44 import org.opendaylight.yangtools.concepts.HierarchicalIdentifier;
45 import org.opendaylight.yangtools.concepts.Immutable;
46 import org.opendaylight.yangtools.concepts.Mutable;
47 import org.opendaylight.yangtools.util.HashCodeBuilder;
48 import org.opendaylight.yangtools.util.ImmutableOffsetMap;
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: 7.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 HierarchicalIdentifier<YangInstanceIdentifier> {
84 private static final long serialVersionUID = 4L;
85 private static final VarHandle TO_STRING_CACHE;
89 TO_STRING_CACHE = MethodHandles.lookup().findVarHandle(YangInstanceIdentifier.class, "toStringCache",
91 } catch (NoSuchFieldException | IllegalAccessException e) {
92 throw new ExceptionInInitializerError(e);
97 private final int hash;
98 @SuppressWarnings("unused")
99 private transient String toStringCache = null;
101 // Package-private to prevent outside subclassing
102 YangInstanceIdentifier(final int hash) {
107 * Return An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual root of the YANG
110 * @return An empty YangInstanceIdentifier
112 public static @NonNull YangInstanceIdentifier empty() {
113 return FixedYangInstanceIdentifier.EMPTY_INSTANCE;
116 abstract @NonNull YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
118 abstract @Nullable Collection<PathArgument> tryPathArguments();
120 abstract @Nullable Collection<PathArgument> tryReversePathArguments();
123 * Check if this instance identifier has empty path arguments, e.g. it is
124 * empty and corresponds to {@link #empty()}.
126 * @return True if this instance identifier is empty, false otherwise.
128 public abstract boolean isEmpty();
131 * Return an optimized version of this identifier, useful when the identifier
132 * will be used very frequently.
134 * @return A optimized equivalent instance.
136 public abstract @NonNull YangInstanceIdentifier toOptimized();
139 * Return the conceptual parent {@link YangInstanceIdentifier}, which has
140 * one item less in {@link #getPathArguments()}.
142 * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #empty()}.
144 public abstract @Nullable YangInstanceIdentifier getParent();
147 * Return the conceptual parent {@link YangInstanceIdentifier}, which has one item less in
148 * {@link #getPathArguments()}.
150 * @return Parent {@link YangInstanceIdentifier}
151 * @throws VerifyException if this object is {@link #empty()}.
153 public abstract @NonNull YangInstanceIdentifier coerceParent();
156 * Return the ancestor {@link YangInstanceIdentifier} with a particular depth, e.g. number of path arguments.
158 * @param depth Ancestor depth
159 * @return Ancestor {@link YangInstanceIdentifier}
160 * @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
162 public abstract @NonNull YangInstanceIdentifier getAncestor(int depth);
165 * Returns an ordered iteration of path arguments.
167 * @return Immutable iteration of path arguments.
169 public abstract @NonNull List<PathArgument> getPathArguments();
172 * Returns an iterable of path arguments in reverse order. This is useful
173 * when walking up a tree organized this way.
175 * @return Immutable iterable of path arguments in reverse order.
177 public abstract @NonNull List<PathArgument> getReversePathArguments();
180 * Returns the last PathArgument. This is equivalent of iterating
181 * to the last element of the iterable returned by {@link #getPathArguments()}.
183 * @return The last past argument, or null if there are no PathArguments.
185 public abstract PathArgument getLastPathArgument();
187 public static @NonNull YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
188 if (Iterables.isEmpty(path)) {
192 final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
193 for (PathArgument a : path) {
197 return FixedYangInstanceIdentifier.create(path, hash.build());
200 public static @NonNull YangInstanceIdentifier create(final PathArgument pathArgument) {
201 return new FixedYangInstanceIdentifier(ImmutableList.of(pathArgument),
202 HashCodeBuilder.nextHashCode(1, pathArgument));
205 public static @NonNull YangInstanceIdentifier create(final PathArgument... path) {
206 // We are forcing a copy, since we cannot trust the user
207 return create(Arrays.asList(path));
211 * Create a {@link YangInstanceIdentifier} by taking a snapshot of provided path and iterating it backwards.
213 * @param pathTowardsRoot Path towards root
214 * @return A {@link YangInstanceIdentifier} instance
215 * @throws NullPointerException if {@code pathTowardsRoot} or any of its members is null
217 public static @NonNull YangInstanceIdentifier createReverse(final Deque<PathArgument> pathTowardsRoot) {
218 final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
219 pathTowardsRoot.size());
220 pathTowardsRoot.descendingIterator().forEachRemaining(builder::add);
221 return YangInstanceIdentifier.create(builder.build());
225 * Create a {@link YangInstanceIdentifier} by walking specified stack backwards and extracting path components
228 * @param stackTowardsRoot Stack towards root,
229 * @return A {@link YangInstanceIdentifier} instance
230 * @throws NullPointerException if {@code pathTowardsRoot} is null
232 public static <T> @NonNull YangInstanceIdentifier createReverse(final Deque<? extends T> stackTowardsRoot,
233 final Function<T, PathArgument> function) {
234 final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
235 stackTowardsRoot.size());
236 final Iterator<? extends T> it = stackTowardsRoot.descendingIterator();
237 while (it.hasNext()) {
238 builder.add(function.apply(it.next()));
240 return YangInstanceIdentifier.create(builder.build());
243 boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
244 return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
248 public boolean equals(final Object obj) {
252 if (!(obj instanceof YangInstanceIdentifier)) {
255 YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
256 if (this.hashCode() != obj.hashCode()) {
260 return pathArgumentsEqual(other);
264 * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments.
266 * @param name QName of {@link NodeIdentifier}
267 * @return Instance Identifier with additional path argument added to the end.
269 public final @NonNull YangInstanceIdentifier node(final QName name) {
270 return node(new NodeIdentifier(name));
274 * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments.
276 * @param arg Path argument which should be added to the end
277 * @return Instance Identifier with additional path argument added to the end.
279 public final @NonNull YangInstanceIdentifier node(final PathArgument arg) {
280 return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
284 * Get the relative path from an ancestor. This method attempts to perform
285 * the reverse of concatenating a base (ancestor) and a path.
288 * Ancestor against which the relative path should be calculated
289 * @return This object's relative path from parent, or Optional.absent() if
290 * the specified parent is not in fact an ancestor of this object.
292 public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
293 if (this == ancestor) {
294 return Optional.of(empty());
296 if (ancestor.isEmpty()) {
297 return Optional.of(this);
300 final Iterator<PathArgument> lit = getPathArguments().iterator();
301 final Iterator<PathArgument> oit = ancestor.getPathArguments().iterator();
304 while (oit.hasNext()) {
305 // Ancestor is not really an ancestor
306 if (!lit.hasNext() || !lit.next().equals(oit.next())) {
307 return Optional.empty();
314 return Optional.of(this);
316 if (!lit.hasNext()) {
317 return Optional.of(empty());
320 return Optional.of(createRelativeIdentifier(common));
324 public final boolean contains(final YangInstanceIdentifier other) {
329 checkArgument(other != null, "other should not be null");
330 final Iterator<PathArgument> lit = getPathArguments().iterator();
331 final Iterator<PathArgument> oit = other.getPathArguments().iterator();
333 while (lit.hasNext()) {
334 if (!oit.hasNext()) {
338 if (!lit.next().equals(oit.next())) {
347 public final String toString() {
349 * The toStringCache is safe, since the object contract requires
350 * immutability of the object and all objects referenced from this
352 * Used lists, maps are immutable. Path Arguments (elements) are also
353 * immutable, since the PathArgument contract requires immutability.
354 * The cache is thread-safe - if multiple computations occurs at the
355 * same time, cache will be overwritten with same result.
357 final String ret = (String) TO_STRING_CACHE.getAcquire(this);
358 return ret != null ? ret : loadToString();
361 private String loadToString() {
362 final StringBuilder builder = new StringBuilder("/");
363 PathArgument prev = null;
364 for (PathArgument argument : getPathArguments()) {
368 builder.append(argument.toRelativeString(prev));
372 final String ret = builder.toString();
373 final String witness = (String) TO_STRING_CACHE.compareAndExchangeRelease(this, null, ret);
374 return witness == null ? ret : witness;
378 public final int hashCode() {
380 * The caching is safe, since the object contract requires
381 * immutability of the object and all objects referenced from this
383 * Used lists, maps are immutable. Path Arguments (elements) are also
384 * immutable, since the PathArgument contract requires immutability.
389 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
390 justification = "https://github.com/spotbugs/spotbugs/issues/811")
391 private static int hashCode(final Object value) {
396 if (byte[].class.equals(value.getClass())) {
397 return Arrays.hashCode((byte[]) value);
400 if (value.getClass().isArray()) {
402 int length = Array.getLength(value);
403 for (int i = 0; i < length; i++) {
404 hash += Objects.hashCode(Array.get(value, i));
410 return Objects.hashCode(value);
413 final Object writeReplace() {
414 return new YIDv1(this);
417 // Static factories & helpers
420 * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied
423 * @param name QName of first node identifier
424 * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
426 public static @NonNull YangInstanceIdentifier of(final QName name) {
427 return create(new NodeIdentifier(name));
431 * Returns new builder for InstanceIdentifier with empty path arguments.
433 * @return new builder for InstanceIdentifier with empty path arguments.
435 public static @NonNull InstanceIdentifierBuilder builder() {
436 return new YangInstanceIdentifierBuilder();
440 * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
442 * @param origin InstanceIdentifier from which path arguments are copied.
443 * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
445 public static @NonNull InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
446 return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
450 * Path argument / component of InstanceIdentifier.
451 * Path argument uniquely identifies node in data tree on particular
455 * This interface itself is used as common parent for actual
456 * path arguments types and should not be implemented by user code.
459 * Path arguments SHOULD contain only minimum of information
460 * required to uniquely identify node on particular subtree level.
463 * For actual path arguments types see:
465 * <li>{@link NodeIdentifier} - Identifier of container or leaf
466 * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
467 * <li>{@link AugmentationIdentifier} - Identifier of augmentation
468 * <li>{@link NodeWithValue} - Identifier of leaf-list entry
471 public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
473 * Returns unique QName of data node as defined in YANG Schema, if available.
476 * @throws UnsupportedOperationException if node type is not applicable, for example in case of an augmentation.
478 @NonNull QName getNodeType();
481 * Return the string representation of this object for use in context
482 * provided by a previous object. This method can be implemented in
483 * terms of {@link #toString()}, but implementations are encourage to
484 * reuse any context already emitted by the previous object.
486 * @param previous Previous path argument
487 * @return String representation
489 @NonNull String toRelativeString(PathArgument previous);
492 private abstract static class AbstractPathArgument implements PathArgument {
493 private static final long serialVersionUID = -4546547994250849340L;
494 private final @NonNull QName nodeType;
495 private transient volatile int hashValue;
497 protected AbstractPathArgument(final QName nodeType) {
498 this.nodeType = requireNonNull(nodeType);
502 public final QName getNodeType() {
507 @SuppressWarnings("checkstyle:parameterName")
508 public int compareTo(final PathArgument o) {
509 return nodeType.compareTo(o.getNodeType());
512 protected int hashCodeImpl() {
513 return nodeType.hashCode();
517 public final int hashCode() {
519 return (local = hashValue) != 0 ? local : (hashValue = hashCodeImpl());
523 public boolean equals(final Object obj) {
527 if (obj == null || this.getClass() != obj.getClass()) {
531 return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
535 public String toString() {
536 return getNodeType().toString();
540 public String toRelativeString(final PathArgument previous) {
541 if (previous instanceof AbstractPathArgument) {
542 final QNameModule mod = previous.getNodeType().getModule();
543 if (getNodeType().getModule().equals(mod)) {
544 return getNodeType().getLocalName();
548 return getNodeType().toString();
551 abstract Object writeReplace();
555 * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
556 * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
558 public static final class NodeIdentifier extends AbstractPathArgument {
559 private static final long serialVersionUID = -2255888212390871347L;
560 private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
561 .build(new CacheLoader<QName, NodeIdentifier>() {
563 public NodeIdentifier load(final QName key) {
564 return new NodeIdentifier(key);
568 public NodeIdentifier(final QName node) {
573 * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
574 * instance cache, resulting in object reuse for equal inputs.
576 * @param node Node's QName
577 * @return A {@link NodeIdentifier}
579 public static @NonNull NodeIdentifier create(final QName node) {
580 return CACHE.getUnchecked(node);
584 Object writeReplace() {
585 return new NIv1(this);
590 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
593 public abstract static class NodeIdentifierWithPredicates extends AbstractPathArgument {
595 public static final class Singleton extends NodeIdentifierWithPredicates {
596 private static final long serialVersionUID = 1L;
598 private final @NonNull QName key;
599 private final @NonNull Object value;
601 Singleton(final QName node, final QName key, final Object value) {
603 this.key = requireNonNull(key);
604 this.value = requireNonNull(value);
608 public SingletonSet<Entry<QName, Object>> entrySet() {
609 return SingletonSet.of(singleEntry());
613 public SingletonSet<QName> keySet() {
614 return SingletonSet.of(key);
618 public boolean containsKey(final QName qname) {
619 return key.equals(requireNonNull(qname));
623 public SingletonSet<Object> values() {
624 return SingletonSet.of(value);
633 public ImmutableMap<QName, Object> asMap() {
634 return ImmutableMap.of(key, value);
638 * Return the single entry contained in this object. This is equivalent to
639 * {@code entrySet().iterator().next()}.
641 * @return A single entry.
643 public @NonNull Entry<QName, Object> singleEntry() {
644 return new SimpleImmutableEntry<>(key, value);
648 boolean equalMapping(final NodeIdentifierWithPredicates other) {
649 final Singleton single = (Singleton) other;
650 return key.equals(single.key) && Objects.deepEquals(value, single.value);
654 Object keyValue(final QName qname) {
655 return key.equals(qname) ? value : null;
659 private static final class Regular extends NodeIdentifierWithPredicates {
660 private static final long serialVersionUID = 1L;
662 private final @NonNull Map<QName, Object> keyValues;
664 Regular(final QName node, final Map<QName, Object> keyValues) {
666 this.keyValues = requireNonNull(keyValues);
670 public Set<Entry<QName, Object>> entrySet() {
671 return keyValues.entrySet();
675 public Set<QName> keySet() {
676 return keyValues.keySet();
680 public boolean containsKey(final QName qname) {
681 return keyValues.containsKey(requireNonNull(qname));
685 public Collection<Object> values() {
686 return keyValues.values();
691 return keyValues.size();
695 public Map<QName, Object> asMap() {
700 Object keyValue(final QName qname) {
701 return keyValues.get(qname);
705 boolean equalMapping(final NodeIdentifierWithPredicates other) {
706 final Map<QName, Object> otherKeyValues = ((Regular) other).keyValues;
707 // TODO: benchmark to see if just calling equals() on the two maps is not faster
708 if (keyValues == otherKeyValues) {
711 if (keyValues.size() != otherKeyValues.size()) {
715 for (Entry<QName, Object> entry : entrySet()) {
716 final Object otherValue = otherKeyValues.get(entry.getKey());
717 if (otherValue == null || !Objects.deepEquals(entry.getValue(), otherValue)) {
726 private static final long serialVersionUID = -4787195606494761540L;
728 NodeIdentifierWithPredicates(final QName node) {
732 public static @NonNull NodeIdentifierWithPredicates of(final QName node) {
733 return new Regular(node, ImmutableMap.of());
736 public static @NonNull NodeIdentifierWithPredicates of(final QName node, final QName key, final Object value) {
737 return new Singleton(node, key, value);
740 public static @NonNull NodeIdentifierWithPredicates of(final QName node, final Entry<QName, Object> entry) {
741 return of(node, entry.getKey(), entry.getValue());
744 public static @NonNull NodeIdentifierWithPredicates of(final QName node, final Map<QName, Object> keyValues) {
745 return keyValues.size() == 1 ? of(keyValues, node)
746 // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
747 : new Regular(node, ImmutableOffsetMap.unorderedCopyOf(keyValues));
750 public static @NonNull NodeIdentifierWithPredicates of(final QName node,
751 final ImmutableOffsetMap<QName, Object> keyValues) {
752 return keyValues.size() == 1 ? of(keyValues, node) : new Regular(node, keyValues);
755 private static @NonNull NodeIdentifierWithPredicates of(final Map<QName, Object> keyValues, final QName node) {
756 return of(node, keyValues.entrySet().iterator().next());
760 * Return the set of predicates keys and values. Keys are guaranteeed to be unique.
762 * @return Predicate set.
764 public abstract @NonNull Set<Entry<QName, Object>> entrySet();
767 * Return the predicate key in the iteration order of {@link #entrySet()}.
769 * @return Predicate values.
771 public abstract @NonNull Set<QName> keySet();
774 * Determine whether a particular predicate key is present.
776 * @param key Predicate key
777 * @return True if the predicate is present, false otherwise
778 * @throws NullPointerException if {@code key} is null
780 public abstract boolean containsKey(QName key);
783 * Return the predicate values in the iteration order of {@link #entrySet()}.
785 * @return Predicate values.
787 public abstract @NonNull Collection<Object> values();
790 public final @Nullable Object getValue(final QName key) {
791 return keyValue(requireNonNull(key));
795 public final <T> @Nullable T getValue(final QName key, final Class<T> valueClass) {
796 return valueClass.cast(getValue(key));
800 * Return the number of predicates present.
802 * @return The number of predicates present.
804 public abstract int size();
807 * A Map-like view of this identifier's predicates. The view is expected to be stable and effectively-immutable.
809 * @return Map of predicates.
812 public abstract @NonNull Map<QName, Object> asMap();
815 protected final int hashCodeImpl() {
816 int result = 31 * super.hashCodeImpl();
817 for (Entry<QName, Object> entry : entrySet()) {
818 result += entry.getKey().hashCode() + YangInstanceIdentifier.hashCode(entry.getValue());
824 @SuppressWarnings("checkstyle:equalsHashCode")
825 public final boolean equals(final Object obj) {
826 return super.equals(obj) && equalMapping((NodeIdentifierWithPredicates) obj);
829 abstract boolean equalMapping(NodeIdentifierWithPredicates other);
831 abstract @Nullable Object keyValue(@NonNull QName qname);
834 public final String toString() {
835 return super.toString() + '[' + asMap() + ']';
839 public final String toRelativeString(final PathArgument previous) {
840 return super.toRelativeString(previous) + '[' + asMap() + ']';
844 final Object writeReplace() {
845 return new NIPv2(this);
850 * Simple path argument identifying a {@link LeafSetEntryNode} leaf
853 public static final class NodeWithValue<T> extends AbstractPathArgument {
854 private static final long serialVersionUID = -3637456085341738431L;
856 private final @NonNull T value;
858 public NodeWithValue(final QName node, final T value) {
860 this.value = requireNonNull(value);
863 public @NonNull T getValue() {
868 protected int hashCodeImpl() {
869 return 31 * super.hashCodeImpl() + YangInstanceIdentifier.hashCode(value);
873 @SuppressWarnings("checkstyle:equalsHashCode")
874 public boolean equals(final Object obj) {
875 if (!super.equals(obj)) {
878 final NodeWithValue<?> other = (NodeWithValue<?>) obj;
879 return Objects.deepEquals(value, other.value);
883 public String toString() {
884 return super.toString() + '[' + value + ']';
888 public String toRelativeString(final PathArgument previous) {
889 return super.toRelativeString(previous) + '[' + value + ']';
893 Object writeReplace() {
894 return new NIVv1(this);
899 * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode}
900 * node in particular subtree.
903 * Augmentation is uniquely identified by set of all possible child nodes.
905 * to identify instance of augmentation,
906 * since RFC6020 states that <code>augment</code> that augment
907 * statement must not add multiple nodes from same namespace
908 * / module to the target node.
910 * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
912 public static final class AugmentationIdentifier implements PathArgument {
913 private static final long serialVersionUID = -8122335594681936939L;
915 private static final LoadingCache<ImmutableSet<QName>, AugmentationIdentifier> CACHE = CacheBuilder.newBuilder()
916 .weakValues().build(new CacheLoader<ImmutableSet<QName>, AugmentationIdentifier>() {
918 public AugmentationIdentifier load(final ImmutableSet<QName> key) {
919 return new AugmentationIdentifier(key);
923 private final @NonNull ImmutableSet<QName> childNames;
926 public QName getNodeType() {
927 // This should rather throw exception than return always null
928 throw new UnsupportedOperationException("Augmentation node has no QName");
932 * Construct new augmentation identifier using supplied set of possible
936 * Set of possible child nodes.
938 public AugmentationIdentifier(final ImmutableSet<QName> childNames) {
939 this.childNames = requireNonNull(childNames);
943 * Construct new augmentation identifier using supplied set of possible
947 * Set of possible child nodes.
949 public AugmentationIdentifier(final Set<QName> childNames) {
950 this.childNames = ImmutableSet.copyOf(childNames);
954 * Return an AugmentationIdentifier for a particular set of QNames. Unlike the constructor, this factory method
955 * uses a global instance cache, resulting in object reuse for equal inputs.
957 * @param childNames Set of possible child nodes
958 * @return An {@link AugmentationIdentifier}
960 public static @NonNull AugmentationIdentifier create(final ImmutableSet<QName> childNames) {
961 return CACHE.getUnchecked(childNames);
965 * Return an AugmentationIdentifier for a particular set of QNames. Unlike the constructor, this factory method
966 * uses a global instance cache, resulting in object reuse for equal inputs.
968 * @param childNames Set of possible child nodes
969 * @return An {@link AugmentationIdentifier}
971 public static @NonNull AugmentationIdentifier create(final Set<QName> childNames) {
972 final AugmentationIdentifier existing = CACHE.getIfPresent(childNames);
973 return existing != null ? existing : create(ImmutableSet.copyOf(childNames));
977 * Returns set of all possible child nodes.
979 * @return set of all possible child nodes.
981 public @NonNull Set<QName> getPossibleChildNames() {
986 public String toString() {
987 return "AugmentationIdentifier{" + "childNames=" + childNames + '}';
991 public String toRelativeString(final PathArgument previous) {
996 public boolean equals(final Object obj) {
1000 if (!(obj instanceof AugmentationIdentifier)) {
1004 AugmentationIdentifier that = (AugmentationIdentifier) obj;
1005 return childNames.equals(that.childNames);
1009 public int hashCode() {
1010 return childNames.hashCode();
1014 @SuppressWarnings("checkstyle:parameterName")
1015 public int compareTo(final PathArgument o) {
1016 if (!(o instanceof AugmentationIdentifier)) {
1019 AugmentationIdentifier other = (AugmentationIdentifier) o;
1020 Set<QName> otherChildNames = other.getPossibleChildNames();
1021 int thisSize = childNames.size();
1022 int otherSize = otherChildNames.size();
1023 if (thisSize == otherSize) {
1024 // Quick Set-based comparison
1025 if (childNames.equals(otherChildNames)) {
1029 // We already know the sets are not equal, but have equal size, hence the sets differ in their elements,
1030 // but potentially share a common set of elements. The most consistent way of comparing them is using
1031 // total ordering defined by QName's compareTo. Hence convert both sets to lists ordered
1032 // by QName.compareTo() and decide on the first differing element.
1033 final List<QName> diff = new ArrayList<>(Sets.symmetricDifference(childNames, otherChildNames));
1034 verify(!diff.isEmpty(), "Augmentation identifiers %s and %s report no difference", this, o);
1035 diff.sort(QName::compareTo);
1036 return childNames.contains(diff.get(0)) ? -1 : 1;
1037 } else if (thisSize < otherSize) {
1044 private Object writeReplace() {
1045 return new AIv1(this);
1050 * Fluent Builder of Instance Identifier instances.
1052 public interface InstanceIdentifierBuilder extends Mutable {
1054 * Adds a {@link PathArgument} to path arguments of resulting instance identifier.
1056 * @param arg A {@link PathArgument} to be added
1057 * @return this builder
1059 @NonNull InstanceIdentifierBuilder node(PathArgument arg);
1062 * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
1064 * @param nodeType QName of {@link NodeIdentifier} which will be added
1065 * @return this builder
1067 @NonNull InstanceIdentifierBuilder node(QName nodeType);
1070 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting
1071 * instance identifier.
1073 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
1074 * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
1075 * @return this builder
1077 @NonNull InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
1080 * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
1082 * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
1083 * @param key QName of key which will be added
1084 * @param value value of key which will be added
1085 * @return this builder
1087 @NonNull InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
1090 * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
1092 * @param args {@link PathArgument}s to be added
1093 * @return this builder
1094 * @throws NullPointerException if any of the arguments is null
1096 @NonNull InstanceIdentifierBuilder append(Collection<? extends PathArgument> args);
1099 * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
1101 * @param args {@link PathArgument}s to be added
1102 * @return this builder
1103 * @throws NullPointerException if any of the arguments is null
1105 default @NonNull InstanceIdentifierBuilder append(final PathArgument... args) {
1106 return append(Arrays.asList(args));
1110 * Builds an {@link YangInstanceIdentifier} with path arguments from this builder.
1112 * @return {@link YangInstanceIdentifier}
1114 @NonNull YangInstanceIdentifier build();