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