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