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;
17 import java.io.IOException;
18 import java.io.Reader;
19 import java.nio.charset.StandardCharsets;
20 import java.nio.file.Files;
21 import java.nio.file.Path;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.Comparator;
25 import java.util.HashMap;
26 import java.util.List;
28 import java.util.Optional;
30 import java.util.stream.Collectors;
31 import org.apache.maven.plugin.MojoExecutionException;
32 import org.apache.maven.plugin.MojoFailureException;
33 import org.apache.maven.project.MavenProject;
34 import org.opendaylight.yangtools.yang.common.YangConstants;
35 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
36 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
37 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
38 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
39 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
40 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
41 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
42 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.sonatype.plexus.build.incremental.BuildContext;
46 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
48 class YangToSourcesProcessor {
49 private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
51 static final String LOG_PREFIX = "yang-to-sources:";
52 private static final String META_INF_STR = "META-INF";
53 private static final String YANG_STR = "yang";
55 static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
56 static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
57 static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
59 private final File yangFilesRootDir;
60 private final Set<File> excludedFiles;
61 private final List<CodeGeneratorArg> codeGenerators;
62 private final MavenProject project;
63 private final boolean inspectDependencies;
64 private final BuildContext buildContext;
65 private final YangProvider yangProvider;
67 private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
68 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
69 final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
70 this.buildContext = Preconditions.checkNotNull(buildContext, "buildContext");
71 this.yangFilesRootDir = Preconditions.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
72 this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
73 this.codeGenerators = ImmutableList.copyOf(codeGenerators);
74 this.project = Preconditions.checkNotNull(project);
75 this.inspectDependencies = inspectDependencies;
76 this.yangProvider = Preconditions.checkNotNull(yangProvider);
80 YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
81 final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
82 final YangProvider yangProvider) {
83 this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
84 inspectDependencies, yangProvider);
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, YangProvider.getInstance());
93 public void execute() throws MojoExecutionException, MojoFailureException {
94 conditionalExecute(false);
97 void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
98 final Optional<ProcessorModuleReactor> optReactor = createReactor();
99 if (!optReactor.isPresent()) {
103 final ProcessorModuleReactor reactor = optReactor.get();
105 final ContextHolder holder;
108 holder = createContextHolder(reactor);
109 } catch (SchemaSourceException | YangSyntaxErrorException e) {
110 throw new MojoFailureException("Failed to process reactor " + reactor, e);
111 } catch (IOException e) {
112 throw new MojoExecutionException("Failed to read reactor " + reactor, e);
115 generateSources(holder);
117 LOG.info("Skipping YANG code generation because property yang.skip is true");
121 final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
123 yangProvider.addYangsToMetaInf(project, models);
124 } catch (IOException e) {
125 throw new MojoExecutionException("Failed write model files for " + models, e);
128 // add META_INF/services
129 File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
130 YangProvider.setResource(generatedServicesDir, project);
131 LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
132 META_INF_YANG_SERVICES_STRING_JAR);
135 @SuppressWarnings("checkstyle:illegalCatch")
136 private Optional<ProcessorModuleReactor> createReactor() throws MojoExecutionException {
137 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
140 * Collect all files which affect YANG context. This includes all
141 * files in current project and optionally any jars/files in the
144 final Collection<File> yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
146 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
147 if (inspectDependencies) {
148 allFiles.addAll(Util.findYangFilesInDependencies(project));
151 if (allFiles.isEmpty()) {
152 LOG.info("{} No input files found", LOG_PREFIX);
153 return Optional.empty();
157 * Check if any of the listed files changed. If no changes occurred,
158 * simply return null, which indicates and of execution.
160 boolean noChange = true;
161 for (final File f : allFiles) {
162 if (buildContext.hasDelta(f)) {
163 LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
170 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
171 return Optional.empty();
174 final YangTextSchemaContextResolver resolver = YangTextSchemaContextResolver.create("maven-plugin");
175 for (final File f : yangFilesInProject) {
176 resolver.registerSource(YangTextSchemaSource.forFile(f));
179 LOG.debug("Processed project files: {}", yangFilesInProject);
180 LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
182 final ProcessorModuleReactor reactor = new ProcessorModuleReactor(resolver);
183 LOG.debug("Initialized reactor {}", reactor, yangFilesInProject);
184 return Optional.of(reactor);
185 } catch (Exception e) {
186 // MojoExecutionException is thrown since execution cannot continue
187 LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
188 Throwable rootCause = Throwables.getRootCause(e);
189 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
194 private ContextHolder createContextHolder(final ProcessorModuleReactor reactor) throws MojoFailureException,
195 IOException, SchemaSourceException, YangSyntaxErrorException {
197 * Set contains all modules generated from input sources. Number of
198 * modules may differ from number of sources due to submodules
199 * (parsed submodule's data are added to its parent module). Set
200 * cannot contains null values.
202 if (inspectDependencies) {
203 final List<YangTextSchemaSource> sourcesInDependencies = Util.findYangFilesInDependenciesAsStream(
205 for (YangTextSchemaSource s : toUniqueSources(sourcesInDependencies)) {
206 reactor.registerSource(s);
210 return reactor.toContext();
213 private static Collection<File> listFiles(final File root, final Collection<File> excludedFiles)
215 if (!root.isDirectory()) {
216 LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
217 return ImmutableList.of();
220 return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
221 if (excludedFiles.contains(f)) {
222 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
226 }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
229 private static Collection<YangTextSchemaSource> toUniqueSources(final Collection<YangTextSchemaSource> sources)
231 final Map<String, YangTextSchemaSource> byContent = new HashMap<>();
232 for (YangTextSchemaSource s : sources) {
233 try (Reader reader = s.asCharSource(StandardCharsets.UTF_8).openStream()) {
234 final String contents = CharStreams.toString(reader);
235 byContent.putIfAbsent(contents, s);
238 return byContent.values();
242 * Call generate on every generator from plugin configuration.
244 @SuppressWarnings("checkstyle:illegalCatch")
245 private void generateSources(final ContextHolder context) throws MojoFailureException {
246 if (codeGenerators.size() == 0) {
247 LOG.warn("{} No code generators provided", LOG_PREFIX);
251 final Map<String, String> thrown = new HashMap<>();
252 for (CodeGeneratorArg codeGenerator : codeGenerators) {
254 generateSourcesWithOneGenerator(context, codeGenerator);
255 } catch (Exception e) {
256 // try other generators, exception will be thrown after
257 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
258 .getCodeGeneratorClass(), e);
259 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
263 if (!thrown.isEmpty()) {
264 String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
265 LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
266 throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
271 * Instantiate generator from class and call required method.
273 private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
274 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
276 codeGeneratorCfg.check();
278 final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
279 LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
281 final File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
283 if (outputDir == null) {
284 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the "
288 project.addCompileSourceRoot(outputDir.getAbsolutePath());
290 LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
291 LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
292 LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
293 .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
295 if (g instanceof BuildContextAware) {
296 ((BuildContextAware)g).setBuildContext(buildContext);
298 if (g instanceof MavenProjectAware) {
299 ((MavenProjectAware)g).setMavenProject(project);
301 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
302 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
304 YangProvider.setResource(resourceBaseDir, project);
305 g.setResourceBaseDir(resourceBaseDir);
306 LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
307 codeGeneratorCfg.getCodeGeneratorClass());
309 if (outputDir.exists()) {
310 Files.walk(outputDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
311 LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
313 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
314 context::moduleToResourcePath);
316 LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
320 * Instantiate object from fully qualified class name.
322 private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
323 ClassNotFoundException, InstantiationException, IllegalAccessException {
324 final Class<?> clazz = Class.forName(codeGeneratorClass);
326 Preconditions.checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz,
328 return baseType.cast(clazz.newInstance());