Merge "Fix checkListKey not checking actual/expected values"
[yangtools.git] / yang / yang-maven-plugin / src / main / java / org / opendaylight / yangtools / yang2sources / plugin / Util.java
index b1dee91efec763483ea461f7fdd0f23cea2a631d..ee9a6897423788f38eeff1bbce37a10103f44411 100644 (file)
@@ -16,7 +16,9 @@ import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.Enumeration;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -25,12 +27,18 @@ import java.util.zip.ZipFile;
 
 import org.apache.commons.io.FileUtils;
 import org.apache.maven.artifact.Artifact;
+import org.apache.maven.artifact.repository.ArtifactRepository;
+import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
+import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
+import org.apache.maven.model.Dependency;
+import org.apache.maven.model.Plugin;
 import org.apache.maven.plugin.MojoFailureException;
 import org.apache.maven.plugin.logging.Log;
 import org.apache.maven.project.MavenProject;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
+import org.apache.maven.repository.RepositorySystem;
 
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
@@ -75,7 +83,10 @@ final class Util {
 
     static Collection<File> listFiles(File root, File[] excludedFiles, Log log) throws FileNotFoundException {
         if (!root.exists()) {
-            throw new FileNotFoundException(root.toString());
+            if (log != null) {
+                log.warn(Util.message("YANG source directory %s not found. No code will be generated.", YangToSourcesProcessor.LOG_PREFIX, root.toString()));
+            }
+            return Collections.emptyList();
         }
         Collection<File> result = new ArrayList<>();
         Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
@@ -115,21 +126,12 @@ final class Util {
     private static Class<?> resolveClass(String codeGeneratorClass, Class<?> baseType) throws ClassNotFoundException {
         Class<?> clazz = Class.forName(codeGeneratorClass);
 
-        if (!isImplemented(baseType, clazz)) {
+        if (!baseType.isAssignableFrom(clazz)) {
             throw new IllegalArgumentException("Code generator " + clazz + " has to implement " + baseType);
         }
         return clazz;
     }
 
-    private static boolean isImplemented(Class<?> expectedIface, Class<?> byClazz) {
-        for (Class<?> iface : byClazz.getInterfaces()) {
-            if (iface.equals(expectedIface)) {
-                return true;
-            }
-        }
-        return false;
-    }
-
     static String message(String message, String logPrefix, Object... args) {
         String innerMessage = String.format(message, args);
         return String.format("%s %s", logPrefix, innerMessage);
@@ -146,6 +148,103 @@ final class Util {
         return dependencies;
     }
 
+    /**
+     * Read current project dependencies and check if it don't grab incorrect
+     * artifacts versions which could be in conflict with plugin dependencies.
+     *
+     * @param project
+     *            current project
+     * @param repoSystem
+     *            repository system
+     * @param localRepo
+     *            local repository
+     * @param remoteRepos
+     *            remote repositories
+     * @param log
+     *            logger
+     */
+    static void checkClasspath(MavenProject project, RepositorySystem repoSystem, ArtifactRepository localRepo,
+            List<ArtifactRepository> remoteRepos, Log log) {
+        Plugin plugin = project.getPlugin(YangToSourcesMojo.PLUGIN_NAME);
+        if (plugin == null) {
+            log.warn(message("%s not found, dependencies version check skipped", YangToSourcesProcessor.LOG_PREFIX,
+                    YangToSourcesMojo.PLUGIN_NAME));
+        } else {
+            Map<Artifact, Collection<Artifact>> pluginDependencies = new HashMap<>();
+            getPluginTransitiveDependencies(plugin, pluginDependencies, repoSystem, localRepo, remoteRepos, log);
+
+            Set<Artifact> projectDependencies = project.getDependencyArtifacts();
+            for (Map.Entry<Artifact, Collection<Artifact>> entry : pluginDependencies.entrySet()) {
+                checkArtifact(entry.getKey(), projectDependencies, log);
+                for (Artifact dependency : entry.getValue()) {
+                    checkArtifact(dependency, projectDependencies, log);
+                }
+            }
+        }
+    }
+
+    /**
+     * Read transitive dependencies of given plugin and store them in map.
+     *
+     * @param plugin
+     *            plugin to read
+     * @param map
+     *            map, where founded transitive dependencies will be stored
+     * @param repoSystem
+     *            repository system
+     * @param localRepository
+     *            local repository
+     * @param remoteRepos
+     *            list of remote repositories
+     * @param log
+     *            logger
+     */
+    private static void getPluginTransitiveDependencies(Plugin plugin, Map<Artifact, Collection<Artifact>> map,
+            RepositorySystem repoSystem, ArtifactRepository localRepository, List<ArtifactRepository> remoteRepos,
+            Log log) {
+
+        List<Dependency> pluginDependencies = plugin.getDependencies();
+        for (Dependency dep : pluginDependencies) {
+            Artifact artifact = repoSystem.createDependencyArtifact(dep);
+
+            ArtifactResolutionRequest request = new ArtifactResolutionRequest();
+            request.setArtifact(artifact);
+            request.setResolveTransitively(true);
+            request.setLocalRepository(localRepository);
+            request.setRemoteRepositories(remoteRepos);
+
+            ArtifactResolutionResult result = repoSystem.resolve(request);
+            Set<Artifact> pluginDependencyDependencies = result.getArtifacts();
+            map.put(artifact, pluginDependencyDependencies);
+        }
+    }
+
+    /**
+     * Check artifact against collection of dependencies. If collection contains
+     * artifact with same groupId and artifactId, but different version, logs a
+     * warning.
+     *
+     * @param artifact
+     *            artifact to check
+     * @param dependencies
+     *            collection of dependencies
+     * @param log
+     *            logger
+     */
+    private static void checkArtifact(Artifact artifact, Collection<Artifact> dependencies, Log log) {
+        for (org.apache.maven.artifact.Artifact d : dependencies) {
+            if (artifact.getGroupId().equals(d.getGroupId()) && artifact.getArtifactId().equals(d.getArtifactId())) {
+                if (!(artifact.getVersion().equals(d.getVersion()))) {
+                    log.warn(message("Dependency resolution conflict:", YangToSourcesProcessor.LOG_PREFIX));
+                    log.warn(message("'%s' dependency [%s] has different version than one "
+                            + "declared in current project [%s]. It is recommended to fix this problem "
+                            + "because it may cause compilation errors.", YangToSourcesProcessor.LOG_PREFIX,
+                            YangToSourcesMojo.PLUGIN_NAME, artifact, d));
+                }
+            }
+        }
+    }
+
     private static final String JAR_SUFFIX = ".jar";
 
     private static boolean isJar(File element) {
@@ -193,6 +292,7 @@ final class Util {
                 List<String> foundFilesForReporting = new ArrayList<>();
                 // is it jar file or directory?
                 if (file.isDirectory()) {
+                    //FIXME: code duplicate
                     File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
                     if (yangDir.exists() && yangDir.isDirectory()) {
                         File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
@@ -248,6 +348,7 @@ final class Util {
             for (File file : filesOnCp) {
                 // is it jar file or directory?
                 if (file.isDirectory()) {
+                    //FIXME: code duplicate
                     File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
                     if (yangDir.exists() && yangDir.isDirectory()) {
                         File[] yangFiles = yangDir.listFiles(new FilenameFilter() {