Eliminate ModuleIdentifier
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / util / SchemaContextUtil.java
index 20fe4ceb3a5401687394ef46377510441eaa9862..628a1c8be42633b3dae02c4dc587cde4b6e71e8c 100644 (file)
@@ -8,23 +8,26 @@
 package org.opendaylight.yangtools.yang.model.util;
 
 import com.google.common.annotations.Beta;
-import com.google.common.base.Function;
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Splitter;
 import com.google.common.collect.Iterables;
-import java.util.Arrays;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Optional;
 import java.util.Set;
+import java.util.regex.Pattern;
 import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
@@ -37,7 +40,10 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
+import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -62,17 +68,16 @@ public final class SchemaContextUtil {
      * the end of the SchemaPath. If the DataSchemaNode is not present in the
      * Schema Context the method will return <code>null</code>. <br>
      * In case that Schema Context or Schema Path are not specified correctly
-     * (i.e. contains <code>null</code> values) the method will return
+     * (i.e. contains <code>null</code> values) the method will throw
      * IllegalArgumentException.
      *
-     * @throws IllegalArgumentException
-     *
      * @param context
      *            Schema Context
      * @param schemaPath
      *            Schema Path to search for
      * @return SchemaNode from the end of the Schema Path or <code>null</code>
      *         if the Node is not present.
+     * @throws IllegalArgumentException if context or schemaPath is not correct.
      */
     public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
@@ -106,8 +111,6 @@ public final class SchemaContextUtil {
      * method will return specified Data Schema Node, otherwise the operation
      * will fail and method will return <code>null</code>.
      *
-     * @throws IllegalArgumentException
-     *
      * @param context
      *            Schema Context
      * @param module
@@ -118,14 +121,16 @@ public final class SchemaContextUtil {
      *         Non-conditional Revision Aware XPath, or <code>null</code> if the
      *         DataSchemaNode is not present in Schema Context.
      */
-    public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module, final RevisionAwareXPath nonCondXPath) {
+    public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
+            final RevisionAwareXPath nonCondXPath) {
         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
         Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
 
         final String strXPath = nonCondXPath.toString();
         if (strXPath != null) {
-            Preconditions.checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
+            Preconditions.checkArgument(strXPath.indexOf('[') == -1,
+                    "Revision Aware XPath may not contain a condition");
             if (nonCondXPath.isAbsolute()) {
                 final List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath);
                 if (qnamedPath != null) {
@@ -161,8 +166,6 @@ public final class SchemaContextUtil {
      * the method will return specified Data Schema Node, otherwise the
      * operation will fail and method will return <code>null</code>.
      *
-     * @throws IllegalArgumentException
-     *
      * @param context
      *            Schema Context
      * @param module
@@ -203,15 +206,12 @@ public final class SchemaContextUtil {
      * If Schema Context or Schema Node contains <code>null</code> references
      * the method will throw IllegalArgumentException
      *
-     * @throws IllegalArgumentException
-     *
      * @param context
      *            Schema Context
      * @param schemaNode
      *            Schema Node
-     * @return Yang Module for specified Schema Context and Schema Node, if
-     *         Schema Node is NOT present, the method will returns
-     *         <code>null</code>
+     * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
+     *         return <code>null</code>
      */
     public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
@@ -219,40 +219,41 @@ public final class SchemaContextUtil {
         Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
                 + "set properly (Schema Path is NULL)");
 
-        final QName qname = Iterables.getFirst(schemaNode.getPath().getPathTowardsRoot(), null);
-        Preconditions.checkState(qname != null,
-                "Schema Path contains invalid state of path parts. " +
-                        "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
-        return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
+        final QName qname = schemaNode.getPath().getLastComponent();
+        Preconditions.checkState(qname != null, "Schema Path contains invalid state of path parts. "
+                + "The Schema Path MUST contain at least ONE QName  which defines namespace and Local name of path.");
+        return context.findModule(qname.getModule()).orElse(null);
     }
 
     public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
         final QName current = path.iterator().next();
 
         LOG.trace("Looking up module {} in context {}", current, path);
-        final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
-        if (module == null) {
+        final Optional<Module> module = context.findModule(current.getModule());
+        if (!module.isPresent()) {
             LOG.debug("Module {} not found", current);
             return null;
         }
 
-        return findNodeInModule(module, path);
+        return findNodeInModule(module.get(), path);
     }
 
     /**
-     * Returns NotificationDefinition from Schema Context
+     * Returns NotificationDefinition from Schema Context.
      *
      * @param schema SchemaContext in which lookup should be performed.
      * @param path Schema Path of notification
      * @return Notification schema or null, if notification is not present in schema context.
      */
     @Beta
-    public static @Nullable NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema,@Nonnull  final SchemaPath path) {
+    @Nullable
+    public static NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema,
+            @Nonnull final SchemaPath path) {
         Preconditions.checkNotNull(schema, "Schema context must not be null.");
         Preconditions.checkNotNull(path, "Schema path must not be null.");
         for (final NotificationDefinition potential : schema.getNotifications()) {
             if (path.equals(potential.getPath())) {
-               return potential;
+                return potential;
             }
         }
         return null;
@@ -266,7 +267,9 @@ public final class SchemaContextUtil {
      * @return Notification schema or null, if notification is not present in schema context.
      */
     @Beta
-    public static @Nullable ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema,@Nonnull  final SchemaPath path) {
+    @Nullable
+    public static ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema,
+            @Nonnull final SchemaPath path) {
         Preconditions.checkNotNull(schema, "Schema context must not be null.");
         Preconditions.checkNotNull(path, "Schema path must not be null.");
         final Iterator<QName> it = path.getPathFromRoot().iterator();
@@ -276,12 +279,36 @@ public final class SchemaContextUtil {
         final QName inOrOut = it.next();
         for (final RpcDefinition potential : schema.getOperations()) {
             if (rpcName.equals(potential.getQName())) {
-               return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
+                return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
             }
         }
         return null;
     }
 
+    /**
+     * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
+     *
+     * @param context SchemaContext to be examined
+     * @return Set of ModuleIdentifiers.
+     */
+    public static Set<SourceIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
+        final Set<SourceIdentifier> ret = new HashSet<>();
+
+        for (Module module : context.getModules()) {
+            ret.add(moduleToIdentifier(module));
+
+            for (Module submodule : module.getSubmodules()) {
+                ret.add(moduleToIdentifier(submodule));
+            }
+        }
+
+        return ret;
+    }
+
+    private static SourceIdentifier moduleToIdentifier(final Module module) {
+        return RevisionSourceIdentifier.create(module.getName(), module.getRevision());
+    }
+
     private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
 
         Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
@@ -391,9 +418,21 @@ public final class SchemaContextUtil {
 
         if (foundNode == null && parent instanceof ChoiceSchemaNode) {
             foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
+
             if (foundNode != null && nextPath.iterator().hasNext()) {
                 foundNode = findNodeIn(foundNode, nextPath);
             }
+
+            if (foundNode == null) {
+                // fallback that tries to map into one of the child cases
+                for (final ChoiceCaseNode caseNode : ((ChoiceSchemaNode) parent).getCases().values()) {
+                    final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
+                    if (maybeChild != null) {
+                        foundNode = findNodeIn(maybeChild, nextPath);
+                        break;
+                    }
+                }
+            }
         }
 
         if (foundNode == null) {
@@ -451,8 +490,6 @@ public final class SchemaContextUtil {
      * If Schema Context, Parent Module or XPath string contains
      * <code>null</code> values, the method will throws IllegalArgumentException
      *
-     * @throws IllegalArgumentException
-     *
      * @param context
      *            Schema Context
      * @param parentModule
@@ -460,13 +497,18 @@ public final class SchemaContextUtil {
      * @param xpath
      *            XPath String
      * @return return a list of QName
+     *
+     * @throws IllegalArgumentException if any arguments are null
+     *
      */
-    private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule, final String xpath) {
+    private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
+            final String xpath) {
+        // FIXME: 2.0.0: this should throw NPE, not IAE
         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
         Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
 
-        final List<QName> path = new LinkedList<QName>();
+        final List<QName> path = new LinkedList<>();
         for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
             if (!pathComponent.isEmpty()) {
                 path.add(stringPathPartToQName(context, parentModule, pathComponent));
@@ -486,8 +528,6 @@ public final class SchemaContextUtil {
      * If Schema Context, Parent Module or Prefixed Path Part refers to
      * <code>null</code> the method will throw IllegalArgumentException
      *
-     * @throws IllegalArgumentException
-     *
      * @param context
      *            Schema Context
      * @param parentModule
@@ -495,8 +535,11 @@ public final class SchemaContextUtil {
      * @param prefixedPathPart
      *            Prefixed Path Part string
      * @return QName from prefixed Path Part String.
+     * @throws IllegalArgumentException if any arguments are null
      */
-    private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule, final String prefixedPathPart) {
+    private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
+            final String prefixedPathPart) {
+        // FIXME: 2.0.0: this should throw NPE, not IAE
         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
         Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
@@ -506,13 +549,14 @@ public final class SchemaContextUtil {
             final String modulePrefix = prefixedName.next();
 
             final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
-            Preconditions.checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
-                    modulePrefix, parentModule.getName());
+            Preconditions.checkArgument(module != null,
+                    "Failed to resolve xpath: no module found for prefix %s in module %s", modulePrefix,
+                    parentModule.getName());
 
             return QName.create(module.getQNameModule(), prefixedName.next());
-        } else {
-            return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
         }
+
+        return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
     }
 
     /**
@@ -528,8 +572,6 @@ public final class SchemaContextUtil {
      * If Schema Context, Module or Prefix are referring to <code>null</code>
      * the method will return IllegalArgumentException
      *
-     * @throws IllegalArgumentException
-     *
      * @param context
      *            Schema Context
      * @param module
@@ -538,8 +580,11 @@ public final class SchemaContextUtil {
      *            Module Prefix
      * @return Module for given prefix in specified Schema Context if is
      *         present, otherwise returns <code>null</code>
+     * @throws IllegalArgumentException if any arguments are null
      */
-    private static Module resolveModuleForPrefix(final SchemaContext context, final Module module, final String prefix) {
+    private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
+            final String prefix) {
+        // FIXME: 2.0.0: this should throw NPE, not IAE
         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
         Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
@@ -551,14 +596,14 @@ public final class SchemaContextUtil {
         final Set<ModuleImport> imports = module.getImports();
         for (final ModuleImport mi : imports) {
             if (prefix.equals(mi.getPrefix())) {
-                return context.findModuleByName(mi.getModuleName(), mi.getRevision());
+                return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
             }
         }
         return null;
     }
 
     /**
-     * @throws IllegalArgumentException
+     * Resolve a relative XPath into a set of QNames.
      *
      * @param context
      *            Schema Context
@@ -569,9 +614,11 @@ public final class SchemaContextUtil {
      * @param actualSchemaNode
      *            actual schema node
      * @return list of QName
+     * @throws IllegalArgumentException if any arguments are null
      */
     private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
             final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
+        // FIXME: 2.0.0: this should throw NPE, not IAE
         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
         Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
@@ -595,25 +642,17 @@ public final class SchemaContextUtil {
 
         if (Iterables.size(schemaNodePath) - colCount >= 0) {
             return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
-                    Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
-                        @Override
-                        public QName apply(final String input) {
-                            return stringPathPartToQName(context, module, input);
-                        }
-                    }));
+                Iterables.transform(Iterables.skip(xpaths, colCount),
+                    input -> stringPathPartToQName(context, module, input)));
         }
         return Iterables.concat(schemaNodePath,
-                Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
-                    @Override
-                    public QName apply(final String input) {
-                        return stringPathPartToQName(context, module, input);
-                    }
-                }));
+                Iterables.transform(Iterables.skip(xpaths, colCount),
+                    input -> stringPathPartToQName(context, module, input)));
     }
 
     /**
-     * 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
-     * type definition.
+     * 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 type definition.
      *
      * @param typeDefinition
      *            type of node which will be extracted
@@ -621,121 +660,111 @@ public final class SchemaContextUtil {
      *            Schema Context
      * @param schema
      *            Schema Node
-     * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null is there to preserve backwards compatibility)
+     * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
+     *         is there to preserve backwards compatibility)
      */
-    public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition, final SchemaContext schemaContext, final SchemaNode schema) {
+    public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
+            final SchemaContext schemaContext, final SchemaNode schema) {
         RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
-        pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
-
-        Module parentModule = findParentModuleByType(schemaContext, schema);
+        pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement),
+            pathStatement.isAbsolute());
 
         final DataSchemaNode dataSchemaNode;
-        if(pathStatement.isAbsolute()) {
-            dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, pathStatement);
+        if (pathStatement.isAbsolute()) {
+            SchemaNode baseSchema = schema;
+            while (baseSchema instanceof DerivableSchemaNode) {
+                final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
+                if (basePotential.isPresent()) {
+                    baseSchema = basePotential.get();
+                } else {
+                    break;
+                }
+            }
+
+            Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
+            dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
+                    pathStatement);
         } else {
-            dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule, schema, pathStatement);
+            Module parentModule = findParentModule(schemaContext, schema);
+            dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
+                    parentModule, schema, pathStatement);
         }
 
         // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
         // and current expected behaviour for such cases is to just use pure string
         // This should throw an exception about incorrect XPath in leafref
-        if(dataSchemaNode == null) {
+        if (dataSchemaNode == null) {
             return null;
         }
 
         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
 
-        if(targetTypeDefinition instanceof LeafrefTypeDefinition) {
-            return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
-        } else {
-            return targetTypeDefinition;
-        }
-    }
-
-    /**
-     * Returns parent Yang Module for specified Schema Context in which Schema
-     * Node is declared. If Schema Node is of type 'ExtendedType' it tries to find parent module
-     * in which the type was originally declared (needed for correct leafref path resolution). <br>
-     * If the Schema Node is not present in Schema Context the
-     * operation will return <code>null</code>. <br>
-     * If Schema Context or Schema Node contains <code>null</code> references
-     * the method will throw IllegalArgumentException
-     *
-     * @throws IllegalArgumentException
-     *
-     * @param schemaContext
-     *            Schema Context
-     * @param schemaNode
-     *            Schema Node
-     * @return Yang Module for specified Schema Context and Schema Node, if
-     *         Schema Node is NOT present, the method will returns
-     *         <code>null</code>
-     */
-    public static Module findParentModuleByType(final SchemaContext schemaContext, final SchemaNode schemaNode) {
-        Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
-        Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
-        TypeDefinition<?> nodeType = null;
-
-        if (schemaNode instanceof LeafSchemaNode) {
-            nodeType = ((LeafSchemaNode) schemaNode).getType();
-        } else if (schemaNode instanceof LeafListSchemaNode) {
-            nodeType = ((LeafListSchemaNode) schemaNode).getType();
-        }
-
-        if (nodeType != null && nodeType instanceof ExtendedType) {
-            while (nodeType.getBaseType() instanceof ExtendedType) {
-                nodeType = nodeType.getBaseType();
-            }
-
-            QNameModule typeDefModuleQname = nodeType.getQName().getModule();
-
-            return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
-                    typeDefModuleQname.getRevision());
+        if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
+            return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
         }
 
-        return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
+        return targetTypeDefinition;
     }
 
     /**
-     * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qName}. This handle case
-     * when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other module as typedef
-     * which is then imported to referenced module.
+     * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
+     * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
+     * module as typedef which is then imported to referenced module.
      *
+     * <p>
      * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
-     *
-     * @param typeDefinition
-     * @param schemaContext
-     * @param qName
-     * @return
      */
     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
