Create YangInstanceIdentifier serialized form
[yangtools.git] / yang / yang-data-api / src / main / java / org / opendaylight / yangtools / yang / data / api / YangInstanceIdentifier.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.data.api;
9
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;
13
14 import com.google.common.annotations.Beta;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.cache.CacheLoader;
17 import com.google.common.cache.LoadingCache;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.ImmutableSet;
21 import com.google.common.collect.Iterables;
22 import com.google.common.collect.Sets;
23 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
24 import java.io.Serializable;
25 import java.lang.reflect.Array;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Deque;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.Objects;
35 import java.util.Optional;
36 import java.util.Set;
37 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
38 import java.util.function.Function;
39 import org.eclipse.jdt.annotation.NonNull;
40 import org.eclipse.jdt.annotation.Nullable;
41 import org.opendaylight.yangtools.concepts.Builder;
42 import org.opendaylight.yangtools.concepts.Immutable;
43 import org.opendaylight.yangtools.concepts.Path;
44 import org.opendaylight.yangtools.util.HashCodeBuilder;
45 import org.opendaylight.yangtools.util.ImmutableOffsetMap;
46 import org.opendaylight.yangtools.util.SharedSingletonMap;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.common.QNameModule;
49 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
50
51 /**
52  * Unique identifier of a particular node instance in the data tree.
53  *
54  * <p>
55  * Java representation of YANG Built-in type <code>instance-identifier</code>,
56  * which conceptually is XPath expression minimized to uniquely identify element
57  * in data tree which conforms to constraints maintained by YANG Model,
58  * effectively this makes Instance Identifier a path to element in data tree.
59  *
60  * <p>
61  * Constraints put in YANG specification on instance-identifier allowed it to be
62  * effectively represented in Java and it's evaluation does not require
63  * full-blown XPath processor.
64  *
65  * <p>
66  * <h3>Path Arguments</h3>
67  * Path to the node represented in instance identifier consists of
68  * {@link PathArgument} which carries necessary information to uniquely identify
69  * node on particular level in the subtree.
70  *
71  * <ul>
72  * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
73  * <code>0..1</code> in particular subtree in data tree.</li>
74  * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item),
75  * which has cardinality <code>0..n</code>.</li>
76  * <li>{@link NodeWithValue} - Identifier of instance <code>leaf</code> node or
77  * <code>leaf-list</code> node.</li>
78  * <li>{@link AugmentationIdentifier} - Identifier of instance of
79  * <code>augmentation</code> node.</li>
80  * </ul>
81  *
82  * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
83  */
84 // FIXME: 4.0.0: this concept needs to be moved to yang-common, as parser components need the ability to refer
85 //               to data nodes -- most notably XPath expressions and {@code default} statement arguments need to be able
86 //               to represent these.
87 // FIXME: FixedYangInstanceIdentifier needs YangInstanceIdentifier initialized, but that includes initializing
88 //        this field. Figure out a way out of this pickle.
89 @SuppressFBWarnings("IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION")
90 public abstract class YangInstanceIdentifier implements Path<YangInstanceIdentifier>, Immutable, Serializable {
91     /**
92      * An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual root of the YANG namespace.
93      */
94     public static final YangInstanceIdentifier EMPTY = FixedYangInstanceIdentifier.EMPTY_INSTANCE;
95
96     private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, String> TOSTRINGCACHE_UPDATER =
97             AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, String.class, "toStringCache");
98     private static final long serialVersionUID = 4L;
99
100     private final int hash;
101     private transient volatile String toStringCache = null;
102
103     // Package-private to prevent outside subclassing
104     YangInstanceIdentifier(final int hash) {
105         this.hash = hash;
106     }
107
108     abstract @NonNull YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
109
110     abstract @Nullable Collection<PathArgument> tryPathArguments();
111
112     abstract @Nullable Collection<PathArgument> tryReversePathArguments();
113
114     /**
115      * Check if this instance identifier has empty path arguments, e.g. it is
116      * empty and corresponds to {@link #EMPTY}.
117      *
118      * @return True if this instance identifier is empty, false otherwise.
119      */
120     public abstract boolean isEmpty();
121
122     /**
123      * Return an optimized version of this identifier, useful when the identifier
124      * will be used very frequently.
125      *
126      * @return A optimized equivalent instance.
127      */
128     @Beta
129     public abstract YangInstanceIdentifier toOptimized();
130
131     /**
132      * Return the conceptual parent {@link YangInstanceIdentifier}, which has
133      * one item less in {@link #getPathArguments()}.
134      *
135      * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #EMPTY}.
136      */
137     public abstract @Nullable YangInstanceIdentifier getParent();
138
139     /**
140      * Return the ancestor {@link YangInstanceIdentifier} with a particular depth, e.g. number of path arguments.
141      *
142      * @param depth Ancestor depth
143      * @return Ancestor {@link YangInstanceIdentifier}
144      * @throws IllegalArgumentException if the specified depth is negative or is greater than the depth of this object.
145      */
146     public abstract @NonNull YangInstanceIdentifier getAncestor(int depth);
147
148     /**
149      * Returns an ordered iteration of path arguments.
150      *
151      * @return Immutable iteration of path arguments.
152      */
153     public abstract List<PathArgument> getPathArguments();
154
155     /**
156      * Returns an iterable of path arguments in reverse order. This is useful
157      * when walking up a tree organized this way.
158      *
159      * @return Immutable iterable of path arguments in reverse order.
160      */
161     public abstract List<PathArgument> getReversePathArguments();
162
163     /**
164      * Returns the last PathArgument. This is equivalent of iterating
165      * to the last element of the iterable returned by {@link #getPathArguments()}.
166      *
167      * @return The last past argument, or null if there are no PathArguments.
168      */
169     public abstract PathArgument getLastPathArgument();
170
171     public static YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
172         if (Iterables.isEmpty(path)) {
173             return EMPTY;
174         }
175
176         final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
177         for (PathArgument a : path) {
178             hash.addArgument(a);
179         }
180
181         return FixedYangInstanceIdentifier.create(path, hash.build());
182     }
183
184     public static YangInstanceIdentifier create(final PathArgument... path) {
185         // We are forcing a copy, since we cannot trust the user
186         return create(Arrays.asList(path));
187     }
188
189     /**
190      * Create a {@link YangInstanceIdentifier} by taking a snapshot of provided path and iterating it backwards.
191      *
192      * @param pathTowardsRoot Path towards root
193      * @return A {@link YangInstanceIdentifier} instance
194      * @throws NullPointerException if {@code pathTowardsRoot} or any of its members is null
195      */
196     public static YangInstanceIdentifier createReverse(final Deque<PathArgument> pathTowardsRoot) {
197         final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
198             pathTowardsRoot.size());
199         pathTowardsRoot.descendingIterator().forEachRemaining(builder::add);
200         return YangInstanceIdentifier.create(builder.build());
201     }
202
203     /**
204      * Create a {@link YangInstanceIdentifier} by walking specified stack backwards and extracting path components
205      * from it.
206      *
207      * @param stackTowardsRoot Stack towards root,
208      * @return A {@link YangInstanceIdentifier} instance
209      * @throws NullPointerException if {@code pathTowardsRoot} is null
210      */
211     public static <T> YangInstanceIdentifier createReverse(final Deque<? extends T> stackTowardsRoot,
212             final Function<T, PathArgument> function) {
213         final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
214             stackTowardsRoot.size());
215         final Iterator<? extends T> it = stackTowardsRoot.descendingIterator();
216         while (it.hasNext()) {
217             builder.add(function.apply(it.next()));
218         }
219         return YangInstanceIdentifier.create(builder.build());
220     }
221
222     boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
223         return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
224     }
225
226     @Override
227     public boolean equals(final Object obj) {
228         if (this == obj) {
229             return true;
230         }
231         if (!(obj instanceof YangInstanceIdentifier)) {
232             return false;
233         }
234         YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
235         if (this.hashCode() != obj.hashCode()) {
236             return false;
237         }
238
239         return pathArgumentsEqual(other);
240     }
241
242     /**
243      * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments.
244      *
245      * @param name QName of {@link NodeIdentifier}
246      * @return Instance Identifier with additional path argument added to the end.
247      */
248     public final YangInstanceIdentifier node(final QName name) {
249         return node(new NodeIdentifier(name));
250     }
251
252     /**
253      * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments.
254      *
255      * @param arg Path argument which should be added to the end
256      * @return Instance Identifier with additional path argument added to the end.
257      */
258     public final YangInstanceIdentifier node(final PathArgument arg) {
259         return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
260     }
261
262     /**
263      * Get the relative path from an ancestor. This method attempts to perform
264      * the reverse of concatenating a base (ancestor) and a path.
265      *
266      * @param ancestor
267      *            Ancestor against which the relative path should be calculated
268      * @return This object's relative path from parent, or Optional.absent() if
269      *         the specified parent is not in fact an ancestor of this object.
270      */
271     public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
272         if (this == ancestor) {
273             return Optional.of(EMPTY);
274         }
275         if (ancestor.isEmpty()) {
276             return Optional.of(this);
277         }
278
279         final Iterator<PathArgument> lit = getPathArguments().iterator();
280         final Iterator<PathArgument> oit = ancestor.getPathArguments().iterator();
281         int common = 0;
282
283         while (oit.hasNext()) {
284             // Ancestor is not really an ancestor
285             if (!lit.hasNext() || !lit.next().equals(oit.next())) {
286                 return Optional.empty();
287             }
288
289             ++common;
290         }
291
292         if (common == 0) {
293             return Optional.of(this);
294         }
295         if (!lit.hasNext()) {
296             return Optional.of(EMPTY);
297         }
298
299         return Optional.of(createRelativeIdentifier(common));
300     }
301
302     @Override
303     public final boolean contains(final YangInstanceIdentifier other) {
304         if (this == other) {
305             return true;
306         }
307
308         checkArgument(other != null, "other should not be null");
309         final Iterator<PathArgument> lit = getPathArguments().iterator();
310         final Iterator<PathArgument> oit = other.getPathArguments().iterator();
311
312         while (lit.hasNext()) {
313             if (!oit.hasNext()) {
314                 return false;
315             }
316
317             if (!lit.next().equals(oit.next())) {
318                 return false;
319             }
320         }
321
322         return true;
323     }
324
325     @Override
326     public final String toString() {
327         /*
328          * The toStringCache is safe, since the object contract requires
329          * immutability of the object and all objects referenced from this
330          * object.
331          * Used lists, maps are immutable. Path Arguments (elements) are also
332          * immutable, since the PathArgument contract requires immutability.
333          * The cache is thread-safe - if multiple computations occurs at the
334          * same time, cache will be overwritten with same result.
335          */
336         String ret = toStringCache;
337         if (ret == null) {
338             final StringBuilder builder = new StringBuilder("/");
339             PathArgument prev = null;
340             for (PathArgument argument : getPathArguments()) {
341                 if (prev != null) {
342                     builder.append('/');
343                 }
344                 builder.append(argument.toRelativeString(prev));
345                 prev = argument;
346             }
347
348             ret = builder.toString();
349             TOSTRINGCACHE_UPDATER.lazySet(this, ret);
350         }
351         return ret;
352     }
353
354     @Override
355     public final int hashCode() {
356         /*
357          * The caching is safe, since the object contract requires
358          * immutability of the object and all objects referenced from this
359          * object.
360          * Used lists, maps are immutable. Path Arguments (elements) are also
361          * immutable, since the PathArgument contract requires immutability.
362          */
363         return hash;
364     }
365
366     private static int hashCode(final Object value) {
367         if (value == null) {
368             return 0;
369         }
370
371         if (byte[].class.equals(value.getClass())) {
372             return Arrays.hashCode((byte[]) value);
373         }
374
375         if (value.getClass().isArray()) {
376             int hash = 0;
377             int length = Array.getLength(value);
378             for (int i = 0; i < length; i++) {
379                 hash += Objects.hashCode(Array.get(value, i));
380             }
381
382             return hash;
383         }
384
385         return Objects.hashCode(value);
386     }
387
388     final Object writeReplace() {
389         return new YIDv1(this);
390     }
391
392     // Static factories & helpers
393
394     /**
395      * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied
396      * QName.
397      *
398      * @param name QName of first node identifier
399      * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
400      */
401     public static YangInstanceIdentifier of(final QName name) {
402         return create(new NodeIdentifier(name));
403     }
404
405     /**
406      * Returns new builder for InstanceIdentifier with empty path arguments.
407      *
408      * @return new builder for InstanceIdentifier with empty path arguments.
409      */
410     public static InstanceIdentifierBuilder builder() {
411         return new YangInstanceIdentifierBuilder();
412     }
413
414     /**
415      * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
416      *
417      * @param origin InstanceIdentifier from which path arguments are copied.
418      * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
419      */
420     public static InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
421         return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
422     }
423
424     /**
425      * Path argument / component of InstanceIdentifier.
426      * Path argument uniquely identifies node in data tree on particular
427      * level.
428      *
429      * <p>
430      * This interface itself is used as common parent for actual
431      * path arguments types and should not be implemented by user code.
432      *
433      * <p>
434      * Path arguments SHOULD contain only minimum of information
435      * required to uniquely identify node on particular subtree level.
436      *
437      * <p>
438      * For actual path arguments types see:
439      * <ul>
440      * <li>{@link NodeIdentifier} - Identifier of container or leaf
441      * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
442      * <li>{@link AugmentationIdentifier} - Identifier of augmentation
443      * <li>{@link NodeWithValue} - Identifier of leaf-list entry
444      * </ul>
445      */
446     public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
447         /**
448          * If applicable returns unique QName of data node as defined in YANG
449          * Schema.
450          *
451          * <p>
452          * This method may return null, if the corresponding schema node, does
453          * not have QName associated, such as in cases of augmentations.
454          *
455          * @return Node type
456          */
457         QName getNodeType();
458
459         /**
460          * Return the string representation of this object for use in context
461          * provided by a previous object. This method can be implemented in
462          * terms of {@link #toString()}, but implementations are encourage to
463          * reuse any context already emitted by the previous object.
464          *
465          * @param previous Previous path argument
466          * @return String representation
467          */
468         String toRelativeString(PathArgument previous);
469     }
470
471     private abstract static class AbstractPathArgument implements PathArgument {
472         private static final long serialVersionUID = -4546547994250849340L;
473         private final QName nodeType;
474         private transient int hashValue;
475         private transient volatile boolean hashGuard = false;
476
477         protected AbstractPathArgument(final QName nodeType) {
478             this.nodeType = requireNonNull(nodeType);
479         }
480
481         @Override
482         public final QName getNodeType() {
483             return nodeType;
484         }
485
486         @Override
487         @SuppressWarnings("checkstyle:parameterName")
488         public int compareTo(final PathArgument o) {
489             return nodeType.compareTo(o.getNodeType());
490         }
491
492         protected int hashCodeImpl() {
493             return 31 + getNodeType().hashCode();
494         }
495
496         @Override
497         public final int hashCode() {
498             if (!hashGuard) {
499                 hashValue = hashCodeImpl();
500                 hashGuard = true;
501             }
502
503             return hashValue;
504         }
505
506         @Override
507         public boolean equals(final Object obj) {
508             if (this == obj) {
509                 return true;
510             }
511             if (obj == null || this.getClass() != obj.getClass()) {
512                 return false;
513             }
514
515             return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
516         }
517
518         @Override
519         public String toString() {
520             return getNodeType().toString();
521         }
522
523         @Override
524         public String toRelativeString(final PathArgument previous) {
525             if (previous instanceof AbstractPathArgument) {
526                 final QNameModule mod = previous.getNodeType().getModule();
527                 if (getNodeType().getModule().equals(mod)) {
528                     return getNodeType().getLocalName();
529                 }
530             }
531
532             return getNodeType().toString();
533         }
534
535         abstract Object writeReplace();
536     }
537
538     /**
539      * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
540      * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
541      */
542     public static final class NodeIdentifier extends AbstractPathArgument {
543         private static final long serialVersionUID = -2255888212390871347L;
544         private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
545                 .build(new CacheLoader<QName, NodeIdentifier>() {
546                     @Override
547                     public NodeIdentifier load(final QName key) {
548                         return new NodeIdentifier(key);
549                     }
550                 });
551
552         public NodeIdentifier(final QName node) {
553             super(node);
554         }
555
556         /**
557          * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
558          * instance cache, resulting in object reuse for equal inputs.
559          *
560          * @param node Node's QName
561          * @return A {@link NodeIdentifier}
562          */
563         public static NodeIdentifier create(final QName node) {
564             return CACHE.getUnchecked(node);
565         }
566
567         @Override
568         Object writeReplace() {
569             return new NIv1(this);
570         }
571     }
572
573     /**
574      * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
575      * overall data tree.
576      */
577     public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
578         private static final long serialVersionUID = -4787195606494761540L;
579
580         private final Map<QName, Object> keyValues;
581
582         // Exposed for NIPv1
583         NodeIdentifierWithPredicates(final Map<QName, Object> keyValues, final QName node) {
584             super(node);
585             this.keyValues = requireNonNull(keyValues);
586         }
587
588         public NodeIdentifierWithPredicates(final QName node) {
589             super(node);
590             this.keyValues = ImmutableMap.of();
591         }
592
593         public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
594             super(node);
595             // Retains ImmutableMap for empty maps. For larger sizes uses a shared key set.
596             this.keyValues = ImmutableOffsetMap.unorderedCopyOf(keyValues);
597         }
598
599         public NodeIdentifierWithPredicates(final QName node, final ImmutableOffsetMap<QName, Object> keyValues) {
600             this(keyValues, node);
601         }
602
603         public NodeIdentifierWithPredicates(final QName node, final SharedSingletonMap<QName, Object> keyValues) {
604             this(keyValues, node);
605         }
606
607         public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
608             this(node, SharedSingletonMap.unorderedOf(key, value));
609         }
610
611         public Map<QName, Object> getKeyValues() {
612             return keyValues;
613         }
614
615         @Override
616         protected int hashCodeImpl() {
617             final int prime = 31;
618             int result = super.hashCodeImpl();
619             result = prime * result;
620
621             for (Entry<QName, Object> entry : keyValues.entrySet()) {
622                 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
623             }
624             return result;
625         }
626
627         @Override
628         @SuppressWarnings("checkstyle:equalsHashCode")
629         public boolean equals(final Object obj) {
630             if (!super.equals(obj)) {
631                 return false;
632             }
633
634             final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
635
636             // TODO: benchmark to see if just calling equals() on the two maps is not faster
637             if (keyValues == otherKeyValues) {
638                 return true;
639             }
640             if (keyValues.size() != otherKeyValues.size()) {
641                 return false;
642             }
643
644             for (Entry<QName, Object> entry : keyValues.entrySet()) {
645                 if (!otherKeyValues.containsKey(entry.getKey())
646                         || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
647
648                     return false;
649                 }
650             }
651
652             return true;
653         }
654
655         @Override
656         public String toString() {
657             return super.toString() + '[' + keyValues + ']';
658         }
659
660         @Override
661         public String toRelativeString(final PathArgument previous) {
662             return super.toRelativeString(previous) + '[' + keyValues + ']';
663         }
664
665         @Override
666         Object writeReplace() {
667             return new NIPv1(this);
668         }
669     }
670
671     /**
672      * Simple path argument identifying a {@link LeafSetEntryNode} leaf
673      * overall data tree.
674      */
675     public static final class NodeWithValue<T> extends AbstractPathArgument {
676         private static final long serialVersionUID = -3637456085341738431L;
677
678         private final T value;
679
680         public NodeWithValue(final QName node, final T value) {
681             super(node);
682             this.value = value;
683         }
684
685         public T getValue() {
686             return value;
687         }
688
689         @Override
690         protected int hashCodeImpl() {
691             final int prime = 31;
692             int result = super.hashCodeImpl();
693             result = prime * result + YangInstanceIdentifier.hashCode(value);
694             return result;
695         }
696
697         @Override
698         @SuppressWarnings("checkstyle:equalsHashCode")
699         public boolean equals(final Object obj) {
700             if (!super.equals(obj)) {
701                 return false;
702             }
703             final NodeWithValue<?> other = (NodeWithValue<?>) obj;
704             return Objects.deepEquals(value, other.value);
705         }
706
707         @Override
708         public String toString() {
709             return super.toString() + '[' + value + ']';
710         }
711
712         @Override
713         public String toRelativeString(final PathArgument previous) {
714             return super.toRelativeString(previous) + '[' + value + ']';
715         }
716
717         @Override
718         Object writeReplace() {
719             return new NIVv1(this);
720         }
721     }
722
723     /**
724      * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode}
725      * node in particular subtree.
726      *
727      * <p>
728      * Augmentation is uniquely identified by set of all possible child nodes.
729      * This is possible
730      * to identify instance of augmentation,
731      * since RFC6020 states that <code>augment</code> that augment
732      * statement must not add multiple nodes from same namespace
733      * / module to the target node.
734      *
735      * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
736      */
737     public static final class AugmentationIdentifier implements PathArgument {
738         private static final long serialVersionUID = -8122335594681936939L;
739         private final ImmutableSet<QName> childNames;
740
741         @Override
742         public QName getNodeType() {
743             // This should rather throw exception than return always null
744             throw new UnsupportedOperationException("Augmentation node has no QName");
745         }
746
747         /**
748          * Construct new augmentation identifier using supplied set of possible
749          * child nodes.
750          *
751          * @param childNames
752          *            Set of possible child nodes.
753          */
754         public AugmentationIdentifier(final Set<QName> childNames) {
755             this.childNames = ImmutableSet.copyOf(childNames);
756         }
757
758         /**
759          * Returns set of all possible child nodes.
760          *
761          * @return set of all possible child nodes.
762          */
763         public Set<QName> getPossibleChildNames() {
764             return childNames;
765         }
766
767         @Override
768         public String toString() {
769             return "AugmentationIdentifier{" + "childNames=" + childNames + '}';
770         }
771
772         @Override
773         public String toRelativeString(final PathArgument previous) {
774             return toString();
775         }
776
777         @Override
778         public boolean equals(final Object obj) {
779             if (this == obj) {
780                 return true;
781             }
782             if (!(obj instanceof AugmentationIdentifier)) {
783                 return false;
784             }
785
786             AugmentationIdentifier that = (AugmentationIdentifier) obj;
787             return childNames.equals(that.childNames);
788         }
789
790         @Override
791         public int hashCode() {
792             return childNames.hashCode();
793         }
794
795         @Override
796         @SuppressWarnings("checkstyle:parameterName")
797         public int compareTo(final PathArgument o) {
798             if (!(o instanceof AugmentationIdentifier)) {
799                 return -1;
800             }
801             AugmentationIdentifier other = (AugmentationIdentifier) o;
802             Set<QName> otherChildNames = other.getPossibleChildNames();
803             int thisSize = childNames.size();
804             int otherSize = otherChildNames.size();
805             if (thisSize == otherSize) {
806                 // Quick Set-based comparison
807                 if (childNames.equals(otherChildNames)) {
808                     return 0;
809                 }
810
811                 // We already know the sets are not equal, but have equal size, hence the sets differ in their elements,
812                 // but potentially share a common set of elements. The most consistent way of comparing them is using
813                 // total ordering defined by QName's compareTo. Hence convert both sets to lists ordered
814                 // by QName.compareTo() and decide on the first differing element.
815                 final List<QName> diff = new ArrayList<>(Sets.symmetricDifference(childNames, otherChildNames));
816                 verify(!diff.isEmpty(), "Augmentation identifiers %s and %s report no difference", this, o);
817                 diff.sort(QName::compareTo);
818                 return childNames.contains(diff.get(0)) ? -1 : 1;
819             } else if (thisSize < otherSize) {
820                 return 1;
821             } else {
822                 return -1;
823             }
824         }
825
826         private Object writeReplace() {
827             return new AIv1(this);
828         }
829     }
830
831     /**
832      * Fluent Builder of Instance Identifier instances.
833      */
834     public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
835         /**
836          * Adds a {@link PathArgument} to path arguments of resulting instance identifier.
837          *
838          * @param arg A {@link PathArgument} to be added
839          * @return this builder
840          */
841         InstanceIdentifierBuilder node(PathArgument arg);
842
843         /**
844          * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
845          *
846          * @param nodeType QName of {@link NodeIdentifier} which will be added
847          * @return this builder
848          */
849         InstanceIdentifierBuilder node(QName nodeType);
850
851         /**
852          * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting
853          * instance identifier.
854          *
855          * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
856          * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
857          * @return this builder
858          */
859         InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
860
861         /**
862          * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
863          *
864          * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
865          * @param key QName of key which will be added
866          * @param value value of key which will be added
867          * @return this builder
868          */
869         InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
870
871         /**
872          * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
873          *
874          * @param args {@link PathArgument}s to be added
875          * @return this builder
876          * @throws NullPointerException if any of the arguments is null
877          */
878         @Beta
879         InstanceIdentifierBuilder append(Collection<? extends PathArgument> args);
880
881         /**
882          * Adds a collection of {@link PathArgument}s to path arguments of resulting instance identifier.
883          *
884          * @param args {@link PathArgument}s to be added
885          * @return this builder
886          * @throws NullPointerException if any of the arguments is null
887          */
888         @Beta
889         default InstanceIdentifierBuilder append(final PathArgument... args) {
890             return append(Arrays.asList(args));
891         }
892
893         /**
894          * Builds an {@link YangInstanceIdentifier} with path arguments from this builder.
895          *
896          * @return {@link YangInstanceIdentifier}
897          */
898         @Override
899         YangInstanceIdentifier build();
900     }
901 }