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.util.ArrayList;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.List;
25 import java.util.Optional;
27 import org.apache.maven.plugin.MojoExecutionException;
28 import org.apache.maven.plugin.MojoFailureException;
29 import org.apache.maven.project.MavenProject;
30 import org.codehaus.plexus.util.FileUtils;
31 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
32 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
33 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
34 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
35 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
36 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
37 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
38 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.sonatype.plexus.build.incremental.BuildContext;
42 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
44 class YangToSourcesProcessor {
45 private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
47 static final String LOG_PREFIX = "yang-to-sources:";
48 private static final String META_INF_STR = "META-INF";
49 private static final String YANG_STR = "yang";
51 static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
52 static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
53 static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
55 private final File yangFilesRootDir;
56 private final Set<File> excludedFiles;
57 private final List<CodeGeneratorArg> codeGenerators;
58 private final MavenProject project;
59 private final boolean inspectDependencies;
60 private final BuildContext buildContext;
61 private final YangProvider yangProvider;
63 private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
64 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
65 final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
66 this.buildContext = Preconditions.checkNotNull(buildContext, "buildContext");
67 this.yangFilesRootDir = Preconditions.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
68 this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
69 this.codeGenerators = ImmutableList.copyOf(codeGenerators);
70 this.project = Preconditions.checkNotNull(project);
71 this.inspectDependencies = inspectDependencies;
72 this.yangProvider = Preconditions.checkNotNull(yangProvider);
76 YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
77 final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
78 final YangProvider yangProvider) {
79 this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
80 inspectDependencies, yangProvider);
83 YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
84 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
85 final MavenProject project, final boolean inspectDependencies) {
86 this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, YangProvider.getInstance());
89 public void execute() throws MojoExecutionException, MojoFailureException {
90 conditionalExecute(false);
93 void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
94 final Optional<ProcessorModuleReactor> optReactor = createReactor();
95 if (!optReactor.isPresent()) {
99 final ProcessorModuleReactor reactor = optReactor.get();
101 final ContextHolder holder;
104 holder = createContextHolder(reactor);
105 } catch (SchemaSourceException | YangSyntaxErrorException e) {
106 throw new MojoFailureException("Failed to process reactor " + reactor, e);
107 } catch (IOException e) {
108 throw new MojoExecutionException("Failed to read reactor " + reactor, e);
111 generateSources(holder);
113 LOG.info("Skipping YANG code generation because property yang.skip is true");
117 final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
119 yangProvider.addYangsToMetaInf(project, models);
120 } catch (IOException e) {
121 throw new MojoExecutionException("Failed write model files for " + models, e);
124 // add META_INF/services
125 File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
126 YangProvider.setResource(generatedServicesDir, project);
127 LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
128 META_INF_YANG_SERVICES_STRING_JAR);
131 @SuppressWarnings("checkstyle:illegalCatch")
132 private Optional<ProcessorModuleReactor> createReactor() throws MojoExecutionException {
133 LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
136 * Collect all files which affect YANG context. This includes all
137 * files in current project and optionally any jars/files in the
140 final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
142 final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
143 if (inspectDependencies) {
144 allFiles.addAll(Util.findYangFilesInDependencies(project));
147 if (allFiles.isEmpty()) {
148 LOG.info("{} No input files found", LOG_PREFIX);
149 return Optional.empty();
153 * Check if any of the listed files changed. If no changes occurred,
154 * simply return null, which indicates and of execution.
156 boolean noChange = true;
157 for (final File f : allFiles) {
158 if (buildContext.hasDelta(f)) {
159 LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
166 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
167 return Optional.empty();
170 final YangTextSchemaContextResolver resolver = YangTextSchemaContextResolver.create("maven-plugin");
171 for (final File f : yangFilesInProject) {
172 resolver.registerSource(YangTextSchemaSource.forFile(f));
175 LOG.debug("Processed project files: {}", yangFilesInProject);
176 LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
178 final ProcessorModuleReactor reactor = new ProcessorModuleReactor(resolver);
179 LOG.debug("Initialized reactor {}", reactor, yangFilesInProject);
180 return Optional.of(reactor);
181 } catch (Exception e) {
182 // MojoExecutionException is thrown since execution cannot continue
183 LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
184 Throwable rootCause = Throwables.getRootCause(e);
185 throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from "
186 + yangFilesRootDir, rootCause);
190 private ContextHolder createContextHolder(final ProcessorModuleReactor reactor) throws MojoFailureException,
191 IOException, SchemaSourceException, YangSyntaxErrorException {
193 * Set contains all modules generated from input sources. Number of
194 * modules may differ from number of sources due to submodules
195 * (parsed submodule's data are added to its parent module). Set
196 * cannot contains null values.
198 if (inspectDependencies) {
199 final List<YangTextSchemaSource> sourcesInDependencies = Util.findYangFilesInDependenciesAsStream(
201 for (YangTextSchemaSource s : toUniqueSources(sourcesInDependencies)) {
202 reactor.registerSource(s);
206 return reactor.toContext();
209 private static Collection<YangTextSchemaSource> toUniqueSources(final Collection<YangTextSchemaSource> sources)
211 final Map<String, YangTextSchemaSource> byContent = new HashMap<>();
212 for (YangTextSchemaSource s : sources) {
213 try (Reader reader = s.asCharSource(StandardCharsets.UTF_8).openStream()) {
214 final String contents = CharStreams.toString(reader);
215 byContent.putIfAbsent(contents, s);
218 return byContent.values();
222 * Call generate on every generator from plugin configuration.
224 @SuppressWarnings("checkstyle:illegalCatch")
225 private void generateSources(final ContextHolder context) throws MojoFailureException {
226 if (codeGenerators.size() == 0) {
227 LOG.warn("{} No code generators provided", LOG_PREFIX);
231 final Map<String, String> thrown = new HashMap<>();
232 for (CodeGeneratorArg codeGenerator : codeGenerators) {
234 generateSourcesWithOneGenerator(context, codeGenerator);
235 } catch (Exception e) {
236 // try other generators, exception will be thrown after
237 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
238 .getCodeGeneratorClass(), e);
239 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
243 if (!thrown.isEmpty()) {
244 String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
245 LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
246 throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
251 * Instantiate generator from class and call required method.
253 private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
254 throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
256 codeGeneratorCfg.check();
258 final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
259 LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
261 final File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
263 if (outputDir == null) {
264 throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the "
268 project.addCompileSourceRoot(outputDir.getAbsolutePath());
270 LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
271 LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
272 LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
273 .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
275 if (g instanceof BuildContextAware) {
276 ((BuildContextAware)g).setBuildContext(buildContext);
278 if (g instanceof MavenProjectAware) {
279 ((MavenProjectAware)g).setMavenProject(project);
281 g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
282 File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
284 YangProvider.setResource(resourceBaseDir, project);
285 g.setResourceBaseDir(resourceBaseDir);
286 LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
287 codeGeneratorCfg.getCodeGeneratorClass());
289 FileUtils.deleteDirectory(outputDir);
290 LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
292 Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
293 context::moduleToResourcePath);
295 LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
299 * Instantiate object from fully qualified class name.
301 private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
302 ClassNotFoundException, InstantiationException, IllegalAccessException {
303 final Class<?> clazz = Class.forName(codeGeneratorClass);
305 Preconditions.checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz,
307 return baseType.cast(clazz.newInstance());