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;
11 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
12 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.collect.Maps;
15 import java.io.Closeable;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.List;
25 import java.util.concurrent.ConcurrentMap;
26 import org.apache.commons.io.IOUtils;
27 import org.apache.maven.model.Resource;
28 import org.apache.maven.plugin.MojoExecutionException;
29 import org.apache.maven.plugin.MojoFailureException;
30 import org.apache.maven.project.MavenProject;
31 import org.opendaylight.yangtools.yang.model.api.Module;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
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.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.sonatype.plexus.build.incremental.BuildContext;
44 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
46 class YangToSourcesProcessor {
47 private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
49 static final String LOG_PREFIX = "yang-to-sources:";
50 static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
51 static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
53 private final File yangFilesRootDir;
54 private final File[] excludedFiles;
55 private final List<CodeGeneratorArg> codeGenerators;
56 private final MavenProject project;
57 private final boolean inspectDependencies;
58 private final BuildContext buildContext;
59 private final YangProvider yangProvider;
60 private final URLSchemaContextResolver resolver;
63 YangToSourcesProcessor(File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
64 MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
65 this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
66 inspectDependencies, yangProvider);
69 private YangToSourcesProcessor(BuildContext buildContext, File yangFilesRootDir, File[] excludedFiles,
70 List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider
72 this.buildContext = Util.checkNotNull(buildContext, "buildContext");
73 this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
74 this.excludedFiles = new File[excludedFiles.length];
76 for (File file : excludedFiles) {
77 this.excludedFiles[i++] = new File(file.getPath());
79 this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
80 this.project = Util.checkNotNull(project, "project");
81 this.inspectDependencies = inspectDependencies;
82 this.yangProvider = yangProvider;
83 this.resolver = URLSchemaContextResolver.create("maven-plugin");
86 YangToSourcesProcessor(BuildContext buildContext, File yangFilesRootDir, File[] excludedFiles,
87 List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies) {
88 this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
91 public void execute() throws MojoExecutionException, MojoFailureException {
92 ContextHolder context = processYang();
93 if (context != null) {
94 generateSources(context);
95 yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
99 private ContextHolder processYang() throws MojoExecutionException {
100 final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
101 SchemaContext resolveSchemaContext;
102 List<Closeable> closeables = new ArrayList<>();
103 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
106 * Collect all files which affect YANG context. This includes all
107 * files in current project and optionally any jars/files in the
110 final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
113 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
114 if (inspectDependencies) {
115 allFiles.addAll(Util.findYangFilesInDependencies(project));
118 if (allFiles.isEmpty()) {
119 LOG.info("{} No input files found", LOG_PREFIX);
124 * Check if any of the listed files changed. If no changes occurred,
125 * simply return null, which indicates and of execution.
127 boolean noChange = true;
128 for (final File f : allFiles) {
129 if (buildContext.hasDelta(f)) {
130 LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
137 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
141 final List<InputStream> yangsInProject = new ArrayList<>();
142 for (final File f : yangFilesInProject) {
143 // FIXME: This is hack - normal path should be reported.
144 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
147 List<InputStream> all = new ArrayList<>(yangsInProject);
148 closeables.addAll(yangsInProject);
151 * Set contains all modules generated from input sources. Number of
152 * modules may differ from number of sources due to submodules
153 * (parsed submodule's data are added to its parent module). Set
154 * cannot contains null values.
156 Set<Module> projectYangModules;
158 if (inspectDependencies) {
159 YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project);
160 Closeable dependentYangResult1 = dependentYangResult;
161 closeables.add(dependentYangResult1);
162 List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
163 all.addAll(yangStreams);
164 closeables.addAll(yangStreams);
167 resolveSchemaContext = reactor.buildEffective(all);
169 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
170 projectYangModules = new HashSet<>();
171 for (Module module : parsedAllYangModules) {
172 if(module.getModuleSourcePath()!=null) {
173 projectYangModules.add(module);
177 for (AutoCloseable closeable : closeables) {
182 LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
183 return new ContextHolder(resolveSchemaContext, projectYangModules);
185 // MojoExecutionException is thrown since execution cannot continue
186 } catch (Exception e) {
187 LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
188 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from " +
189 yangFilesRootDir, e);
193 private List<InputStream> toStreamsWithoutDuplicates(List<YangSourceFromDependency> list) throws IOException {
194 ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
196 for (YangSourceFromDependency yangFromDependency : list) {
197 try (InputStream dataStream = yangFromDependency.openStream()) {
198 String contents = IOUtils.toString(dataStream);
199 byContent.putIfAbsent(contents, yangFromDependency);
203 List<InputStream> inputs = new ArrayList<>(byContent.size());
204 for (YangSourceFromDependency entry : byContent.values()) {
205 inputs.add(entry.openStream());
210 static class YangProvider {
211 private static final Logger LOG = LoggerFactory.getLogger(YangProvider.class);
213 void addYangsToMetaInf(MavenProject project, File yangFilesRootDir, File[] excludedFiles)
214 throws MojoFailureException {
216 // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
218 File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
219 addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, generatedYangDir);
221 // Also copy to the actual build output dir if different than "target". When running in
222 // Eclipse this can differ (eg "target-ide").
224 File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
225 CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
226 if(!actualGeneratedYangDir.equals(generatedYangDir)) {
227 addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
231 private void addYangsToMetaInf(MavenProject project, File yangFilesRootDir,
232 File[] excludedFiles, File generatedYangDir)
233 throws MojoFailureException {
235 File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
236 withMetaInf.mkdirs();
239 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles);
240 for (File file : files) {
241 org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
243 } catch (IOException e) {
244 LOG.warn("Failed to generate files into root {}", yangFilesRootDir, e);
245 throw new MojoFailureException("Unable to list yang files into resource folder", e);
248 setResource(generatedYangDir, project);
250 LOG.debug("{} Yang files from: {} marked as resources: {}", LOG_PREFIX, yangFilesRootDir,
251 META_INF_YANG_STRING_JAR);
254 private static void setResource(File targetYangDir, MavenProject project) {
255 Resource res = new Resource();
256 res.setDirectory(targetYangDir.getPath());
257 project.addResource(res);
262 * Call generate on every generator from plugin configuration
264 private void generateSources(ContextHolder context) throws MojoFailureException {
265 if (codeGenerators.size() == 0) {
266 LOG.warn("{} No code generators provided", LOG_PREFIX);
270 Map<String, String> thrown = Maps.newHashMap();
271 for (CodeGeneratorArg codeGenerator : codeGenerators) {
273 generateSourcesWithOneGenerator(context, codeGenerator);
274 } catch (Exception e) {
275 // try other generators, exception will be thrown after
276 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
277 .getCodeGeneratorClass(), e);
278 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
282 if (!thrown.isEmpty()) {
283 String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
284 LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
285 throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
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("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
300 File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
302 if (outputDir != null) {
303 project.addCompileSourceRoot(outputDir.getAbsolutePath());
305 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " +
309 LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
310 LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
311 LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
312 .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("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
326 codeGeneratorCfg.getCodeGeneratorClass());
328 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
330 LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);