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 java.util.concurrent.ConcurrentMap;
24 import org.apache.commons.io.IOUtils;
25 import org.apache.maven.model.Resource;
26 import org.apache.maven.plugin.MojoExecutionException;
27 import org.apache.maven.plugin.MojoFailureException;
28 import org.apache.maven.plugin.logging.Log;
29 import org.apache.maven.project.MavenProject;
30 import org.opendaylight.yangtools.yang.model.api.Module;
31 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
32 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
33 import org.opendaylight.yangtools.yang.parser.repo.URLSchemaContextResolver;
34 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
35 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
36 import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
37 import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
38 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
39 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
40 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
41 import org.sonatype.plexus.build.incremental.BuildContext;
42 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
44 class YangToSourcesProcessor {
45 static final String LOG_PREFIX = "yang-to-sources:";
46 static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
47 static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
49 private final Log log;
50 private final File yangFilesRootDir;
51 private final File[] excludedFiles;
52 private final List<CodeGeneratorArg> codeGenerators;
53 private final MavenProject project;
54 private final boolean inspectDependencies;
55 private final BuildContext buildContext;
56 private final YangProvider yangProvider;
57 private final URLSchemaContextResolver resolver;
60 YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
61 MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
62 this(new DefaultBuildContext(), log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, yangProvider);
65 private YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles,
66 List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
67 this.buildContext = Util.checkNotNull(buildContext, "buildContext");
68 this.log = Util.checkNotNull(log, "log");
69 this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
70 this.excludedFiles = new File[excludedFiles.length];
72 for (File file : excludedFiles) {
73 this.excludedFiles[i++] = new File(file.getPath());
75 this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
76 this.project = Util.checkNotNull(project, "project");
77 this.inspectDependencies = inspectDependencies;
78 this.yangProvider = yangProvider;
79 this.resolver = URLSchemaContextResolver.create("maven-plugin");
82 YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
83 MavenProject project, boolean inspectDependencies) {
84 this(log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
87 public void execute() throws MojoExecutionException, MojoFailureException {
88 ContextHolder context = processYang();
89 if (context != null) {
90 generateSources(context);
91 yangProvider.addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles);
95 private ContextHolder processYang() throws MojoExecutionException {
96 YangParserImpl parser = new YangParserImpl();
97 List<Closeable> closeables = new ArrayList<>();
98 log.info(Util.message("Inspecting %s", LOG_PREFIX, yangFilesRootDir));
101 * Collect all files which affect YANG context. This includes all
102 * files in current project and optionally any jars/files in the
105 final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles, log);
108 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
109 if (inspectDependencies) {
110 allFiles.addAll(Util.findYangFilesInDependencies(log, project));
113 if (allFiles.isEmpty()) {
114 log.info(Util.message("No input files found", LOG_PREFIX));
119 * Check if any of the listed files changed. If no changes occurred,
120 * simply return null, which indicates and of execution.
122 boolean noChange = true;
123 for (final File f : allFiles) {
124 if (buildContext.hasDelta(f)) {
125 log.debug(Util.message("buildContext %s indicates %s changed, forcing regeneration", LOG_PREFIX, buildContext, f));
131 log.info(Util.message("None of %s input files changed", LOG_PREFIX, allFiles.size()));
135 final List<InputStream> yangsInProject = new ArrayList<>();
136 for (final File f : yangFilesInProject) {
137 // FIXME: This is hack - normal path should be reported.
138 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
141 List<InputStream> all = new ArrayList<>(yangsInProject);
142 closeables.addAll(yangsInProject);
143 Map<InputStream, Module> allYangModules;
146 * Set contains all modules generated from input sources. Number of
147 * modules may differ from number of sources due to submodules
148 * (parsed submodule's data are added to its parent module). Set
149 * cannot contains null values.
151 Set<Module> projectYangModules;
153 if (inspectDependencies) {
154 YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
155 Closeable dependentYangResult1 = dependentYangResult;
156 closeables.add(dependentYangResult1);
157 List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
158 all.addAll(yangStreams);
159 closeables.addAll(yangStreams);
162 allYangModules = parser.parseYangModelsFromStreamsMapped(all);
164 projectYangModules = new HashSet<>();
165 for (InputStream inProject : yangsInProject) {
166 Module module = allYangModules.get(inProject);
167 if (module != null) {
168 projectYangModules.add(module);
173 for (AutoCloseable closeable : closeables) {
178 Set<Module> parsedAllYangModules = new HashSet<>(allYangModules.values());
179 SchemaContext resolveSchemaContext = parser.resolveSchemaContext(parsedAllYangModules);
180 log.info(Util.message("%s files parsed from %s", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject));
181 return new ContextHolder(resolveSchemaContext, projectYangModules);
183 // MojoExecutionException is thrown since execution cannot continue
184 } catch (Exception e) {
185 String message = Util.message("Unable to parse %s files from %s", LOG_PREFIX, Util.YANG_SUFFIX,
187 log.error(message, e);
188 throw new MojoExecutionException(message, e);
192 private List<InputStream> toStreamsWithoutDuplicates(List<YangSourceFromDependency> list) throws IOException {
193 ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
195 for (YangSourceFromDependency yangFromDependency : list) {
196 try (InputStream dataStream = yangFromDependency.openStream()) {
197 String contents = IOUtils.toString(dataStream);
198 byContent.putIfAbsent(contents, yangFromDependency);
202 List<InputStream> inputs = new ArrayList<>(byContent.size());
203 for (YangSourceFromDependency entry : byContent.values()) {
204 inputs.add(entry.openStream());
209 static class YangProvider {
211 void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
212 throws MojoFailureException {
214 // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
216 File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
217 addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, generatedYangDir);
219 // Also copy to the actual build output dir if different than "target". When running in
220 // Eclipse this can differ (eg "target-ide").
222 File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
223 CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
224 if(!actualGeneratedYangDir.equals(generatedYangDir)) {
225 addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
229 private void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir,
230 File[] excludedFiles, File generatedYangDir)
231 throws MojoFailureException {
233 File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
234 withMetaInf.mkdirs();
237 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, log);
238 for (File file : files) {
239 org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
241 } catch (IOException e) {
242 log.warn(String.format("Failed to generate files into root %s", yangFilesRootDir), e);
243 throw new MojoFailureException("Unable to list yang files into resource folder", e);
246 setResource(generatedYangDir, project);
248 log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
249 META_INF_YANG_STRING_JAR));
252 private static void setResource(File targetYangDir, MavenProject project) {
253 Resource res = new Resource();
254 res.setDirectory(targetYangDir.getPath());
255 project.addResource(res);
260 * Call generate on every generator from plugin configuration
262 private void generateSources(ContextHolder context) throws MojoFailureException {
263 if (codeGenerators.size() == 0) {
264 log.warn(Util.message("No code generators provided", LOG_PREFIX));
268 Map<String, String> thrown = Maps.newHashMap();
269 for (CodeGeneratorArg codeGenerator : codeGenerators) {
271 generateSourcesWithOneGenerator(context, codeGenerator);
272 } catch (Exception e) {
273 // try other generators, exception will be thrown after
275 Util.message("Unable to generate sources with %s generator", LOG_PREFIX,
276 codeGenerator.getCodeGeneratorClass()), e);
277 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
281 if (!thrown.isEmpty()) {
282 String message = Util.message(
283 "One or more code generators failed, including failed list(generatorClass=exception) %s",
284 LOG_PREFIX, thrown.toString());
286 throw new MojoFailureException(message);
291 * Instantiate generator from class and call required method
293 private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
294 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
296 codeGeneratorCfg.check();
298 BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
299 log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX,
300 codeGeneratorCfg.getCodeGeneratorClass()));
302 File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
304 if (outputDir != null) {
305 project.addCompileSourceRoot(outputDir.getAbsolutePath());
307 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the pom.xml");
310 log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir));
311 log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir()));
312 log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
313 codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
315 if (g instanceof BuildContextAware) {
316 ((BuildContextAware)g).setBuildContext(buildContext);
318 if (g instanceof MavenProjectAware) {
319 ((MavenProjectAware)g).setMavenProject(project);
321 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
322 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
324 YangProvider.setResource(resourceBaseDir, project);
325 g.setResourceBaseDir(resourceBaseDir);
326 log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir,
327 codeGeneratorCfg.getCodeGeneratorClass()));
329 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
331 log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),