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