-            final SchemaContext schemaContext, final QName qName) {
+            final SchemaContext schemaContext, final QName qname) {
         final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
-        final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
+        final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(
+            stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
         if (!strippedPathStatement.isAbsolute()) {
             return null;
         }
 
-        final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace(),qName.getRevision());
-        final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, strippedPathStatement);
+        final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
+        Preconditions.checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
+
+        final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
+            parentModule.get(), strippedPathStatement);
         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
-            return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
-        } else {
-            return targetTypeDefinition;
+            return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
+        }
+
+        return targetTypeDefinition;
+    }
+
+    private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
+            final SchemaNode schemaNode) {
+        Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
+        Preconditions.checkArgument(schemaNode instanceof TypedSchemaNode, "Unsupported node %s", schemaNode);
+
+        TypeDefinition<?> nodeType = ((TypedSchemaNode) schemaNode).getType();
+        if (nodeType.getBaseType() != null) {
+            while (nodeType.getBaseType() != null) {
+                nodeType = nodeType.getBaseType();
+            }
+
+            return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
         }
+
+        return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
     }
 
+    private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
+
     /**
      * Removes conditions from xPath pointed to target node.
      *
      * @param pathStatement
      *            xPath to target node
      * @return string representation of xPath without conditions
-     *
      */
