Implemented support for generating YangModuleInfo implementation.
[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.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;
21 import java.util.Map;
22 import java.util.Set;
23 import java.util.zip.ZipEntry;
24 import java.util.zip.ZipFile;
25
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;
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     private static void toCache(final File rootDir, final Collection<File> yangFiles) {
104         cache.put(rootDir, yangFiles);
105     }
106
107     /**
108      * Instantiate object from fully qualified class name
109      */
110     static <T> T getInstance(String codeGeneratorClass, Class<T> baseType) throws ClassNotFoundException,
111             InstantiationException, IllegalAccessException {
112         return baseType.cast(resolveClass(codeGeneratorClass, baseType).newInstance());
113     }
114
115     private static Class<?> resolveClass(String codeGeneratorClass, Class<?> baseType) throws ClassNotFoundException {
116         Class<?> clazz = Class.forName(codeGeneratorClass);
117
118         if (!isImplemented(baseType, clazz)) {
119             throw new IllegalArgumentException("Code generator " + clazz + " has to implement " + baseType);
120         }
121         return clazz;
122     }
123
124     private static boolean isImplemented(Class<?> expectedIface, Class<?> byClazz) {
125         for (Class<?> iface : byClazz.getInterfaces()) {
126             if (iface.equals(expectedIface)) {
127                 return true;
128             }
129         }
130         return false;
131     }
132
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);
136     }
137
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);
144             }
145         }
146         return dependencies;
147     }
148
149     private static final String JAR_SUFFIX = ".jar";
150
151     private static boolean isJar(File element) {
152         return (element.isFile() && element.getName().endsWith(JAR_SUFFIX)) ? true : false;
153     }
154
155     static <T> T checkNotNull(T obj, String paramName) {
156         return Preconditions.checkNotNull(obj, "Parameter " + paramName + " is null");
157     }
158
159     static final class YangsInZipsResult implements Closeable {
160         private final List<InputStream> yangStreams;
161         private final List<Closeable> zipInputStreams;
162
163         private YangsInZipsResult(List<InputStream> yangStreams, List<Closeable> zipInputStreams) {
164             this.yangStreams = yangStreams;
165             this.zipInputStreams = zipInputStreams;
166         }
167
168         @Override
169         public void close() throws IOException {
170             for (InputStream is : yangStreams) {
171                 is.close();
172             }
173             for (Closeable is : zipInputStreams) {
174                 is.close();
175             }
176         }
177
178         public List<InputStream> getYangStreams() {
179             return this.yangStreams;
180         }
181     }
182
183     static YangsInZipsResult findYangFilesInDependenciesAsStream(Log log, MavenProject project)
184             throws MojoFailureException {
185         List<InputStream> yangsFromDependencies = new ArrayList<>();
186         List<Closeable> zips = new ArrayList<>();
187         try {
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));
191
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() {
199                             @Override
200                             public boolean accept(File dir, String name) {
201                                 return name.endsWith(".yang") && new File(dir, name).isFile();
202                             }
203                         });
204                         for (File yangFile : yangFiles) {
205                             yangsFromDependencies.add(new NamedFileInputStream(yangFile, YangToSourcesProcessor.META_INF_YANG_STRING + File.separator + yangFile.getName()));
206                         }
207                     }
208
209                 } else {
210                     ZipFile zip = new ZipFile(file);
211                     zips.add(zip);
212
213                     Enumeration<? extends ZipEntry> entries = zip.entries();
214                     while (entries.hasMoreElements()) {
215                         ZipEntry entry = entries.nextElement();
216                         String entryName = entry.getName();
217
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
222                             // parsed.
223                             InputStream entryStream = zip.getInputStream(entry);
224                             yangsFromDependencies.add(entryStream);
225                         }
226                     }
227                 }
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));
231                 }
232
233             }
234         } catch (Exception e) {
235             throw new MojoFailureException(e.getMessage(), e);
236         }
237         return new YangsInZipsResult(yangsFromDependencies, zips);
238     }
239
240     static Collection<File> findYangFilesInDependencies(Log log, MavenProject project) throws MojoFailureException {
241         final List<File> yangsFilesFromDependencies = new ArrayList<>();
242
243         try {
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));
247
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() {
254                             @Override
255                             public boolean accept(File dir, String name) {
256                                 return name.endsWith(".yang") && new File(dir, name).isFile();
257                             }
258                         });
259
260                         yangsFilesFromDependencies.addAll(Arrays.asList(yangFiles));
261                     }
262                 } else {
263                     try (ZipFile zip = new ZipFile(file)) {
264
265                         final Enumeration<? extends ZipEntry> entries = zip.entries();
266                         while (entries.hasMoreElements()) {
267                             ZipEntry entry = entries.nextElement();
268                             String entryName = entry.getName();
269
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,
273                                         file, entryName));
274                                 yangsFilesFromDependencies.add(file);
275                                 break;
276                             }
277                         }
278                     }
279                 }
280             }
281         } catch (Exception e) {
282             throw new MojoFailureException("Failed to scan for YANG files in depedencies", e);
283         }
284         return yangsFilesFromDependencies;
285     }
286
287     static final class ContextHolder {
288         private final SchemaContext context;
289         private final Set<Module> yangModules;
290
291         ContextHolder(SchemaContext context, Set<Module> yangModules) {
292             this.context = context;
293             this.yangModules = yangModules;
294         }
295
296         SchemaContext getContext() {
297             return context;
298         }
299
300         Set<Module> getYangModules() {
301             return yangModules;
302         }
303     }
304
305 }