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