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.FileNotFoundException;
13 import java.io.FilenameFilter;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.Collection;
19 import java.util.Enumeration;
20 import java.util.List;
23 import java.util.zip.ZipEntry;
24 import java.util.zip.ZipFile;
26 import org.apache.commons.io.FileUtils;
27 import org.apache.maven.artifact.Artifact;
28 import org.apache.maven.plugin.MojoFailureException;
29 import org.apache.maven.plugin.logging.Log;
30 import org.apache.maven.project.MavenProject;
31 import org.opendaylight.yangtools.yang.model.api.Module;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
33 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
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 private static void toCache(final File rootDir, final Collection<File> yangFiles) {
104 cache.put(rootDir, yangFiles);
108 * Instantiate object from fully qualified class name
110 static <T> T getInstance(String codeGeneratorClass, Class<T> baseType) throws ClassNotFoundException,
111 InstantiationException, IllegalAccessException {
112 return baseType.cast(resolveClass(codeGeneratorClass, baseType).newInstance());
115 private static Class<?> resolveClass(String codeGeneratorClass, Class<?> baseType) throws ClassNotFoundException {
116 Class<?> clazz = Class.forName(codeGeneratorClass);
118 if (!isImplemented(baseType, clazz)) {
119 throw new IllegalArgumentException("Code generator " + clazz + " has to implement " + baseType);
124 private static boolean isImplemented(Class<?> expectedIface, Class<?> byClazz) {
125 for (Class<?> iface : byClazz.getInterfaces()) {
126 if (iface.equals(expectedIface)) {
133 static String message(String message, String logPrefix, Object... args) {
134 String innerMessage = String.format(message, args);
135 return String.format("%s %s", logPrefix, innerMessage);
138 static List<File> getClassPath(MavenProject project) {
139 List<File> dependencies = Lists.newArrayList();
140 for (Artifact element : project.getArtifacts()) {
141 File asFile = element.getFile();
142 if (isJar(asFile) || asFile.isDirectory()) {
143 dependencies.add(asFile);
149 private static final String JAR_SUFFIX = ".jar";
151 private static boolean isJar(File element) {
152 return (element.isFile() && element.getName().endsWith(JAR_SUFFIX)) ? true : false;
155 static <T> T checkNotNull(T obj, String paramName) {
156 return Preconditions.checkNotNull(obj, "Parameter " + paramName + " is null");
159 static final class YangsInZipsResult implements Closeable {
160 private final List<InputStream> yangStreams;
161 private final List<Closeable> zipInputStreams;
163 private YangsInZipsResult(List<InputStream> yangStreams, List<Closeable> zipInputStreams) {
164 this.yangStreams = yangStreams;
165 this.zipInputStreams = zipInputStreams;
169 public void close() throws IOException {
170 for (InputStream is : yangStreams) {
173 for (Closeable is : zipInputStreams) {
178 public List<InputStream> getYangStreams() {
179 return this.yangStreams;
183 static YangsInZipsResult findYangFilesInDependenciesAsStream(Log log, MavenProject project)
184 throws MojoFailureException {
185 List<InputStream> yangsFromDependencies = new ArrayList<>();
186 List<Closeable> zips = new ArrayList<>();
188 List<File> filesOnCp = Util.getClassPath(project);
189 log.info(Util.message("Searching for yang files in following dependencies: %s",
190 YangToSourcesProcessor.LOG_PREFIX, filesOnCp));
192 for (File file : filesOnCp) {
193 List<String> foundFilesForReporting = new ArrayList<>();
194 // is it jar file or directory?
195 if (file.isDirectory()) {
196 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
197 if (yangDir.exists() && yangDir.isDirectory()) {
198 File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
200 public boolean accept(File dir, String name) {
201 return name.endsWith(".yang") && new File(dir, name).isFile();
204 for (File yangFile : yangFiles) {
205 yangsFromDependencies.add(new NamedFileInputStream(yangFile, YangToSourcesProcessor.META_INF_YANG_STRING + File.separator + yangFile.getName()));
210 ZipFile zip = new ZipFile(file);
213 Enumeration<? extends ZipEntry> entries = zip.entries();
214 while (entries.hasMoreElements()) {
215 ZipEntry entry = entries.nextElement();
216 String entryName = entry.getName();
218 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
219 && !entry.isDirectory() && entryName.endsWith(".yang")) {
220 foundFilesForReporting.add(entryName);
221 // This will be closed after all streams are
223 InputStream entryStream = zip.getInputStream(entry);
224 yangsFromDependencies.add(entryStream);
228 if (foundFilesForReporting.size() > 0) {
229 log.info(Util.message("Found %d yang files in %s: %s", YangToSourcesProcessor.LOG_PREFIX,
230 foundFilesForReporting.size(), file, foundFilesForReporting));
234 } catch (Exception e) {
235 throw new MojoFailureException(e.getMessage(), e);
237 return new YangsInZipsResult(yangsFromDependencies, zips);
240 static Collection<File> findYangFilesInDependencies(Log log, MavenProject project) throws MojoFailureException {
241 final List<File> yangsFilesFromDependencies = new ArrayList<>();
244 List<File> filesOnCp = Util.getClassPath(project);
245 log.info(Util.message("Searching for yang files in following dependencies: %s",
246 YangToSourcesProcessor.LOG_PREFIX, filesOnCp));
248 for (File file : filesOnCp) {
249 // is it jar file or directory?
250 if (file.isDirectory()) {
251 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
252 if (yangDir.exists() && yangDir.isDirectory()) {
253 File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
255 public boolean accept(File dir, String name) {
256 return name.endsWith(".yang") && new File(dir, name).isFile();
260 yangsFilesFromDependencies.addAll(Arrays.asList(yangFiles));
263 try (ZipFile zip = new ZipFile(file)) {
265 final Enumeration<? extends ZipEntry> entries = zip.entries();
266 while (entries.hasMoreElements()) {
267 ZipEntry entry = entries.nextElement();
268 String entryName = entry.getName();
270 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)
271 && !entry.isDirectory() && entryName.endsWith(".yang")) {
272 log.debug(Util.message("Found a YANG file in %s: %s", YangToSourcesProcessor.LOG_PREFIX,
274 yangsFilesFromDependencies.add(file);
281 } catch (Exception e) {
282 throw new MojoFailureException("Failed to scan for YANG files in depedencies", e);
284 return yangsFilesFromDependencies;
287 static final class ContextHolder {
288 private final SchemaContext context;
289 private final Set<Module> yangModules;
291 ContextHolder(SchemaContext context, Set<Module> yangModules) {
292 this.context = context;
293 this.yangModules = yangModules;
296 SchemaContext getContext() {
300 Set<Module> getYangModules() {