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 static org.opendaylight.yangtools.yang.common.YangConstants.RFC6020_YANG_FILE_EXTENSION;
12 import com.google.common.base.Splitter;
13 import com.google.common.collect.Iterables;
14 import java.io.Closeable;
16 import java.io.FileNotFoundException;
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;
26 import java.util.Optional;
28 import java.util.zip.ZipEntry;
29 import java.util.zip.ZipFile;
30 import org.apache.commons.io.FileUtils;
31 import org.apache.maven.artifact.Artifact;
32 import org.apache.maven.artifact.repository.ArtifactRepository;
33 import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
34 import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
35 import org.apache.maven.model.Dependency;
36 import org.apache.maven.model.Plugin;
37 import org.apache.maven.plugin.MojoFailureException;
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;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
48 * It isn't desirable to create instances of this class
53 static final String YANG_SUFFIX = "yang";
55 private static final Logger LOG = LoggerFactory.getLogger(Util.class);
57 static Collection<File> listFiles(final File root, final Collection<File> excludedFiles) throws FileNotFoundException {
59 LOG.warn("{} YANG source directory {} not found. No code will be generated.", YangToSourcesProcessor
60 .LOG_PREFIX, root.toString());
62 return Collections.emptyList();
64 Collection<File> result = new ArrayList<>();
65 Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
66 for (File f : yangFiles) {
67 if (excludedFiles.contains(f)) {
68 LOG.info("{} {} file excluded {}", YangToSourcesProcessor.LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(),
78 static List<File> getClassPath(final MavenProject project) {
79 List<File> dependencies = new ArrayList<>();
80 for (Artifact element : project.getArtifacts()) {
81 File asFile = element.getFile();
82 if (isJar(asFile) || asFile.isDirectory()) {
83 dependencies.add(asFile);
90 * Read current project dependencies and check if it don't grab incorrect
91 * artifacts versions which could be in conflict with plugin dependencies.
100 * remote repositories
102 static void checkClasspath(final MavenProject project, final RepositorySystem repoSystem,
103 final ArtifactRepository localRepo, final List<ArtifactRepository> remoteRepos) {
104 Plugin plugin = project.getPlugin(YangToSourcesMojo.PLUGIN_NAME);
105 if (plugin == null) {
106 LOG.warn("{} {} not found, dependencies version check skipped", YangToSourcesProcessor.LOG_PREFIX,
107 YangToSourcesMojo.PLUGIN_NAME);
109 Map<Artifact, Collection<Artifact>> pluginDependencies = new HashMap<>();
110 getPluginTransitiveDependencies(plugin, pluginDependencies, repoSystem, localRepo, remoteRepos);
112 Set<Artifact> projectDependencies = project.getDependencyArtifacts();
113 for (Map.Entry<Artifact, Collection<Artifact>> entry : pluginDependencies.entrySet()) {
114 checkArtifact(entry.getKey(), projectDependencies);
115 for (Artifact dependency : entry.getValue()) {
116 checkArtifact(dependency, projectDependencies);
123 * Read transitive dependencies of given plugin and store them in map.
128 * map, where founded transitive dependencies will be stored
131 * @param localRepository
134 * list of remote repositories
136 private static void getPluginTransitiveDependencies(final Plugin plugin,
137 final Map<Artifact, Collection<Artifact>> map, final RepositorySystem repoSystem,
138 final ArtifactRepository localRepository, final List<ArtifactRepository> remoteRepos) {
140 List<Dependency> pluginDependencies = plugin.getDependencies();
141 for (Dependency dep : pluginDependencies) {
142 Artifact artifact = repoSystem.createDependencyArtifact(dep);
144 ArtifactResolutionRequest request = new ArtifactResolutionRequest();
145 request.setArtifact(artifact);
146 request.setResolveTransitively(true);
147 request.setLocalRepository(localRepository);
148 request.setRemoteRepositories(remoteRepos);
150 ArtifactResolutionResult result = repoSystem.resolve(request);
151 Set<Artifact> pluginDependencyDependencies = result.getArtifacts();
152 map.put(artifact, pluginDependencyDependencies);
157 * Check artifact against collection of dependencies. If collection contains
158 * artifact with same groupId and artifactId, but different version, logs a
163 * @param dependencies
164 * collection of dependencies
166 private static void checkArtifact(final Artifact artifact, final Collection<Artifact> dependencies) {
167 for (org.apache.maven.artifact.Artifact d : dependencies) {
168 if (artifact.getGroupId().equals(d.getGroupId()) && artifact.getArtifactId().equals(d.getArtifactId())) {
169 if (!(artifact.getVersion().equals(d.getVersion()))) {
170 LOG.warn("{} Dependency resolution conflict:", YangToSourcesProcessor.LOG_PREFIX);
171 LOG.warn("{} '{}' dependency [{}] has different version than one declared in current project [{}]" +
172 ". It is recommended to fix this problem because it may cause compilation errors.",
173 YangToSourcesProcessor.LOG_PREFIX, YangToSourcesMojo.PLUGIN_NAME, artifact, d);
179 private static final String JAR_SUFFIX = ".jar";
181 private static boolean isJar(final File element) {
182 return (element.isFile() && element.getName().endsWith(JAR_SUFFIX));
185 static final class YangsInZipsResult implements Closeable {
186 private final List<YangSourceFromDependency> yangStreams;
187 private final List<Closeable> zipInputStreams;
189 private YangsInZipsResult(final List<YangSourceFromDependency> yangStreams,
190 final List<Closeable> zipInputStreams) {
191 this.yangStreams = yangStreams;
192 this.zipInputStreams = zipInputStreams;
196 public void close() throws IOException {
197 for (Closeable is : zipInputStreams) {
202 public List<YangSourceFromDependency> getYangStreams() {
203 return this.yangStreams;
207 static YangsInZipsResult findYangFilesInDependenciesAsStream(final MavenProject project)
208 throws MojoFailureException {
209 List<YangSourceFromDependency> yangsFromDependencies = new ArrayList<>();
210 List<Closeable> zips = new ArrayList<>();
212 List<File> filesOnCp = Util.getClassPath(project);
213 LOG.info("{} Searching for yang files in following dependencies: {}", YangToSourcesProcessor.LOG_PREFIX,
216 for (File file : filesOnCp) {
217 List<String> foundFilesForReporting = new ArrayList<>();
218 // is it jar file or directory?
219 if (file.isDirectory()) {
220 //FIXME: code duplicate
221 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
222 if (yangDir.exists() && yangDir.isDirectory()) {
223 File[] yangFiles = yangDir.listFiles(
224 (dir, name) -> name.endsWith(RFC6020_YANG_FILE_EXTENSION) && new File(dir, name).isFile());
225 for (final File yangFile : yangFiles) {
226 yangsFromDependencies.add(new YangSourceFromFile(yangFile));
231 ZipFile zip = new ZipFile(file);
234 Enumeration<? extends ZipEntry> entries = zip.entries();
235 while (entries.hasMoreElements()) {
236 ZipEntry entry = entries.nextElement();
237 String entryName = entry.getName();
239 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
240 && !entry.isDirectory() && entryName.endsWith(RFC6020_YANG_FILE_EXTENSION)) {
241 foundFilesForReporting.add(entryName);
242 yangsFromDependencies.add(new YangSourceInZipFile(zip, entry));
246 if (foundFilesForReporting.size() > 0) {
247 LOG.info("{} Found {} yang files in {}: {}", YangToSourcesProcessor.LOG_PREFIX,
248 foundFilesForReporting.size(), file, foundFilesForReporting);
252 } catch (Exception e) {
253 throw new MojoFailureException(e.getMessage(), e);
255 return new YangsInZipsResult(yangsFromDependencies, zips);
259 * Find all dependencies which contains yang sources
261 * Returns collection of YANG files and Zip files which contains YANG files.
263 * FIXME: Rename to what class is actually doing.
267 * @throws MojoFailureException
269 static Collection<File> findYangFilesInDependencies(final MavenProject project) throws MojoFailureException {
270 final List<File> yangsFilesFromDependencies = new ArrayList<>();
272 List<File> filesOnCp;
274 filesOnCp = Util.getClassPath(project);
275 } catch (Exception e) {
276 throw new MojoFailureException("Failed to scan for YANG files in dependencies", e);
278 LOG.info("{} Searching for yang files in following dependencies: {}", YangToSourcesProcessor.LOG_PREFIX,
281 for (File file : filesOnCp) {
283 // is it jar file or directory?
284 if (file.isDirectory()) {
285 //FIXME: code duplicate
286 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
287 if (yangDir.exists() && yangDir.isDirectory()) {
288 File[] yangFiles = yangDir.listFiles(
289 (dir, name) -> name.endsWith(RFC6020_YANG_FILE_EXTENSION) && new File(dir, name).isFile());
291 yangsFilesFromDependencies.addAll(Arrays.asList(yangFiles));
294 try (ZipFile zip = new ZipFile(file)) {
296 final Enumeration<? extends ZipEntry> entries = zip.entries();
297 while (entries.hasMoreElements()) {
298 ZipEntry entry = entries.nextElement();
299 String entryName = entry.getName();
301 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
302 && !entry.isDirectory() && entryName.endsWith(RFC6020_YANG_FILE_EXTENSION)) {
303 LOG.debug("{} Found a YANG file in {}: {}", YangToSourcesProcessor.LOG_PREFIX, file,
305 yangsFilesFromDependencies.add(file);
311 } catch (Exception e) {
312 throw new MojoFailureException("Failed to scan for YANG files in dependency: " + file.toString(), e);
315 return yangsFilesFromDependencies;
318 static final class ContextHolder {
319 private static final Splitter SEP_SPLITTER = Splitter.on(File.separator);
321 private final SchemaContext context;
322 private final Set<Module> yangModules;
323 private final Set<Module> yangFiles;
325 ContextHolder(final SchemaContext context, final Set<Module> yangModules, final Set<Module> yangFiles) {
326 this.context = context;
327 this.yangModules = yangModules;
328 this.yangFiles = yangFiles;
331 SchemaContext getContext() {
335 Set<Module> getYangModules() {
339 Set<Module> getYangFiles() {
343 Optional<String> moduleToResourcePath(final Module mod) {
344 if (!yangFiles.contains(mod)) {
345 return Optional.empty();
348 return Optional.of("/" + YangToSourcesProcessor.META_INF_YANG_STRING_JAR + "/"
349 + Iterables.getLast(SEP_SPLITTER.split(mod.getModuleSourcePath())));