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<NamedFileInputStream> 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<>();
149 all.addAll(yangsInProject);
150 closeables.addAll(yangsInProject);
153 * Set contains all modules generated from input sources. Number of
154 * modules may differ from number of sources due to submodules
155 * (parsed submodule's data are added to its parent module). Set
156 * cannot contains null values.
158 Set<Module> projectYangModules;
160 if (inspectDependencies) {
161 YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project);
162 Closeable dependentYangResult1 = dependentYangResult;
163 closeables.add(dependentYangResult1);
164 List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
165 all.addAll(yangStreams);
166 closeables.addAll(yangStreams);
169 resolveSchemaContext = reactor.buildEffective(all);
171 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
172 projectYangModules = new HashSet<>();
173 for (Module module : parsedAllYangModules) {
174 final String path = module.getModuleSourcePath();
176 LOG.debug("Looking for source {}", path);
177 for (NamedFileInputStream is : yangsInProject) {
178 LOG.debug("In project destination {}", is.getFileDestination());
179 if (path.equals(is.getFileDestination())) {
180 LOG.debug("Module {} belongs to current project", module);
181 projectYangModules.add(module);
188 for (AutoCloseable closeable : closeables) {
193 LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
194 return new ContextHolder(resolveSchemaContext, projectYangModules);
196 // MojoExecutionException is thrown since execution cannot continue
197 } catch (Exception e) {
198 LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
199 Throwable rootCause = Throwables.getRootCause(e);
200 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from " +
201 yangFilesRootDir, rootCause);
205 private List<InputStream> toStreamsWithoutDuplicates(List<YangSourceFromDependency> list) throws IOException {
206 ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
208 for (YangSourceFromDependency yangFromDependency : list) {
209 try (InputStream dataStream = yangFromDependency.openStream()) {
210 String contents = IOUtils.toString(dataStream);
211 byContent.putIfAbsent(contents, yangFromDependency);
215 List<InputStream> inputs = new ArrayList<>(byContent.size());
216 for (YangSourceFromDependency entry : byContent.values()) {
217 inputs.add(entry.openStream());
222 static class YangProvider {
223 private static final Logger LOG = LoggerFactory.getLogger(YangProvider.class);
225 void addYangsToMetaInf(MavenProject project, File yangFilesRootDir, File[] excludedFiles)
226 throws MojoFailureException {
228 // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
230 File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
231 addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, generatedYangDir);
233 // Also copy to the actual build output dir if different than "target". When running in
234 // Eclipse this can differ (eg "target-ide").
236 File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
237 CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
238 if(!actualGeneratedYangDir.equals(generatedYangDir)) {
239 addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
243 private void addYangsToMetaInf(MavenProject project, File yangFilesRootDir,
244 File[] excludedFiles, File generatedYangDir)
245 throws MojoFailureException {
247 File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
248 withMetaInf.mkdirs();
251 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles);
252 for (File file : files) {
253 org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
255 } catch (IOException e) {
256 LOG.warn("Failed to generate files into root {}", yangFilesRootDir, e);
257 throw new MojoFailureException("Unable to list yang files into resource folder", e);
260 setResource(generatedYangDir, project);
262 LOG.debug("{} Yang files from: {} marked as resources: {}", LOG_PREFIX, yangFilesRootDir,
263 META_INF_YANG_STRING_JAR);
266 private static void setResource(File targetYangDir, MavenProject project) {
267 Resource res = new Resource();
268 res.setDirectory(targetYangDir.getPath());
269 project.addResource(res);
274 * Call generate on every generator from plugin configuration
276 private void generateSources(ContextHolder context) throws MojoFailureException {
277 if (codeGenerators.size() == 0) {
278 LOG.warn("{} No code generators provided", LOG_PREFIX);
282 Map<String, String> thrown = Maps.newHashMap();
283 for (CodeGeneratorArg codeGenerator : codeGenerators) {
285 generateSourcesWithOneGenerator(context, codeGenerator);
286 } catch (Exception e) {
287 // try other generators, exception will be thrown after
288 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
289 .getCodeGeneratorClass(), e);
290 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
294 if (!thrown.isEmpty()) {
295 String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
296 LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
297 throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
302 * Instantiate generator from class and call required method
304 private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
305 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
307 codeGeneratorCfg.check();
309 BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
310 LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
312 File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
314 if (outputDir != null) {
315 project.addCompileSourceRoot(outputDir.getAbsolutePath());
317 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " +
321 LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
322 LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
323 LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
324 .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
326 if (g instanceof BuildContextAware) {
327 ((BuildContextAware)g).setBuildContext(buildContext);
329 if (g instanceof MavenProjectAware) {
330 ((MavenProjectAware)g).setMavenProject(project);
332 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
333 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
335 YangProvider.setResource(resourceBaseDir, project);
336 g.setResourceBaseDir(resourceBaseDir);
337 LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
338 codeGeneratorCfg.getCodeGeneratorClass());
340 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
342 LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);