Added tests for yang.model.util
[yangtools.git] / yang / yang-maven-plugin / src / main / java / org / opendaylight / yangtools / yang2sources / plugin / YangToSourcesProcessor.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 com.google.common.annotations.VisibleForTesting;
11 import com.google.common.collect.Maps;
12 import java.io.Closeable;
13 import java.io.File;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.HashSet;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Set;
23 import org.apache.maven.model.Resource;
24 import org.apache.maven.plugin.MojoExecutionException;
25 import org.apache.maven.plugin.MojoFailureException;
26 import org.apache.maven.plugin.logging.Log;
27 import org.apache.maven.project.MavenProject;
28 import org.opendaylight.yangtools.yang.model.api.Module;
29 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
30 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
31 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
32 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
33 import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
34 import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
35 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
36 import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
37 import org.sonatype.plexus.build.incremental.BuildContext;
38 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
39
40 class YangToSourcesProcessor {
41     static final String LOG_PREFIX = "yang-to-sources:";
42     static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
43     static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
44
45     private final Log log;
46     private final File yangFilesRootDir;
47     private final File[] excludedFiles;
48     private final List<CodeGeneratorArg> codeGenerators;
49     private final MavenProject project;
50     private final boolean inspectDependencies;
51     private final BuildContext buildContext;
52     private YangProvider yangProvider;
53
54     @VisibleForTesting
55     YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
56             MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
57         this(new DefaultBuildContext(), log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, yangProvider);
58     }
59
60     private YangToSourcesProcessor(BuildContext buildContext,  Log log, File yangFilesRootDir, File[] excludedFiles,
61             List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
62         this.buildContext = Util.checkNotNull(buildContext, "buildContext");
63         this.log = Util.checkNotNull(log, "log");
64         this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
65         this.excludedFiles = new File[excludedFiles.length];
66         int i = 0;
67         for (File file : excludedFiles) {
68             this.excludedFiles[i++] = new File(file.getPath());
69         }
70         this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
71         this.project = Util.checkNotNull(project, "project");
72         this.inspectDependencies = inspectDependencies;
73         this.yangProvider = yangProvider;
74     }
75
76     YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
77             MavenProject project, boolean inspectDependencies) {
78         this(log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
79     }
80
81     public void execute() throws MojoExecutionException, MojoFailureException {
82         ContextHolder context = processYang();
83         if (context != null) {
84             generateSources(context);
85             yangProvider.addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles);
86         }
87     }
88
89     private ContextHolder processYang() throws MojoExecutionException {
90         YangParserImpl parser = new YangParserImpl();
91         List<Closeable> closeables = new ArrayList<>();
92         log.info(Util.message("Inspecting %s", LOG_PREFIX, yangFilesRootDir));
93         try {
94             /*
95              * Collect all files which affect YANG context. This includes all
96              * files in current project and optionally any jars/files in the
97              * dependencies.
98              */
99             final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles, log);
100             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
101             if (inspectDependencies) {
102                 allFiles.addAll(Util.findYangFilesInDependencies(log, project));
103             }
104
105             if (allFiles.isEmpty()) {
106                 log.info(Util.message("No input files found", LOG_PREFIX));
107                 return null;
108             }
109
110             /*
111              * Check if any of the listed files changed. If no changes occurred,
112              * simply return null, which indicates and of execution.
113              */
114             boolean noChange = true;
115             for (final File f : allFiles) {
116                 if (buildContext.hasDelta(f)) {
117                     log.debug(Util.message("buildContext %s indicates %s changed, forcing regeneration", LOG_PREFIX, buildContext, f));
118                     noChange = false;
119                 }
120             }
121
122             if (noChange) {
123                 log.info(Util.message("None of %s input files changed", LOG_PREFIX, allFiles.size()));
124                 return null;
125             }
126
127             final List<InputStream> yangsInProject = new ArrayList<>();
128             for (final File f : yangFilesInProject) {
129                 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
130             }
131
132             List<InputStream> all = new ArrayList<>(yangsInProject);
133             closeables.addAll(yangsInProject);
134             Map<InputStream, Module> allYangModules;
135
136             /**
137              * Set contains all modules generated from input sources. Number of
138              * modules may differ from number of sources due to submodules
139              * (parsed submodule's data are added to its parent module). Set
140              * cannot contains null values.
141              */
142             Set<Module> projectYangModules;
143             try {
144                 if (inspectDependencies) {
145                     YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
146                     Closeable dependentYangResult1 = dependentYangResult;
147                     closeables.add(dependentYangResult1);
148                     all.addAll(dependentYangResult.getYangStreams());
149                 }
150
151                 allYangModules = parser.parseYangModelsFromStreamsMapped(all);
152
153                 projectYangModules = new HashSet<>();
154                 for (InputStream inProject : yangsInProject) {
155                     Module module = allYangModules.get(inProject);
156                     if (module != null) {
157                         projectYangModules.add(module);
158                     }
159                 }
160
161             } finally {
162                 for (AutoCloseable closeable : closeables) {
163                     closeable.close();
164                 }
165             }
166
167             Set<Module> parsedAllYangModules = new HashSet<>(allYangModules.values());
168             SchemaContext resolveSchemaContext = parser.resolveSchemaContext(parsedAllYangModules);
169             log.info(Util.message("%s files parsed from %s", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject));
170             return new ContextHolder(resolveSchemaContext, projectYangModules);
171
172             // MojoExecutionException is thrown since execution cannot continue
173         } catch (Exception e) {
174             String message = Util.message("Unable to parse %s files from %s", LOG_PREFIX, Util.YANG_SUFFIX,
175                     yangFilesRootDir);
176             log.error(message, e);
177             throw new MojoExecutionException(message, e);
178         }
179     }
180
181     static class YangProvider {
182
183
184
185         void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
186                 throws MojoFailureException {
187
188             // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
189             File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
190
191             File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
192             withMetaInf.mkdirs();
193
194             try {
195                 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, null);
196                 for (File file : files) {
197                     org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
198                 }
199             } catch (IOException e) {
200                 String message = "Unable to list yang files into resource folder";
201                 log.warn(message, e);
202                 throw new MojoFailureException(message, e);
203             }
204
205             setResource(generatedYangDir, project);
206
207             log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
208                     META_INF_YANG_STRING_JAR));
209         }
210
211         private static void setResource(File targetYangDir, MavenProject project) {
212             Resource res = new Resource();
213             res.setDirectory(targetYangDir.getPath());
214             project.addResource(res);
215         }
216     }
217
218     /**
219      * Call generate on every generator from plugin configuration
220      */
221     private void generateSources(ContextHolder context) throws MojoFailureException {
222         if (codeGenerators.size() == 0) {
223             log.warn(Util.message("No code generators provided", LOG_PREFIX));
224             return;
225         }
226
227         Map<String, String> thrown = Maps.newHashMap();
228         for (CodeGeneratorArg codeGenerator : codeGenerators) {
229             try {
230                 generateSourcesWithOneGenerator(context, codeGenerator);
231             } catch (Exception e) {
232                 // try other generators, exception will be thrown after
233                 log.error(
234                         Util.message("Unable to generate sources with %s generator", LOG_PREFIX,
235                                 codeGenerator.getCodeGeneratorClass()), e);
236                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
237             }
238         }
239
240         if (!thrown.isEmpty()) {
241             String message = Util.message(
242                     "One or more code generators failed, including failed list(generatorClass=exception) %s",
243                     LOG_PREFIX, thrown.toString());
244             log.error(message);
245             throw new MojoFailureException(message);
246         }
247     }
248
249     /**
250      * Instantiate generator from class and call required method
251      */
252     private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
253             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
254
255         codeGeneratorCfg.check();
256
257         CodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), CodeGenerator.class);
258         log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX,
259                 codeGeneratorCfg.getCodeGeneratorClass()));
260
261         File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
262
263         if (outputDir != null) {
264           project.addCompileSourceRoot(outputDir.getAbsolutePath());
265         } else {
266           throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the pom.xml");
267         }
268
269         log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir));
270         log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir()));
271         log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
272                 codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
273
274         if (g instanceof BuildContextAware) {
275             ((BuildContextAware)g).setBuildContext(buildContext);
276         }
277         g.setLog(log);
278         g.setMavenProject(project);
279         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
280         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
281
282         YangProvider.setResource(resourceBaseDir, project);
283         g.setResourceBaseDir(resourceBaseDir);
284         log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir,
285                 codeGeneratorCfg.getCodeGeneratorClass()));
286
287         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
288
289         log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),
290                 generated));
291     }
292
293 }