Merge "Switch to using plexus-build-api for file output"
[yangtools.git] / yang / yang-maven-plugin / src / main / java / org / opendaylight / yangtools / yang2sources / plugin / Util.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang2sources.plugin;
9
10 import java.io.Closeable;
11 import java.io.File;
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;
22 import java.util.Map;
23 import java.util.Set;
24 import java.util.zip.ZipEntry;
25 import java.util.zip.ZipFile;
26
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;
34
35 import com.google.common.base.Preconditions;
36 import com.google.common.collect.Lists;
37 import com.google.common.collect.Maps;
38
39 final class Util {
40
41     /**
42      * It isn't desirable to create instances of this class
43      */
44     private Util() {
45     }
46
47     static final String YANG_SUFFIX = "yang";
48
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
54     // only once.
55     private static Map<File, Collection<File>> cache = Maps.newHashMapWithExpectedSize(CACHE_SIZE);
56
57     /**
58      * List files recursively and return as array of String paths. Use cache of
59      * size 1.
60      */
61     static Collection<File> listFiles(File root) throws FileNotFoundException {
62         if (cache.get(root) != null) {
63             return cache.get(root);
64         }
65
66         if (!root.exists()) {
67             throw new FileNotFoundException(root.toString());
68         }
69
70         Collection<File> yangFiles = FileUtils.listFiles(root, new String[] { YANG_SUFFIX }, true);
71
72         toCache(root, yangFiles);
73         return yangFiles;
74     }
75
76     static Collection<File> listFiles(File root, File[] excludedFiles, Log log) throws FileNotFoundException {
77         if (!root.exists()) {
78             throw new FileNotFoundException(root.toString());
79         }
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) {
85                 if (ex.equals(f)) {
86                     excluded = true;
87                     break;
88                 }
89             }
90             if (excluded) {
91                 if (log != null) {
92                     log.info(Util.message("%s file excluded %s", YangToSourcesProcessor.LOG_PREFIX,
93                             Util.YANG_SUFFIX.toUpperCase(), f));
94                 }
95             } else {
96                 result.add(f);
97             }
98         }
99
100         return result;
101     }
102
103     static class NamedFileInputStream extends FileInputStream {
104         private final File file;
105
106         NamedFileInputStream(File file) throws FileNotFoundException {
107             super(file);
108             this.file = file;
109         }
110
111         @Override
112         public String toString() {
113             return getClass().getSimpleName() + "{" + file + "}";
114         }
115     }
116
117     private static void toCache(final File rootDir, final Collection<File> yangFiles) {
118         cache.put(rootDir, yangFiles);
119     }
120
121     /**
122      * Instantiate object from fully qualified class name
123      */
124     static <T> T getInstance(String codeGeneratorClass, Class<T> baseType) throws ClassNotFoundException,
125             InstantiationException, IllegalAccessException {
126         return baseType.cast(resolveClass(codeGeneratorClass, baseType).newInstance());
127     }
128
129     private static Class<?> resolveClass(String codeGeneratorClass, Class<?> baseType) throws ClassNotFoundException {
130         Class<?> clazz = Class.forName(codeGeneratorClass);
131
132         if (!isImplemented(baseType, clazz)) {
133             throw new IllegalArgumentException("Code generator " + clazz + " has to implement " + baseType);
134         }
135         return clazz;
136     }
137
138     private static boolean isImplemented(Class<?> expectedIface, Class<?> byClazz) {
139         for (Class<?> iface : byClazz.getInterfaces()) {
140             if (iface.equals(expectedIface)) {
141                 return true;
142             }
143         }
144         return false;
145     }
146
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);
150     }
151
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);
158             }
159         }
160         return dependencies;
161     }
162
163     private static final String JAR_SUFFIX = ".jar";
164
165     private static boolean isJar(File element) {
166         return (element.isFile() && element.getName().endsWith(JAR_SUFFIX)) ? true : false;
167     }
168
169     static <T> T checkNotNull(T obj, String paramName) {
170         return Preconditions.checkNotNull(obj, "Parameter " + paramName + " is null");
171     }
172
173     static final class YangsInZipsResult implements Closeable {
174         private final List<InputStream> yangStreams;
175         private final List<Closeable> zipInputStreams;
176
177         private YangsInZipsResult(List<InputStream> yangStreams, List<Closeable> zipInputStreams) {
178             this.yangStreams = yangStreams;
179             this.zipInputStreams = zipInputStreams;
180         }
181
182         @Override
183         public void close() throws IOException {
184             for (InputStream is : yangStreams) {
185                 is.close();
186             }
187             for (Closeable is : zipInputStreams) {
188                 is.close();
189             }
190         }
191
192         public List<InputStream> getYangStreams() {
193             return this.yangStreams;
194         }
195     }
196
197     static YangsInZipsResult findYangFilesInDependenciesAsStream(Log log, MavenProject project)
198             throws MojoFailureException {
199         List<InputStream> yangsFromDependencies = new ArrayList<>();
200         List<Closeable> zips = new ArrayList<>();
201         try {
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));
205
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() {
213                             @Override
214                             public boolean accept(File dir, String name) {
215                                 return name.endsWith(".yang") && new File(dir, name).isFile();
216                             }
217                         });
218                         for (File yangFile : yangFiles) {
219                             yangsFromDependencies.add(new NamedFileInputStream(yangFile));
220                         }
221                     }
222
223                 } else {
224                     ZipFile zip = new ZipFile(file);
225                     zips.add(zip);
226
227                     Enumeration<? extends ZipEntry> entries = zip.entries();
228                     while (entries.hasMoreElements()) {
229                         ZipEntry entry = entries.nextElement();
230                         String entryName = entry.getName();
231
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
236                             // parsed.
237                             InputStream entryStream = zip.getInputStream(entry);
238                             yangsFromDependencies.add(entryStream);
239                         }
240                     }
241                 }
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));
245                 }
246
247             }
248         } catch (Exception e) {
249             throw new MojoFailureException(e.getMessage(), e);
250         }
251         return new YangsInZipsResult(yangsFromDependencies, zips);
252     }
253
254     static Collection<File> findYangFilesInDependencies(Log log, MavenProject project) throws MojoFailureException {
255         final List<File> yangsFilesFromDependencies = new ArrayList<>();
256
257         try {
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));
261
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() {
268                             @Override
269                             public boolean accept(File dir, String name) {
270                                 return name.endsWith(".yang") && new File(dir, name).isFile();
271                             }
272                         });
273
274                         yangsFilesFromDependencies.addAll(Arrays.asList(yangFiles));
275                     }
276                 } else {
277                     try (ZipFile zip = new ZipFile(file)) {
278
279                         final Enumeration<? extends ZipEntry> entries = zip.entries();
280                         while (entries.hasMoreElements()) {
281                             ZipEntry entry = entries.nextElement();
282                             String entryName = entry.getName();
283
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,
287                                         file, entryName));
288                                 yangsFilesFromDependencies.add(file);
289                                 break;
290                             }
291                         }
292                     }
293                 }
294             }
295         } catch (Exception e) {
296             throw new MojoFailureException("Failed to scan for YANG files in depedencies", e);
297         }
298         return yangsFilesFromDependencies;
299     }
300
301     static final class ContextHolder {
302         private final SchemaContext context;
303         private final Set<Module> yangModules;
304
305         ContextHolder(SchemaContext context, Set<Module> yangModules) {
306             this.context = context;
307             this.yangModules = yangModules;
308         }
309
310         SchemaContext getContext() {
311             return context;
312         }
313
314         Set<Module> getYangModules() {
315             return yangModules;
316         }
317     }
318
319 }