Bug 6897: [YANG 1.1] Allow notifications to be tied to data nodes
[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.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Splitter;
15 import com.google.common.collect.Iterables;
16 import java.util.Iterator;
17 import java.util.LinkedList;
18 import java.util.List;
19 import java.util.Set;
20 import java.util.regex.Pattern;
21 import javax.annotation.Nonnull;
22 import javax.annotation.Nullable;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.common.QNameModule;
25 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
26 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
29 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
32 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.Module;
35 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
36 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
37 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
38 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
42 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * The Schema Context Util contains support methods for searching through Schema
50  * Context modules for specified schema nodes via Schema Path or Revision Aware
51  * XPath. The Schema Context Util is designed as mixin, so it is not
52  * instantiable.
53  *
54  */
55 public final class SchemaContextUtil {
56     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
57     private static final Splitter COLON_SPLITTER = Splitter.on(':');
58     private static final Splitter SLASH_SPLITTER = Splitter.on('/');
59
60     private SchemaContextUtil() {
61     }
62
63     /**
64      * Method attempts to find DataSchemaNode in Schema Context via specified
65      * Schema Path. The returned DataSchemaNode from method will be the node at
66      * the end of the SchemaPath. If the DataSchemaNode is not present in the
67      * Schema Context the method will return <code>null</code>. <br>
68      * In case that Schema Context or Schema Path are not specified correctly
69      * (i.e. contains <code>null</code> values) the method will return
70      * IllegalArgumentException.
71      *
72      * @param context
73      *            Schema Context
74      * @param schemaPath
75      *            Schema Path to search for
76      * @return SchemaNode from the end of the Schema Path or <code>null</code>
77      *         if the Node is not present.
78      *
79      * @throws IllegalArgumentException
80      */
81     public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
82         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
83         Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
84
85         final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
86         if (prefixedPath == null) {
87             LOG.debug("Schema path {} has null path", schemaPath);
88             return null;
89         }
90
91         LOG.trace("Looking for path {} in context {}", schemaPath, context);
92         return findNodeInSchemaContext(context, prefixedPath);
93     }
94
95     /**
96      * Method attempts to find DataSchemaNode inside of provided Schema Context
97      * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
98      * specified Module MUST be present in Schema Context otherwise the
99      * operation would fail and return <code>null</code>. <br>
100      * The Revision Aware XPath MUST be specified WITHOUT the conditional
101      * statement (i.e. without [cond]) in path, because in this state the Schema
102      * Context is completely unaware of data state and will be not able to
103      * properly resolve XPath. If the XPath contains condition the method will
104      * return IllegalArgumentException. <br>
105      * In case that Schema Context or Module or Revision Aware XPath contains
106      * <code>null</code> references the method will throw
107      * IllegalArgumentException <br>
108      * If the Revision Aware XPath is correct and desired Data Schema Node is
109      * present in Yang module or in depending module in Schema Context the
110      * method will return specified Data Schema Node, otherwise the operation
111      * will fail and method will return <code>null</code>.
112      *
113      * @param context
114      *            Schema Context
115      * @param module
116      *            Yang Module
117      * @param nonCondXPath
118      *            Non Conditional Revision Aware XPath
119      * @return Returns Data Schema Node for specified Schema Context for given
120      *         Non-conditional Revision Aware XPath, or <code>null</code> if the
121      *         DataSchemaNode is not present in Schema Context.
122      * @throws IllegalArgumentException
123      */
124     public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
125             final RevisionAwareXPath nonCondXPath) {
126         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
127         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
128         Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
129
130         final String strXPath = nonCondXPath.toString();
131         if (strXPath != null) {
132             Preconditions.checkArgument(strXPath.indexOf('[') == -1,
133                     "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      * @param context
170      *            Schema Context
171      * @param module
172      *            Yang Module
173      * @param actualSchemaNode
174      *            Actual Schema Node
175      * @param relativeXPath
176      *            Relative Non Conditional Revision Aware XPath
177      * @return DataSchemaNode if is present in specified Schema Context for
178      *         given relative Revision Aware XPath, otherwise will return
179      *         <code>null</code>.
180      *
181      * @throws IllegalArgumentException
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      * @param context
212      *            Schema Context
213      * @param schemaNode
214      *            Schema Node
215      * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
216      *         return <code>null</code>
217      *
218      * @throws IllegalArgumentException
219      */
220     public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
221         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
222         Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
223         Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
224                 + "set properly (Schema Path is NULL)");
225
226         final QName qname = schemaNode.getPath().getLastComponent();
227         Preconditions.checkState(qname != null, "Schema Path contains invalid state of path parts. "
228                 + "The Schema Path MUST contain at least ONE QName  which defines namespace and Local name of path.");
229         return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
230     }
231
232     public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
233         final QName current = path.iterator().next();
234
235         LOG.trace("Looking up module {} in context {}", current, path);
236         final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
237         if (module == null) {
238             LOG.debug("Module {} not found", current);
239             return null;
240         }
241
242         return findNodeInModule(module, path);
243     }
244
245     /**
246      * Returns NotificationDefinition from Schema Context
247      *
248      * @param schema SchemaContext in which lookup should be performed.
249      * @param path Schema Path of notification
250      * @return Notification schema or null, if notification is not present in schema context.
251      */
252     @Beta
253     @Nullable public static NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema,
254             @Nonnull final SchemaPath path) {
255         Preconditions.checkNotNull(schema, "Schema context must not be null.");
256         Preconditions.checkNotNull(path, "Schema path must not be null.");
257         for (final NotificationDefinition potential : schema.getNotifications()) {
258             if (path.equals(potential.getPath())) {
259                return potential;
260             }
261         }
262         return null;
263     }
264
265     /**
266      * Returns RPC Input or Output Data container from RPC definition.
267      *
268      * @param schema SchemaContext in which lookup should be performed.
269      * @param path Schema path of RPC input/output data container
270      * @return Notification schema or null, if notification is not present in schema context.
271      */
272     @Beta
273     @Nullable public static ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema,
274             @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
400             if (foundNode != null && nextPath.iterator().hasNext()) {
401                 foundNode = findNodeIn(foundNode, nextPath);
402             }
403
404             if (foundNode == null) {
405                 // fallback that tries to map into one of the child cases
406                 for (final ChoiceCaseNode caseNode : ((ChoiceSchemaNode) parent).getCases()) {
407                     final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
408                     if (maybeChild != null) {
409                         foundNode = findNodeIn(maybeChild, nextPath);
410                         break;
411                     }
412                 }
413             }
414         }
415
416         if (foundNode == null) {
417             LOG.debug("No node matching {} found in node {}", path, parent);
418         }
419
420         return foundNode;
421
422     }
423
424     private static Iterable<QName> nextLevel(final Iterable<QName> path) {
425         return Iterables.skip(path, 1);
426     }
427
428     private static RpcDefinition getRpcByName(final Module module, final QName name) {
429         for (final RpcDefinition rpc : module.getRpcs()) {
430             if (rpc.getQName().equals(name)) {
431                 return rpc;
432             }
433         }
434         return null;
435     }
436
437     private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
438         for (final NotificationDefinition notification : module.getNotifications()) {
439             if (notification.getQName().equals(name)) {
440                 return notification;
441             }
442         }
443         return null;
444     }
445
446     private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
447         for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
448             if (grouping.getQName().equals(name)) {
449                 return grouping;
450             }
451         }
452         return null;
453     }
454
455     private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) {
456         for (final GroupingDefinition grouping : rpc.getGroupings()) {
457             if (grouping.getQName().equals(name)) {
458                 return grouping;
459             }
460         }
461         return null;
462     }
463
464     /**
465      * Transforms string representation of XPath to Queue of QNames. The XPath
466      * is split by "/" and for each part of XPath is assigned correct module in
467      * Schema Path. <br>
468      * If Schema Context, Parent Module or XPath string contains
469      * <code>null</code> values, the method will throws IllegalArgumentException
470      *
471      * @param context
472      *            Schema Context
473      * @param parentModule
474      *            Parent Module
475      * @param xpath
476      *            XPath String
477      * @return return a list of QName
478      *
479      * @throws IllegalArgumentException
480      */
481     private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
482             final String xpath) {
483         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
484         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
485         Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
486
487         final List<QName> path = new LinkedList<>();
488         for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
489             if (!pathComponent.isEmpty()) {
490                 path.add(stringPathPartToQName(context, parentModule, pathComponent));
491             }
492         }
493         return path;
494     }
495
496     /**
497      * Transforms part of Prefixed Path as java String to QName. <br>
498      * If the string contains module prefix separated by ":" (i.e.
499      * mod:container) this module is provided from from Parent Module list of
500      * imports. If the Prefixed module is present in Schema Context the QName
501      * can be constructed. <br>
502      * If the Prefixed Path Part does not contains prefix the Parent's Module
503      * namespace is taken for construction of QName. <br>
504      * If Schema Context, Parent Module or Prefixed Path Part refers to
505      * <code>null</code> the method will throw IllegalArgumentException
506      *
507      * @param context
508      *            Schema Context
509      * @param parentModule
510      *            Parent Module
511      * @param prefixedPathPart
512      *            Prefixed Path Part string
513      * @return QName from prefixed Path Part String.
514      *
515      * @throws IllegalArgumentException
516      */
517     private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
518             final String prefixedPathPart) {
519         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
520         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
521         Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
522
523         if (prefixedPathPart.indexOf(':') != -1) {
524             final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
525             final String modulePrefix = prefixedName.next();
526
527             final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
528             Preconditions.checkArgument(module != null,
529                     "Failed to resolve xpath: no module found for prefix %s in module %s", modulePrefix,
530                     parentModule.getName());
531
532             return QName.create(module.getQNameModule(), prefixedName.next());
533         }
534
535         return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
536     }
537
538     /**
539      * Method will attempt to resolve and provide Module reference for specified
540      * module prefix. Each Yang module could contains multiple imports which
541      * MUST be associated with corresponding module prefix. The method simply
542      * looks into module imports and returns the module that is bounded with
543      * specified prefix. If the prefix is not present in module or the prefixed
544      * module is not present in specified Schema Context, the method will return
545      * <code>null</code>. <br>
546      * If String prefix is the same as prefix of the specified Module the
547      * reference to this module is returned. <br>
548      * If Schema Context, Module or Prefix are referring to <code>null</code>
549      * the method will return IllegalArgumentException
550      *
551      * @param context
552      *            Schema Context
553      * @param module
554      *            Yang Module
555      * @param prefix
556      *            Module Prefix
557      * @return Module for given prefix in specified Schema Context if is
558      *         present, otherwise returns <code>null</code>
559      *
560      * @throws IllegalArgumentException
561      */
562     private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
563             final String prefix) {
564         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
565         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
566         Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
567
568         if (prefix.equals(module.getPrefix())) {
569             return module;
570         }
571
572         final Set<ModuleImport> imports = module.getImports();
573         for (final ModuleImport mi : imports) {
574             if (prefix.equals(mi.getPrefix())) {
575                 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
576             }
577         }
578         return null;
579     }
580
581     /**
582      * @param context
583      *            Schema Context
584      * @param module
585      *            Yang Module
586      * @param relativeXPath
587      *            Non conditional Revision Aware Relative XPath
588      * @param actualSchemaNode
589      *            actual schema node
590      * @return list of QName
591      *
592      * @throws IllegalArgumentException
593      */
594     private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
595             final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
596         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
597         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
598         Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
599         Preconditions.checkState(!relativeXPath.isAbsolute(),
600                 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
601                         + "for non relative Revision Aware XPath use findDataSchemaNode method");
602         Preconditions.checkState(actualSchemaNode.getPath() != null,
603                 "Schema Path reference for Leafref cannot be NULL");
604
605         final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
606
607         // Find out how many "parent" components there are
608         // FIXME: is .contains() the right check here?
609         // FIXME: case ../../node1/node2/../node3/../node4
610         int colCount = 0;
611         for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
612             ++colCount;
613         }
614
615         final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
616
617         if (Iterables.size(schemaNodePath) - colCount >= 0) {
618             return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
619                 Iterables.transform(Iterables.skip(xpaths, colCount),
620                     input -> stringPathPartToQName(context, module, input)));
621         }
622         return Iterables.concat(schemaNodePath,
623                 Iterables.transform(Iterables.skip(xpaths, colCount),
624                     input -> stringPathPartToQName(context, module, input)));
625     }
626
627     /**
628      * Extracts the base type of node on which schema node points to. If target node is again of type
629      * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
630      *
631      * @param typeDefinition
632      *            type of node which will be extracted
633      * @param schemaContext
634      *            Schema Context
635      * @param schema
636      *            Schema Node
637      * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
638      *         is there to preserve backwards compatibility)
639      */
640     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
641             final SchemaContext schemaContext, final SchemaNode schema) {
642         RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
643         pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement),
644             pathStatement.isAbsolute());
645
646         final DataSchemaNode dataSchemaNode;
647         if (pathStatement.isAbsolute()) {
648             SchemaNode baseSchema = schema;
649             while (baseSchema instanceof DerivableSchemaNode) {
650                 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
651                 if (basePotential.isPresent()) {
652                     baseSchema = basePotential.get();
653                 } else {
654                     break;
655                 }
656             }
657
658             Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
659             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
660                     pathStatement);
661         } else {
662             Module parentModule = findParentModule(schemaContext, schema);
663             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
664                     parentModule, schema, pathStatement);
665         }
666
667         // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
668         // and current expected behaviour for such cases is to just use pure string
669         // This should throw an exception about incorrect XPath in leafref
670         if (dataSchemaNode == null) {
671             return null;
672         }
673
674         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
675
676         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
677             return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
678         }
679
680         return targetTypeDefinition;
681     }
682
683     private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
684             final SchemaNode schemaNode) {
685         Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
686         Preconditions.checkArgument(schemaNode instanceof TypedSchemaNode, "Unsupported node %s", schemaNode);
687
688         TypeDefinition<?> nodeType = ((TypedSchemaNode) schemaNode).getType();
689         if (nodeType.getBaseType() != null) {
690             while (nodeType.getBaseType() != null) {
691                 nodeType = nodeType.getBaseType();
692             }
693
694             final QNameModule typeDefModuleQname = nodeType.getQName().getModule();
695             return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
696                     typeDefModuleQname.getRevision());
697         }
698
699         return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
700     }
701
702     /**
703      * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qName}. This handle
704      * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
705      * module as typedef which is then imported to referenced module.
706      *
707      * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
708      *
709      * @param typeDefinition
710      * @param schemaContext
711      * @param qName
712      */
713     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
714             final SchemaContext schemaContext, final QName qName) {
715         final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
716         final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(
717             stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
718         if (!strippedPathStatement.isAbsolute()) {
719             return null;
720         }
721
722         final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace()
723             ,qName.getRevision());
724         final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
725             parentModule, strippedPathStatement);
726         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
727         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
728             return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
729         }
730
731         return targetTypeDefinition;
732     }
733
734     private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
735
736     /**
737      * Removes conditions from xPath pointed to target node.
738      *
739      * @param pathStatement
740      *            xPath to target node
741      * @return string representation of xPath without conditions
742      *
743      */
744     @VisibleForTesting
745     static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
746         return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
747     }
748
749     /**
750      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
751      *
752      * @param node
753      *            a node representing LeafSchemaNode
754      * @return concrete type definition of node value
755      */
756     private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
757         TypeDefinition<?> baseType = node.getType();
758         while (baseType.getBaseType() != null) {
759             baseType = baseType.getBaseType();
760         }
761         return baseType;
762     }
763
764     /**
765      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
766      *
767      * @param node
768      *            a node representing LeafListSchemaNode
769      * @return concrete type definition of node value
770      */
771     private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
772         TypeDefinition<?> baseType = node.getType();
773         while (baseType.getBaseType() != null) {
774             baseType = baseType.getBaseType();
775         }
776         return baseType;
777     }
778
779     /**
780      * Gets the base type of DataSchemaNode value.
781      *
782      * @param node
783      *            a node representing DataSchemaNode
784      * @return concrete type definition of node value
785      */
786     private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
787         if (node instanceof LeafListSchemaNode) {
788             return typeDefinition((LeafListSchemaNode) node);
789         } else if (node instanceof LeafSchemaNode) {
790             return typeDefinition((LeafSchemaNode) node);
791         } else {
792             throw new IllegalArgumentException("Unhandled parameter type: " + node);
793         }
794     }
795 }