Use TypedSchemaNode
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / util / SchemaContextUtil.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.model.util;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Function;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Splitter;
16 import com.google.common.collect.Iterables;
17 import java.util.Collections;
18 import java.util.Iterator;
19 import java.util.LinkedList;
20 import java.util.List;
21 import java.util.Set;
22 import java.util.regex.Pattern;
23 import javax.annotation.Nonnull;
24 import javax.annotation.Nullable;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.common.QNameModule;
27 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
30 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
33 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.Module;
36 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
37 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
38 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
39 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
43 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  * The Schema Context Util contains support methods for searching through Schema
51  * Context modules for specified schema nodes via Schema Path or Revision Aware
52  * XPath. The Schema Context Util is designed as mixin, so it is not
53  * instantiable.
54  *
55  */
56 public final class SchemaContextUtil {
57     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
58     private static final Splitter COLON_SPLITTER = Splitter.on(':');
59     private static final Splitter SLASH_SPLITTER = Splitter.on('/');
60
61     private SchemaContextUtil() {
62     }
63
64     /**
65      * Method attempts to find DataSchemaNode in Schema Context via specified
66      * Schema Path. The returned DataSchemaNode from method will be the node at
67      * the end of the SchemaPath. If the DataSchemaNode is not present in the
68      * Schema Context the method will return <code>null</code>. <br>
69      * In case that Schema Context or Schema Path are not specified correctly
70      * (i.e. contains <code>null</code> values) the method will return
71      * IllegalArgumentException.
72      *
73      * @throws IllegalArgumentException
74      *
75      * @param context
76      *            Schema Context
77      * @param schemaPath
78      *            Schema Path to search for
79      * @return SchemaNode from the end of the Schema Path or <code>null</code>
80      *         if the Node is not present.
81      */
82     public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
83         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
84         Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
85
86         final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
87         if (prefixedPath == null) {
88             LOG.debug("Schema path {} has null path", schemaPath);
89             return null;
90         }
91
92         LOG.trace("Looking for path {} in context {}", schemaPath, context);
93         return findNodeInSchemaContext(context, prefixedPath);
94     }
95
96     /**
97      * Method attempts to find DataSchemaNode inside of provided Schema Context
98      * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
99      * specified Module MUST be present in Schema Context otherwise the
100      * operation would fail and return <code>null</code>. <br>
101      * The Revision Aware XPath MUST be specified WITHOUT the conditional
102      * statement (i.e. without [cond]) in path, because in this state the Schema
103      * Context is completely unaware of data state and will be not able to
104      * properly resolve XPath. If the XPath contains condition the method will
105      * return IllegalArgumentException. <br>
106      * In case that Schema Context or Module or Revision Aware XPath contains
107      * <code>null</code> references the method will throw
108      * IllegalArgumentException <br>
109      * If the Revision Aware XPath is correct and desired Data Schema Node is
110      * present in Yang module or in depending module in Schema Context the
111      * method will return specified Data Schema Node, otherwise the operation
112      * will fail and method will return <code>null</code>.
113      *
114      * @throws IllegalArgumentException
115      *
116      * @param context
117      *            Schema Context
118      * @param module
119      *            Yang Module
120      * @param nonCondXPath
121      *            Non Conditional Revision Aware XPath
122      * @return Returns Data Schema Node for specified Schema Context for given
123      *         Non-conditional Revision Aware XPath, or <code>null</code> if the
124      *         DataSchemaNode is not present in Schema Context.
125      */
126     public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module, final RevisionAwareXPath nonCondXPath) {
127         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
128         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
129         Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
130
131         final String strXPath = nonCondXPath.toString();
132         if (strXPath != null) {
133             Preconditions.checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
134             if (nonCondXPath.isAbsolute()) {
135                 final List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath);
136                 if (qnamedPath != null) {
137                     return findNodeInSchemaContext(context, qnamedPath);
138                 }
139             }
140         }
141         return null;
142     }
143
144     /**
145      * Method attempts to find DataSchemaNode inside of provided Schema Context
146      * and Yang Module accordingly to Non-conditional relative Revision Aware
147      * XPath. The specified Module MUST be present in Schema Context otherwise
148      * the operation would fail and return <code>null</code>. <br>
149      * The relative Revision Aware XPath MUST be specified WITHOUT the
150      * conditional statement (i.e. without [cond]) in path, because in this
151      * state the Schema Context is completely unaware of data state and will be
152      * not able to properly resolve XPath. If the XPath contains condition the
153      * method will return IllegalArgumentException. <br>
154      * The Actual Schema Node MUST be specified correctly because from this
155      * Schema Node will search starts. If the Actual Schema Node is not correct
156      * the operation will simply fail, because it will be unable to find desired
157      * DataSchemaNode. <br>
158      * In case that Schema Context or Module or Actual Schema Node or relative
159      * Revision Aware XPath contains <code>null</code> references the method
160      * will throw IllegalArgumentException <br>
161      * If the Revision Aware XPath doesn't have flag
162      * <code>isAbsolute == false</code> the method will throw
163      * IllegalArgumentException. <br>
164      * If the relative Revision Aware XPath is correct and desired Data Schema
165      * Node is present in Yang module or in depending module in Schema Context
166      * the method will return specified Data Schema Node, otherwise the
167      * operation will fail and method will return <code>null</code>.
168      *
169      * @throws IllegalArgumentException
170      *
171      * @param context
172      *            Schema Context
173      * @param module
174      *            Yang Module
175      * @param actualSchemaNode
176      *            Actual Schema Node
177      * @param relativeXPath
178      *            Relative Non Conditional Revision Aware XPath
179      * @return DataSchemaNode if is present in specified Schema Context for
180      *         given relative Revision Aware XPath, otherwise will return
181      *         <code>null</code>.
182      */
183     public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
184             final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
185         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
186         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
187         Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
188         Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
189         Preconditions.checkState(!relativeXPath.isAbsolute(),
190                 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
191                         + "for non relative Revision Aware XPath use findDataSchemaNode method");
192
193         final SchemaPath actualNodePath = actualSchemaNode.getPath();
194         if (actualNodePath != null) {
195             final Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
196
197             if (qnamePath != null) {
198                 return findNodeInSchemaContext(context, qnamePath);
199             }
200         }
201         return null;
202     }
203
204     /**
205      * Returns parent Yang Module for specified Schema Context in which Schema
206      * Node is declared. If the Schema Node is not present in Schema Context the
207      * operation will return <code>null</code>. <br>
208      * If Schema Context or Schema Node contains <code>null</code> references
209      * the method will throw IllegalArgumentException
210      *
211      * @throws IllegalArgumentException
212      *
213      * @param context
214      *            Schema Context
215      * @param schemaNode
216      *            Schema Node
217      * @return Yang Module for specified Schema Context and Schema Node, if
218      *         Schema Node is NOT present, the method will returns
219      *         <code>null</code>
220      */
221     public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
222         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
223         Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
224         Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
225                 + "set properly (Schema Path is NULL)");
226
227         final QName qname = schemaNode.getPath().getLastComponent();
228         Preconditions.checkState(qname != null,
229                 "Schema Path contains invalid state of path parts. " +
230                         "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
231         return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
232     }
233
234     public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
235         final QName current = path.iterator().next();
236
237         LOG.trace("Looking up module {} in context {}", current, path);
238         final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
239         if (module == null) {
240             LOG.debug("Module {} not found", current);
241             return null;
242         }
243
244         return findNodeInModule(module, path);
245     }
246
247     /**
248      * Returns NotificationDefinition from Schema Context
249      *
250      * @param schema SchemaContext in which lookup should be performed.
251      * @param path Schema Path of notification
252      * @return Notification schema or null, if notification is not present in schema context.
253      */
254     @Beta
255     @Nullable public static NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema, @Nonnull final SchemaPath path) {
256         Preconditions.checkNotNull(schema, "Schema context must not be null.");
257         Preconditions.checkNotNull(path, "Schema path must not be null.");
258         for (final NotificationDefinition potential : schema.getNotifications()) {
259             if (path.equals(potential.getPath())) {
260                return potential;
261             }
262         }
263         return null;
264     }
265
266     /**
267      * Returns RPC Input or Output Data container from RPC definition.
268      *
269      * @param schema SchemaContext in which lookup should be performed.
270      * @param path Schema path of RPC input/output data container
271      * @return Notification schema or null, if notification is not present in schema context.
272      */
273     @Beta
274     @Nullable public static ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema, @Nonnull final SchemaPath path) {
275         Preconditions.checkNotNull(schema, "Schema context must not be null.");
276         Preconditions.checkNotNull(path, "Schema path must not be null.");
277         final Iterator<QName> it = path.getPathFromRoot().iterator();
278         Preconditions.checkArgument(it.hasNext(), "Rpc must have QName.");
279         final QName rpcName = it.next();
280         Preconditions.checkArgument(it.hasNext(), "input or output must be part of path.");
281         final QName inOrOut = it.next();
282         for (final RpcDefinition potential : schema.getOperations()) {
283             if (rpcName.equals(potential.getQName())) {
284                return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
285             }
286         }
287         return null;
288     }
289
290     private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
291
292         Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
293         Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
294
295         if (!path.iterator().hasNext()) {
296             LOG.debug("No node matching {} found in node {}", path, module);
297             return null;
298         }
299
300         final QName current = path.iterator().next();
301         LOG.trace("Looking for node {} in module {}", current, module);
302
303         SchemaNode foundNode = null;
304         final Iterable<QName> nextPath = nextLevel(path);
305
306         foundNode = module.getDataChildByName(current);
307         if (foundNode != null && nextPath.iterator().hasNext()) {
308             foundNode = findNodeIn(foundNode, nextPath);
309         }
310
311         if (foundNode == null) {
312             foundNode = getGroupingByName(module, current);
313             if (foundNode != null && nextPath.iterator().hasNext()) {
314                 foundNode = findNodeIn(foundNode, nextPath);
315             }
316         }
317
318         if (foundNode == null) {
319             foundNode = getRpcByName(module, current);
320             if (foundNode != null && nextPath.iterator().hasNext()) {
321                 foundNode = findNodeIn(foundNode, nextPath);
322             }
323         }
324
325         if (foundNode == null) {
326             foundNode = getNotificationByName(module, current);
327             if (foundNode != null && nextPath.iterator().hasNext()) {
328                 foundNode = findNodeIn(foundNode, nextPath);
329             }
330         }
331
332         if (foundNode == null) {
333             LOG.debug("No node matching {} found in node {}", path, module);
334         }
335
336         return foundNode;
337
338     }
339
340     private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
341
342         Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL");
343         Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
344
345         if (!path.iterator().hasNext()) {
346             LOG.debug("No node matching {} found in node {}", path, parent);
347             return null;
348         }
349
350         final QName current = path.iterator().next();
351         LOG.trace("Looking for node {} in node {}", current, parent);
352
353         SchemaNode foundNode = null;
354         final Iterable<QName> nextPath = nextLevel(path);
355
356         if (parent instanceof DataNodeContainer) {
357             final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
358
359             foundNode = parentDataNodeContainer.getDataChildByName(current);
360             if (foundNode != null && nextPath.iterator().hasNext()) {
361                 foundNode = findNodeIn(foundNode, nextPath);
362             }
363
364             if (foundNode == null) {
365                 foundNode = getGroupingByName(parentDataNodeContainer, current);
366                 if (foundNode != null && nextPath.iterator().hasNext()) {
367                     foundNode = findNodeIn(foundNode, nextPath);
368                 }
369             }
370         }
371
372         if (foundNode == null && parent instanceof RpcDefinition) {
373             final RpcDefinition parentRpcDefinition = (RpcDefinition) parent;
374
375             if (current.getLocalName().equals("input")) {
376                 foundNode = parentRpcDefinition.getInput();
377                 if (foundNode != null && nextPath.iterator().hasNext()) {
378                     foundNode = findNodeIn(foundNode, nextPath);
379                 }
380             }
381
382             if (current.getLocalName().equals("output")) {
383                 foundNode = parentRpcDefinition.getOutput();
384                 if (foundNode != null && nextPath.iterator().hasNext()) {
385                     foundNode = findNodeIn(foundNode, nextPath);
386                 }
387             }
388
389             if (foundNode == null) {
390                 foundNode = getGroupingByName(parentRpcDefinition, current);
391                 if (foundNode != null && nextPath.iterator().hasNext()) {
392                     foundNode = findNodeIn(foundNode, nextPath);
393                 }
394             }
395         }
396
397         if (foundNode == null && parent instanceof ChoiceSchemaNode) {
398             foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
399             if (foundNode != null && nextPath.iterator().hasNext()) {
400                 foundNode = findNodeIn(foundNode, nextPath);
401             }
402         }
403
404         if (foundNode == null) {
405             LOG.debug("No node matching {} found in node {}", path, parent);
406         }
407
408         return foundNode;
409
410     }
411
412     private static Iterable<QName> nextLevel(final Iterable<QName> path) {
413         return Iterables.skip(path, 1);
414     }
415
416     private static RpcDefinition getRpcByName(final Module module, final QName name) {
417         for (final RpcDefinition rpc : module.getRpcs()) {
418             if (rpc.getQName().equals(name)) {
419                 return rpc;
420             }
421         }
422         return null;
423     }
424
425     private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
426         for (final NotificationDefinition notification : module.getNotifications()) {
427             if (notification.getQName().equals(name)) {
428                 return notification;
429             }
430         }
431         return null;
432     }
433
434     private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
435         for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
436             if (grouping.getQName().equals(name)) {
437                 return grouping;
438             }
439         }
440         return null;
441     }
442
443     private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) {
444         for (final GroupingDefinition grouping : rpc.getGroupings()) {
445             if (grouping.getQName().equals(name)) {
446                 return grouping;
447             }
448         }
449         return null;
450     }
451
452     /**
453      * Transforms string representation of XPath to Queue of QNames. The XPath
454      * is split by "/" and for each part of XPath is assigned correct module in
455      * Schema Path. <br>
456      * If Schema Context, Parent Module or XPath string contains
457      * <code>null</code> values, the method will throws IllegalArgumentException
458      *
459      * @throws IllegalArgumentException
460      *
461      * @param context
462      *            Schema Context
463      * @param parentModule
464      *            Parent Module
465      * @param xpath
466      *            XPath String
467      * @return return a list of QName
468      */
469     private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule, final String xpath) {
470         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
471         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
472         Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
473
474         final List<QName> path = new LinkedList<>();
475         for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
476             if (!pathComponent.isEmpty()) {
477                 path.add(stringPathPartToQName(context, parentModule, pathComponent));
478             }
479         }
480         return path;
481     }
482
483     /**
484      * Transforms part of Prefixed Path as java String to QName. <br>
485      * If the string contains module prefix separated by ":" (i.e.
486      * mod:container) this module is provided from from Parent Module list of
487      * imports. If the Prefixed module is present in Schema Context the QName
488      * can be constructed. <br>
489      * If the Prefixed Path Part does not contains prefix the Parent's Module
490      * namespace is taken for construction of QName. <br>
491      * If Schema Context, Parent Module or Prefixed Path Part refers to
492      * <code>null</code> the method will throw IllegalArgumentException
493      *
494      * @throws IllegalArgumentException
495      *
496      * @param context
497      *            Schema Context
498      * @param parentModule
499      *            Parent Module
500      * @param prefixedPathPart
501      *            Prefixed Path Part string
502      * @return QName from prefixed Path Part String.
503      */
504     private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule, final String prefixedPathPart) {
505         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
506         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
507         Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
508
509         if (prefixedPathPart.indexOf(':') != -1) {
510             final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
511             final String modulePrefix = prefixedName.next();
512
513             final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
514             Preconditions.checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
515                     modulePrefix, parentModule.getName());
516
517             return QName.create(module.getQNameModule(), prefixedName.next());
518         } else {
519             return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
520         }
521     }
522
523     /**
524      * Method will attempt to resolve and provide Module reference for specified
525      * module prefix. Each Yang module could contains multiple imports which
526      * MUST be associated with corresponding module prefix. The method simply
527      * looks into module imports and returns the module that is bounded with
528      * specified prefix. If the prefix is not present in module or the prefixed
529      * module is not present in specified Schema Context, the method will return
530      * <code>null</code>. <br>
531      * If String prefix is the same as prefix of the specified Module the
532      * reference to this module is returned. <br>
533      * If Schema Context, Module or Prefix are referring to <code>null</code>
534      * the method will return IllegalArgumentException
535      *
536      * @throws IllegalArgumentException
537      *
538      * @param context
539      *            Schema Context
540      * @param module
541      *            Yang Module
542      * @param prefix
543      *            Module Prefix
544      * @return Module for given prefix in specified Schema Context if is
545      *         present, otherwise returns <code>null</code>
546      */
547     private static Module resolveModuleForPrefix(final SchemaContext context, final Module module, final String prefix) {
548         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
549         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
550         Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
551
552         if (prefix.equals(module.getPrefix())) {
553             return module;
554         }
555
556         final Set<ModuleImport> imports = module.getImports();
557         for (final ModuleImport mi : imports) {
558             if (prefix.equals(mi.getPrefix())) {
559                 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
560             }
561         }
562         return null;
563     }
564
565     /**
566      * @throws IllegalArgumentException
567      *
568      * @param context
569      *            Schema Context
570      * @param module
571      *            Yang Module
572      * @param relativeXPath
573      *            Non conditional Revision Aware Relative XPath
574      * @param actualSchemaNode
575      *            actual schema node
576      * @return list of QName
577      */
578     private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
579             final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
580         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
581         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
582         Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
583         Preconditions.checkState(!relativeXPath.isAbsolute(),
584                 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
585                         + "for non relative Revision Aware XPath use findDataSchemaNode method");
586         Preconditions.checkState(actualSchemaNode.getPath() != null,
587                 "Schema Path reference for Leafref cannot be NULL");
588
589         final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
590
591         // Find out how many "parent" components there are
592         // FIXME: is .contains() the right check here?
593         // FIXME: case ../../node1/node2/../node3/../node4
594         int colCount = 0;
595         for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
596             ++colCount;
597         }
598
599         final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
600
601         if (Iterables.size(schemaNodePath) - colCount >= 0) {
602             return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
603                     Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
604                         @Override
605                         public QName apply(final String input) {
606                             return stringPathPartToQName(context, module, input);
607                         }
608                     }));
609         }
610         return Iterables.concat(schemaNodePath,
611                 Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
612                     @Override
613                     public QName apply(final String input) {
614                         return stringPathPartToQName(context, module, input);
615                     }
616                 }));
617     }
618
619     /**
620      * Extracts the base type of node on which schema node points to. If target node is again of type LeafrefTypeDefinition, methods will be call recursively until it reach concrete
621      * type definition.
622      *
623      * @param typeDefinition
624      *            type of node which will be extracted
625      * @param schemaContext
626      *            Schema Context
627      * @param schema
628      *            Schema Node
629      * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null is there to preserve backwards compatibility)
630      */
631     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition, final SchemaContext schemaContext, final SchemaNode schema) {
632         RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
633         pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
634
635         final DataSchemaNode dataSchemaNode;
636         if (pathStatement.isAbsolute()) {
637             SchemaNode baseSchema = schema;
638             while (baseSchema instanceof DerivableSchemaNode) {
639                 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
640                 if (basePotential.isPresent()) {
641                     baseSchema = basePotential.get();
642                 } else {
643                     break;
644                 }
645             }
646
647             Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
648             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
649                     pathStatement);
650         } else {
651             Module parentModule = findParentModule(schemaContext, schema);
652             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
653                     parentModule, schema, pathStatement);
654         }
655
656         // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
657         // and current expected behaviour for such cases is to just use pure string
658         // This should throw an exception about incorrect XPath in leafref
659         if (dataSchemaNode == null) {
660             return null;
661         }
662
663         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
664
665         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
666             return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
667         } else {
668             return targetTypeDefinition;
669         }
670     }
671
672     private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
673             final SchemaNode schemaNode) {
674         Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
675         Preconditions.checkArgument(schemaNode instanceof TypedSchemaNode, "Unsupported node %s", schemaNode);
676
677         TypeDefinition<?> nodeType = ((TypedSchemaNode) schemaNode).getType();
678         if (nodeType.getBaseType() != null) {
679             while (nodeType.getBaseType() != null) {
680                 nodeType = nodeType.getBaseType();
681             }
682
683             final QNameModule typeDefModuleQname = nodeType.getQName().getModule();
684             return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
685                     typeDefModuleQname.getRevision());
686         }
687
688         return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
689     }
690
691     /**
692      * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qName}. This handle case
693      * when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other module as typedef
694      * which is then imported to referenced module.
695      *
696      * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
697      *
698      * @param typeDefinition
699      * @param schemaContext
700      * @param qName
701      * @return
702      */
703     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
704             final SchemaContext schemaContext, final QName qName) {
705         final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
706         final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
707         if (!strippedPathStatement.isAbsolute()) {
708             return null;
709         }
710
711         final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace(),qName.getRevision());
712         final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, strippedPathStatement);
713         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
714         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
715             return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
716         } else {
717             return targetTypeDefinition;
718         }
719     }
720
721     private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
722
723     /**
724      * Removes conditions from xPath pointed to target node.
725      *
726      * @param pathStatement
727      *            xPath to target node
728      * @return string representation of xPath without conditions
729      *
730      */
731     @VisibleForTesting
732     static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
733         return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
734     }
735
736     /**
737      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
738      *
739      * @param node
740      *            a node representing LeafSchemaNode
741      * @return concrete type definition of node value
742      */
743     private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
744         TypeDefinition<?> baseType = node.getType();
745         while (baseType.getBaseType() != null) {
746             baseType = baseType.getBaseType();
747         }
748         return baseType;
749     }
750
751     /**
752      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
753      *
754      * @param node
755      *            a node representing LeafListSchemaNode
756      * @return concrete type definition of node value
757      */
758     private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
759         TypeDefinition<?> baseType = node.getType();
760         while (baseType.getBaseType() != null) {
761             baseType = baseType.getBaseType();
762         }
763         return baseType;
764     }
765
766     /**
767      * Gets the base type of DataSchemaNode value.
768      *
769      * @param node
770      *            a node representing DataSchemaNode
771      * @return concrete type definition of node value
772      */
773     private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
774         if (node instanceof LeafListSchemaNode) {
775             return typeDefinition((LeafListSchemaNode) node);
776         } else if (node instanceof LeafSchemaNode) {
777             return typeDefinition((LeafSchemaNode) node);
778         } else {
779             throw new IllegalArgumentException("Unhandled parameter types: " + Collections.<Object>singletonList(node).toString());
780         }
781     }
782 }