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 @SuppressWarnings("checkstyle:illegalCatch")
122 private ContextHolder processYang() throws MojoExecutionException {
123 SchemaContext resolveSchemaContext;
124 List<Closeable> closeables = new ArrayList<>();
125 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
128 * Collect all files which affect YANG context. This includes all
129 * files in current project and optionally any jars/files in the
132 final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
134 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
135 if (inspectDependencies) {
136 allFiles.addAll(Util.findYangFilesInDependencies(project));
139 if (allFiles.isEmpty()) {
140 LOG.info("{} No input files found", LOG_PREFIX);
145 * Check if any of the listed files changed. If no changes occurred,
146 * simply return null, which indicates and of execution.
148 boolean noChange = true;
149 for (final File f : allFiles) {
150 if (buildContext.hasDelta(f)) {
151 LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
158 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
162 final List<NamedFileInputStream> yangsInProject = new ArrayList<>();
163 for (final File f : yangFilesInProject) {
164 // FIXME: This is hack - normal path should be reported.
165 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
168 List<InputStream> all = new ArrayList<>();
169 all.addAll(yangsInProject);
170 closeables.addAll(yangsInProject);
173 * Set contains all modules generated from input sources. Number of
174 * modules may differ from number of sources due to submodules
175 * (parsed submodule's data are added to its parent module). Set
176 * cannot contains null values.
178 final Set<Module> projectYangModules = new HashSet<>();
179 final Set<Module> projectYangFiles = new HashSet<>();
181 if (inspectDependencies) {
182 YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project);
183 Closeable dependentYangResult1 = dependentYangResult;
184 closeables.add(dependentYangResult1);
185 List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
186 all.addAll(yangStreams);
187 closeables.addAll(yangStreams);
190 resolveSchemaContext = YangParserTestUtils.parseYangStreams(all);
192 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
193 for (Module module : parsedAllYangModules) {
194 if (containedInFiles(yangsInProject, module)) {
195 LOG.debug("Module {} belongs to current project", module);
196 projectYangModules.add(module);
197 projectYangFiles.add(module);
199 for (Module sub : module.getSubmodules()) {
200 if (containedInFiles(yangsInProject, sub)) {
201 LOG.debug("Submodule {} belongs to current project", sub);
202 projectYangFiles.add(sub);
204 LOG.warn("Submodule {} not found in input files", sub);
210 for (AutoCloseable closeable : closeables) {
215 LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
216 LOG.debug("Project YANG files: {}", projectYangFiles);
218 return new ContextHolder(resolveSchemaContext, projectYangModules, projectYangFiles);
220 // MojoExecutionException is thrown since execution cannot continue
221 } catch (Exception e) {
222 LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
223 Throwable rootCause = Throwables.getRootCause(e);
224 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from "
225 + yangFilesRootDir, rootCause);
229 private static boolean containedInFiles(final List<NamedFileInputStream> files, final Module module) {
230 final String path = module.getModuleSourcePath();
232 LOG.debug("Looking for source {}", path);
233 for (NamedFileInputStream is : files) {
234 LOG.debug("In project destination {}", is.getFileDestination());
235 if (path.equals(is.getFileDestination())) {
244 private static List<InputStream> toStreamsWithoutDuplicates(final List<YangSourceFromDependency> list)
246 final Map<String, YangSourceFromDependency> byContent = new HashMap<>();
248 for (YangSourceFromDependency yangFromDependency : list) {
249 try (Reader reader = yangFromDependency.asCharSource(StandardCharsets.UTF_8).openStream()) {
250 final String contents = CharStreams.toString(reader);
251 byContent.putIfAbsent(contents, yangFromDependency);
252 } catch (IOException e) {
253 throw new IOException("Exception when reading from: " + yangFromDependency.getDescription(), e);
257 List<InputStream> inputs = new ArrayList<>(byContent.size());
258 for (YangSourceFromDependency entry : byContent.values()) {
259 inputs.add(entry.openStream());
265 * Call generate on every generator from plugin configuration.
267 @SuppressWarnings("checkstyle:illegalCatch")
268 private void generateSources(final ContextHolder context) throws MojoFailureException {
269 if (codeGenerators.size() == 0) {
270 LOG.warn("{} No code generators provided", LOG_PREFIX);
274 final Map<String, String> thrown = new HashMap<>();
275 for (CodeGeneratorArg codeGenerator : codeGenerators) {
277 generateSourcesWithOneGenerator(context, codeGenerator);
278 } catch (Exception e) {
279 // try other generators, exception will be thrown after
280 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
281 .getCodeGeneratorClass(), e);
282 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
286 if (!thrown.isEmpty()) {
287 String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
288 LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
289 throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
294 * Instantiate generator from class and call required method.
296 private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
297 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
299 codeGeneratorCfg.check();
301 final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
302 LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
304 final File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
306 if (outputDir == null) {
307 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the "
311 project.addCompileSourceRoot(outputDir.getAbsolutePath());
313 LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
314 LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
315 LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
316 .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
318 if (g instanceof BuildContextAware) {
319 ((BuildContextAware)g).setBuildContext(buildContext);
321 if (g instanceof MavenProjectAware) {
322 ((MavenProjectAware)g).setMavenProject(project);
324 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
325 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
327 YangProvider.setResource(resourceBaseDir, project);
328 g.setResourceBaseDir(resourceBaseDir);
329 LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
330 codeGeneratorCfg.getCodeGeneratorClass());
332 FileUtils.deleteDirectory(outputDir);
333 LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
335 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
336 context::moduleToResourcePath);
338 LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
342 * Instantiate object from fully qualified class name.
344 private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
345 ClassNotFoundException, InstantiationException, IllegalAccessException {
346 final Class<?> clazz = Class.forName(codeGeneratorClass);
348 Preconditions.checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz,
350 return baseType.cast(clazz.newInstance());