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.Collections;
20 import java.util.Enumeration;
21 import java.util.HashMap;
22 import java.util.List;
25 import java.util.zip.ZipEntry;
26 import java.util.zip.ZipFile;
28 import org.apache.commons.io.FileUtils;
29 import org.apache.maven.artifact.Artifact;
30 import org.apache.maven.artifact.repository.ArtifactRepository;
31 import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
32 import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
33 import org.apache.maven.model.Dependency;
34 import org.apache.maven.model.Plugin;
35 import org.apache.maven.plugin.MojoFailureException;
36 import org.apache.maven.plugin.logging.Log;
37 import org.apache.maven.project.MavenProject;
38 import org.opendaylight.yangtools.yang.model.api.Module;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
41 import org.apache.maven.repository.RepositorySystem;
43 import com.google.common.base.Preconditions;
44 import com.google.common.collect.Lists;
45 import com.google.common.collect.Maps;
50 * It isn't desirable to create instances of this class
55 static final String YANG_SUFFIX = "yang";
57 private static final int CACHE_SIZE = 10;
58 // Cache for listed directories and found yang files. Typically yang files
59 // are utilized twice. First: code is generated during generate-sources
60 // phase Second: yang files are copied as resources during
61 // generate-resources phase. This cache ensures that yang files are listed
63 private static Map<File, Collection<File>> cache = Maps.newHashMapWithExpectedSize(CACHE_SIZE);
66 * List files recursively and return as array of String paths. Use cache of
69 static Collection<File> listFiles(File root) throws FileNotFoundException {
70 if (cache.get(root) != null) {
71 return cache.get(root);
75 throw new FileNotFoundException(root.toString());
78 Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
80 toCache(root, yangFiles);
84 static Collection<File> listFiles(File root, File[] excludedFiles, Log log) throws FileNotFoundException {
87 log.warn(Util.message("YANG source directory %s not found. No code will be generated.", YangToSourcesProcessor.LOG_PREFIX, root.toString()));
89 return Collections.emptyList();
91 Collection<File> result = new ArrayList<>();
92 Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
93 for (File f : yangFiles) {
94 boolean excluded = false;
95 for (File ex : excludedFiles) {
103 log.info(Util.message("%s file excluded %s", YangToSourcesProcessor.LOG_PREFIX,
104 Util.YANG_SUFFIX.toUpperCase(), f));
114 private static void toCache(final File rootDir, final Collection<File> yangFiles) {
115 cache.put(rootDir, yangFiles);
119 * Instantiate object from fully qualified class name
121 static <T> T getInstance(String codeGeneratorClass, Class<T> baseType) throws ClassNotFoundException,
122 InstantiationException, IllegalAccessException {
123 return baseType.cast(resolveClass(codeGeneratorClass, baseType).newInstance());
126 private static Class<?> resolveClass(String codeGeneratorClass, Class<?> baseType) throws ClassNotFoundException {
127 Class<?> clazz = Class.forName(codeGeneratorClass);
129 if (!baseType.isAssignableFrom(clazz)) {
130 throw new IllegalArgumentException("Code generator " + clazz + " has to implement " + baseType);
135 static String message(String message, String logPrefix, Object... args) {
136 String innerMessage = String.format(message, args);
137 return String.format("%s %s", logPrefix, innerMessage);
140 static List<File> getClassPath(MavenProject project) {
141 List<File> dependencies = Lists.newArrayList();
142 for (Artifact element : project.getArtifacts()) {
143 File asFile = element.getFile();
144 if (isJar(asFile) || asFile.isDirectory()) {
145 dependencies.add(asFile);
152 * Read current project dependencies and check if it don't grab incorrect
153 * artifacts versions which could be in conflict with plugin dependencies.
162 * remote repositories
166 static void checkClasspath(MavenProject project, RepositorySystem repoSystem, ArtifactRepository localRepo,
167 List<ArtifactRepository> remoteRepos, Log log) {
168 Plugin plugin = project.getPlugin(YangToSourcesMojo.PLUGIN_NAME);
169 if (plugin == null) {
170 log.warn(message("%s not found, dependencies version check skipped", YangToSourcesProcessor.LOG_PREFIX,
171 YangToSourcesMojo.PLUGIN_NAME));
173 Map<Artifact, Collection<Artifact>> pluginDependencies = new HashMap<>();
174 getPluginTransitiveDependencies(plugin, pluginDependencies, repoSystem, localRepo, remoteRepos, log);
176 Set<Artifact> projectDependencies = project.getDependencyArtifacts();
177 for (Map.Entry<Artifact, Collection<Artifact>> entry : pluginDependencies.entrySet()) {
178 checkArtifact(entry.getKey(), projectDependencies, log);
179 for (Artifact dependency : entry.getValue()) {
180 checkArtifact(dependency, projectDependencies, log);
187 * Read transitive dependencies of given plugin and store them in map.
192 * map, where founded transitive dependencies will be stored
195 * @param localRepository
198 * list of remote repositories
202 private static void getPluginTransitiveDependencies(Plugin plugin, Map<Artifact, Collection<Artifact>> map,
203 RepositorySystem repoSystem, ArtifactRepository localRepository, List<ArtifactRepository> remoteRepos,
206 List<Dependency> pluginDependencies = plugin.getDependencies();
207 for (Dependency dep : pluginDependencies) {
208 Artifact artifact = repoSystem.createDependencyArtifact(dep);
210 ArtifactResolutionRequest request = new ArtifactResolutionRequest();
211 request.setArtifact(artifact);
212 request.setResolveTransitively(true);
213 request.setLocalRepository(localRepository);
214 request.setRemoteRepositories(remoteRepos);
216 ArtifactResolutionResult result = repoSystem.resolve(request);
217 Set<Artifact> pluginDependencyDependencies = result.getArtifacts();
218 map.put(artifact, pluginDependencyDependencies);
223 * Check artifact against collection of dependencies. If collection contains
224 * artifact with same groupId and artifactId, but different version, logs a
229 * @param dependencies
230 * collection of dependencies
234 private static void checkArtifact(Artifact artifact, Collection<Artifact> dependencies, Log log) {
235 for (org.apache.maven.artifact.Artifact d : dependencies) {
236 if (artifact.getGroupId().equals(d.getGroupId()) && artifact.getArtifactId().equals(d.getArtifactId())) {
237 if (!(artifact.getVersion().equals(d.getVersion()))) {
238 log.warn(message("Dependency resolution conflict:", YangToSourcesProcessor.LOG_PREFIX));
239 log.warn(message("'%s' dependency [%s] has different version than one "
240 + "declared in current project [%s]. It is recommended to fix this problem "
241 + "because it may cause compilation errors.", YangToSourcesProcessor.LOG_PREFIX,
242 YangToSourcesMojo.PLUGIN_NAME, artifact, d));
248 private static final String JAR_SUFFIX = ".jar";
250 private static boolean isJar(File element) {
251 return (element.isFile() && element.getName().endsWith(JAR_SUFFIX)) ? true : false;
254 static <T> T checkNotNull(T obj, String paramName) {
255 return Preconditions.checkNotNull(obj, "Parameter " + paramName + " is null");
258 static final class YangsInZipsResult implements Closeable {
259 private final List<InputStream> yangStreams;
260 private final List<Closeable> zipInputStreams;
262 private YangsInZipsResult(List<InputStream> yangStreams, List<Closeable> zipInputStreams) {
263 this.yangStreams = yangStreams;
264 this.zipInputStreams = zipInputStreams;
268 public void close() throws IOException {
269 for (InputStream is : yangStreams) {
272 for (Closeable is : zipInputStreams) {
277 public List<InputStream> getYangStreams() {
278 return this.yangStreams;
282 static YangsInZipsResult findYangFilesInDependenciesAsStream(Log log, MavenProject project)
283 throws MojoFailureException {
284 List<InputStream> yangsFromDependencies = new ArrayList<>();
285 List<Closeable> zips = new ArrayList<>();
287 List<File> filesOnCp = Util.getClassPath(project);
288 log.info(Util.message("Searching for yang files in following dependencies: %s",
289 YangToSourcesProcessor.LOG_PREFIX, filesOnCp));
291 for (File file : filesOnCp) {
292 List<String> foundFilesForReporting = new ArrayList<>();
293 // is it jar file or directory?
294 if (file.isDirectory()) {
295 //FIXME: code duplicate
296 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
297 if (yangDir.exists() && yangDir.isDirectory()) {
298 File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
300 public boolean accept(File dir, String name) {
301 return name.endsWith(".yang") && new File(dir, name).isFile();
304 for (File yangFile : yangFiles) {
305 yangsFromDependencies.add(new NamedFileInputStream(yangFile, YangToSourcesProcessor.META_INF_YANG_STRING + File.separator + yangFile.getName()));
310 ZipFile zip = new ZipFile(file);
313 Enumeration<? extends ZipEntry> entries = zip.entries();
314 while (entries.hasMoreElements()) {
315 ZipEntry entry = entries.nextElement();
316 String entryName = entry.getName();
318 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
319 && !entry.isDirectory() && entryName.endsWith(".yang")) {
320 foundFilesForReporting.add(entryName);
321 // This will be closed after all streams are
323 InputStream entryStream = zip.getInputStream(entry);
324 yangsFromDependencies.add(entryStream);
328 if (foundFilesForReporting.size() > 0) {
329 log.info(Util.message("Found %d yang files in %s: %s", YangToSourcesProcessor.LOG_PREFIX,
330 foundFilesForReporting.size(), file, foundFilesForReporting));
334 } catch (Exception e) {
335 throw new MojoFailureException(e.getMessage(), e);
337 return new YangsInZipsResult(yangsFromDependencies, zips);
340 static Collection<File> findYangFilesInDependencies(Log log, MavenProject project) throws MojoFailureException {
341 final List<File> yangsFilesFromDependencies = new ArrayList<>();
344 List<File> filesOnCp = Util.getClassPath(project);
345 log.info(Util.message("Searching for yang files in following dependencies: %s",
346 YangToSourcesProcessor.LOG_PREFIX, filesOnCp));
348 for (File file : filesOnCp) {
349 // is it jar file or directory?
350 if (file.isDirectory()) {
351 //FIXME: code duplicate
352 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
353 if (yangDir.exists() && yangDir.isDirectory()) {
354 File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
356 public boolean accept(File dir, String name) {
357 return name.endsWith(".yang") && new File(dir, name).isFile();
361 yangsFilesFromDependencies.addAll(Arrays.asList(yangFiles));
364 try (ZipFile zip = new ZipFile(file)) {
366 final Enumeration<? extends ZipEntry> entries = zip.entries();
367 while (entries.hasMoreElements()) {
368 ZipEntry entry = entries.nextElement();
369 String entryName = entry.getName();
371 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
372 && !entry.isDirectory() && entryName.endsWith(".yang")) {
373 log.debug(Util.message("Found a YANG file in %s: %s", YangToSourcesProcessor.LOG_PREFIX,
375 yangsFilesFromDependencies.add(file);
382 } catch (Exception e) {
383 throw new MojoFailureException("Failed to scan for YANG files in depedencies", e);
385 return yangsFilesFromDependencies;
388 static final class ContextHolder {
389 private final SchemaContext context;
390 private final Set<Module> yangModules;
392 ContextHolder(SchemaContext context, Set<Module> yangModules) {
393 this.context = context;
394 this.yangModules = yangModules;
397 SchemaContext getContext() {
401 Set<Module> getYangModules() {