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 static java.util.Objects.requireNonNull;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.io.CharStreams;
19 import java.io.IOException;
20 import java.io.Reader;
21 import java.nio.charset.StandardCharsets;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.Optional;
32 import java.util.stream.Collectors;
33 import org.apache.maven.plugin.MojoExecutionException;
34 import org.apache.maven.plugin.MojoFailureException;
35 import org.apache.maven.project.MavenProject;
36 import org.opendaylight.yangtools.yang.common.YangConstants;
37 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
38 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
39 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
40 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
41 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
42 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
43 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
44 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.sonatype.plexus.build.incremental.BuildContext;
48 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
50 class YangToSourcesProcessor {
51 private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
53 static final String LOG_PREFIX = "yang-to-sources:";
54 private static final String META_INF_STR = "META-INF";
55 private static final String YANG_STR = "yang";
57 static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
58 static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
59 static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
61 private final File yangFilesRootDir;
62 private final Set<File> excludedFiles;
63 private final List<CodeGeneratorArg> codeGenerators;
64 private final MavenProject project;
65 private final boolean inspectDependencies;
66 private final BuildContext buildContext;
67 private final YangProvider yangProvider;
69 private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
70 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
71 final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
72 this.buildContext = requireNonNull(buildContext, "buildContext");
73 this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
74 this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
75 this.codeGenerators = ImmutableList.copyOf(codeGenerators);
76 this.project = requireNonNull(project);
77 this.inspectDependencies = inspectDependencies;
78 this.yangProvider = requireNonNull(yangProvider);
82 YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
83 final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
84 final YangProvider yangProvider) {
85 this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
86 inspectDependencies, yangProvider);
89 YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
90 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
91 final MavenProject project, final boolean inspectDependencies) {
92 this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, YangProvider.getInstance());
95 public void execute() throws MojoExecutionException, MojoFailureException {
96 conditionalExecute(false);
99 void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
100 final Optional<ProcessorModuleReactor> optReactor = createReactor();
101 if (!optReactor.isPresent()) {
105 final ProcessorModuleReactor reactor = optReactor.get();
107 final ContextHolder holder;
110 holder = createContextHolder(reactor);
111 } catch (SchemaSourceException | YangSyntaxErrorException e) {
112 throw new MojoFailureException("Failed to process reactor " + reactor, e);
113 } catch (IOException e) {
114 throw new MojoExecutionException("Failed to read reactor " + reactor, e);
117 generateSources(holder);
119 LOG.info("Skipping YANG code generation because property yang.skip is true");
123 final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
125 yangProvider.addYangsToMetaInf(project, models);
126 } catch (IOException e) {
127 throw new MojoExecutionException("Failed write model files for " + models, e);
130 // add META_INF/services
131 File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
132 YangProvider.setResource(generatedServicesDir, project);
133 LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
134 META_INF_YANG_SERVICES_STRING_JAR);
137 @SuppressWarnings("checkstyle:illegalCatch")
138 private Optional<ProcessorModuleReactor> createReactor() throws MojoExecutionException {
139 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
142 * Collect all files which affect YANG context. This includes all
143 * files in current project and optionally any jars/files in the
146 final Collection<File> yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
148 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
149 if (inspectDependencies) {
150 allFiles.addAll(Util.findYangFilesInDependencies(project));
153 if (allFiles.isEmpty()) {
154 LOG.info("{} No input files found", LOG_PREFIX);
155 return Optional.empty();
159 * Check if any of the listed files changed. If no changes occurred,
160 * simply return null, which indicates and of execution.
162 if (!allFiles.stream().anyMatch(buildContext::hasDelta)) {
163 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
164 return Optional.empty();
167 final YangTextSchemaContextResolver resolver = YangTextSchemaContextResolver.create("maven-plugin");
168 for (final File f : yangFilesInProject) {
169 resolver.registerSource(YangTextSchemaSource.forFile(f));
172 LOG.debug("Processed project files: {}", yangFilesInProject);
173 LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
175 final ProcessorModuleReactor reactor = new ProcessorModuleReactor(resolver);
176 LOG.debug("Initialized reactor {}", reactor, yangFilesInProject);
177 return Optional.of(reactor);
178 } catch (Exception e) {
179 // MojoExecutionException is thrown since execution cannot continue
180 LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
181 Throwable rootCause = Throwables.getRootCause(e);
182 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
187 private ContextHolder createContextHolder(final ProcessorModuleReactor reactor) throws MojoFailureException,
188 IOException, SchemaSourceException, YangSyntaxErrorException {
190 * Set contains all modules generated from input sources. Number of
191 * modules may differ from number of sources due to submodules
192 * (parsed submodule's data are added to its parent module). Set
193 * cannot contains null values.
195 if (inspectDependencies) {
196 final List<YangTextSchemaSource> sourcesInDependencies = Util.findYangFilesInDependenciesAsStream(
198 for (YangTextSchemaSource s : toUniqueSources(sourcesInDependencies)) {
199 reactor.registerSource(s);
203 return reactor.toContext();
206 private static Collection<File> listFiles(final File root, final Collection<File> excludedFiles)
208 if (!root.isDirectory()) {
209 LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
210 return ImmutableList.of();
213 return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
214 if (excludedFiles.contains(f)) {
215 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
219 }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
222 private static Collection<YangTextSchemaSource> toUniqueSources(final Collection<YangTextSchemaSource> sources)
224 final Map<String, YangTextSchemaSource> byContent = new HashMap<>();
225 for (YangTextSchemaSource s : sources) {
226 try (Reader reader = s.asCharSource(StandardCharsets.UTF_8).openStream()) {
227 final String contents = CharStreams.toString(reader);
228 byContent.putIfAbsent(contents, s);
231 return byContent.values();
235 * Call generate on every generator from plugin configuration.
237 @SuppressWarnings("checkstyle:illegalCatch")
238 private void generateSources(final ContextHolder context) throws MojoFailureException {
239 if (codeGenerators.size() == 0) {
240 LOG.warn("{} No code generators provided", LOG_PREFIX);
244 final Map<String, String> thrown = new HashMap<>();
245 for (CodeGeneratorArg codeGenerator : codeGenerators) {
247 generateSourcesWithOneGenerator(context, codeGenerator);
248 } catch (Exception e) {
249 // try other generators, exception will be thrown after
250 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
251 .getCodeGeneratorClass(), e);
252 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
256 if (!thrown.isEmpty()) {
257 String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
258 LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
259 throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
264 * Instantiate generator from class and call required method.
266 private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
267 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
269 codeGeneratorCfg.check();
271 final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
272 LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
274 final File outputDir = requireNonNull(codeGeneratorCfg.getOutputBaseDir(project),
275 "outputBaseDir is null. Please provide a valid outputBaseDir value in pom.xml");
277 project.addCompileSourceRoot(outputDir.getAbsolutePath());
279 LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
280 LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
281 LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
282 .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
284 if (g instanceof BuildContextAware) {
285 ((BuildContextAware)g).setBuildContext(buildContext);
287 if (g instanceof MavenProjectAware) {
288 ((MavenProjectAware)g).setMavenProject(project);
290 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
291 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
293 YangProvider.setResource(resourceBaseDir, project);
294 g.setResourceBaseDir(resourceBaseDir);
295 LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
296 codeGeneratorCfg.getCodeGeneratorClass());
298 if (outputDir.exists()) {
299 Files.walk(outputDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
300 LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
302 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
303 context::moduleToResourcePath);
305 LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
309 * Instantiate object from fully qualified class name.
311 private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
312 ClassNotFoundException, InstantiationException, IllegalAccessException {
313 final Class<?> clazz = Class.forName(codeGeneratorClass);
315 Preconditions.checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz,
317 return baseType.cast(clazz.newInstance());