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.project.MavenProject;
38 import org.apache.maven.repository.RepositorySystem;
39 import org.opendaylight.yangtools.yang.model.api.Module;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
47 * It isn't desirable to create instances of this class
52 static final String YANG_SUFFIX = "yang";
54 private static final Logger LOG = LoggerFactory.getLogger(Util.class);
55 private static final int CACHE_SIZE = 10;
56 // Cache for listed directories and found yang files. Typically yang files
57 // are utilized twice. First: code is generated during generate-sources
58 // phase Second: yang files are copied as resources during
59 // generate-resources phase. This cache ensures that yang files are listed
61 private static Map<File, Collection<File>> cache = Maps.newHashMapWithExpectedSize(CACHE_SIZE);
64 * List files recursively and return as array of String paths. Use cache of
67 static Collection<File> listFiles(File root) throws FileNotFoundException {
68 if (cache.get(root) != null) {
69 return cache.get(root);
73 throw new FileNotFoundException(root.toString());
76 Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
78 toCache(root, yangFiles);
82 static Collection<File> listFiles(File root, File[] excludedFiles) throws FileNotFoundException {
84 LOG.warn("{} YANG source directory {} not found. No code will be generated.", YangToSourcesProcessor
85 .LOG_PREFIX, root.toString());
87 return Collections.emptyList();
89 Collection<File> result = new ArrayList<>();
90 Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
91 for (File f : yangFiles) {
92 boolean excluded = false;
93 for (File ex : excludedFiles) {
100 LOG.info("{} {} file excluded {}", YangToSourcesProcessor.LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(),
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 List<File> getClassPath(MavenProject project) {
132 List<File> dependencies = Lists.newArrayList();
133 for (Artifact element : project.getArtifacts()) {
134 File asFile = element.getFile();
135 if (isJar(asFile) || asFile.isDirectory()) {
136 dependencies.add(asFile);
143 * Read current project dependencies and check if it don't grab incorrect
144 * artifacts versions which could be in conflict with plugin dependencies.
153 * remote repositories
155 static void checkClasspath(MavenProject project, RepositorySystem repoSystem, ArtifactRepository localRepo,
156 List<ArtifactRepository> remoteRepos) {
157 Plugin plugin = project.getPlugin(YangToSourcesMojo.PLUGIN_NAME);
158 if (plugin == null) {
159 LOG.warn("{} {} not found, dependencies version check skipped", YangToSourcesProcessor.LOG_PREFIX,
160 YangToSourcesMojo.PLUGIN_NAME);
162 Map<Artifact, Collection<Artifact>> pluginDependencies = new HashMap<>();
163 getPluginTransitiveDependencies(plugin, pluginDependencies, repoSystem, localRepo, remoteRepos);
165 Set<Artifact> projectDependencies = project.getDependencyArtifacts();
166 for (Map.Entry<Artifact, Collection<Artifact>> entry : pluginDependencies.entrySet()) {
167 checkArtifact(entry.getKey(), projectDependencies);
168 for (Artifact dependency : entry.getValue()) {
169 checkArtifact(dependency, projectDependencies);
176 * Read transitive dependencies of given plugin and store them in map.
181 * map, where founded transitive dependencies will be stored
184 * @param localRepository
187 * list of remote repositories
189 private static void getPluginTransitiveDependencies(Plugin plugin, Map<Artifact, Collection<Artifact>> map,
190 RepositorySystem repoSystem, ArtifactRepository localRepository, List<ArtifactRepository> remoteRepos) {
192 List<Dependency> pluginDependencies = plugin.getDependencies();
193 for (Dependency dep : pluginDependencies) {
194 Artifact artifact = repoSystem.createDependencyArtifact(dep);
196 ArtifactResolutionRequest request = new ArtifactResolutionRequest();
197 request.setArtifact(artifact);
198 request.setResolveTransitively(true);
199 request.setLocalRepository(localRepository);
200 request.setRemoteRepositories(remoteRepos);
202 ArtifactResolutionResult result = repoSystem.resolve(request);
203 Set<Artifact> pluginDependencyDependencies = result.getArtifacts();
204 map.put(artifact, pluginDependencyDependencies);
209 * Check artifact against collection of dependencies. If collection contains
210 * artifact with same groupId and artifactId, but different version, logs a
215 * @param dependencies
216 * collection of dependencies
218 private static void checkArtifact(Artifact artifact, Collection<Artifact> dependencies) {
219 for (org.apache.maven.artifact.Artifact d : dependencies) {
220 if (artifact.getGroupId().equals(d.getGroupId()) && artifact.getArtifactId().equals(d.getArtifactId())) {
221 if (!(artifact.getVersion().equals(d.getVersion()))) {
222 LOG.warn("{} Dependency resolution conflict:", YangToSourcesProcessor.LOG_PREFIX);
223 LOG.warn("{} '{}' dependency [{}] has different version than one declared in current project [{}]" +
224 ". It is recommended to fix this problem because it may cause compilation errors.",
225 YangToSourcesProcessor.LOG_PREFIX, YangToSourcesMojo.PLUGIN_NAME, artifact, d);
231 private static final String JAR_SUFFIX = ".jar";
233 private static boolean isJar(File element) {
234 return (element.isFile() && element.getName().endsWith(JAR_SUFFIX));
237 static <T> T checkNotNull(T obj, String paramName) {
238 return Preconditions.checkNotNull(obj, "Parameter " + paramName + " is null");
241 static final class YangsInZipsResult implements Closeable {
242 private final List<YangSourceFromDependency> yangStreams;
243 private final List<Closeable> zipInputStreams;
245 private YangsInZipsResult(List<YangSourceFromDependency> yangStreams, List<Closeable> zipInputStreams) {
246 this.yangStreams = yangStreams;
247 this.zipInputStreams = zipInputStreams;
251 public void close() throws IOException {
252 for (Closeable is : zipInputStreams) {
257 public List<YangSourceFromDependency> getYangStreams() {
258 return this.yangStreams;
262 static YangsInZipsResult findYangFilesInDependenciesAsStream(MavenProject project)
263 throws MojoFailureException {
264 List<YangSourceFromDependency> yangsFromDependencies = new ArrayList<>();
265 List<Closeable> zips = new ArrayList<>();
267 List<File> filesOnCp = Util.getClassPath(project);
268 LOG.info("{} Searching for yang files in following dependencies: {}", YangToSourcesProcessor.LOG_PREFIX,
271 for (File file : filesOnCp) {
272 List<String> foundFilesForReporting = new ArrayList<>();
273 // is it jar file or directory?
274 if (file.isDirectory()) {
275 //FIXME: code duplicate
276 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
277 if (yangDir.exists() && yangDir.isDirectory()) {
278 File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
280 public boolean accept(File dir, String name) {
281 return name.endsWith(".yang") && new File(dir, name).isFile();
284 for (final File yangFile : yangFiles) {
285 yangsFromDependencies.add(new YangSourceFromFile(yangFile));
290 ZipFile zip = new ZipFile(file);
293 Enumeration<? extends ZipEntry> entries = zip.entries();
294 while (entries.hasMoreElements()) {
295 ZipEntry entry = entries.nextElement();
296 String entryName = entry.getName();
298 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
299 && !entry.isDirectory() && entryName.endsWith(".yang")) {
300 foundFilesForReporting.add(entryName);
301 yangsFromDependencies.add(new YangSourceInZipFile(zip, entry));
305 if (foundFilesForReporting.size() > 0) {
306 LOG.info("{} Found {} yang files in {}: {}", YangToSourcesProcessor.LOG_PREFIX,
307 foundFilesForReporting.size(), file, foundFilesForReporting);
311 } catch (Exception e) {
312 throw new MojoFailureException(e.getMessage(), e);
314 return new YangsInZipsResult(yangsFromDependencies, zips);
318 * Find all dependencies which contains yang sources
320 * Returns collection of YANG files and Zip files which contains YANG files.
322 * FIXME: Rename to what class is actually doing.
326 * @throws MojoFailureException
328 static Collection<File> findYangFilesInDependencies(MavenProject project) throws MojoFailureException {
329 final List<File> yangsFilesFromDependencies = new ArrayList<>();
331 List<File> filesOnCp;
333 filesOnCp = Util.getClassPath(project);
334 } catch (Exception e) {
335 throw new MojoFailureException("Failed to scan for YANG files in dependencies", e);
337 LOG.info("{} Searching for yang files in following dependencies: {}", YangToSourcesProcessor.LOG_PREFIX,
340 for (File file : filesOnCp) {
342 // is it jar file or directory?
343 if (file.isDirectory()) {
344 //FIXME: code duplicate
345 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
346 if (yangDir.exists() && yangDir.isDirectory()) {
347 File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
349 public boolean accept(File dir, String name) {
350 return name.endsWith(".yang") && new File(dir, name).isFile();
354 yangsFilesFromDependencies.addAll(Arrays.asList(yangFiles));
357 try (ZipFile zip = new ZipFile(file)) {
359 final Enumeration<? extends ZipEntry> entries = zip.entries();
360 while (entries.hasMoreElements()) {
361 ZipEntry entry = entries.nextElement();
362 String entryName = entry.getName();
364 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
365 && !entry.isDirectory() && entryName.endsWith(".yang")) {
366 LOG.debug("{} Found a YANG file in {}: {}", YangToSourcesProcessor.LOG_PREFIX, file,
368 yangsFilesFromDependencies.add(file);
374 } catch (Exception e) {
375 throw new MojoFailureException("Failed to scan for YANG files in dependency: " + file.toString(), e);
378 return yangsFilesFromDependencies;
381 static final class ContextHolder {
382 private final SchemaContext context;
383 private final Set<Module> yangModules;
385 ContextHolder(SchemaContext context, Set<Module> yangModules) {
386 this.context = context;
387 this.yangModules = yangModules;
390 SchemaContext getContext() {
394 Set<Module> getYangModules() {