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";
44 static final File META_INF_YANG_DIR = new File(META_INF_YANG_STRING);
46 private final Log log;
47 private final File yangFilesRootDir;
48 private final File[] excludedFiles;
49 private final List<CodeGeneratorArg> codeGenerators;
50 private final MavenProject project;
51 private final boolean inspectDependencies;
52 private final BuildContext buildContext;
53 private YangProvider yangProvider;
56 YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
57 MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
58 this(new DefaultBuildContext(), log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, yangProvider);
61 private YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles,
62 List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
63 this.buildContext = Util.checkNotNull(buildContext, "buildContext");
64 this.log = Util.checkNotNull(log, "log");
65 this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
66 this.excludedFiles = new File[excludedFiles.length];
68 for (File file : excludedFiles) {
69 this.excludedFiles[i++] = new File(file.getPath());
71 this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
72 this.project = Util.checkNotNull(project, "project");
73 this.inspectDependencies = inspectDependencies;
74 this.yangProvider = yangProvider;
77 YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
78 MavenProject project, boolean inspectDependencies) {
79 this(log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
82 public void execute() throws MojoExecutionException, MojoFailureException {
83 ContextHolder context = processYang();
84 if (context != null) {
85 generateSources(context);
86 yangProvider.addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles);
90 private ContextHolder processYang() throws MojoExecutionException {
91 YangParserImpl parser = new YangParserImpl();
92 List<Closeable> closeables = new ArrayList<>();
93 log.info(Util.message("Inspecting %s", LOG_PREFIX, yangFilesRootDir));
96 * Collect all files which affect YANG context. This includes all
97 * files in current project and optionally any jars/files in the
100 final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles, log);
101 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
102 if (inspectDependencies) {
103 allFiles.addAll(Util.findYangFilesInDependencies(log, project));
106 if (allFiles.isEmpty()) {
107 log.info(Util.message("No input files found", LOG_PREFIX));
112 * Check if any of the listed files changed. If no changes occurred,
113 * simply return null, which indicates and of execution.
115 boolean noChange = true;
116 for (final File f : allFiles) {
117 if (buildContext.hasDelta(f)) {
118 log.debug(Util.message("buildContext %s indicates %s changed, forcing regeneration", LOG_PREFIX, buildContext, f));
124 log.info(Util.message("None of %s input files changed", LOG_PREFIX, allFiles.size()));
128 final List<InputStream> yangsInProject = new ArrayList<>();
129 for (final File f : yangFilesInProject) {
130 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
133 List<InputStream> all = new ArrayList<>(yangsInProject);
134 closeables.addAll(yangsInProject);
135 Map<InputStream, Module> allYangModules;
138 * Set contains all modules generated from input sources. Number of
139 * modules may differ from number of sources due to submodules
140 * (parsed submodule's data are added to its parent module). Set
141 * cannot contains null values.
143 Set<Module> projectYangModules;
145 if (inspectDependencies) {
146 YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
147 Closeable dependentYangResult1 = dependentYangResult;
148 closeables.add(dependentYangResult1);
149 all.addAll(dependentYangResult.getYangStreams());
152 allYangModules = parser.parseYangModelsFromStreamsMapped(all);
154 projectYangModules = new HashSet<>();
155 for (InputStream inProject : yangsInProject) {
156 Module module = allYangModules.get(inProject);
157 if (module != null) {
158 projectYangModules.add(module);
163 for (AutoCloseable closeable : closeables) {
168 Set<Module> parsedAllYangModules = new HashSet<>(allYangModules.values());
169 SchemaContext resolveSchemaContext = parser.resolveSchemaContext(parsedAllYangModules);
170 log.info(Util.message("%s files parsed from %s", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject));
171 return new ContextHolder(resolveSchemaContext, projectYangModules);
173 // MojoExecutionException is thrown since execution cannot continue
174 } catch (Exception e) {
175 String message = Util.message("Unable to parse %s files from %s", LOG_PREFIX, Util.YANG_SUFFIX,
177 log.error(message, e);
178 throw new MojoExecutionException(message, e);
182 static class YangProvider {
184 private static final String YANG_RESOURCE_DIR = "target" + File.separator + "yang";
186 void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
187 throws MojoFailureException {
188 File targetYangDir = new File(project.getBasedir(), YANG_RESOURCE_DIR);
191 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, null);
192 for (File file : files) {
193 org.apache.commons.io.FileUtils.copyFile(file, new File(targetYangDir, file.getName()));
195 } catch (IOException e) {
196 String message = "Unable to list yang files into resource folder";
197 log.warn(message, e);
198 throw new MojoFailureException(message, e);
201 setResource(targetYangDir, META_INF_YANG_STRING_JAR, project);
203 log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
204 META_INF_YANG_STRING_JAR));
207 private static void setResource(File targetYangDir, String targetPath, MavenProject project) {
208 Resource res = new Resource();
209 res.setDirectory(targetYangDir.getPath());
210 if (targetPath != null) {
211 res.setTargetPath(targetPath);
213 project.addResource(res);
218 * Call generate on every generator from plugin configuration
220 private void generateSources(ContextHolder context) throws MojoFailureException {
221 if (codeGenerators.size() == 0) {
222 log.warn(Util.message("No code generators provided", LOG_PREFIX));
226 Map<String, String> thrown = Maps.newHashMap();
227 for (CodeGeneratorArg codeGenerator : codeGenerators) {
229 generateSourcesWithOneGenerator(context, codeGenerator);
230 } catch (Exception e) {
231 // try other generators, exception will be thrown after
233 Util.message("Unable to generate sources with %s generator", LOG_PREFIX,
234 codeGenerator.getCodeGeneratorClass()), e);
235 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
239 if (!thrown.isEmpty()) {
240 String message = Util.message(
241 "One or more code generators failed, including failed list(generatorClass=exception) %s",
242 LOG_PREFIX, thrown.toString());
244 throw new MojoFailureException(message);
249 * Instantiate generator from class and call required method
251 private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
252 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
254 codeGeneratorCfg.check();
256 CodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), CodeGenerator.class);
257 log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX,
258 codeGeneratorCfg.getCodeGeneratorClass()));
260 File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
262 if (outputDir != null) {
263 project.addCompileSourceRoot(outputDir.getAbsolutePath());
265 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the pom.xml");
268 log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir));
269 log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir()));
270 log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
271 codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
273 if (g instanceof BuildContextAware) {
274 ((BuildContextAware)g).setBuildContext(buildContext);
277 g.setMavenProject(project);
278 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
279 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
281 YangProvider.setResource(resourceBaseDir, null, project);
282 g.setResourceBaseDir(resourceBaseDir);
283 log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir,
284 codeGeneratorCfg.getCodeGeneratorClass()));
286 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
288 log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),