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 com.google.common.annotations.VisibleForTesting;
11 import com.google.common.collect.Maps;
12 import java.io.Closeable;
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;
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.BasicCodeGenerator;
36 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
37 import org.opendaylight.yangtools.yang2sources.spi.MavenLogAware;
38 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
39 import org.sonatype.plexus.build.incremental.BuildContext;
40 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
42 class YangToSourcesProcessor {
43 static final String LOG_PREFIX = "yang-to-sources:";
44 static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
45 static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
47 private final Log log;
48 private final File yangFilesRootDir;
49 private final File[] excludedFiles;
50 private final List<CodeGeneratorArg> codeGenerators;
51 private final MavenProject project;
52 private final boolean inspectDependencies;
53 private final BuildContext buildContext;
54 private final YangProvider yangProvider;
57 YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
58 MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
59 this(new DefaultBuildContext(), log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, yangProvider);
62 private YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles,
63 List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
64 this.buildContext = Util.checkNotNull(buildContext, "buildContext");
65 this.log = Util.checkNotNull(log, "log");
66 this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
67 this.excludedFiles = new File[excludedFiles.length];
69 for (File file : excludedFiles) {
70 this.excludedFiles[i++] = new File(file.getPath());
72 this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
73 this.project = Util.checkNotNull(project, "project");
74 this.inspectDependencies = inspectDependencies;
75 this.yangProvider = yangProvider;
78 YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
79 MavenProject project, boolean inspectDependencies) {
80 this(log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
83 public void execute() throws MojoExecutionException, MojoFailureException {
84 ContextHolder context = processYang();
85 if (context != null) {
86 generateSources(context);
87 yangProvider.addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles);
91 private ContextHolder processYang() throws MojoExecutionException {
92 YangParserImpl parser = new YangParserImpl();
93 List<Closeable> closeables = new ArrayList<>();
94 log.info(Util.message("Inspecting %s", LOG_PREFIX, yangFilesRootDir));
97 * Collect all files which affect YANG context. This includes all
98 * files in current project and optionally any jars/files in the
101 final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles, log);
102 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
103 if (inspectDependencies) {
104 allFiles.addAll(Util.findYangFilesInDependencies(log, project));
107 if (allFiles.isEmpty()) {
108 log.info(Util.message("No input files found", LOG_PREFIX));
113 * Check if any of the listed files changed. If no changes occurred,
114 * simply return null, which indicates and of execution.
116 boolean noChange = true;
117 for (final File f : allFiles) {
118 if (buildContext.hasDelta(f)) {
119 log.debug(Util.message("buildContext %s indicates %s changed, forcing regeneration", LOG_PREFIX, buildContext, f));
125 log.info(Util.message("None of %s input files changed", LOG_PREFIX, allFiles.size()));
129 final List<InputStream> yangsInProject = new ArrayList<>();
130 for (final File f : yangFilesInProject) {
131 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
134 List<InputStream> all = new ArrayList<>(yangsInProject);
135 closeables.addAll(yangsInProject);
136 Map<InputStream, Module> allYangModules;
139 * Set contains all modules generated from input sources. Number of
140 * modules may differ from number of sources due to submodules
141 * (parsed submodule's data are added to its parent module). Set
142 * cannot contains null values.
144 Set<Module> projectYangModules;
146 if (inspectDependencies) {
147 YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
148 Closeable dependentYangResult1 = dependentYangResult;
149 closeables.add(dependentYangResult1);
150 all.addAll(dependentYangResult.getYangStreams());
153 allYangModules = parser.parseYangModelsFromStreamsMapped(all);
155 projectYangModules = new HashSet<>();
156 for (InputStream inProject : yangsInProject) {
157 Module module = allYangModules.get(inProject);
158 if (module != null) {
159 projectYangModules.add(module);
164 for (AutoCloseable closeable : closeables) {
169 Set<Module> parsedAllYangModules = new HashSet<>(allYangModules.values());
170 SchemaContext resolveSchemaContext = parser.resolveSchemaContext(parsedAllYangModules);
171 log.info(Util.message("%s files parsed from %s", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject));
172 return new ContextHolder(resolveSchemaContext, projectYangModules);
174 // MojoExecutionException is thrown since execution cannot continue
175 } catch (Exception e) {
176 String message = Util.message("Unable to parse %s files from %s", LOG_PREFIX, Util.YANG_SUFFIX,
178 log.error(message, e);
179 throw new MojoExecutionException(message, e);
183 static class YangProvider {
185 void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
186 throws MojoFailureException {
188 // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
190 File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
191 addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, generatedYangDir);
193 // Also copy to the actual build output dir if different than "target". When running in
194 // Eclipse this can differ (eg "target-ide").
196 File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
197 CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
198 if(!actualGeneratedYangDir.equals(generatedYangDir)) {
199 addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
203 private void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir,
204 File[] excludedFiles, File generatedYangDir)
205 throws MojoFailureException {
207 File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
208 withMetaInf.mkdirs();
211 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, log);
212 for (File file : files) {
213 org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
215 } catch (IOException e) {
216 log.warn(String.format("Failed to generate files into root %s", yangFilesRootDir), e);
217 throw new MojoFailureException("Unable to list yang files into resource folder", e);
220 setResource(generatedYangDir, project);
222 log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
223 META_INF_YANG_STRING_JAR));
226 private static void setResource(File targetYangDir, MavenProject project) {
227 Resource res = new Resource();
228 res.setDirectory(targetYangDir.getPath());
229 project.addResource(res);
234 * Call generate on every generator from plugin configuration
236 private void generateSources(ContextHolder context) throws MojoFailureException {
237 if (codeGenerators.size() == 0) {
238 log.warn(Util.message("No code generators provided", LOG_PREFIX));
242 Map<String, String> thrown = Maps.newHashMap();
243 for (CodeGeneratorArg codeGenerator : codeGenerators) {
245 generateSourcesWithOneGenerator(context, codeGenerator);
246 } catch (Exception e) {
247 // try other generators, exception will be thrown after
249 Util.message("Unable to generate sources with %s generator", LOG_PREFIX,
250 codeGenerator.getCodeGeneratorClass()), e);
251 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
255 if (!thrown.isEmpty()) {
256 String message = Util.message(
257 "One or more code generators failed, including failed list(generatorClass=exception) %s",
258 LOG_PREFIX, thrown.toString());
260 throw new MojoFailureException(message);
265 * Instantiate generator from class and call required method
267 private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
268 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
270 codeGeneratorCfg.check();
272 BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
273 log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX,
274 codeGeneratorCfg.getCodeGeneratorClass()));
276 File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
278 if (outputDir != null) {
279 project.addCompileSourceRoot(outputDir.getAbsolutePath());
281 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the pom.xml");
284 log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir));
285 log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir()));
286 log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
287 codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
289 if (g instanceof MavenLogAware) {
290 ((MavenLogAware)g).setLog(log);
292 if (g instanceof BuildContextAware) {
293 ((BuildContextAware)g).setBuildContext(buildContext);
295 if (g instanceof MavenProjectAware) {
296 ((MavenProjectAware)g).setMavenProject(project);
298 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
299 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
301 YangProvider.setResource(resourceBaseDir, project);
302 g.setResourceBaseDir(resourceBaseDir);
303 log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir,
304 codeGeneratorCfg.getCodeGeneratorClass()));
306 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
308 log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),