Refactor TypedSchemaNode
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / util / SchemaContextUtil.java
index 21d2d28113fcb2ef6d68c402a97a8f6a5fb800d0..3c367be6427e953795c183ff203e92f5fa077baf 100644 (file)
@@ -9,19 +9,19 @@ package org.opendaylight.yangtools.yang.model.util;
 
 import com.google.common.annotations.Beta;
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Splitter;
 import com.google.common.collect.Iterables;
+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;
@@ -40,8 +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.TypedDataSchemaNode;
 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;
 
@@ -66,7 +68,7 @@ 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.
      *
      * @param context
@@ -75,8 +77,7 @@ public final class SchemaContextUtil {
      *            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
+     * @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");
@@ -119,7 +120,6 @@ public final class SchemaContextUtil {
      * @return Returns Data Schema Node for specified Schema Context for given
      *         Non-conditional Revision Aware XPath, or <code>null</code> if the
      *         DataSchemaNode is not present in Schema Context.
-     * @throws IllegalArgumentException
      */
     public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
             final RevisionAwareXPath nonCondXPath) {
@@ -177,8 +177,6 @@ public final class SchemaContextUtil {
      * @return DataSchemaNode if is present in specified Schema Context for
      *         given relative Revision Aware XPath, otherwise will return
      *         <code>null</code>.
-     *
-     * @throws IllegalArgumentException
      */
     public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
             final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
@@ -214,8 +212,6 @@ public final class SchemaContextUtil {
      *            Schema Node
      * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
      *         return <code>null</code>
-     *
-     * @throws IllegalArgumentException
      */
     public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
@@ -226,37 +222,38 @@ public final class SchemaContextUtil {
         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.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
+        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
-    @Nullable public static NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema,
+    @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;
@@ -270,7 +267,8 @@ public final class SchemaContextUtil {
      * @return Notification schema or null, if notification is not present in schema context.
      */
     @Beta
-    @Nullable public static ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema,
+    @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.");
@@ -281,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");
@@ -403,7 +425,7 @@ public final class SchemaContextUtil {
 
             if (foundNode == null) {
                 // fallback that tries to map into one of the child cases
-                for (final ChoiceCaseNode caseNode : ((ChoiceSchemaNode) parent).getCases()) {
+                for (final ChoiceCaseNode caseNode : ((ChoiceSchemaNode) parent).getCases().values()) {
                     final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
                     if (maybeChild != null) {
                         foundNode = findNodeIn(maybeChild, nextPath);
@@ -476,10 +498,12 @@ public final class SchemaContextUtil {
      *            XPath String
      * @return return a list of QName
      *
-     * @throws IllegalArgumentException
+     * @throws IllegalArgumentException if any arguments are null
+     *
      */
     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");
@@ -511,11 +535,11 @@ public final class SchemaContextUtil {
      * @param prefixedPathPart
      *            Prefixed Path Part string
      * @return QName from prefixed Path Part String.
-     *
-     * @throws IllegalArgumentException
+     * @throws IllegalArgumentException if any arguments are null
      */
     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!");
@@ -556,11 +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
+     * @throws IllegalArgumentException if any arguments are null
      */
     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");
@@ -572,13 +596,15 @@ 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;
     }
 
     /**
+     * Resolve a relative XPath into a set of QNames.
+     *
      * @param context
      *            Schema Context
      * @param module
@@ -588,11 +614,11 @@ public final class SchemaContextUtil {
      * @param actualSchemaNode
      *            actual schema node
      * @return list of QName
-     *
-     * @throws IllegalArgumentException
+     * @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");
@@ -674,44 +700,22 @@ public final class SchemaContextUtil {
         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
 
         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
-            return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
+            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();
-            }
-
-            final QNameModule typeDefModuleQname = nodeType.getQName().getModule();
-            return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
-                    typeDefModuleQname.getRevision());
-        }
-
-        return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
-    }
-
     /**
-     * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qName}. This handle
+     * 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
      */
     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());
@@ -719,18 +723,36 @@ public final class SchemaContextUtil {
             return null;
         }
 
-        final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace()
-            ,qName.getRevision());
+        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, strippedPathStatement);
+            parentModule.get(), strippedPathStatement);
         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
-            return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
+            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 TypedDataSchemaNode, "Unsupported node %s", schemaNode);
+
+        TypeDefinition<?> nodeType = ((TypedDataSchemaNode) 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("\\[[^\\[\\]]*\\]");
 
     /**
@@ -739,7 +761,6 @@ public final class SchemaContextUtil {
      * @param pathStatement
      *            xPath to target node
      * @return string representation of xPath without conditions
-     *
      */
     @VisibleForTesting
     static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {