BUG-3263: return a Collection for path arguments
[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  * This program and the accompanying materials are made available under the
4  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
5  * and is available at http://www.eclipse.org/legal/epl-v10.html
6  */
7 package org.opendaylight.yangtools.yang.data.api;
8
9 import com.google.common.base.Optional;
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.collect.ImmutableSet;
13 import com.google.common.collect.Iterables;
14 import java.io.Serializable;
15 import java.lang.reflect.Array;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.Objects;
23 import java.util.Set;
24 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
25 import javax.annotation.Nonnull;
26 import javax.annotation.Nullable;
27 import org.opendaylight.yangtools.concepts.Builder;
28 import org.opendaylight.yangtools.concepts.Immutable;
29 import org.opendaylight.yangtools.concepts.Path;
30 import org.opendaylight.yangtools.util.HashCodeBuilder;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.QNameModule;
33 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
34
35 /**
36  * Unique identifier of a particular node instance in the data tree.
37  *
38  * <p>
39  * Java representation of YANG Built-in type <code>instance-identifier</code>,
40  * which conceptually is XPath expression minimized to uniquely identify element
41  * in data tree which conforms to constraints maintained by YANG Model,
42  * effectively this makes Instance Identifier a path to element in data tree.
43  * <p>
44  * Constraints put in YANG specification on instance-identifier allowed it to be
45  * effectively represented in Java and it's evaluation does not require
46  * full-blown XPath processor.
47  * <p>
48  * <h3>Path Arguments</h3>
49  * Path to the node represented in instance identifier consists of
50  * {@link PathArgument} which carries necessary information to uniquely identify
51  * node on particular level in the subtree.
52  * <p>
53  * <ul>
54  * <li>{@link NodeIdentifier} - Identifier of node, which has cardinality
55  * <code>0..1</code> in particular subtree in data tree.</li>
56  * <li>{@link NodeIdentifierWithPredicates} - Identifier of node (list item),
57  * which has cardinality <code>0..n</code>.</li>
58  * <li>{@link NodeWithValue} - Identifier of instance <code>leaf</code> node or
59  * <code>leaf-list</code> node.</li>
60  * <li>{@link AugmentationIdentifier} - Identifier of instance of
61  * <code>augmentation</code> node.</li>
62  * </ul>
63  *
64  *
65  * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
66  */
67 public abstract class YangInstanceIdentifier extends IterablePathArguments implements Path<YangInstanceIdentifier>, Immutable, Serializable {
68     /**
69      * An empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual
70      * root of the YANG namespace.
71      */
72     public static final YangInstanceIdentifier EMPTY = FixedYangInstanceIdentifier.EMPTY_INSTANCE;
73
74     private static final AtomicReferenceFieldUpdater<YangInstanceIdentifier, String> TOSTRINGCACHE_UPDATER =
75             AtomicReferenceFieldUpdater.newUpdater(YangInstanceIdentifier.class, String.class, "toStringCache");
76     private static final long serialVersionUID = 4L;
77
78     private final int hash;
79     private transient volatile String toStringCache = null;
80
81     // Package-private to prevent outside subclassing
82     YangInstanceIdentifier(final int hash) {
83         this.hash = hash;
84     }
85
86     @Nonnull abstract YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
87     @Nonnull abstract Collection<PathArgument> tryPathArguments();
88     @Nonnull abstract Collection<PathArgument> tryReversePathArguments();
89
90     /**
91      * Check if this instance identifier has empty path arguments, e.g. it is
92      * empty and corresponds to {@link #EMPTY}.
93      *
94      * @return True if this instance identifier is empty, false otherwise.
95      */
96     public abstract boolean isEmpty();
97
98     /**
99      * Return the conceptual parent {@link YangInstanceIdentifier}, which has
100      * one item less in {@link #getPathArguments()}.
101      *
102      * @return Parent {@link YangInstanceIdentifier}, or null if this is object is {@link #EMPTY}.
103      */
104     @Nullable public abstract YangInstanceIdentifier getParent();
105
106     /**
107      * Returns a list of path arguments.
108      *
109      * @deprecated Use {@link #getPathArguments()} instead.
110      * @return Immutable list of path arguments.
111      */
112     @Deprecated
113     public abstract List<PathArgument> getPath();
114
115     /**
116      * Returns an ordered iteration of path arguments.
117      *
118      * @return Immutable iteration of path arguments.
119      */
120     @Override
121     public abstract Collection<PathArgument> getPathArguments();
122
123     /**
124      * Returns an iterable of path arguments in reverse order. This is useful
125      * when walking up a tree organized this way.
126      *
127      * @return Immutable iterable of path arguments in reverse order.
128      */
129     @Override
130     public abstract Collection<PathArgument> getReversePathArguments();
131
132     /**
133      * Returns the last PathArgument. This is equivalent of iterating
134      * to the last element of the iterable returned by {@link #getPathArguments()}.
135      *
136      * @return The last past argument, or null if there are no PathArguments.
137      */
138     public abstract PathArgument getLastPathArgument();
139
140     public static YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
141         if (Iterables.isEmpty(path)) {
142             return EMPTY;
143         }
144
145         final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
146         for (PathArgument a : path) {
147             hash.addArgument(a);
148         }
149
150         return FixedYangInstanceIdentifier.create(path, hash.build());
151     }
152
153     public static YangInstanceIdentifier create(final PathArgument... path) {
154         // We are forcing a copy, since we cannot trust the user
155         return create(Arrays.asList(path));
156     }
157
158     @Override
159     public final int hashCode() {
160         /*
161          * The caching is safe, since the object contract requires
162          * immutability of the object and all objects referenced from this
163          * object.
164          * Used lists, maps are immutable. Path Arguments (elements) are also
165          * immutable, since the PathArgument contract requires immutability.
166          */
167         return hash;
168     }
169
170     boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
171         return Iterables.elementsEqual(getPathArguments(), other.getPathArguments());
172     }
173
174     @Override
175     public boolean equals(final Object obj) {
176         if (this == obj) {
177             return true;
178         }
179         if (!(obj instanceof YangInstanceIdentifier)) {
180             return false;
181         }
182         YangInstanceIdentifier other = (YangInstanceIdentifier) obj;
183         if (this.hashCode() != obj.hashCode()) {
184             return false;
185         }
186
187         return pathArgumentsEqual(other);
188     }
189
190     /**
191      * Constructs a new Instance Identifier with new {@link NodeIdentifier} added to the end of path arguments
192      *
193      * @param name QName of {@link NodeIdentifier}
194      * @return Instance Identifier with additional path argument added to the end.
195      */
196     public final YangInstanceIdentifier node(final QName name) {
197         return node(new NodeIdentifier(name));
198     }
199
200     /**
201      *
202      * Constructs a new Instance Identifier with new {@link PathArgument} added to the end of path arguments
203      *
204      * @param arg Path argument which should be added to the end
205      * @return Instance Identifier with additional path argument added to the end.
206      */
207     public final YangInstanceIdentifier node(final PathArgument arg) {
208         return new StackedYangInstanceIdentifier(this, arg, HashCodeBuilder.nextHashCode(hash, arg));
209     }
210
211     /**
212      * Get the relative path from an ancestor. This method attempts to perform
213      * the reverse of concatenating a base (ancestor) and a path.
214      *
215      * @param ancestor
216      *            Ancestor against which the relative path should be calculated
217      * @return This object's relative path from parent, or Optional.absent() if
218      *         the specified parent is not in fact an ancestor of this object.
219      */
220     public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
221         final Iterator<?> lit = getPathArguments().iterator();
222         final Iterator<?> oit = ancestor.getPathArguments().iterator();
223         int common = 0;
224
225         while (oit.hasNext()) {
226             // Ancestor is not really an ancestor
227             if (!lit.hasNext() || !lit.next().equals(oit.next())) {
228                 return Optional.absent();
229             }
230
231             ++common;
232         }
233
234         if (common == 0) {
235             return Optional.of(this);
236         }
237         if (!lit.hasNext()) {
238             return Optional.of(EMPTY);
239         }
240
241         return Optional.of(createRelativeIdentifier(common));
242     }
243
244     private static int hashCode(final Object value) {
245         if (value == null) {
246             return 0;
247         }
248
249         if (value.getClass().equals(byte[].class)) {
250             return Arrays.hashCode((byte[]) value);
251         }
252
253         if (value.getClass().isArray()) {
254             int hash = 0;
255             int length = Array.getLength(value);
256             for (int i = 0; i < length; i++) {
257                 hash += Objects.hashCode(Array.get(value, i));
258             }
259
260             return hash;
261         }
262
263         return Objects.hashCode(value);
264     }
265
266     // Static factories & helpers
267
268     /**
269      *
270      * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied QName
271      *
272      * @param name QName of first node identifier
273      * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
274      */
275     public static YangInstanceIdentifier of(final QName name) {
276         return create(new NodeIdentifier(name));
277     }
278
279     /**
280      *
281      * Returns new builder for InstanceIdentifier with empty path arguments.
282      *
283      * @return new builder for InstanceIdentifier with empty path arguments.
284      */
285     public static InstanceIdentifierBuilder builder() {
286         return new YangInstanceIdentifierBuilder();
287     }
288
289     /**
290      *
291      * Returns new builder for InstanceIdentifier with path arguments copied from original instance identifier.
292      *
293      * @param origin Instace Identifier from which path arguments are copied.
294      * @return new builder for InstanceIdentifier with path arguments copied from original instance identifier.
295      */
296     public static InstanceIdentifierBuilder builder(final YangInstanceIdentifier origin) {
297         return new YangInstanceIdentifierBuilder(origin.getPathArguments(), origin.hashCode());
298     }
299
300     /**
301      * Path argument / component of InstanceIdentifier
302      *
303      * Path argument uniquely identifies node in data tree on particular
304      * level.
305      * <p>
306      * This interface itself is used as common parent for actual
307      * path arguments types and should not be implemented by user code.
308      * <p>
309      * Path arguments SHOULD contain only minimum of information
310      * required to uniquely identify node on particular subtree level.
311      *
312      * For actual path arguments types see:
313      * <ul>
314      * <li>{@link NodeIdentifier} - Identifier of container or leaf
315      * <li>{@link NodeIdentifierWithPredicates} - Identifier of list entries, which have key defined
316      * <li>{@link AugmentationIdentifier} - Identifier of augmentation
317      * <li>{@link NodeWithValue} - Identifier of leaf-list entry
318      * </ul>
319      */
320     public interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable {
321         /**
322          * If applicable returns unique QName of data node as defined in YANG
323          * Schema.
324          *
325          * This method may return null, if the corresponding schema node, does
326          * not have QName associated, such as in cases of augmentations.
327          *
328          * @return Node type
329          */
330         QName getNodeType();
331
332         /**
333          * Return the string representation of this object for use in context
334          * provided by a previous object. This method can be implemented in
335          * terms of {@link #toString()}, but implementations are encourage to
336          * reuse any context already emitted by the previous object.
337          *
338          * @param previous Previous path argument
339          * @return String representation
340          */
341         String toRelativeString(PathArgument previous);
342     }
343
344     private static abstract class AbstractPathArgument implements PathArgument {
345         private static final long serialVersionUID = -4546547994250849340L;
346         private final QName nodeType;
347         private transient int hashValue;
348         private volatile transient boolean hashGuard = false;
349
350         protected AbstractPathArgument(final QName nodeType) {
351             this.nodeType = Preconditions.checkNotNull(nodeType);
352         }
353
354         @Override
355         public final QName getNodeType() {
356             return nodeType;
357         }
358
359         @Override
360         public int compareTo(final PathArgument o) {
361             return nodeType.compareTo(o.getNodeType());
362         }
363
364         protected int hashCodeImpl() {
365             return 31 + getNodeType().hashCode();
366         }
367
368         @Override
369         public final int hashCode() {
370             if (!hashGuard) {
371                 hashValue = hashCodeImpl();
372                 hashGuard = true;
373             }
374
375             return hashValue;
376         }
377
378         @Override
379         public boolean equals(final Object obj) {
380             if (this == obj) {
381                 return true;
382             }
383             if (obj == null || this.getClass() != obj.getClass()) {
384                 return false;
385             }
386
387             return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
388         }
389
390         @Override
391         public String toString() {
392             return getNodeType().toString();
393         }
394
395         @Override
396         public String toRelativeString(final PathArgument previous) {
397             if (previous instanceof AbstractPathArgument) {
398                 final QNameModule mod = ((AbstractPathArgument)previous).getNodeType().getModule();
399                 if (getNodeType().getModule().equals(mod)) {
400                     return getNodeType().getLocalName();
401                 }
402             }
403
404             return getNodeType().toString();
405         }
406     }
407
408     /**
409      * Fluent Builder of Instance Identifier instances
410      */
411     public interface InstanceIdentifierBuilder extends Builder<YangInstanceIdentifier> {
412         /**
413          * Adds {@link NodeIdentifier} with supplied QName to path arguments of resulting instance identifier.
414          *
415          * @param nodeType QName of {@link NodeIdentifier} which will be added
416          * @return this builder
417          */
418         InstanceIdentifierBuilder node(QName nodeType);
419
420         /**
421          * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key values to path arguments of resulting instance identifier.
422          *
423          * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
424          * @param keyValues Map of key components and their respective values for {@link NodeIdentifierWithPredicates}
425          * @return this builder
426          */
427         InstanceIdentifierBuilder nodeWithKey(QName nodeType, Map<QName, Object> keyValues);
428
429         /**
430          * Adds {@link NodeIdentifierWithPredicates} with supplied QName and key, value.
431          *
432          * @param nodeType QName of {@link NodeIdentifierWithPredicates} which will be added
433          * @param key QName of key which will be added
434          * @param value value of key which will be added
435          * @return this builder
436          */
437         InstanceIdentifierBuilder nodeWithKey(QName nodeType, QName key, Object value);
438
439         /**
440          *
441          * Builds an {@link YangInstanceIdentifier} with path arguments from this builder
442          *
443          * @return {@link YangInstanceIdentifier}
444          */
445         @Override
446         YangInstanceIdentifier build();
447
448         /*
449          * @deprecated use #build()
450          */
451         @Deprecated
452         YangInstanceIdentifier toInstance();
453     }
454
455     /**
456      * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
457      * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
458      */
459     public static final class NodeIdentifier extends AbstractPathArgument {
460         private static final long serialVersionUID = -2255888212390871347L;
461
462         public NodeIdentifier(final QName node) {
463             super(node);
464         }
465     }
466
467     /**
468      * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
469      * overall data tree.
470      */
471     public static final class NodeIdentifierWithPredicates extends AbstractPathArgument {
472         private static final long serialVersionUID = -4787195606494761540L;
473
474         private final Map<QName, Object> keyValues;
475
476         public NodeIdentifierWithPredicates(final QName node, final Map<QName, Object> keyValues) {
477             super(node);
478             this.keyValues = ImmutableMap.copyOf(keyValues);
479         }
480
481         public NodeIdentifierWithPredicates(final QName node, final QName key, final Object value) {
482             this(node, ImmutableMap.of(key, value));
483         }
484
485         public Map<QName, Object> getKeyValues() {
486             return keyValues;
487         }
488
489         @Override
490         protected int hashCodeImpl() {
491             final int prime = 31;
492             int result = super.hashCodeImpl();
493             result = prime * result;
494
495             for (Entry<QName, Object> entry : keyValues.entrySet()) {
496                 result += Objects.hashCode(entry.getKey()) + YangInstanceIdentifier.hashCode(entry.getValue());
497             }
498             return result;
499         }
500
501         @Override
502         public boolean equals(final Object obj) {
503             if (!super.equals(obj)) {
504                 return false;
505             }
506
507             final Map<QName, Object> otherKeyValues = ((NodeIdentifierWithPredicates) obj).keyValues;
508             if (keyValues.size() != otherKeyValues.size()) {
509                 return false;
510             }
511
512             for (Entry<QName, Object> entry : keyValues.entrySet()) {
513                 if (!otherKeyValues.containsKey(entry.getKey())
514                         || !Objects.deepEquals(entry.getValue(), otherKeyValues.get(entry.getKey()))) {
515
516                     return false;
517                 }
518             }
519
520             return true;
521         }
522
523         @Override
524         public String toString() {
525             return super.toString() + '[' + keyValues + ']';
526         }
527
528         @Override
529         public String toRelativeString(final PathArgument previous) {
530             return super.toRelativeString(previous) + '[' + keyValues + ']';
531         }
532     }
533
534     /**
535      * Simple path argument identifying a {@link LeafSetEntryNode} leaf
536      * overall data tree.
537      */
538     public static final class NodeWithValue extends AbstractPathArgument {
539         private static final long serialVersionUID = -3637456085341738431L;
540
541         private final Object value;
542
543         public NodeWithValue(final QName node, final Object value) {
544             super(node);
545             this.value = value;
546         }
547
548         public Object getValue() {
549             return value;
550         }
551
552         @Override
553         protected int hashCodeImpl() {
554             final int prime = 31;
555             int result = super.hashCodeImpl();
556             result = prime * result + ((value == null) ? 0 : YangInstanceIdentifier.hashCode(value));
557             return result;
558         }
559
560         @Override
561         public boolean equals(final Object obj) {
562             if (!super.equals(obj)) {
563                 return false;
564             }
565             final NodeWithValue other = (NodeWithValue) obj;
566             return Objects.deepEquals(value, other.value);
567         }
568
569         @Override
570         public String toString() {
571             return super.toString() + '[' + value + ']';
572         }
573
574         @Override
575         public String toRelativeString(final PathArgument previous) {
576             return super.toRelativeString(previous) + '[' + value + ']';
577         }
578     }
579
580     /**
581      * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode} node in
582      * particular subtree.
583      *
584      * Augmentation is uniquely identified by set of all possible child nodes.
585      * This is possible
586      * to identify instance of augmentation,
587      * since RFC6020 states that <code>augment</code> that augment
588      * statement must not add multiple nodes from same namespace
589      * / module to the target node.
590      *
591      *
592      * @see <a href="http://tools.ietf.org/html/rfc6020#section-7.15">RFC6020</a>
593      */
594     public static final class AugmentationIdentifier implements PathArgument {
595         private static final long serialVersionUID = -8122335594681936939L;
596         private final ImmutableSet<QName> childNames;
597
598         @Override
599         public QName getNodeType() {
600             // This should rather throw exception than return always null
601             throw new UnsupportedOperationException("Augmentation node has no QName");
602         }
603
604         /**
605          *
606          * Construct new augmentation identifier using supplied set of possible
607          * child nodes
608          *
609          * @param childNames
610          *            Set of possible child nodes.
611          */
612         public AugmentationIdentifier(final Set<QName> childNames) {
613             this.childNames = ImmutableSet.copyOf(childNames);
614         }
615
616         /**
617          * Returns set of all possible child nodes
618          *
619          * @return set of all possible child nodes.
620          */
621         public Set<QName> getPossibleChildNames() {
622             return childNames;
623         }
624
625         @Override
626         public String toString() {
627             final StringBuilder sb = new StringBuilder("AugmentationIdentifier{");
628             sb.append("childNames=").append(childNames).append('}');
629             return sb.toString();
630         }
631
632         @Override
633         public String toRelativeString(final PathArgument previous) {
634             return toString();
635         }
636
637         @Override
638         public boolean equals(final Object o) {
639             if (this == o) {
640                 return true;
641             }
642             if (!(o instanceof AugmentationIdentifier)) {
643                 return false;
644             }
645
646             AugmentationIdentifier that = (AugmentationIdentifier) o;
647             return childNames.equals(that.childNames);
648         }
649
650         @Override
651         public int hashCode() {
652             return childNames.hashCode();
653         }
654
655         @Override
656         public int compareTo(final PathArgument o) {
657             if (!(o instanceof AugmentationIdentifier)) {
658                 return -1;
659             }
660             AugmentationIdentifier other = (AugmentationIdentifier) o;
661             Set<QName> otherChildNames = other.getPossibleChildNames();
662             int thisSize = childNames.size();
663             int otherSize = otherChildNames.size();
664             if (thisSize == otherSize) {
665                 Iterator<QName> otherIterator = otherChildNames.iterator();
666                 for (QName name : childNames) {
667                     int c = name.compareTo(otherIterator.next());
668                     if (c != 0) {
669                         return c;
670                     }
671                 }
672                 return 0;
673             } else if (thisSize < otherSize) {
674                 return 1;
675             } else {
676                 return -1;
677             }
678         }
679     }
680
681     @Override
682     public final boolean contains(final YangInstanceIdentifier other) {
683         Preconditions.checkArgument(other != null, "other should not be null");
684
685         final Iterator<?> lit = getPathArguments().iterator();
686         final Iterator<?> oit = other.getPathArguments().iterator();
687
688         while (lit.hasNext()) {
689             if (!oit.hasNext()) {
690                 return false;
691             }
692
693             if (!lit.next().equals(oit.next())) {
694                 return false;
695             }
696         }
697
698         return true;
699     }
700
701     @Override
702     public final String toString() {
703         /*
704          * The toStringCache is safe, since the object contract requires
705          * immutability of the object and all objects referenced from this
706          * object.
707          * Used lists, maps are immutable. Path Arguments (elements) are also
708          * immutable, since the PathArgument contract requires immutability.
709          * The cache is thread-safe - if multiple computations occurs at the
710          * same time, cache will be overwritten with same result.
711          */
712         String ret = toStringCache;
713         if (ret == null) {
714             final StringBuilder builder = new StringBuilder("/");
715             PathArgument prev = null;
716             for (PathArgument argument : getPathArguments()) {
717                 if (prev != null) {
718                     builder.append('/');
719                 }
720                 builder.append(argument.toRelativeString(prev));
721                 prev = argument;
722             }
723
724             ret = builder.toString();
725             TOSTRINGCACHE_UPDATER.lazySet(this, ret);
726         }
727         return ret;
728     }
729 }