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.base.Throwables;
12 import com.google.common.collect.Maps;
13 import java.io.Closeable;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.HashSet;
21 import java.util.List;
24 import java.util.concurrent.ConcurrentMap;
25 import org.apache.commons.io.IOUtils;
26 import org.apache.maven.model.Resource;
27 import org.apache.maven.plugin.MojoExecutionException;
28 import org.apache.maven.plugin.MojoFailureException;
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.repo.YangTextSchemaContextResolver;
33 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
34 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
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";
52 static final String META_INF_YANG_SERVICES_STRING_JAR = "META-INF" + "/" + "services";
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 YangTextSchemaContextResolver resolver;
64 YangToSourcesProcessor(final File yangFilesRootDir, final File[] excludedFiles, final List<CodeGeneratorArg> codeGenerators,
65 final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
66 this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
67 inspectDependencies, yangProvider);
70 private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir, final File[] excludedFiles,
71 final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies, final 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 = YangTextSchemaContextResolver.create("maven-plugin");
87 YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir, final File[] excludedFiles,
88 final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final 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 void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
102 LOG.info("Skipping YANG code generation because property yang.skip is true");
104 // But manually add resources
106 yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
108 // add META_INF/services
109 File generatedServicesDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_SERVICES_GENERATED_DIR);
110 YangProvider.setResource(generatedServicesDir, project);
111 LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
112 META_INF_YANG_SERVICES_STRING_JAR);
120 private ContextHolder processYang() throws MojoExecutionException {
121 SchemaContext resolveSchemaContext;
122 List<Closeable> closeables = new ArrayList<>();
123 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
126 * Collect all files which affect YANG context. This includes all
127 * files in current project and optionally any jars/files in the
130 final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
133 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
134 if (inspectDependencies) {
135 allFiles.addAll(Util.findYangFilesInDependencies(project));
138 if (allFiles.isEmpty()) {
139 LOG.info("{} No input files found", LOG_PREFIX);
144 * Check if any of the listed files changed. If no changes occurred,
145 * simply return null, which indicates and of execution.
147 boolean noChange = true;
148 for (final File f : allFiles) {
149 if (buildContext.hasDelta(f)) {
150 LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
157 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
161 final List<NamedFileInputStream> yangsInProject = new ArrayList<>();
162 for (final File f : yangFilesInProject) {
163 // FIXME: This is hack - normal path should be reported.
164 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
167 List<InputStream> all = new ArrayList<>();
168 all.addAll(yangsInProject);
169 closeables.addAll(yangsInProject);
172 * Set contains all modules generated from input sources. Number of
173 * modules may differ from number of sources due to submodules
174 * (parsed submodule's data are added to its parent module). Set
175 * cannot contains null values.
177 Set<Module> projectYangModules;
179 if (inspectDependencies) {
180 YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project);
181 Closeable dependentYangResult1 = dependentYangResult;
182 closeables.add(dependentYangResult1);
183 List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
184 all.addAll(yangStreams);
185 closeables.addAll(yangStreams);
188 resolveSchemaContext = YangParserTestUtils.parseYangStreams(all);
190 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
191 projectYangModules = new HashSet<>();
192 for (Module module : parsedAllYangModules) {
193 final String path = module.getModuleSourcePath();
195 LOG.debug("Looking for source {}", path);
196 for (NamedFileInputStream is : yangsInProject) {
197 LOG.debug("In project destination {}", is.getFileDestination());
198 if (path.equals(is.getFileDestination())) {
199 LOG.debug("Module {} belongs to current project", module);
200 projectYangModules.add(module);
207 for (AutoCloseable closeable : closeables) {
212 LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
213 return new ContextHolder(resolveSchemaContext, projectYangModules);
215 // MojoExecutionException is thrown since execution cannot continue
216 } catch (Exception e) {
217 LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
218 Throwable rootCause = Throwables.getRootCause(e);
219 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from " +
220 yangFilesRootDir, rootCause);
224 private static List<InputStream> toStreamsWithoutDuplicates(final List<YangSourceFromDependency> list) throws IOException {
225 ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
227 for (YangSourceFromDependency yangFromDependency : list) {
228 try (InputStream dataStream = yangFromDependency.openStream()) {
229 String contents = IOUtils.toString(dataStream);
230 byContent.putIfAbsent(contents, yangFromDependency);
231 } catch (IOException e) {
232 throw new IOException("Exception when reading from: " + yangFromDependency.getDescription(), e);
236 List<InputStream> inputs = new ArrayList<>(byContent.size());
237 for (YangSourceFromDependency entry : byContent.values()) {
238 inputs.add(entry.openStream());
243 static class YangProvider {
244 private static final Logger LOG = LoggerFactory.getLogger(YangProvider.class);
246 void addYangsToMetaInf(final MavenProject project, final File yangFilesRootDir, final File[] excludedFiles)
247 throws MojoFailureException {
249 // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
251 File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
252 addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, generatedYangDir);
254 // Also copy to the actual build output dir if different than "target". When running in
255 // Eclipse this can differ (eg "target-ide").
257 File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
258 CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
259 if (!actualGeneratedYangDir.equals(generatedYangDir)) {
260 addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
264 private static void addYangsToMetaInf(final MavenProject project, final File yangFilesRootDir,
265 final File[] excludedFiles, final File generatedYangDir) throws MojoFailureException {
267 File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
268 withMetaInf.mkdirs();
271 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles);
272 for (File file : files) {
273 org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
275 } catch (IOException e) {
276 LOG.warn("Failed to generate files into root {}", yangFilesRootDir, e);
277 throw new MojoFailureException("Unable to list yang files into resource folder", e);
280 setResource(generatedYangDir, project);
282 LOG.debug("{} Yang files from: {} marked as resources: {}", LOG_PREFIX, yangFilesRootDir,
283 META_INF_YANG_STRING_JAR);
286 private static void setResource(final File targetYangDir, final MavenProject project) {
287 Resource res = new Resource();
288 res.setDirectory(targetYangDir.getPath());
289 project.addResource(res);
294 * Call generate on every generator from plugin configuration
296 private void generateSources(final ContextHolder context) throws MojoFailureException {
297 if (codeGenerators.size() == 0) {
298 LOG.warn("{} No code generators provided", LOG_PREFIX);
302 Map<String, String> thrown = Maps.newHashMap();
303 for (CodeGeneratorArg codeGenerator : codeGenerators) {
305 generateSourcesWithOneGenerator(context, codeGenerator);
306 } catch (Exception e) {
307 // try other generators, exception will be thrown after
308 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
309 .getCodeGeneratorClass(), e);
310 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
314 if (!thrown.isEmpty()) {
315 String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
316 LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
317 throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
322 * Instantiate generator from class and call required method
324 private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
325 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
327 codeGeneratorCfg.check();
329 BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
330 LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
332 File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
334 if (outputDir != null) {
335 project.addCompileSourceRoot(outputDir.getAbsolutePath());
337 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " +
341 LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
342 LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
343 LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
344 .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
346 if (g instanceof BuildContextAware) {
347 ((BuildContextAware)g).setBuildContext(buildContext);
349 if (g instanceof MavenProjectAware) {
350 ((MavenProjectAware)g).setMavenProject(project);
352 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
353 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
355 YangProvider.setResource(resourceBaseDir, project);
356 g.setResourceBaseDir(resourceBaseDir);
357 LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
358 codeGeneratorCfg.getCodeGeneratorClass());
360 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
362 LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);