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