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.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;
34 import com.google.common.base.Preconditions;
35 import com.google.common.collect.Lists;
36 import com.google.common.collect.Maps;
39 static final String YANG_SUFFIX = "yang";
41 // Cache for listed directories and found yang files. Typically yang files
42 // are utilized twice. First: code is generated during generate-sources
43 // phase Second: yang files are copied as resources during
44 // generate-resources phase. This cache ensures that yang files are listed
46 private static Map<File, Collection<File>> cache = Maps.newHashMapWithExpectedSize(10);
49 * List files recursively and return as array of String paths. Use cache of
52 static Collection<File> listFiles(File root) throws FileNotFoundException {
53 if (cache.get(root) != null)
54 return cache.get(root);
57 throw new FileNotFoundException(root.toString());
60 Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
62 toCache(root, yangFiles);
66 static Collection<File> listFiles(File root, File[] excludedFiles, Log log) throws FileNotFoundException {
68 throw new FileNotFoundException(root.toString());
70 Collection<File> result = new ArrayList<>();
71 Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
72 for (File f : yangFiles) {
73 boolean excluded = false;
74 for (File ex : excludedFiles) {
82 log.info(Util.message("%s file excluded %s", YangToSourcesProcessor.LOG_PREFIX,
83 Util.YANG_SUFFIX.toUpperCase(), f));
93 static List<InputStream> listFilesAsStream(File rootDir, File[] excludedFiles, Log log)
94 throws FileNotFoundException {
95 List<InputStream> is = new ArrayList<InputStream>();
97 Collection<File> files = listFiles(rootDir, excludedFiles, log);
98 for (File f : files) {
99 is.add(new NamedFileInputStream(f));
105 static class NamedFileInputStream extends FileInputStream {
106 private final File file;
108 NamedFileInputStream(File file) throws FileNotFoundException {
114 public String toString() {
115 return getClass().getSimpleName() + "{" + file + "}";
119 private static void toCache(final File rootDir, final Collection<File> yangFiles) {
120 cache.put(rootDir, yangFiles);
124 * Instantiate object from fully qualified class name
126 static <T> T getInstance(String codeGeneratorClass, Class<T> baseType) throws ClassNotFoundException,
127 InstantiationException, IllegalAccessException {
128 return baseType.cast(resolveClass(codeGeneratorClass, baseType).newInstance());
131 private static Class<?> resolveClass(String codeGeneratorClass, Class<?> baseType) throws ClassNotFoundException {
132 Class<?> clazz = Class.forName(codeGeneratorClass);
134 if (!isImplemented(baseType, clazz))
135 throw new IllegalArgumentException("Code generator " + clazz + " has to implement " + baseType);
139 private static boolean isImplemented(Class<?> expectedIface, Class<?> byClazz) {
140 for (Class<?> iface : byClazz.getInterfaces()) {
141 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 final static class YangsInZipsResult implements Closeable {
174 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) {
193 static YangsInZipsResult findYangFilesInDependenciesAsStream(Log log, MavenProject project)
194 throws MojoFailureException {
195 List<InputStream> yangsFromDependencies = new ArrayList<>();
196 List<Closeable> zips = new ArrayList<>();
198 List<File> filesOnCp = Util.getClassPath(project);
199 log.info(Util.message("Searching for yang files in following dependencies: %s",
200 YangToSourcesProcessor.LOG_PREFIX, filesOnCp));
202 for (File file : filesOnCp) {
203 List<String> foundFilesForReporting = new ArrayList<>();
204 // is it jar file or directory?
205 if (file.isDirectory()) {
206 File yangDir = new File(file, YangToSourcesProcessor.META_INF_YANG_STRING);
207 if (yangDir.exists() && yangDir.isDirectory()) {
208 File[] yangFiles = yangDir.listFiles(new FilenameFilter() {
210 public boolean accept(File dir, String name) {
211 return name.endsWith(".yang") && new File(dir, name).isFile();
214 for (File yangFile : yangFiles) {
215 yangsFromDependencies.add(new NamedFileInputStream(yangFile));
220 ZipFile zip = new ZipFile(file);
223 Enumeration<? extends ZipEntry> entries = zip.entries();
224 while (entries.hasMoreElements()) {
225 ZipEntry entry = entries.nextElement();
226 String entryName = entry.getName();
228 if (entryName.startsWith(YangToSourcesProcessor.META_INF_YANG_STRING_JAR)) {
229 if (entry.isDirectory() == false && entryName.endsWith(".yang")) {
230 foundFilesForReporting.add(entryName);
231 // This will be closed after all strams are
233 InputStream entryStream = zip.getInputStream(entry);
234 yangsFromDependencies.add(entryStream);
239 if (foundFilesForReporting.size() > 0) {
240 log.info(Util.message("Found %d yang files in %s: %s", YangToSourcesProcessor.LOG_PREFIX,
241 foundFilesForReporting.size(), file, foundFilesForReporting));
245 } catch (Exception e) {
246 throw new MojoFailureException(e.getMessage(), e);
248 return new YangsInZipsResult(yangsFromDependencies, zips);
251 final static class ContextHolder {
252 private final SchemaContext context;
253 private final Set<Module> yangModules;
255 ContextHolder(SchemaContext context, Set<Module> yangModules) {
256 this.context = context;
257 this.yangModules = yangModules;
260 SchemaContext getContext() {
264 Set<Module> getYangModules() {