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 java.util.HashSet;
12 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
13 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.collect.Maps;
16 import java.io.Closeable;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.List;
26 import java.util.concurrent.ConcurrentMap;
27 import org.apache.commons.io.IOUtils;
28 import org.apache.maven.model.Resource;
29 import org.apache.maven.plugin.MojoExecutionException;
30 import org.apache.maven.plugin.MojoFailureException;
31 import org.apache.maven.plugin.logging.Log;
32 import org.apache.maven.project.MavenProject;
33 import org.opendaylight.yangtools.yang.model.api.Module;
34 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
35 import org.opendaylight.yangtools.yang.parser.repo.URLSchemaContextResolver;
36 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
37 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
38 import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
39 import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
40 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
41 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
42 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
43 import org.sonatype.plexus.build.incremental.BuildContext;
44 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
46 class YangToSourcesProcessor {
47 static final String LOG_PREFIX = "yang-to-sources:";
48 static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
49 static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
51 private final Log log;
52 private final File yangFilesRootDir;
53 private final File[] excludedFiles;
54 private final List<CodeGeneratorArg> codeGenerators;
55 private final MavenProject project;
56 private final boolean inspectDependencies;
57 private final BuildContext buildContext;
58 private final YangProvider yangProvider;
59 private final URLSchemaContextResolver resolver;
62 YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
63 MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
64 this(new DefaultBuildContext(), log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, yangProvider);
67 private YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles,
68 List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
69 this.buildContext = Util.checkNotNull(buildContext, "buildContext");
70 this.log = Util.checkNotNull(log, "log");
71 this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
72 this.excludedFiles = new File[excludedFiles.length];
74 for (File file : excludedFiles) {
75 this.excludedFiles[i++] = new File(file.getPath());
77 this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
78 this.project = Util.checkNotNull(project, "project");
79 this.inspectDependencies = inspectDependencies;
80 this.yangProvider = yangProvider;
81 this.resolver = URLSchemaContextResolver.create("maven-plugin");
84 YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
85 MavenProject project, boolean inspectDependencies) {
86 this(log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
89 public void execute() throws MojoExecutionException, MojoFailureException {
90 ContextHolder context = processYang();
91 if (context != null) {
92 generateSources(context);
93 yangProvider.addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles);
97 private ContextHolder processYang() throws MojoExecutionException {
98 final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
99 SchemaContext resolveSchemaContext;
100 List<Closeable> closeables = new ArrayList<>();
101 log.info(Util.message("Inspecting %s", LOG_PREFIX, yangFilesRootDir));
104 * Collect all files which affect YANG context. This includes all
105 * files in current project and optionally any jars/files in the
108 final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles, log);
111 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
112 if (inspectDependencies) {
113 allFiles.addAll(Util.findYangFilesInDependencies(log, project));
116 if (allFiles.isEmpty()) {
117 log.info(Util.message("No input files found", LOG_PREFIX));
122 * Check if any of the listed files changed. If no changes occurred,
123 * simply return null, which indicates and of execution.
125 boolean noChange = true;
126 for (final File f : allFiles) {
127 if (buildContext.hasDelta(f)) {
128 log.debug(Util.message("buildContext %s indicates %s changed, forcing regeneration", LOG_PREFIX, buildContext, f));
134 log.info(Util.message("None of %s input files changed", LOG_PREFIX, allFiles.size()));
138 final List<InputStream> yangsInProject = new ArrayList<>();
139 for (final File f : yangFilesInProject) {
140 // FIXME: This is hack - normal path should be reported.
141 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
144 List<InputStream> all = new ArrayList<>(yangsInProject);
145 closeables.addAll(yangsInProject);
148 * Set contains all modules generated from input sources. Number of
149 * modules may differ from number of sources due to submodules
150 * (parsed submodule's data are added to its parent module). Set
151 * cannot contains null values.
153 Set<Module> projectYangModules;
155 if (inspectDependencies) {
156 YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
157 Closeable dependentYangResult1 = dependentYangResult;
158 closeables.add(dependentYangResult1);
159 List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
160 all.addAll(yangStreams);
161 closeables.addAll(yangStreams);
164 resolveSchemaContext = reactor.buildEffective(all);
166 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
167 projectYangModules = new HashSet<>();
168 for (Module module : parsedAllYangModules) {
169 if(module.getModuleSourcePath()!=null) {
170 projectYangModules.add(module);
174 for (AutoCloseable closeable : closeables) {
179 log.info(Util.message("%s files parsed from %s", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject));
180 return new ContextHolder(resolveSchemaContext, projectYangModules);
182 // MojoExecutionException is thrown since execution cannot continue
183 } catch (Exception e) {
184 String message = Util.message("Unable to parse %s files from %s", LOG_PREFIX, Util.YANG_SUFFIX,
186 log.error(message, e);
187 throw new MojoExecutionException(message, e);
191 private List<InputStream> toStreamsWithoutDuplicates(List<YangSourceFromDependency> list) throws IOException {
192 ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
194 for (YangSourceFromDependency yangFromDependency : list) {
195 try (InputStream dataStream = yangFromDependency.openStream()) {
196 String contents = IOUtils.toString(dataStream);
197 byContent.putIfAbsent(contents, yangFromDependency);
201 List<InputStream> inputs = new ArrayList<>(byContent.size());
202 for (YangSourceFromDependency entry : byContent.values()) {
203 inputs.add(entry.openStream());
208 static class YangProvider {
210 void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
211 throws MojoFailureException {
213 // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
215 File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
216 addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, generatedYangDir);
218 // Also copy to the actual build output dir if different than "target". When running in
219 // Eclipse this can differ (eg "target-ide").
221 File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
222 CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
223 if(!actualGeneratedYangDir.equals(generatedYangDir)) {
224 addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
228 private void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir,
229 File[] excludedFiles, File generatedYangDir)
230 throws MojoFailureException {
232 File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
233 withMetaInf.mkdirs();
236 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, log);
237 for (File file : files) {
238 org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
240 } catch (IOException e) {
241 log.warn(String.format("Failed to generate files into root %s", yangFilesRootDir), e);
242 throw new MojoFailureException("Unable to list yang files into resource folder", e);
245 setResource(generatedYangDir, project);
247 log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
248 META_INF_YANG_STRING_JAR));
251 private static void setResource(File targetYangDir, MavenProject project) {
252 Resource res = new Resource();
253 res.setDirectory(targetYangDir.getPath());
254 project.addResource(res);
259 * Call generate on every generator from plugin configuration
261 private void generateSources(ContextHolder context) throws MojoFailureException {
262 if (codeGenerators.size() == 0) {
263 log.warn(Util.message("No code generators provided", LOG_PREFIX));
267 Map<String, String> thrown = Maps.newHashMap();
268 for (CodeGeneratorArg codeGenerator : codeGenerators) {
270 generateSourcesWithOneGenerator(context, codeGenerator);
271 } catch (Exception e) {
272 // try other generators, exception will be thrown after
274 Util.message("Unable to generate sources with %s generator", LOG_PREFIX,
275 codeGenerator.getCodeGeneratorClass()), e);
276 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
280 if (!thrown.isEmpty()) {
281 String message = Util.message(
282 "One or more code generators failed, including failed list(generatorClass=exception) %s",
283 LOG_PREFIX, thrown.toString());
285 throw new MojoFailureException(message);
290 * Instantiate generator from class and call required method
292 private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
293 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
295 codeGeneratorCfg.check();
297 BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
298 log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX,
299 codeGeneratorCfg.getCodeGeneratorClass()));
301 File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
303 if (outputDir != null) {
304 project.addCompileSourceRoot(outputDir.getAbsolutePath());
306 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the pom.xml");
309 log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir));
310 log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir()));
311 log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
312 codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
314 if (g instanceof BuildContextAware) {
315 ((BuildContextAware)g).setBuildContext(buildContext);
317 if (g instanceof MavenProjectAware) {
318 ((MavenProjectAware)g).setMavenProject(project);
320 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
321 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
323 YangProvider.setResource(resourceBaseDir, project);
324 g.setResourceBaseDir(resourceBaseDir);
325 log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir,
326 codeGeneratorCfg.getCodeGeneratorClass()));
328 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
330 log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),