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.base.Throwables;
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.project.MavenProject;
32 import org.opendaylight.yangtools.yang.model.api.Module;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
34 import org.opendaylight.yangtools.yang.parser.repo.URLSchemaContextResolver;
35 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
36 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
37 import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
38 import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
39 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
40 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
41 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.sonatype.plexus.build.incremental.BuildContext;
45 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
47 class YangToSourcesProcessor {
48 private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
50 static final String LOG_PREFIX = "yang-to-sources:";
51 static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
52 static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
54 private final File yangFilesRootDir;
55 private final File[] excludedFiles;
56 private final List<CodeGeneratorArg> codeGenerators;
57 private final MavenProject project;
58 private final boolean inspectDependencies;
59 private final BuildContext buildContext;
60 private final YangProvider yangProvider;
61 private final URLSchemaContextResolver resolver;
64 YangToSourcesProcessor(File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
65 MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
66 this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
67 inspectDependencies, yangProvider);
70 private YangToSourcesProcessor(BuildContext buildContext, File yangFilesRootDir, File[] excludedFiles,
71 List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider
73 this.buildContext = Util.checkNotNull(buildContext, "buildContext");
74 this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
75 this.excludedFiles = new File[excludedFiles.length];
77 for (File file : excludedFiles) {
78 this.excludedFiles[i++] = new File(file.getPath());
80 this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
81 this.project = Util.checkNotNull(project, "project");
82 this.inspectDependencies = inspectDependencies;
83 this.yangProvider = yangProvider;
84 this.resolver = URLSchemaContextResolver.create("maven-plugin");
87 YangToSourcesProcessor(BuildContext buildContext, File yangFilesRootDir, File[] excludedFiles,
88 List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies) {
89 this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
92 public void execute() throws MojoExecutionException, MojoFailureException {
93 ContextHolder context = processYang();
94 if (context != null) {
95 generateSources(context);
96 yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
100 private ContextHolder processYang() throws MojoExecutionException {
101 final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
102 SchemaContext resolveSchemaContext;
103 List<Closeable> closeables = new ArrayList<>();
104 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
107 * Collect all files which affect YANG context. This includes all
108 * files in current project and optionally any jars/files in the
111 final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
114 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
115 if (inspectDependencies) {
116 allFiles.addAll(Util.findYangFilesInDependencies(project));
119 if (allFiles.isEmpty()) {
120 LOG.info("{} No input files found", LOG_PREFIX);
125 * Check if any of the listed files changed. If no changes occurred,
126 * simply return null, which indicates and of execution.
128 boolean noChange = true;
129 for (final File f : allFiles) {
130 if (buildContext.hasDelta(f)) {
131 LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
138 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
142 final List<InputStream> yangsInProject = new ArrayList<>();
143 for (final File f : yangFilesInProject) {
144 // FIXME: This is hack - normal path should be reported.
145 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
148 List<InputStream> all = new ArrayList<>(yangsInProject);
149 closeables.addAll(yangsInProject);
152 * Set contains all modules generated from input sources. Number of
153 * modules may differ from number of sources due to submodules
154 * (parsed submodule's data are added to its parent module). Set
155 * cannot contains null values.
157 Set<Module> projectYangModules;
159 if (inspectDependencies) {
160 YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project);
161 Closeable dependentYangResult1 = dependentYangResult;
162 closeables.add(dependentYangResult1);
163 List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
164 all.addAll(yangStreams);
165 closeables.addAll(yangStreams);
168 resolveSchemaContext = reactor.buildEffective(all);
170 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
171 projectYangModules = new HashSet<>();
172 for (Module module : parsedAllYangModules) {
173 if(module.getModuleSourcePath()!=null) {
174 projectYangModules.add(module);
178 for (AutoCloseable closeable : closeables) {
183 LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
184 return new ContextHolder(resolveSchemaContext, projectYangModules);
186 // MojoExecutionException is thrown since execution cannot continue
187 } catch (Exception e) {
188 LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
189 Throwable rootCause = Throwables.getRootCause(e);
190 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from " +
191 yangFilesRootDir, rootCause);
195 private List<InputStream> toStreamsWithoutDuplicates(List<YangSourceFromDependency> list) throws IOException {
196 ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
198 for (YangSourceFromDependency yangFromDependency : list) {
199 try (InputStream dataStream = yangFromDependency.openStream()) {
200 String contents = IOUtils.toString(dataStream);
201 byContent.putIfAbsent(contents, yangFromDependency);
205 List<InputStream> inputs = new ArrayList<>(byContent.size());
206 for (YangSourceFromDependency entry : byContent.values()) {
207 inputs.add(entry.openStream());
212 static class YangProvider {
213 private static final Logger LOG = LoggerFactory.getLogger(YangProvider.class);
215 void addYangsToMetaInf(MavenProject project, File yangFilesRootDir, File[] excludedFiles)
216 throws MojoFailureException {
218 // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
220 File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
221 addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, generatedYangDir);
223 // Also copy to the actual build output dir if different than "target". When running in
224 // Eclipse this can differ (eg "target-ide").
226 File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
227 CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
228 if(!actualGeneratedYangDir.equals(generatedYangDir)) {
229 addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
233 private void addYangsToMetaInf(MavenProject project, File yangFilesRootDir,
234 File[] excludedFiles, File generatedYangDir)
235 throws MojoFailureException {
237 File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
238 withMetaInf.mkdirs();
241 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles);
242 for (File file : files) {
243 org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
245 } catch (IOException e) {
246 LOG.warn("Failed to generate files into root {}", yangFilesRootDir, e);
247 throw new MojoFailureException("Unable to list yang files into resource folder", e);
250 setResource(generatedYangDir, project);
252 LOG.debug("{} Yang files from: {} marked as resources: {}", LOG_PREFIX, yangFilesRootDir,
253 META_INF_YANG_STRING_JAR);
256 private static void setResource(File targetYangDir, MavenProject project) {
257 Resource res = new Resource();
258 res.setDirectory(targetYangDir.getPath());
259 project.addResource(res);
264 * Call generate on every generator from plugin configuration
266 private void generateSources(ContextHolder context) throws MojoFailureException {
267 if (codeGenerators.size() == 0) {
268 LOG.warn("{} No code generators provided", LOG_PREFIX);
272 Map<String, String> thrown = Maps.newHashMap();
273 for (CodeGeneratorArg codeGenerator : codeGenerators) {
275 generateSourcesWithOneGenerator(context, codeGenerator);
276 } catch (Exception e) {
277 // try other generators, exception will be thrown after
278 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
279 .getCodeGeneratorClass(), e);
280 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
284 if (!thrown.isEmpty()) {
285 String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
286 LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
287 throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
292 * Instantiate generator from class and call required method
294 private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
295 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
297 codeGeneratorCfg.check();
299 BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
300 LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, 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 " +
311 LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
312 LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
313 LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
314 .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
316 if (g instanceof BuildContextAware) {
317 ((BuildContextAware)g).setBuildContext(buildContext);
319 if (g instanceof MavenProjectAware) {
320 ((MavenProjectAware)g).setMavenProject(project);
322 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
323 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
325 YangProvider.setResource(resourceBaseDir, project);
326 g.setResourceBaseDir(resourceBaseDir);
327 LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
328 codeGeneratorCfg.getCodeGeneratorClass());
330 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
332 LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);