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.common.QNameModule;
38 import org.opendaylight.yangtools.yang.model.api.Module;
39 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
40 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
41 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
48 * It isn't desirable to create instances of this class.
53 private static final Logger LOG = LoggerFactory.getLogger(Util.class);
55 static List<File> getClassPath(final MavenProject project) {
56 final List<File> dependencies = new ArrayList<>();
57 for (Artifact element : project.getArtifacts()) {
58 File asFile = element.getFile();
59 if (isJar(asFile) || asFile.isDirectory()) {
60 dependencies.add(asFile);
67 * Read current project dependencies and check if it don't grab incorrect
68 * artifacts versions which could be in conflict with plugin dependencies.
79 static void checkClasspath(final MavenProject project, final RepositorySystem repoSystem,
80 final ArtifactRepository localRepo, final List<ArtifactRepository> remoteRepos) {
81 Plugin plugin = project.getPlugin(YangToSourcesMojo.PLUGIN_NAME);
83 LOG.warn("{} {} not found, dependencies version check skipped", LOG_PREFIX, YangToSourcesMojo.PLUGIN_NAME);
85 Map<Artifact, Collection<Artifact>> pluginDependencies = new HashMap<>();
86 getPluginTransitiveDependencies(plugin, pluginDependencies, repoSystem, localRepo, remoteRepos);
88 Set<Artifact> projectDependencies = project.getDependencyArtifacts();
89 for (Map.Entry<Artifact, Collection<Artifact>> entry : pluginDependencies.entrySet()) {
90 checkArtifact(entry.getKey(), projectDependencies);
91 for (Artifact dependency : entry.getValue()) {
92 checkArtifact(dependency, projectDependencies);
99 * Read transitive dependencies of given plugin and store them in map.
104 * map, where founded transitive dependencies will be stored
107 * @param localRepository
110 * list of remote repositories
112 private static void getPluginTransitiveDependencies(final Plugin plugin,
113 final Map<Artifact, Collection<Artifact>> map, final RepositorySystem repoSystem,
114 final ArtifactRepository localRepository, final List<ArtifactRepository> remoteRepos) {
116 List<Dependency> pluginDependencies = plugin.getDependencies();
117 for (Dependency dep : pluginDependencies) {
118 Artifact artifact = repoSystem.createDependencyArtifact(dep);
120 ArtifactResolutionRequest request = new ArtifactResolutionRequest();
121 request.setArtifact(artifact);
122 request.setResolveTransitively(true);
123 request.setLocalRepository(localRepository);
124 request.setRemoteRepositories(remoteRepos);
126 ArtifactResolutionResult result = repoSystem.resolve(request);
127 Set<Artifact> pluginDependencyDependencies = result.getArtifacts();
128 map.put(artifact, pluginDependencyDependencies);
133 * Check artifact against collection of dependencies. If collection contains
134 * artifact with same groupId and artifactId, but different version, logs a
139 * @param dependencies
140 * collection of dependencies
142 private static void checkArtifact(final Artifact artifact, final Collection<Artifact> dependencies) {
143 for (org.apache.maven.artifact.Artifact d : dependencies) {
144 if (artifact.getGroupId().equals(d.getGroupId()) && artifact.getArtifactId().equals(d.getArtifactId())) {
145 if (!artifact.getVersion().equals(d.getVersion())) {
146 LOG.warn("{} Dependency resolution conflict:", LOG_PREFIX);
147 LOG.warn("{} '{}' dependency [{}] has different version than one declared in current project [{}]"
148 + ". It is recommended to fix this problem because it may cause compilation errors.",
149 LOG_PREFIX, YangToSourcesMojo.PLUGIN_NAME, artifact, d);
155 private static boolean isJar(final File element) {
156 return element.isFile() && element.getName().endsWith(".jar");
159 @SuppressWarnings("checkstyle:illegalCatch")
160 static List<YangTextSchemaSource> findYangFilesInDependenciesAsStream(final MavenProject project)
161 throws MojoFailureException {
163 final List<File> filesOnCp = Util.getClassPath(project);
164 LOG.info("{} Searching for yang files in following dependencies: {}", LOG_PREFIX, filesOnCp);
166 final List<YangTextSchemaSource> yangsFromDependencies = new ArrayList<>();
167 for (File file : filesOnCp) {
168 final List<String> foundFilesForReporting = new ArrayList<>();
169 // is it jar file or directory?
170 if (file.isDirectory()) {
171 //FIXME: code duplicate
172 File yangDir = new File(file, META_INF_YANG_STRING);
173 if (yangDir.exists() && yangDir.isDirectory()) {
174 File[] yangFiles = yangDir.listFiles(
175 (dir, name) -> name.endsWith(RFC6020_YANG_FILE_EXTENSION) && new File(dir, name).isFile());
176 for (final File yangFile : yangFiles) {
177 foundFilesForReporting.add(yangFile.getName());
178 yangsFromDependencies.add(YangTextSchemaSource.forFile(yangFile));
182 try (ZipFile zip = new ZipFile(file)) {
183 final Enumeration<? extends ZipEntry> entries = zip.entries();
184 while (entries.hasMoreElements()) {
185 final ZipEntry entry = entries.nextElement();
186 final String entryName = entry.getName();
188 if (entryName.startsWith(META_INF_YANG_STRING_JAR) && !entry.isDirectory()
189 && entryName.endsWith(RFC6020_YANG_FILE_EXTENSION)) {
190 foundFilesForReporting.add(entryName);
192 yangsFromDependencies.add(YangTextSchemaSource.delegateForByteSource(
193 entryName.substring(entryName.lastIndexOf('/') + 1),
194 ByteSource.wrap(ByteStreams.toByteArray(zip.getInputStream(entry)))));
199 if (foundFilesForReporting.size() > 0) {
200 LOG.info("{} Found {} yang files in {}: {}", LOG_PREFIX, foundFilesForReporting.size(), file,
201 foundFilesForReporting);
206 return yangsFromDependencies;
207 } catch (Exception e) {
208 throw new MojoFailureException(e.getMessage(), e);
213 * Find all dependencies which contains yang sources.
214 * Returns collection of YANG files and Zip files which contains YANG files.
217 // FIXME: Rename to what class is actually doing.
218 @SuppressWarnings("checkstyle:illegalCatch")
219 static Collection<File> findYangFilesInDependencies(final MavenProject project) throws MojoFailureException {
220 final List<File> yangsFilesFromDependencies = new ArrayList<>();
222 final List<File> filesOnCp;
224 filesOnCp = Util.getClassPath(project);
225 } catch (Exception e) {
226 throw new MojoFailureException("Failed to scan for YANG files in dependencies", e);
228 LOG.info("{} Searching for yang files in following dependencies: {}", LOG_PREFIX, filesOnCp);
230 for (File file : filesOnCp) {
232 // is it jar file or directory?
233 if (file.isDirectory()) {
234 //FIXME: code duplicate
235 File yangDir = new File(file, META_INF_YANG_STRING);
236 if (yangDir.exists() && yangDir.isDirectory()) {
237 File[] yangFiles = yangDir.listFiles(
238 (dir, name) -> name.endsWith(RFC6020_YANG_FILE_EXTENSION) && new File(dir, name).isFile());
240 yangsFilesFromDependencies.addAll(Arrays.asList(yangFiles));
243 try (ZipFile zip = new ZipFile(file)) {
245 final Enumeration<? extends ZipEntry> entries = zip.entries();
246 while (entries.hasMoreElements()) {
247 ZipEntry entry = entries.nextElement();
248 String entryName = entry.getName();
250 if (entryName.startsWith(META_INF_YANG_STRING_JAR)
251 && !entry.isDirectory() && entryName.endsWith(RFC6020_YANG_FILE_EXTENSION)) {
252 LOG.debug("{} Found a YANG file in {}: {}", LOG_PREFIX, file, entryName);
253 yangsFilesFromDependencies.add(file);
259 } catch (Exception e) {
260 throw new MojoFailureException("Failed to scan for YANG files in dependency: " + file.toString(), e);
263 return yangsFilesFromDependencies;
266 static SourceIdentifier moduleToIdentifier(final Module module) {
267 final QNameModule mod = module.getQNameModule();
268 final String rev = mod.getFormattedRevision();
269 return rev != null ? RevisionSourceIdentifier.create(module.getName(), rev)
270 : RevisionSourceIdentifier.create(module.getName());