Remove useless UnsupportedOperationException throws
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / util / ModuleDependencySort.java
index 1d04ee310fee44559d23ca5be1bdb710a9ccfc66..83c2e07d9061064353d837a07bd6045f8f8f5923 100644 (file)
@@ -12,9 +12,11 @@ import com.google.common.collect.HashBasedTable;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Table;
 import java.net.URI;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
@@ -38,11 +40,19 @@ import org.slf4j.LoggerFactory;
 public final class ModuleDependencySort {
     private static final Logger LOG = LoggerFactory.getLogger(ModuleDependencySort.class);
 
+    private ModuleDependencySort() {
+        // Hidden on purpose
+    }
+
     /**
-     * It is not desirable to instance this class.
+     * Topological sort of module dependency graph.
+     *
+     * @param modules YANG modules
+     * @return Sorted list of Modules. Modules can be further processed in returned order.
+     * @throws IllegalArgumentException when provided modules are not consistent.
      */
-    private ModuleDependencySort() {
-        throw new UnsupportedOperationException();
+    public static List<Module> sort(final Module... modules) {
+        return sort(Arrays.asList(modules));
     }
 
     /**
@@ -98,7 +108,7 @@ public final class ModuleDependencySort {
             }
 
             // no need to check if other Type of object, check is performed in process modules
-            for (final ModuleImport imprt : module.getImports()) {
+            for (final ModuleImport imprt : allImports(module)) {
                 final String toName = imprt.getModuleName();
                 final Optional<Revision> toRevision = imprt.getRevision();
 
@@ -127,6 +137,19 @@ public final class ModuleDependencySort {
         }
     }
 
+    private static Collection<ModuleImport> allImports(final Module mod) {
+        if (mod.getSubmodules().isEmpty()) {
+            return mod.getImports();
+        }
+
+        final Collection<ModuleImport> concat = new LinkedHashSet<>();
+        concat.addAll(mod.getImports());
+        for (Module sub : mod.getSubmodules()) {
+            concat.addAll(sub.getImports());
+        }
+        return concat;
+    }
+
     /**
      * Get imported module by its name and revision from moduleGraph.
      */
@@ -140,7 +163,7 @@ public final class ModuleDependencySort {
         }
 
         // If revision is not specified in import, but module exists with different revisions, take first one
-        if (toRevision == null) {
+        if (!toRevision.isPresent()) {
             final Map<Optional<Revision>, ModuleNodeImpl> modulerevs = moduleGraph.row(toName);
 
             if (!modulerevs.isEmpty()) {