2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.yang2sources.plugin;
10 import java.io.Closeable;
12 import java.io.FileNotFoundException;
13 import java.io.FilenameFilter;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.Collection;
19 import java.util.Enumeration;
20 import java.util.HashMap;
21 import java.util.List;
24 import java.util.zip.ZipEntry;
25 import java.util.zip.ZipFile;
27 import org.apache.commons.io.FileUtils;
28 import org.apache.maven.artifact.Artifact;
29 import org.apache.maven.model.Dependency;
30 import org.apache.maven.model.Plugin;
31 import org.apache.maven.plugin.MojoFailureException;
32 import org.apache.maven.plugin.logging.Log;
33 import org.apache.maven.project.MavenProject;
34 import org.opendaylight.yangtools.yang.model.api.Module;
35 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
36 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
37 import org.sonatype.aether.RepositorySystem;
38 import org.sonatype.aether.RepositorySystemSession;
39 import org.sonatype.aether.collection.CollectRequest;
40 import org.sonatype.aether.graph.DependencyFilter;
41 import org.sonatype.aether.repository.RemoteRepository;
42 import org.sonatype.aether.resolution.ArtifactResult;
43 import org.sonatype.aether.resolution.DependencyRequest;
44 import org.sonatype.aether.resolution.DependencyResolutionException;
45 import org.sonatype.aether.util.artifact.JavaScopes;
46 import org.sonatype.aether.util.filter.DependencyFilterUtils;
48 import com.google.common.base.Preconditions;
49 import com.google.common.collect.Lists;
50 import com.google.common.collect.Maps;
55 * It isn't desirable to create instances of this class
60 static final String YANG_SUFFIX = "yang";
62 private static final int CACHE_SIZE = 10;
63 // Cache for listed directories and found yang files. Typically yang files
64 // are utilized twice. First: code is generated during generate-sources
65 // phase Second: yang files are copied as resources during
66 // generate-resources phase. This cache ensures that yang files are listed
68 private static Map<File, Collection<File>> cache = Maps.newHashMapWithExpectedSize(CACHE_SIZE);
71 * List files recursively and return as array of String paths. Use cache of
74 static Collection<File> listFiles(File root) throws FileNotFoundException {
75 if (cache.get(root) != null) {
76 return cache.get(root);
80 throw new FileNotFoundException(root.toString());
83 Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
85 toCache(root, yangFiles);
89 static Collection<File> listFiles(File root, File[] excludedFiles, Log log) throws FileNotFoundException {
91 throw new FileNotFoundException(root.toString());
93 Collection<File> result = new ArrayList<>();
94 Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
95 for (File f : yangFiles) {
96 boolean excluded = false;
97 for (File ex : excludedFiles) {
105 log.info(Util.message("%s file excluded %s", YangToSourcesProcessor.LOG_PREFIX,
106 Util.YANG_SUFFIX.toUpperCase(), f));
116 private static void toCache(final File rootDir, final Collection<File> yangFiles) {
117 cache.put(rootDir, yangFiles);
121 * Instantiate object from fully qualified class name
123 static <T> T getInstance(String codeGeneratorClass, Class<T> baseType) throws ClassNotFoundException,
124 InstantiationException, IllegalAccessException {
125 return baseType.cast(resolveClass(codeGeneratorClass, baseType).newInstance());
128 private static Class<?> resolveClass(String codeGeneratorClass, Class<?> baseType) throws ClassNotFoundException {
129 Class<?> clazz = Class.forName(codeGeneratorClass);
131 if (!isImplemented(baseType, clazz)) {
132 throw new IllegalArgumentException("Code generator " + clazz + " has to implement " + baseType);
137 private static boolean isImplemented(Class<?> expectedIface, Class<?> byClazz) {
138 for (Class<?> iface : byClazz.getInterfaces()) {
139 if (iface.equals(expectedIface)) {
146 static String message(String message, String logPrefix, Object... args) {
147 String innerMessage = String.format(message, args);
148 return String.format("%s %s", logPrefix, innerMessage);
151 static List<File> getClassPath(MavenProject project) {
152 List<File> dependencies = Lists.newArrayList();
153 for (Artifact element : project.getArtifacts()) {
154 File asFile = element.getFile();
155 if (isJar(asFile) || asFile.isDirectory()) {
156 dependencies.add(asFile);
163 * Read current project dependencies and check if it don't grab incorrect
164 * artifacts versions which could be in conflict with plugin dependencies.
173 * repository system session
175 * remote repositories
177 static void checkClasspath(MavenProject project, Log log, RepositorySystem repoSystem,
178 RepositorySystemSession repoSession, List<RemoteRepository> remoteRepos) {
179 Plugin plugin = project.getPlugin(YangToSourcesMojo.PLUGIN_NAME);
180 if (plugin == null) {
181 log.warn(message("%s not found, dependencies version check skipped", YangToSourcesProcessor.LOG_PREFIX,
182 YangToSourcesMojo.PLUGIN_NAME));
184 Map<org.sonatype.aether.artifact.Artifact, List<org.sonatype.aether.artifact.Artifact>> pluginDependencies = new HashMap<>();
185 getPluginTransitiveDependencies(plugin, pluginDependencies, repoSystem, repoSession, remoteRepos, log);
187 Set<Artifact> projectDependencies = project.getDependencyArtifacts();
188 for (Map.Entry<org.sonatype.aether.artifact.Artifact, List<org.sonatype.aether.artifact.Artifact>> entry : pluginDependencies
190 checkArtifact(entry.getKey(), projectDependencies, log);
191 for (org.sonatype.aether.artifact.Artifact dependency : entry.getValue()) {
192 checkArtifact(dependency, projectDependencies, log);
199 * Read transitive dependencies of given plugin and store them in map.
204 * map, where founded transitive dependencies will be stored
208 * repository system session
210 * list of remote repositories
214 private static void getPluginTransitiveDependencies(Plugin plugin,
215 Map<org.sonatype.aether.artifact.Artifact, List<org.sonatype.aether.artifact.Artifact>> map,
216 RepositorySystem repoSystem, RepositorySystemSession repoSession, List<RemoteRepository> remoteRepos,
218 for (Dependency dep : plugin.getDependencies()) {
219 String artifactCoords = dep.getGroupId() + ":" + dep.getArtifactId() + ":" + dep.getVersion();
220 org.sonatype.aether.artifact.Artifact artifact = new org.sonatype.aether.util.artifact.DefaultArtifact(
223 if (!(map.containsKey(artifact))) {
224 DependencyFilter classpathFlter = DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE);
225 CollectRequest collectRequest = new CollectRequest();
226 collectRequest.setRoot(new org.sonatype.aether.graph.Dependency(artifact, JavaScopes.COMPILE));
227 collectRequest.setRepositories(remoteRepos);
228 DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, classpathFlter);
230 List<ArtifactResult> artifactResults;
232 artifactResults = repoSystem.resolveDependencies(repoSession, dependencyRequest)
233 .getArtifactResults();
234 List<org.sonatype.aether.artifact.Artifact> deps = new ArrayList<>();
235 for (ArtifactResult ar : artifactResults) {
236 deps.add(ar.getArtifact());
238 map.put(artifact, deps);
239 } catch (DependencyResolutionException e) {
240 log.warn(message("Failed to resolve plugin dependencies, version check skipped",
241 YangToSourcesProcessor.LOG_PREFIX));
248 * Check artifact against collection of dependencies. If collection contains
249 * artifact with same groupId and artifactId, but different version, logs a
254 * @param dependencies
255 * collection of dependencies
259 private static void checkArtifact(org.sonatype.aether.artifact.Artifact artifact, Collection<Artifact> dependencies,
261 for (Artifact d : dependencies) {
262 if (artifact.getGroupId().equals(d.getGroupId()) && artifact.getArtifactId().equals(d.getArtifactId())) {
263 if (!(artifact.getVersion().equals(d.getVersion()))) {
264 log.warn(message("Dependency resolution conflict:", YangToSourcesProcessor.LOG_PREFIX));
265 log.warn(message("'%s' dependency [%s] has different version than one "
266 + "declared in current project [%s]. It is recommended to fix this problem "
267 + "because it may cause compilation errors.", YangToSourcesProcessor.LOG_PREFIX,
268 YangToSourcesMojo.PLUGIN_NAME, artifact, d));
274 private static final String JAR_SUFFIX = ".jar";
276 private static boolean isJar(File element) {
277 return (element.isFile() && element.getName().endsWith(JAR_SUFFIX)) ? true : false;
280 static <T> T checkNotNull(T obj, String paramName) {
281 return Preconditions.checkNotNull(obj, "Parameter " + paramName + " is null");
284 static final class YangsInZipsResult implements Closeable {
285 private final List<InputStream> yangStreams;
286 private final List<Closeable> zipInputStreams;
288 private YangsInZipsResult(List<InputStream> yangStreams, List<Closeable> zipInputStreams) {
289 this.yangStreams = yangStreams;
290 this.zipInputStreams = zipInputStreams;
294 public void close() throws IOException {
295 for (InputStream is : yangStreams) {
298 for (Closeable is : zipInputStreams) {
303 public List<InputStream> getYangStreams() {
304 return this.yangStreams;
308 static YangsInZipsResult findYangFilesInDependenciesAsStream(Log log, MavenProject project)
309 throws MojoFailureException {
310 List<InputStream> yangsFromDependencies = new ArrayList<>();
311 List<Closeable> zips = new ArrayList<>();
313 List<File> filesOnCp = Util.getClassPath(project);
314 log.info(Util.message("Searching for yang files in following dependencies: %s",
315 YangToSourcesProcessor.LOG_PREFIX, filesOnCp));
317 for (File file : filesOnCp) {
318 List<String> foundFilesForReporting = new ArrayList<>();
319 // is it jar file or directory?
320 if (file.isDirectory()) {
321 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
322 if (yangDir.exists() && yangDir.isDirectory()) {
323 File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
325 public boolean accept(File dir, String name) {
326 return name.endsWith(".yang") && new File(dir, name).isFile();
329 for (File yangFile : yangFiles) {
330 yangsFromDependencies.add(new NamedFileInputStream(yangFile, YangToSourcesProcessor.META_INF_YANG_STRING + File.separator + yangFile.getName()));
335 ZipFile zip = new ZipFile(file);
338 Enumeration<? extends ZipEntry> entries = zip.entries();
339 while (entries.hasMoreElements()) {
340 ZipEntry entry = entries.nextElement();
341 String entryName = entry.getName();
343 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
344 && !entry.isDirectory() && entryName.endsWith(".yang")) {
345 foundFilesForReporting.add(entryName);
346 // This will be closed after all streams are
348 InputStream entryStream = zip.getInputStream(entry);
349 yangsFromDependencies.add(entryStream);
353 if (foundFilesForReporting.size() > 0) {
354 log.info(Util.message("Found %d yang files in %s: %s", YangToSourcesProcessor.LOG_PREFIX,
355 foundFilesForReporting.size(), file, foundFilesForReporting));
359 } catch (Exception e) {
360 throw new MojoFailureException(e.getMessage(), e);
362 return new YangsInZipsResult(yangsFromDependencies, zips);
365 static Collection<File> findYangFilesInDependencies(Log log, MavenProject project) throws MojoFailureException {
366 final List<File> yangsFilesFromDependencies = new ArrayList<>();
369 List<File> filesOnCp = Util.getClassPath(project);
370 log.info(Util.message("Searching for yang files in following dependencies: %s",
371 YangToSourcesProcessor.LOG_PREFIX, filesOnCp));
373 for (File file : filesOnCp) {
374 // is it jar file or directory?
375 if (file.isDirectory()) {
376 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
377 if (yangDir.exists() && yangDir.isDirectory()) {
378 File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
380 public boolean accept(File dir, String name) {
381 return name.endsWith(".yang") && new File(dir, name).isFile();
385 yangsFilesFromDependencies.addAll(Arrays.asList(yangFiles));
388 try (ZipFile zip = new ZipFile(file)) {
390 final Enumeration<? extends ZipEntry> entries = zip.entries();
391 while (entries.hasMoreElements()) {
392 ZipEntry entry = entries.nextElement();
393 String entryName = entry.getName();
395 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
396 && !entry.isDirectory() && entryName.endsWith(".yang")) {
397 log.debug(Util.message("Found a YANG file in %s: %s", YangToSourcesProcessor.LOG_PREFIX,
399 yangsFilesFromDependencies.add(file);
406 } catch (Exception e) {
407 throw new MojoFailureException("Failed to scan for YANG files in depedencies", e);
409 return yangsFilesFromDependencies;
412 static final class ContextHolder {
413 private final SchemaContext context;
414 private final Set<Module> yangModules;
416 ContextHolder(SchemaContext context, Set<Module> yangModules) {
417 this.context = context;
418 this.yangModules = yangModules;
421 SchemaContext getContext() {
425 Set<Module> getYangModules() {