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.collect.Maps;
12 import java.io.Closeable;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.HashSet;
20 import java.util.List;
23 import java.util.concurrent.ConcurrentMap;
24 import org.apache.commons.io.IOUtils;
25 import org.apache.maven.model.Resource;
26 import org.apache.maven.plugin.MojoExecutionException;
27 import org.apache.maven.plugin.MojoFailureException;
28 import org.apache.maven.plugin.logging.Log;
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.impl.YangParserImpl;
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.MavenLogAware;
41 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
42 import org.sonatype.plexus.build.incremental.BuildContext;
43 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
45 class YangToSourcesProcessor {
46 static final String LOG_PREFIX = "yang-to-sources:";
47 static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
48 static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
50 private final Log log;
51 private final File yangFilesRootDir;
52 private final File[] excludedFiles;
53 private final List<CodeGeneratorArg> codeGenerators;
54 private final MavenProject project;
55 private final boolean inspectDependencies;
56 private final BuildContext buildContext;
57 private final YangProvider yangProvider;
58 private final URLSchemaContextResolver resolver;
61 YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
62 MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
63 this(new DefaultBuildContext(), log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, yangProvider);
66 private YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles,
67 List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
68 this.buildContext = Util.checkNotNull(buildContext, "buildContext");
69 this.log = Util.checkNotNull(log, "log");
70 this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
71 this.excludedFiles = new File[excludedFiles.length];
73 for (File file : excludedFiles) {
74 this.excludedFiles[i++] = new File(file.getPath());
76 this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
77 this.project = Util.checkNotNull(project, "project");
78 this.inspectDependencies = inspectDependencies;
79 this.yangProvider = yangProvider;
80 this.resolver = URLSchemaContextResolver.create("maven-plugin");
83 YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
84 MavenProject project, boolean inspectDependencies) {
85 this(log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
88 public void execute() throws MojoExecutionException, MojoFailureException {
89 ContextHolder context = processYang();
90 if (context != null) {
91 generateSources(context);
92 yangProvider.addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles);
96 private ContextHolder processYang() throws MojoExecutionException {
97 YangParserImpl parser = new YangParserImpl();
98 List<Closeable> closeables = new ArrayList<>();
99 log.info(Util.message("Inspecting %s", LOG_PREFIX, yangFilesRootDir));
102 * Collect all files which affect YANG context. This includes all
103 * files in current project and optionally any jars/files in the
106 final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles, log);
109 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
110 if (inspectDependencies) {
111 allFiles.addAll(Util.findYangFilesInDependencies(log, project));
114 if (allFiles.isEmpty()) {
115 log.info(Util.message("No input files found", LOG_PREFIX));
120 * Check if any of the listed files changed. If no changes occurred,
121 * simply return null, which indicates and of execution.
123 boolean noChange = true;
124 for (final File f : allFiles) {
125 if (buildContext.hasDelta(f)) {
126 log.debug(Util.message("buildContext %s indicates %s changed, forcing regeneration", LOG_PREFIX, buildContext, f));
132 log.info(Util.message("None of %s input files changed", LOG_PREFIX, allFiles.size()));
136 final List<InputStream> yangsInProject = new ArrayList<>();
137 for (final File f : yangFilesInProject) {
138 // FIXME: This is hack - normal path should be reported.
139 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
142 List<InputStream> all = new ArrayList<>(yangsInProject);
143 closeables.addAll(yangsInProject);
144 Map<InputStream, Module> allYangModules;
147 * Set contains all modules generated from input sources. Number of
148 * modules may differ from number of sources due to submodules
149 * (parsed submodule's data are added to its parent module). Set
150 * cannot contains null values.
152 Set<Module> projectYangModules;
154 if (inspectDependencies) {
155 YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
156 Closeable dependentYangResult1 = dependentYangResult;
157 closeables.add(dependentYangResult1);
158 List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
159 all.addAll(yangStreams);
160 closeables.addAll(yangStreams);
163 allYangModules = parser.parseYangModelsFromStreamsMapped(all);
165 projectYangModules = new HashSet<>();
166 for (InputStream inProject : yangsInProject) {
167 Module module = allYangModules.get(inProject);
168 if (module != null) {
169 projectYangModules.add(module);
174 for (AutoCloseable closeable : closeables) {
179 Set<Module> parsedAllYangModules = new HashSet<>(allYangModules.values());
180 SchemaContext resolveSchemaContext = parser.resolveSchemaContext(parsedAllYangModules);
181 log.info(Util.message("%s files parsed from %s", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject));
182 return new ContextHolder(resolveSchemaContext, projectYangModules);
184 // MojoExecutionException is thrown since execution cannot continue
185 } catch (Exception e) {
186 String message = Util.message("Unable to parse %s files from %s", LOG_PREFIX, Util.YANG_SUFFIX,
188 log.error(message, e);
189 throw new MojoExecutionException(message, 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 {
212 void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
213 throws MojoFailureException {
215 // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
217 File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
218 addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, generatedYangDir);
220 // Also copy to the actual build output dir if different than "target". When running in
221 // Eclipse this can differ (eg "target-ide").
223 File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
224 CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
225 if(!actualGeneratedYangDir.equals(generatedYangDir)) {
226 addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
230 private void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir,
231 File[] excludedFiles, File generatedYangDir)
232 throws MojoFailureException {
234 File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
235 withMetaInf.mkdirs();
238 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, log);
239 for (File file : files) {
240 org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
242 } catch (IOException e) {
243 log.warn(String.format("Failed to generate files into root %s", yangFilesRootDir), e);
244 throw new MojoFailureException("Unable to list yang files into resource folder", e);
247 setResource(generatedYangDir, project);
249 log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
250 META_INF_YANG_STRING_JAR));
253 private static void setResource(File targetYangDir, MavenProject project) {
254 Resource res = new Resource();
255 res.setDirectory(targetYangDir.getPath());
256 project.addResource(res);
261 * Call generate on every generator from plugin configuration
263 private void generateSources(ContextHolder context) throws MojoFailureException {
264 if (codeGenerators.size() == 0) {
265 log.warn(Util.message("No code generators provided", LOG_PREFIX));
269 Map<String, String> thrown = Maps.newHashMap();
270 for (CodeGeneratorArg codeGenerator : codeGenerators) {
272 generateSourcesWithOneGenerator(context, codeGenerator);
273 } catch (Exception e) {
274 // try other generators, exception will be thrown after
276 Util.message("Unable to generate sources with %s generator", LOG_PREFIX,
277 codeGenerator.getCodeGeneratorClass()), e);
278 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
282 if (!thrown.isEmpty()) {
283 String message = Util.message(
284 "One or more code generators failed, including failed list(generatorClass=exception) %s",
285 LOG_PREFIX, thrown.toString());
287 throw new MojoFailureException(message);
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(Util.message("Code generator instantiated from %s", LOG_PREFIX,
301 codeGeneratorCfg.getCodeGeneratorClass()));
303 File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
305 if (outputDir != null) {
306 project.addCompileSourceRoot(outputDir.getAbsolutePath());
308 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the pom.xml");
311 log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir));
312 log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir()));
313 log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
314 codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
316 if (g instanceof MavenLogAware) {
317 ((MavenLogAware)g).setLog(log);
319 if (g instanceof BuildContextAware) {
320 ((BuildContextAware)g).setBuildContext(buildContext);
322 if (g instanceof MavenProjectAware) {
323 ((MavenProjectAware)g).setMavenProject(project);
325 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
326 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
328 YangProvider.setResource(resourceBaseDir, project);
329 g.setResourceBaseDir(resourceBaseDir);
330 log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir,
331 codeGeneratorCfg.getCodeGeneratorClass()));
333 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
335 log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),