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