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.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;
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";
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 final YangProvider yangProvider;
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);
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];
67 for (File file : excludedFiles) {
68 this.excludedFiles[i++] = new File(file.getPath());
70 this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
71 this.project = Util.checkNotNull(project, "project");
72 this.inspectDependencies = inspectDependencies;
73 this.yangProvider = yangProvider;
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());
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);
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));
95 * Collect all files which affect YANG context. This includes all
96 * files in current project and optionally any jars/files in the
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));
105 if (allFiles.isEmpty()) {
106 log.info(Util.message("No input files found", LOG_PREFIX));
111 * Check if any of the listed files changed. If no changes occurred,
112 * simply return null, which indicates and of execution.
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));
123 log.info(Util.message("None of %s input files changed", LOG_PREFIX, allFiles.size()));
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()));
132 List<InputStream> all = new ArrayList<>(yangsInProject);
133 closeables.addAll(yangsInProject);
134 Map<InputStream, Module> allYangModules;
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.
142 Set<Module> projectYangModules;
144 if (inspectDependencies) {
145 YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
146 Closeable dependentYangResult1 = dependentYangResult;
147 closeables.add(dependentYangResult1);
148 all.addAll(dependentYangResult.getYangStreams());
151 allYangModules = parser.parseYangModelsFromStreamsMapped(all);
153 projectYangModules = new HashSet<>();
154 for (InputStream inProject : yangsInProject) {
155 Module module = allYangModules.get(inProject);
156 if (module != null) {
157 projectYangModules.add(module);
162 for (AutoCloseable closeable : closeables) {
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);
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,
176 log.error(message, e);
177 throw new MojoExecutionException(message, e);
181 static class YangProvider {
183 void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
184 throws MojoFailureException {
186 // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
188 File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
189 addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, generatedYangDir);
191 // Also copy to the actual build output dir if different than "target". When running in
192 // Eclipse this can differ (eg "target-ide").
194 File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
195 CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
196 if(!actualGeneratedYangDir.equals(generatedYangDir)) {
197 addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
201 private void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir,
202 File[] excludedFiles, File generatedYangDir)
203 throws MojoFailureException {
205 File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
206 withMetaInf.mkdirs();
209 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, log);
210 for (File file : files) {
211 org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
213 } catch (IOException e) {
214 log.warn(String.format("Failed to generate files into root %s", yangFilesRootDir), e);
215 throw new MojoFailureException("Unable to list yang files into resource folder", e);
218 setResource(generatedYangDir, project);
220 log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
221 META_INF_YANG_STRING_JAR));
224 private static void setResource(File targetYangDir, MavenProject project) {
225 Resource res = new Resource();
226 res.setDirectory(targetYangDir.getPath());
227 project.addResource(res);
232 * Call generate on every generator from plugin configuration
234 private void generateSources(ContextHolder context) throws MojoFailureException {
235 if (codeGenerators.size() == 0) {
236 log.warn(Util.message("No code generators provided", LOG_PREFIX));
240 Map<String, String> thrown = Maps.newHashMap();
241 for (CodeGeneratorArg codeGenerator : codeGenerators) {
243 generateSourcesWithOneGenerator(context, codeGenerator);
244 } catch (Exception e) {
245 // try other generators, exception will be thrown after
247 Util.message("Unable to generate sources with %s generator", LOG_PREFIX,
248 codeGenerator.getCodeGeneratorClass()), e);
249 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
253 if (!thrown.isEmpty()) {
254 String message = Util.message(
255 "One or more code generators failed, including failed list(generatorClass=exception) %s",
256 LOG_PREFIX, thrown.toString());
258 throw new MojoFailureException(message);
263 * Instantiate generator from class and call required method
265 private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
266 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
268 codeGeneratorCfg.check();
270 CodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), CodeGenerator.class);
271 log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX,
272 codeGeneratorCfg.getCodeGeneratorClass()));
274 File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
276 if (outputDir != null) {
277 project.addCompileSourceRoot(outputDir.getAbsolutePath());
279 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the pom.xml");
282 log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir));
283 log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir()));
284 log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
285 codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
287 if (g instanceof BuildContextAware) {
288 ((BuildContextAware)g).setBuildContext(buildContext);
291 g.setMavenProject(project);
292 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
293 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
295 YangProvider.setResource(resourceBaseDir, project);
296 g.setResourceBaseDir(resourceBaseDir);
297 log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir,
298 codeGeneratorCfg.getCodeGeneratorClass()));
300 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
302 log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),