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