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 java.io.Closeable;
12 import java.io.FileInputStream;
13 import java.io.FileNotFoundException;
14 import java.io.FilenameFilter;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.util.ArrayList;
18 import java.util.Arrays;
19 import java.util.Collection;
20 import java.util.Enumeration;
21 import java.util.List;
24 import java.util.zip.ZipEntry;
25 import java.util.zip.ZipFile;
27 import org.apache.commons.io.FileUtils;
28 import org.apache.maven.artifact.Artifact;
29 import org.apache.maven.plugin.MojoFailureException;
30 import org.apache.maven.plugin.logging.Log;
31 import org.apache.maven.project.MavenProject;
32 import org.opendaylight.yangtools.yang.model.api.Module;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
35 import com.google.common.base.Preconditions;
36 import com.google.common.collect.Lists;
37 import com.google.common.collect.Maps;
42 * It isn't desirable to create instances of this class
47 static final String YANG_SUFFIX = "yang";
49 private static final int CACHE_SIZE = 10;
50 // Cache for listed directories and found yang files. Typically yang files
51 // are utilized twice. First: code is generated during generate-sources
52 // phase Second: yang files are copied as resources during
53 // generate-resources phase. This cache ensures that yang files are listed
55 private static Map<File, Collection<File>> cache = Maps.newHashMapWithExpectedSize(CACHE_SIZE);
58 * List files recursively and return as array of String paths. Use cache of
61 static Collection<File> listFiles(File root) throws FileNotFoundException {
62 if (cache.get(root) != null) {
63 return cache.get(root);
67 throw new FileNotFoundException(root.toString());
70 Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
72 toCache(root, yangFiles);
76 static Collection<File> listFiles(File root, File[] excludedFiles, Log log) throws FileNotFoundException {
78 throw new FileNotFoundException(root.toString());
80 Collection<File> result = new ArrayList<>();
81 Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
82 for (File f : yangFiles) {
83 boolean excluded = false;
84 for (File ex : excludedFiles) {
92 log.info(Util.message("%s file excluded %s", YangToSourcesProcessor.LOG_PREFIX,
93 Util.YANG_SUFFIX.toUpperCase(), f));
103 static class NamedFileInputStream extends FileInputStream {
104 private final File file;
106 NamedFileInputStream(File file) throws FileNotFoundException {
112 public String toString() {
113 return getClass().getSimpleName() + "{" + file + "}";
117 private static void toCache(final File rootDir, final Collection<File> yangFiles) {
118 cache.put(rootDir, yangFiles);
122 * Instantiate object from fully qualified class name
124 static <T> T getInstance(String codeGeneratorClass, Class<T> baseType) throws ClassNotFoundException,
125 InstantiationException, IllegalAccessException {
126 return baseType.cast(resolveClass(codeGeneratorClass, baseType).newInstance());
129 private static Class<?> resolveClass(String codeGeneratorClass, Class<?> baseType) throws ClassNotFoundException {
130 Class<?> clazz = Class.forName(codeGeneratorClass);
132 if (!isImplemented(baseType, clazz)) {
133 throw new IllegalArgumentException("Code generator " + clazz + " has to implement " + baseType);
138 private static boolean isImplemented(Class<?> expectedIface, Class<?> byClazz) {
139 for (Class<?> iface : byClazz.getInterfaces()) {
140 if (iface.equals(expectedIface)) {
147 static String message(String message, String logPrefix, Object... args) {
148 String innerMessage = String.format(message, args);
149 return String.format("%s %s", logPrefix, innerMessage);
152 static List<File> getClassPath(MavenProject project) {
153 List<File> dependencies = Lists.newArrayList();
154 for (Artifact element : project.getArtifacts()) {
155 File asFile = element.getFile();
156 if (isJar(asFile) || asFile.isDirectory()) {
157 dependencies.add(asFile);
163 private static final String JAR_SUFFIX = ".jar";
165 private static boolean isJar(File element) {
166 return (element.isFile() && element.getName().endsWith(JAR_SUFFIX)) ? true : false;
169 static <T> T checkNotNull(T obj, String paramName) {
170 return Preconditions.checkNotNull(obj, "Parameter " + paramName + " is null");
173 static final class YangsInZipsResult implements Closeable {
174 private final List<InputStream> yangStreams;
175 private final List<Closeable> zipInputStreams;
177 private YangsInZipsResult(List<InputStream> yangStreams, List<Closeable> zipInputStreams) {
178 this.yangStreams = yangStreams;
179 this.zipInputStreams = zipInputStreams;
183 public void close() throws IOException {
184 for (InputStream is : yangStreams) {
187 for (Closeable is : zipInputStreams) {
192 public List<InputStream> getYangStreams() {
193 return this.yangStreams;
197 static YangsInZipsResult findYangFilesInDependenciesAsStream(Log log, MavenProject project)
198 throws MojoFailureException {
199 List<InputStream> yangsFromDependencies = new ArrayList<>();
200 List<Closeable> zips = new ArrayList<>();
202 List<File> filesOnCp = Util.getClassPath(project);
203 log.info(Util.message("Searching for yang files in following dependencies: %s",
204 YangToSourcesProcessor.LOG_PREFIX, filesOnCp));
206 for (File file : filesOnCp) {
207 List<String> foundFilesForReporting = new ArrayList<>();
208 // is it jar file or directory?
209 if (file.isDirectory()) {
210 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
211 if (yangDir.exists() && yangDir.isDirectory()) {
212 File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
214 public boolean accept(File dir, String name) {
215 return name.endsWith(".yang") && new File(dir, name).isFile();
218 for (File yangFile : yangFiles) {
219 yangsFromDependencies.add(new NamedFileInputStream(yangFile));
224 ZipFile zip = new ZipFile(file);
227 Enumeration<? extends ZipEntry> entries = zip.entries();
228 while (entries.hasMoreElements()) {
229 ZipEntry entry = entries.nextElement();
230 String entryName = entry.getName();
232 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
233 && !entry.isDirectory() && entryName.endsWith(".yang")) {
234 foundFilesForReporting.add(entryName);
235 // This will be closed after all streams are
237 InputStream entryStream = zip.getInputStream(entry);
238 yangsFromDependencies.add(entryStream);
242 if (foundFilesForReporting.size() > 0) {
243 log.info(Util.message("Found %d yang files in %s: %s", YangToSourcesProcessor.LOG_PREFIX,
244 foundFilesForReporting.size(), file, foundFilesForReporting));
248 } catch (Exception e) {
249 throw new MojoFailureException(e.getMessage(), e);
251 return new YangsInZipsResult(yangsFromDependencies, zips);
254 static Collection<File> findYangFilesInDependencies(Log log, MavenProject project) throws MojoFailureException {
255 final List<File> yangsFilesFromDependencies = new ArrayList<>();
258 List<File> filesOnCp = Util.getClassPath(project);
259 log.info(Util.message("Searching for yang files in following dependencies: %s",
260 YangToSourcesProcessor.LOG_PREFIX, filesOnCp));
262 for (File file : filesOnCp) {
263 // is it jar file or directory?
264 if (file.isDirectory()) {
265 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
266 if (yangDir.exists() && yangDir.isDirectory()) {
267 File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
269 public boolean accept(File dir, String name) {
270 return name.endsWith(".yang") && new File(dir, name).isFile();
274 yangsFilesFromDependencies.addAll(Arrays.asList(yangFiles));
277 try (ZipFile zip = new ZipFile(file)) {
279 final Enumeration<? extends ZipEntry> entries = zip.entries();
280 while (entries.hasMoreElements()) {
281 ZipEntry entry = entries.nextElement();
282 String entryName = entry.getName();
284 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
285 && !entry.isDirectory() && entryName.endsWith(".yang")) {
286 log.debug(Util.message("Found a YANG file in %s: %s", YangToSourcesProcessor.LOG_PREFIX,
288 yangsFilesFromDependencies.add(file);
295 } catch (Exception e) {
296 throw new MojoFailureException("Failed to scan for YANG files in depedencies", e);
298 return yangsFilesFromDependencies;
301 static final class ContextHolder {
302 private final SchemaContext context;
303 private final Set<Module> yangModules;
305 ContextHolder(SchemaContext context, Set<Module> yangModules) {
306 this.context = context;
307 this.yangModules = yangModules;
310 SchemaContext getContext() {
314 Set<Module> getYangModules() {