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;
11 import static org.opendaylight.yangtools.yang2sources.plugin.YangToSourcesProcessor.LOG_PREFIX;
12 import static org.opendaylight.yangtools.yang2sources.plugin.YangToSourcesProcessor.META_INF_YANG_STRING;
13 import static org.opendaylight.yangtools.yang2sources.plugin.YangToSourcesProcessor.META_INF_YANG_STRING_JAR;
15 import com.google.common.io.ByteSource;
16 import com.google.common.io.ByteStreams;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.Enumeration;
22 import java.util.HashMap;
23 import java.util.List;
26 import java.util.zip.ZipEntry;
27 import java.util.zip.ZipFile;
28 import org.apache.maven.artifact.Artifact;
29 import org.apache.maven.artifact.repository.ArtifactRepository;
30 import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
31 import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
32 import org.apache.maven.model.Dependency;
33 import org.apache.maven.model.Plugin;
34 import org.apache.maven.plugin.MojoFailureException;
35 import org.apache.maven.project.MavenProject;
36 import org.apache.maven.repository.RepositorySystem;
37 import org.opendaylight.yangtools.yang.model.api.Module;
38 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
39 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
40 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
47 * It isn't desirable to create instances of this class.
52 private static final Logger LOG = LoggerFactory.getLogger(Util.class);
54 static List<File> getClassPath(final MavenProject project) {
55 final List<File> dependencies = new ArrayList<>();
56 for (Artifact element : project.getArtifacts()) {
57 File asFile = element.getFile();
58 if (isJar(asFile) || asFile.isDirectory()) {
59 dependencies.add(asFile);
66 * Read current project dependencies and check if it don't grab incorrect
67 * artifacts versions which could be in conflict with plugin dependencies.
78 static void checkClasspath(final MavenProject project, final RepositorySystem repoSystem,
79 final ArtifactRepository localRepo, final List<ArtifactRepository> remoteRepos) {
80 Plugin plugin = project.getPlugin(YangToSourcesMojo.PLUGIN_NAME);
82 LOG.warn("{} {} not found, dependencies version check skipped", LOG_PREFIX, YangToSourcesMojo.PLUGIN_NAME);
84 Map<Artifact, Collection<Artifact>> pluginDependencies = new HashMap<>();
85 getPluginTransitiveDependencies(plugin, pluginDependencies, repoSystem, localRepo, remoteRepos);
87 Set<Artifact> projectDependencies = project.getDependencyArtifacts();
88 for (Map.Entry<Artifact, Collection<Artifact>> entry : pluginDependencies.entrySet()) {
89 checkArtifact(entry.getKey(), projectDependencies);
90 for (Artifact dependency : entry.getValue()) {
91 checkArtifact(dependency, projectDependencies);
98 * Read transitive dependencies of given plugin and store them in map.
103 * map, where founded transitive dependencies will be stored
106 * @param localRepository
109 * list of remote repositories
111 private static void getPluginTransitiveDependencies(final Plugin plugin,
112 final Map<Artifact, Collection<Artifact>> map, final RepositorySystem repoSystem,
113 final ArtifactRepository localRepository, final List<ArtifactRepository> remoteRepos) {
115 List<Dependency> pluginDependencies = plugin.getDependencies();
116 for (Dependency dep : pluginDependencies) {
117 Artifact artifact = repoSystem.createDependencyArtifact(dep);
119 ArtifactResolutionRequest request = new ArtifactResolutionRequest();
120 request.setArtifact(artifact);
121 request.setResolveTransitively(true);
122 request.setLocalRepository(localRepository);
123 request.setRemoteRepositories(remoteRepos);
125 ArtifactResolutionResult result = repoSystem.resolve(request);
126 Set<Artifact> pluginDependencyDependencies = result.getArtifacts();
127 map.put(artifact, pluginDependencyDependencies);
132 * Check artifact against collection of dependencies. If collection contains
133 * artifact with same groupId and artifactId, but different version, logs a
138 * @param dependencies
139 * collection of dependencies
141 private static void checkArtifact(final Artifact artifact, final Collection<Artifact> dependencies) {
142 for (org.apache.maven.artifact.Artifact d : dependencies) {
143 if (artifact.getGroupId().equals(d.getGroupId()) && artifact.getArtifactId().equals(d.getArtifactId())) {
144 if (!artifact.getVersion().equals(d.getVersion())) {
145 LOG.warn("{} Dependency resolution conflict:", LOG_PREFIX);
146 LOG.warn("{} '{}' dependency [{}] has different version than one declared in current project [{}]"
147 + ". It is recommended to fix this problem because it may cause compilation errors.",
148 LOG_PREFIX, YangToSourcesMojo.PLUGIN_NAME, artifact, d);
154 private static boolean isJar(final File element) {
155 return element.isFile() && element.getName().endsWith(".jar");
158 @SuppressWarnings("checkstyle:illegalCatch")
159 static List<YangTextSchemaSource> findYangFilesInDependenciesAsStream(final MavenProject project)
160 throws MojoFailureException {
162 final List<File> filesOnCp = Util.getClassPath(project);
163 LOG.info("{} Searching for yang files in following dependencies: {}", LOG_PREFIX, filesOnCp);
165 final List<YangTextSchemaSource> yangsFromDependencies = new ArrayList<>();
166 for (File file : filesOnCp) {
167 final List<String> foundFilesForReporting = new ArrayList<>();
168 // is it jar file or directory?
169 if (file.isDirectory()) {
170 //FIXME: code duplicate
171 File yangDir = new File(file, META_INF_YANG_STRING);
172 if (yangDir.exists() && yangDir.isDirectory()) {
173 File[] yangFiles = yangDir.listFiles(
174 (dir, name) -> name.endsWith(RFC6020_YANG_FILE_EXTENSION) && new File(dir, name).isFile());
175 for (final File yangFile : yangFiles) {
176 foundFilesForReporting.add(yangFile.getName());
177 yangsFromDependencies.add(YangTextSchemaSource.forFile(yangFile));
181 try (ZipFile zip = new ZipFile(file)) {
182 final Enumeration<? extends ZipEntry> entries = zip.entries();
183 while (entries.hasMoreElements()) {
184 final ZipEntry entry = entries.nextElement();
185 final String entryName = entry.getName();
187 if (entryName.startsWith(META_INF_YANG_STRING_JAR) && !entry.isDirectory()
188 && entryName.endsWith(RFC6020_YANG_FILE_EXTENSION)) {
189 foundFilesForReporting.add(entryName);
191 yangsFromDependencies.add(YangTextSchemaSource.delegateForByteSource(
192 entryName.substring(entryName.lastIndexOf('/') + 1),
193 ByteSource.wrap(ByteStreams.toByteArray(zip.getInputStream(entry)))));
198 if (foundFilesForReporting.size() > 0) {
199 LOG.info("{} Found {} yang files in {}: {}", LOG_PREFIX, foundFilesForReporting.size(), file,
200 foundFilesForReporting);
205 return yangsFromDependencies;
206 } catch (Exception e) {
207 throw new MojoFailureException(e.getMessage(), e);
212 * Find all dependencies which contains yang sources.
213 * Returns collection of YANG files and Zip files which contains YANG files.
216 // FIXME: Rename to what class is actually doing.
217 @SuppressWarnings("checkstyle:illegalCatch")
218 static Collection<File> findYangFilesInDependencies(final MavenProject project) throws MojoFailureException {
219 final List<File> yangsFilesFromDependencies = new ArrayList<>();
221 final List<File> filesOnCp;
223 filesOnCp = Util.getClassPath(project);
224 } catch (Exception e) {
225 throw new MojoFailureException("Failed to scan for YANG files in dependencies", e);
227 LOG.info("{} Searching for yang files in following dependencies: {}", LOG_PREFIX, filesOnCp);
229 for (File file : filesOnCp) {
231 // is it jar file or directory?
232 if (file.isDirectory()) {
233 //FIXME: code duplicate
234 File yangDir = new File(file, META_INF_YANG_STRING);
235 if (yangDir.exists() && yangDir.isDirectory()) {
236 File[] yangFiles = yangDir.listFiles(
237 (dir, name) -> name.endsWith(RFC6020_YANG_FILE_EXTENSION) && new File(dir, name).isFile());
239 yangsFilesFromDependencies.addAll(Arrays.asList(yangFiles));
242 try (ZipFile zip = new ZipFile(file)) {
244 final Enumeration<? extends ZipEntry> entries = zip.entries();
245 while (entries.hasMoreElements()) {
246 ZipEntry entry = entries.nextElement();
247 String entryName = entry.getName();
249 if (entryName.startsWith(META_INF_YANG_STRING_JAR)
250 && !entry.isDirectory() && entryName.endsWith(RFC6020_YANG_FILE_EXTENSION)) {
251 LOG.debug("{} Found a YANG file in {}: {}", LOG_PREFIX, file, entryName);
252 yangsFilesFromDependencies.add(file);
258 } catch (Exception e) {
259 throw new MojoFailureException("Failed to scan for YANG files in dependency: " + file.toString(), e);
262 return yangsFilesFromDependencies;
265 static SourceIdentifier moduleToIdentifier(final Module module) {
266 return RevisionSourceIdentifier.create(module.getName(), module.getRevision());