-    private static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
-        return pathStatement.toString().replaceAll("\\[.*\\]", "");
+    @VisibleForTesting
+    static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
+        return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
     }
 
     /**
@@ -745,7 +774,7 @@ public final class SchemaContextUtil {
      *            a node representing LeafSchemaNode
      * @return concrete type definition of node value
      */
-    private static TypeDefinition<? extends Object> typeDefinition(final LeafSchemaNode node) {
+    private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
         TypeDefinition<?> baseType = node.getType();
         while (baseType.getBaseType() != null) {
             baseType = baseType.getBaseType();
@@ -760,7 +789,7 @@ public final class SchemaContextUtil {
      *            a node representing LeafListSchemaNode
      * @return concrete type definition of node value
      */
-    private static TypeDefinition<? extends Object> typeDefinition(final LeafListSchemaNode node) {
+    private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
         TypeDefinition<?> baseType = node.getType();
         while (baseType.getBaseType() != null) {
             baseType = baseType.getBaseType();
@@ -775,13 +804,13 @@ public final class SchemaContextUtil {
      *            a node representing DataSchemaNode
      * @return concrete type definition of node value
      */
-    private static TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
+    private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
         if (node instanceof LeafListSchemaNode) {
             return typeDefinition((LeafListSchemaNode) node);
         } else if (node instanceof LeafSchemaNode) {
             return typeDefinition((LeafSchemaNode) node);
         } else {
-            throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
+            throw new IllegalArgumentException("Unhandled parameter type: " + node);
         }
     }
 }