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 com.google.common.base.Preconditions;
11 import com.google.common.collect.Lists;
12 import com.google.common.collect.Maps;
13 import java.io.Closeable;
15 import java.io.FileNotFoundException;
16 import java.io.FilenameFilter;
17 import java.io.IOException;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Enumeration;
23 import java.util.HashMap;
24 import java.util.List;
27 import java.util.zip.ZipEntry;
28 import java.util.zip.ZipFile;
29 import org.apache.commons.io.FileUtils;
30 import org.apache.maven.artifact.Artifact;
31 import org.apache.maven.artifact.repository.ArtifactRepository;
32 import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
33 import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
34 import org.apache.maven.model.Dependency;
35 import org.apache.maven.model.Plugin;
36 import org.apache.maven.plugin.MojoFailureException;
37 import org.apache.maven.plugin.logging.Log;
38 import org.apache.maven.project.MavenProject;
39 import org.apache.maven.repository.RepositorySystem;
40 import org.opendaylight.yangtools.yang.model.api.Module;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 * It isn't desirable to create instances of this class
51 static final String YANG_SUFFIX = "yang";
53 private static final int CACHE_SIZE = 10;
54 // Cache for listed directories and found yang files. Typically yang files
55 // are utilized twice. First: code is generated during generate-sources
56 // phase Second: yang files are copied as resources during
57 // generate-resources phase. This cache ensures that yang files are listed
59 private static Map<File, Collection<File>> cache = Maps.newHashMapWithExpectedSize(CACHE_SIZE);
62 * List files recursively and return as array of String paths. Use cache of
65 static Collection<File> listFiles(File root) throws FileNotFoundException {
66 if (cache.get(root) != null) {
67 return cache.get(root);
71 throw new FileNotFoundException(root.toString());
74 Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
76 toCache(root, yangFiles);
80 static Collection<File> listFiles(File root, File[] excludedFiles, Log log) throws FileNotFoundException {
83 log.warn(Util.message("YANG source directory %s not found. No code will be generated.", YangToSourcesProcessor.LOG_PREFIX, root.toString()));
85 return Collections.emptyList();
87 Collection<File> result = new ArrayList<>();
88 Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
89 for (File f : yangFiles) {
90 boolean excluded = false;
91 for (File ex : excludedFiles) {
99 log.info(Util.message("%s file excluded %s", YangToSourcesProcessor.LOG_PREFIX,
100 Util.YANG_SUFFIX.toUpperCase(), f));
110 private static void toCache(final File rootDir, final Collection<File> yangFiles) {
111 cache.put(rootDir, yangFiles);
115 * Instantiate object from fully qualified class name
117 static <T> T getInstance(String codeGeneratorClass, Class<T> baseType) throws ClassNotFoundException,
118 InstantiationException, IllegalAccessException {
119 return baseType.cast(resolveClass(codeGeneratorClass, baseType).newInstance());
122 private static Class<?> resolveClass(String codeGeneratorClass, Class<?> baseType) throws ClassNotFoundException {
123 Class<?> clazz = Class.forName(codeGeneratorClass);
125 if (!baseType.isAssignableFrom(clazz)) {
126 throw new IllegalArgumentException("Code generator " + clazz + " has to implement " + baseType);
131 static String message(String message, String logPrefix, Object... args) {
132 String innerMessage = String.format(message, args);
133 return String.format("%s %s", logPrefix, innerMessage);
136 static List<File> getClassPath(MavenProject project) {
137 List<File> dependencies = Lists.newArrayList();
138 for (Artifact element : project.getArtifacts()) {
139 File asFile = element.getFile();
140 if (isJar(asFile) || asFile.isDirectory()) {
141 dependencies.add(asFile);
148 * Read current project dependencies and check if it don't grab incorrect
149 * artifacts versions which could be in conflict with plugin dependencies.
158 * remote repositories
162 static void checkClasspath(MavenProject project, RepositorySystem repoSystem, ArtifactRepository localRepo,
163 List<ArtifactRepository> remoteRepos, Log log) {
164 Plugin plugin = project.getPlugin(YangToSourcesMojo.PLUGIN_NAME);
165 if (plugin == null) {
166 log.warn(message("%s not found, dependencies version check skipped", YangToSourcesProcessor.LOG_PREFIX,
167 YangToSourcesMojo.PLUGIN_NAME));
169 Map<Artifact, Collection<Artifact>> pluginDependencies = new HashMap<>();
170 getPluginTransitiveDependencies(plugin, pluginDependencies, repoSystem, localRepo, remoteRepos, log);
172 Set<Artifact> projectDependencies = project.getDependencyArtifacts();
173 for (Map.Entry<Artifact, Collection<Artifact>> entry : pluginDependencies.entrySet()) {
174 checkArtifact(entry.getKey(), projectDependencies, log);
175 for (Artifact dependency : entry.getValue()) {
176 checkArtifact(dependency, projectDependencies, log);
183 * Read transitive dependencies of given plugin and store them in map.
188 * map, where founded transitive dependencies will be stored
191 * @param localRepository
194 * list of remote repositories
198 private static void getPluginTransitiveDependencies(Plugin plugin, Map<Artifact, Collection<Artifact>> map,
199 RepositorySystem repoSystem, ArtifactRepository localRepository, List<ArtifactRepository> remoteRepos,
202 List<Dependency> pluginDependencies = plugin.getDependencies();
203 for (Dependency dep : pluginDependencies) {
204 Artifact artifact = repoSystem.createDependencyArtifact(dep);
206 ArtifactResolutionRequest request = new ArtifactResolutionRequest();
207 request.setArtifact(artifact);
208 request.setResolveTransitively(true);
209 request.setLocalRepository(localRepository);
210 request.setRemoteRepositories(remoteRepos);
212 ArtifactResolutionResult result = repoSystem.resolve(request);
213 Set<Artifact> pluginDependencyDependencies = result.getArtifacts();
214 map.put(artifact, pluginDependencyDependencies);
219 * Check artifact against collection of dependencies. If collection contains
220 * artifact with same groupId and artifactId, but different version, logs a
225 * @param dependencies
226 * collection of dependencies
230 private static void checkArtifact(Artifact artifact, Collection<Artifact> dependencies, Log log) {
231 for (org.apache.maven.artifact.Artifact d : dependencies) {
232 if (artifact.getGroupId().equals(d.getGroupId()) && artifact.getArtifactId().equals(d.getArtifactId())) {
233 if (!(artifact.getVersion().equals(d.getVersion()))) {
234 log.warn(message("Dependency resolution conflict:", YangToSourcesProcessor.LOG_PREFIX));
235 log.warn(message("'%s' dependency [%s] has different version than one "
236 + "declared in current project [%s]. It is recommended to fix this problem "
237 + "because it may cause compilation errors.", YangToSourcesProcessor.LOG_PREFIX,
238 YangToSourcesMojo.PLUGIN_NAME, artifact, d));
244 private static final String JAR_SUFFIX = ".jar";
246 private static boolean isJar(File element) {
247 return (element.isFile() && element.getName().endsWith(JAR_SUFFIX)) ? true : false;
250 static <T> T checkNotNull(T obj, String paramName) {
251 return Preconditions.checkNotNull(obj, "Parameter " + paramName + " is null");
254 static final class YangsInZipsResult implements Closeable {
255 private final List<YangSourceFromDependency> yangStreams;
256 private final List<Closeable> zipInputStreams;
258 private YangsInZipsResult(List<YangSourceFromDependency> yangStreams, List<Closeable> zipInputStreams) {
259 this.yangStreams = yangStreams;
260 this.zipInputStreams = zipInputStreams;
264 public void close() throws IOException {
265 for (Closeable is : zipInputStreams) {
270 public List<YangSourceFromDependency> getYangStreams() {
271 return this.yangStreams;
275 static YangsInZipsResult findYangFilesInDependenciesAsStream(Log log, MavenProject project)
276 throws MojoFailureException {
277 List<YangSourceFromDependency> yangsFromDependencies = new ArrayList<>();
278 List<Closeable> zips = new ArrayList<>();
280 List<File> filesOnCp = Util.getClassPath(project);
281 log.info(Util.message("Searching for yang files in following dependencies: %s",
282 YangToSourcesProcessor.LOG_PREFIX, filesOnCp));
284 for (File file : filesOnCp) {
285 List<String> foundFilesForReporting = new ArrayList<>();
286 // is it jar file or directory?
287 if (file.isDirectory()) {
288 //FIXME: code duplicate
289 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
290 if (yangDir.exists() && yangDir.isDirectory()) {
291 File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
293 public boolean accept(File dir, String name) {
294 return name.endsWith(".yang") && new File(dir, name).isFile();
297 for (final File yangFile : yangFiles) {
298 yangsFromDependencies.add(new YangSourceFromFile(file));
303 ZipFile zip = new ZipFile(file);
306 Enumeration<? extends ZipEntry> entries = zip.entries();
307 while (entries.hasMoreElements()) {
308 ZipEntry entry = entries.nextElement();
309 String entryName = entry.getName();
311 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
312 && !entry.isDirectory() && entryName.endsWith(".yang")) {
313 foundFilesForReporting.add(entryName);
314 yangsFromDependencies.add(new YangSourceInZipFile(zip, entry));
318 if (foundFilesForReporting.size() > 0) {
319 log.info(Util.message("Found %d yang files in %s: %s", YangToSourcesProcessor.LOG_PREFIX,
320 foundFilesForReporting.size(), file, foundFilesForReporting));
324 } catch (Exception e) {
325 throw new MojoFailureException(e.getMessage(), e);
327 return new YangsInZipsResult(yangsFromDependencies, zips);
331 * Find all dependencies which contains yang sources
333 * Returns collection of YANG files and Zip files which contains YANG files.
335 * FIXME: Rename to what class is actually doing.
340 * @throws MojoFailureException
342 static Collection<File> findYangFilesInDependencies(Log log, MavenProject project) throws MojoFailureException {
343 final List<File> yangsFilesFromDependencies = new ArrayList<>();
346 List<File> filesOnCp = Util.getClassPath(project);
347 log.info(Util.message("Searching for yang files in following dependencies: %s",
348 YangToSourcesProcessor.LOG_PREFIX, filesOnCp));
350 for (File file : filesOnCp) {
351 // is it jar file or directory?
352 if (file.isDirectory()) {
353 //FIXME: code duplicate
354 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
355 if (yangDir.exists() && yangDir.isDirectory()) {
356 File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
358 public boolean accept(File dir, String name) {
359 return name.endsWith(".yang") && new File(dir, name).isFile();
363 yangsFilesFromDependencies.addAll(Arrays.asList(yangFiles));
366 try (ZipFile zip = new ZipFile(file)) {
368 final Enumeration<? extends ZipEntry> entries = zip.entries();
369 while (entries.hasMoreElements()) {
370 ZipEntry entry = entries.nextElement();
371 String entryName = entry.getName();
373 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
374 && !entry.isDirectory() && entryName.endsWith(".yang")) {
375 log.debug(Util.message("Found a YANG file in %s: %s", YangToSourcesProcessor.LOG_PREFIX,
377 yangsFilesFromDependencies.add(file);
384 } catch (Exception e) {
385 throw new MojoFailureException("Failed to scan for YANG files in depedencies", e);
387 return yangsFilesFromDependencies;
390 static final class ContextHolder {
391 private final SchemaContext context;
392 private final Set<Module> yangModules;
394 ContextHolder(SchemaContext context, Set<Module> yangModules) {
395 this.context = context;
396 this.yangModules = yangModules;
399 SchemaContext getContext() {
403 Set<Module> getYangModules() {