Do not create temporary array for module sorting
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / util / ModuleDependencySort.java
index a377eb5548f0ebc097c83ddae0745d9cc155391c..bc980c03a0f6cdd5510fa3f61ad3b44aea40fb5c 100644 (file)
@@ -7,40 +7,44 @@
  */
 package org.opendaylight.yangtools.yang.parser.util;
 
-import java.util.ArrayList;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Function;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import java.net.URI;
 import java.util.Arrays;
-import java.util.Collections;
+import java.util.Collection;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
-
+import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
-import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.Node;
 import org.opendaylight.yangtools.yang.parser.util.TopologicalSort.NodeImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-
 /**
- * Creates a module dependency graph from provided {@link ModuleBuilder}s and
- * provides a {@link #sort()} method. It is topological sort and returns modules
- * in order in which they should be processed (e.g. if A imports B, sort returns
- * {B, A}).
+ * Creates a module dependency graph from provided {@link Module}s and
+ * provides a {@link #sort(Module...)} method. It is topological sort and
+ * returns modules in order in which they should be processed (e.g. if A imports
+ * B, sort returns {B, A}).
  */
 public final class ModuleDependencySort {
 
-    private static final Date DEFAULT_REVISION = new Date(0);
+    private static final Date DEFAULT_REVISION = SimpleDateFormatUtil.DEFAULT_DATE_REV;
     private static final Logger LOGGER = LoggerFactory.getLogger(ModuleDependencySort.class);
+    private static final Function<Node, Module> TOPOLOGY_FUNCTION = input -> {
+        if (input == null) {
+            return null;
+        }
+        return ((ModuleNodeImpl) input).getReference();
+    };
 
     /**
      * It is not desirable to instance this class
@@ -49,65 +53,33 @@ public final class ModuleDependencySort {
     }
 
     /**
-     * Topological sort of module builder dependency graph.
-     * 
-     * @return Sorted list of Module builders. Modules can be further processed
-     *         in returned order.
+     * Topological sort of module dependency graph.
+     *
+     * @param modules YANG modules
+     * @return Sorted list of Modules. Modules can be further processed in
+     *         returned order.
      */
-    public static List<ModuleBuilder> sort(ModuleBuilder... builders) {
-        List<Node> sorted = sortInternal(Arrays.asList(builders));
-        // Cast to ModuleBuilder from Node and return
-        return Lists.transform(sorted, new Function<Node, ModuleBuilder>() {
-
-            @Override
-            public ModuleBuilder apply(Node input) {
-                return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
-            }
-        });
-    }
-
-    public static List<ModuleBuilder> sortWithContext(SchemaContext context, ModuleBuilder... builders) {
-        List<Object> modules = new ArrayList<Object>();
-        Collections.addAll(modules, builders);
-        modules.addAll(context.getModules());
-
-        List<Node> sorted = sortInternal(modules);
-        // Cast to ModuleBuilder from Node if possible and return
-        return Lists.transform(sorted, new Function<Node, ModuleBuilder>() {
-
-            @Override
-            public ModuleBuilder apply(Node input) {
-                if (((ModuleNodeImpl) input).getReference() instanceof ModuleBuilder) {
-                    return (ModuleBuilder) ((ModuleNodeImpl) input).getReference();
-                } else {
-                    return null;
-                }
-            }
-        });
+    public static List<Module> sort(final Module... modules) {
+        return sort(Arrays.asList(modules));
     }
 
     /**
      * Topological sort of module dependency graph.
-     * 
+     *
+     * @param modules YANG modules
      * @return Sorted list of Modules. Modules can be further processed in
      *         returned order.
      */
-    public static List<Module> sort(Module... modules) {
-        List<Node> sorted = sortInternal(Arrays.asList(modules));
+    public static List<Module> sort(final Iterable<Module> modules) {
+        final List<TopologicalSort.Node> sorted = sortInternal(modules);
         // Cast to Module from Node and return
-        return Lists.transform(sorted, new Function<Node, Module>() {
-
-            @Override
-            public Module apply(Node input) {
-                return (Module) ((ModuleNodeImpl) input).getReference();
-            }
-        });
+        return Lists.transform(sorted, TOPOLOGY_FUNCTION);
     }
 
-    private static List<Node> sortInternal(List<?> modules) {
+    private static List<TopologicalSort.Node> sortInternal(final Iterable<Module> modules) {
         Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = createModuleGraph(modules);
 
-        Set<Node> nodes = Sets.newHashSet();
+        Set<TopologicalSort.Node> nodes = Sets.newHashSet();
         for (Map<Date, ModuleNodeImpl> map : moduleGraph.values()) {
             for (ModuleNodeImpl node : map.values()) {
                 nodes.add(node);
@@ -118,7 +90,7 @@ public final class ModuleDependencySort {
     }
 
     @VisibleForTesting
-    static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(List<?> builders) {
+    static Map<String, Map<Date, ModuleNodeImpl>> createModuleGraph(final Iterable<Module> builders) {
         Map<String, Map<Date, ModuleNodeImpl>> moduleGraph = Maps.newHashMap();
 
         processModules(moduleGraph, builders);
@@ -130,25 +102,38 @@ public final class ModuleDependencySort {
     /**
      * Extract module:revision from module builders
      */
-    private static void processDependencies(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, List<?> builders) {
-        Map<String, Date> imported = Maps.newHashMap();
+    private static void processDependencies(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
+            final Iterable<Module> mmbs) {
+        Map<URI, Module> allNS = new HashMap<>();
 
         // Create edges in graph
-        for (Object mb : builders) {
-
-            String fromName = null;
-            Date fromRevision = null;
-            Set<ModuleImport> imports = null;
-
-            if (mb instanceof Module) {
-                fromName = ((Module) mb).getName();
-                fromRevision = ((Module) mb).getRevision();
-                imports = ((Module) mb).getImports();
-            } else if (mb instanceof ModuleBuilder) {
-                fromName = ((ModuleBuilder) mb).getName();
-                fromRevision = ((ModuleBuilder) mb).getRevision();
-                imports = ((ModuleBuilder) mb).getModuleImports();
+        for (Module module : mmbs) {
+            Map<String, Date> imported = Maps.newHashMap();
+
+            String fromName;
+            Date fromRevision;
+            Collection<ModuleImport> imports;
+            URI ns;
+
+            fromName = module.getName();
+            fromRevision = module.getRevision();
+            imports = module.getImports();
+            ns = module.getNamespace();
+
+            // check for existence of module with same namespace
+            if (allNS.containsKey(ns)) {
+                final Module mod = allNS.get(ns);
+                final String name = mod.getName();
+                final Date revision = mod.getRevision();
+                if (!fromName.equals(name)) {
+                    LOGGER.warn(
+                            "Error while sorting module [{}, {}]: module with same namespace ({}) already loaded: [{}, {}]",
+                            fromName, fromRevision, ns, name, revision);
+                }
+            } else {
+                allNS.put(ns, module);
             }
+
             // no need to check if other Type of object, check is performed in
             // process modules
 
@@ -184,8 +169,8 @@ public final class ModuleDependencySort {
     /**
      * Get imported module by its name and revision from moduleGraph
      */
-    private static ModuleNodeImpl getModuleByNameAndRevision(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
-            String fromName, Date fromRevision, String toName, Date toRevision) {
+    private static ModuleNodeImpl getModuleByNameAndRevision(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
+            final String fromName, final Date fromRevision, final String toName, final Date toRevision) {
         ModuleNodeImpl to = null;
 
         if (moduleGraph.get(toName) == null || !moduleGraph.get(toName).containsKey(toRevision)) {
@@ -194,11 +179,14 @@ public final class ModuleDependencySort {
             if (moduleGraph.get(toName) != null && !moduleGraph.get(toName).isEmpty()
                     && toRevision.equals(DEFAULT_REVISION)) {
                 to = moduleGraph.get(toName).values().iterator().next();
-                LOGGER.warn(String
+                LOGGER.trace(String
                         .format("Import:%s:%s by module:%s:%s does not specify revision, using:%s:%s for module dependency sort",
                                 toName, formatRevDate(toRevision), fromName, formatRevDate(fromRevision), to.getName(),
                                 formatRevDate(to.getRevision())));
             } else {
+                LOGGER.warn(String.format("Not existing module imported:%s:%s by:%s:%s", toName,
+                        formatRevDate(toRevision), fromName, formatRevDate(fromRevision)));
+                LOGGER.warn("Available models: {}", moduleGraph);
                 ex(String.format("Not existing module imported:%s:%s by:%s:%s", toName, formatRevDate(toRevision),
                         fromName, formatRevDate(fromRevision)));
             }
@@ -208,7 +196,7 @@ public final class ModuleDependencySort {
         return to;
     }
 
-    private static void ex(String message) {
+    private static void ex(final String message) {
         throw new YangValidationException(message);
     }
 
@@ -216,56 +204,44 @@ public final class ModuleDependencySort {
      * Extract dependencies from module builders or modules to fill dependency
      * graph
      */
-    private static void processModules(Map<String, Map<Date, ModuleNodeImpl>> moduleGraph, List<?> builders) {
+    private static void processModules(final Map<String, Map<Date, ModuleNodeImpl>> moduleGraph,
+            final Iterable<Module> modules) {
 
         // Process nodes
-        for (Object mb : builders) {
-
-            String name = null;
-            Date rev = null;
-
-            if (mb instanceof Module) {
-                name = ((Module) mb).getName();
-                rev = ((Module) mb).getRevision();
-            } else if (mb instanceof ModuleBuilder) {
-                name = ((ModuleBuilder) mb).getName();
-                rev = ((ModuleBuilder) mb).getRevision();
-            } else {
-                throw new IllegalStateException(String.format(
-                        "Unexpected type of node for sort, expected only:%s, %s, got:%s", Module.class,
-                        ModuleBuilder.class, mb.getClass()));
-            }
+        for (Module momb : modules) {
 
+            String name = momb.getName();
+            Date rev = momb.getRevision();
             if (rev == null) {
                 rev = DEFAULT_REVISION;
             }
 
             if (moduleGraph.get(name) == null) {
-                moduleGraph.put(name, Maps.<Date, ModuleNodeImpl> newHashMap());
+                moduleGraph.put(name, Maps.newHashMap());
             }
 
             if (moduleGraph.get(name).get(rev) != null) {
                 ex(String.format("Module:%s with revision:%s declared twice", name, formatRevDate(rev)));
             }
 
-            moduleGraph.get(name).put(rev, new ModuleNodeImpl(name, rev, mb));
+            moduleGraph.get(name).put(rev, new ModuleNodeImpl(name, rev, momb));
         }
     }
 
-    private static String formatRevDate(Date rev) {
-        return rev.equals(DEFAULT_REVISION) ? "default" : YangParserListenerImpl.SIMPLE_DATE_FORMAT.format(rev);
+    private static String formatRevDate(final Date rev) {
+        return rev.equals(DEFAULT_REVISION) ? "default" : SimpleDateFormatUtil.getRevisionFormat().format(rev);
     }
 
     @VisibleForTesting
     static class ModuleNodeImpl extends NodeImpl {
         private final String name;
         private final Date revision;
-        private final Object originalObject;
+        private final Module originalObject;
 
-        public ModuleNodeImpl(String name, Date revision, Object builder) {
+        public ModuleNodeImpl(final String name, final Date revision, final Module module) {
             this.name = name;
             this.revision = revision;
-            this.originalObject = builder;
+            this.originalObject = module;
         }
 
         public String getName() {
@@ -280,13 +256,13 @@ public final class ModuleDependencySort {
         public int hashCode() {
             final int prime = 31;
             int result = 1;
-            result = prime * result + ((name == null) ? 0 : name.hashCode());
-            result = prime * result + ((revision == null) ? 0 : revision.hashCode());
+            result = prime * result + Objects.hashCode(name);
+            result = prime * result + Objects.hashCode(revision);
             return result;
         }
 
         @Override
-        public boolean equals(Object obj) {
+        public boolean equals(final Object obj) {
             if (this == obj) {
                 return true;
             }
@@ -319,7 +295,7 @@ public final class ModuleDependencySort {
             return "Module [name=" + name + ", revision=" + formatRevDate(revision) + "]";
         }
 
-        public Object getReference() {
+        public Module getReference() {
             return originalObject;
         }