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.Preconditions;
12 import com.google.common.base.Throwables;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.io.CharStreams;
16 import java.io.Closeable;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.Reader;
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
29 import org.apache.maven.plugin.MojoExecutionException;
30 import org.apache.maven.plugin.MojoFailureException;
31 import org.apache.maven.project.MavenProject;
32 import org.codehaus.plexus.util.FileUtils;
33 import org.opendaylight.yangtools.yang.model.api.Module;
34 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
35 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
36 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
37 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
38 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
39 import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
40 import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
41 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
42 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
43 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.sonatype.plexus.build.incremental.BuildContext;
47 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
49 class YangToSourcesProcessor {
50 private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
52 static final String LOG_PREFIX = "yang-to-sources:";
53 static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
54 static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
55 static final String META_INF_YANG_SERVICES_STRING_JAR = "META-INF" + "/" + "services";
57 private final File yangFilesRootDir;
58 private final Set<File> excludedFiles;
59 private final List<CodeGeneratorArg> codeGenerators;
60 private final MavenProject project;
61 private final boolean inspectDependencies;
62 private final BuildContext buildContext;
63 private final YangProvider yangProvider;
64 private final YangTextSchemaContextResolver resolver;
67 YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
68 final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
69 final YangProvider yangProvider) {
70 this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
71 inspectDependencies, yangProvider);
74 private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
75 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
76 final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
77 this.buildContext = Preconditions.checkNotNull(buildContext, "buildContext");
78 this.yangFilesRootDir = Preconditions.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
79 this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
80 this.codeGenerators = ImmutableList.copyOf(codeGenerators);
81 this.project = Preconditions.checkNotNull(project);
82 this.inspectDependencies = inspectDependencies;
83 this.yangProvider = yangProvider;
84 this.resolver = YangTextSchemaContextResolver.create("maven-plugin");
87 YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
88 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
89 final MavenProject project, final boolean inspectDependencies) {
90 this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
93 public void execute() throws MojoExecutionException, MojoFailureException {
94 ContextHolder context = processYang();
95 if (context != null) {
96 generateSources(context);
97 yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
101 void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
103 LOG.info("Skipping YANG code generation because property yang.skip is true");
105 // But manually add resources
107 yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
109 // add META_INF/services
110 File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
111 YangProvider.setResource(generatedServicesDir, project);
112 LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
113 META_INF_YANG_SERVICES_STRING_JAR);
121 private ContextHolder processYang() throws MojoExecutionException {
122 SchemaContext resolveSchemaContext;
123 List<Closeable> closeables = new ArrayList<>();
124 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
127 * Collect all files which affect YANG context. This includes all
128 * files in current project and optionally any jars/files in the
131 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 final Set<Module> projectYangModules = new HashSet<>();
178 final Set<Module> projectYangFiles = new HashSet<>();
180 if (inspectDependencies) {
181 YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project);
182 Closeable dependentYangResult1 = dependentYangResult;
183 closeables.add(dependentYangResult1);
184 List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
185 all.addAll(yangStreams);
186 closeables.addAll(yangStreams);
189 resolveSchemaContext = YangParserTestUtils.parseYangStreams(all);
191 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
192 for (Module module : parsedAllYangModules) {
193 if (containedInFiles(yangsInProject, module)) {
194 LOG.debug("Module {} belongs to current project", module);
195 projectYangModules.add(module);
196 projectYangFiles.add(module);
198 for (Module sub : module.getSubmodules()) {
199 if (containedInFiles(yangsInProject, sub)) {
200 LOG.debug("Submodule {} belongs to current project", sub);
201 projectYangFiles.add(sub);
203 LOG.warn("Submodule {} not found in input files", sub);
209 for (AutoCloseable closeable : closeables) {
214 LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
215 LOG.debug("Project YANG files: {}", projectYangFiles);
217 return new ContextHolder(resolveSchemaContext, projectYangModules, projectYangFiles);
219 // MojoExecutionException is thrown since execution cannot continue
220 } catch (Exception e) {
221 LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
222 Throwable rootCause = Throwables.getRootCause(e);
223 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from " +
224 yangFilesRootDir, rootCause);
228 private static boolean containedInFiles(final List<NamedFileInputStream> files, final Module module) {
229 final String path = module.getModuleSourcePath();
231 LOG.debug("Looking for source {}", path);
232 for (NamedFileInputStream is : files) {
233 LOG.debug("In project destination {}", is.getFileDestination());
234 if (path.equals(is.getFileDestination())) {
243 private static List<InputStream> toStreamsWithoutDuplicates(final List<YangSourceFromDependency> list)
245 final Map<String, YangSourceFromDependency> byContent = new HashMap<>();
247 for (YangSourceFromDependency yangFromDependency : list) {
248 try (Reader reader = yangFromDependency.asCharSource(StandardCharsets.UTF_8).openStream()) {
249 final String contents = CharStreams.toString(reader);
250 byContent.putIfAbsent(contents, yangFromDependency);
251 } catch (IOException e) {
252 throw new IOException("Exception when reading from: " + yangFromDependency.getDescription(), e);
256 List<InputStream> inputs = new ArrayList<>(byContent.size());
257 for (YangSourceFromDependency entry : byContent.values()) {
258 inputs.add(entry.openStream());
264 * Call generate on every generator from plugin configuration
266 private void generateSources(final ContextHolder context) throws MojoFailureException {
267 if (codeGenerators.size() == 0) {
268 LOG.warn("{} No code generators provided", LOG_PREFIX);
272 final Map<String, String> thrown = new HashMap<>();
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(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
295 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
297 codeGeneratorCfg.check();
299 BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
300 LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
302 final File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
304 if (outputDir == null) {
305 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " +
309 project.addCompileSourceRoot(outputDir.getAbsolutePath());
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 FileUtils.deleteDirectory(outputDir);
331 LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
333 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
334 context::moduleToResourcePath);
336 LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
340 * Instantiate object from fully qualified class name
342 private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
343 ClassNotFoundException, InstantiationException, IllegalAccessException {
344 final Class<?> clazz = Class.forName(codeGeneratorClass);
346 Preconditions.checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz,
348 return baseType.cast(clazz.newInstance());