*/
package org.opendaylight.yangtools.yang2sources.plugin;
-import java.util.HashSet;
-import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
-import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.Maps;
-import java.io.Closeable;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.io.CharStreams;
import java.io.File;
import java.io.IOException;
-import java.io.InputStream;
+import java.io.Reader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
+import java.util.ServiceLoader;
import java.util.Set;
-import java.util.concurrent.ConcurrentMap;
-import org.apache.commons.io.IOUtils;
-import org.apache.maven.model.Resource;
+import java.util.stream.Collectors;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.repo.URLSchemaContextResolver;
-import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
+import org.opendaylight.yangtools.yang.common.YangConstants;
+import org.opendaylight.yangtools.yang.model.parser.api.YangParser;
+import org.opendaylight.yangtools.yang.model.parser.api.YangParserException;
+import org.opendaylight.yangtools.yang.model.parser.api.YangParserFactory;
+import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
+import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
-import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
-import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
class YangToSourcesProcessor {
private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
+ private static final YangParserFactory DEFAULT_PARSER_FACTORY;
+
+ static {
+ final Iterator<YangParserFactory> it = ServiceLoader.load(YangParserFactory.class).iterator();
+ checkState(it.hasNext(), "Failed to find a YangParserFactory implementation");
+ DEFAULT_PARSER_FACTORY = it.next();
+ }
static final String LOG_PREFIX = "yang-to-sources:";
- static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
- static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
+ private static final String META_INF_STR = "META-INF";
+ private static final String YANG_STR = "yang";
+
+ static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
+ static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
+ static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
+ private final YangParserFactory parserFactory;
private final File yangFilesRootDir;
- private final File[] excludedFiles;
+ private final Set<File> excludedFiles;
private final List<CodeGeneratorArg> codeGenerators;
private final MavenProject project;
private final boolean inspectDependencies;
private final BuildContext buildContext;
private final YangProvider yangProvider;
- private final URLSchemaContextResolver resolver;
+
+ private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
+ final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
+ final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
+ this.buildContext = requireNonNull(buildContext, "buildContext");
+ this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
+ this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
+ this.codeGenerators = ImmutableList.copyOf(codeGenerators);
+ this.project = requireNonNull(project);
+ this.inspectDependencies = inspectDependencies;
+ this.yangProvider = requireNonNull(yangProvider);
+ this.parserFactory = DEFAULT_PARSER_FACTORY;
+ }
@VisibleForTesting
- YangToSourcesProcessor(File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
- MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
+ YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
+ final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
+ final YangProvider yangProvider) {
this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
inspectDependencies, yangProvider);
}
- private YangToSourcesProcessor(BuildContext buildContext, File yangFilesRootDir, File[] excludedFiles,
- List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider
- yangProvider) {
- this.buildContext = Util.checkNotNull(buildContext, "buildContext");
- this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
- this.excludedFiles = new File[excludedFiles.length];
- int i = 0;
- for (File file : excludedFiles) {
- this.excludedFiles[i++] = new File(file.getPath());
- }
- this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
- this.project = Util.checkNotNull(project, "project");
- this.inspectDependencies = inspectDependencies;
- this.yangProvider = yangProvider;
- this.resolver = URLSchemaContextResolver.create("maven-plugin");
+ YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
+ final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
+ final MavenProject project, final boolean inspectDependencies) {
+ this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, YangProvider.getInstance());
}
- YangToSourcesProcessor(BuildContext buildContext, File yangFilesRootDir, File[] excludedFiles,
- List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies) {
- this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
+ public void execute() throws MojoExecutionException, MojoFailureException {
+ conditionalExecute(false);
}
- public void execute() throws MojoExecutionException, MojoFailureException {
- ContextHolder context = processYang();
- if (context != null) {
- generateSources(context);
- yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
+ void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
+ final Optional<ProcessorModuleReactor> optReactor = createReactor();
+ if (!optReactor.isPresent()) {
+ return;
+ }
+
+ final ProcessorModuleReactor reactor = optReactor.get();
+ if (!skip) {
+ final ContextHolder holder;
+
+ try {
+ holder = createContextHolder(reactor);
+ } catch (YangParserException e) {
+ throw new MojoFailureException("Failed to process reactor " + reactor, e);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Failed to read reactor " + reactor, e);
+ }
+
+ generateSources(holder);
+ } else {
+ LOG.info("Skipping YANG code generation because property yang.skip is true");
}
+
+ // add META_INF/yang
+ final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
+ try {
+ yangProvider.addYangsToMetaInf(project, models);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Failed write model files for " + models, e);
+ }
+
+ // add META_INF/services
+ File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
+ YangProvider.setResource(generatedServicesDir, project);
+ LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
+ META_INF_YANG_SERVICES_STRING_JAR);
}
- private ContextHolder processYang() throws MojoExecutionException {
- final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
- SchemaContext resolveSchemaContext;
- List<Closeable> closeables = new ArrayList<>();
+ @SuppressWarnings("checkstyle:illegalCatch")
+ private Optional<ProcessorModuleReactor> createReactor() throws MojoExecutionException {
LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
try {
/*
* files in current project and optionally any jars/files in the
* dependencies.
*/
- final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
-
+ final Collection<File> yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
if (inspectDependencies) {
}
if (allFiles.isEmpty()) {
- LOG.info("{} No input files found", LOG_PREFIX);
- return null;
+ LOG.info("{} No input files found", LOG_PREFIX);
+ return Optional.empty();
}
/*
* Check if any of the listed files changed. If no changes occurred,
* simply return null, which indicates and of execution.
*/
- boolean noChange = true;
- for (final File f : allFiles) {
- if (buildContext.hasDelta(f)) {
- LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
- buildContext, f);
- noChange = false;
- }
- }
-
- if (noChange) {
+ if (!allFiles.stream().anyMatch(buildContext::hasDelta)) {
LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
- return null;
+ return Optional.empty();
}
- final List<InputStream> yangsInProject = new ArrayList<>();
+ // FIXME: add correct mode
+ final YangParser parser = parserFactory.createParser();
+ final List<YangTextSchemaSource> sourcesInProject = new ArrayList<>(yangFilesInProject.size());
for (final File f : yangFilesInProject) {
- // FIXME: This is hack - normal path should be reported.
- yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
- }
+ final YangTextSchemaSource textSource = YangTextSchemaSource.forFile(f);
+ final ASTSchemaSource astSource = TextToASTTransformer.transformText(textSource);
- List<InputStream> all = new ArrayList<>(yangsInProject);
- closeables.addAll(yangsInProject);
+ parser.addSource(astSource);
- /**
- * Set contains all modules generated from input sources. Number of
- * modules may differ from number of sources due to submodules
- * (parsed submodule's data are added to its parent module). Set
- * cannot contains null values.
- */
- Set<Module> projectYangModules;
- try {
- if (inspectDependencies) {
- YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project);
- Closeable dependentYangResult1 = dependentYangResult;
- closeables.add(dependentYangResult1);
- List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
- all.addAll(yangStreams);
- closeables.addAll(yangStreams);
- }
-
- resolveSchemaContext = reactor.buildEffective(all);
-
- Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
- projectYangModules = new HashSet<>();
- for (Module module : parsedAllYangModules) {
- if(module.getModuleSourcePath()!=null) {
- projectYangModules.add(module);
- }
- }
- } finally {
- for (AutoCloseable closeable : closeables) {
- closeable.close();
+ if (!astSource.getIdentifier().equals(textSource.getIdentifier())) {
+ // AST indicates a different source identifier, make sure we use that
+ sourcesInProject.add(YangTextSchemaSource.delegateForByteSource(astSource.getIdentifier(),
+ textSource));
+ } else {
+ sourcesInProject.add(textSource);
}
}
- LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
- return new ContextHolder(resolveSchemaContext, projectYangModules);
+ LOG.debug("Processed project files: {}", yangFilesInProject);
+ LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
- // MojoExecutionException is thrown since execution cannot continue
+ final ProcessorModuleReactor reactor = new ProcessorModuleReactor(parser, sourcesInProject);
+ LOG.debug("Initialized reactor {}", reactor, yangFilesInProject);
+ return Optional.of(reactor);
} catch (Exception e) {
- LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
- throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from " +
- yangFilesRootDir, e);
+ // MojoExecutionException is thrown since execution cannot continue
+ LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
+ Throwable rootCause = Throwables.getRootCause(e);
+ throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
+ rootCause);
}
}
- private List<InputStream> toStreamsWithoutDuplicates(List<YangSourceFromDependency> list) throws IOException {
- ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
-
- for (YangSourceFromDependency yangFromDependency : list) {
- try (InputStream dataStream = yangFromDependency.openStream()) {
- String contents = IOUtils.toString(dataStream);
- byContent.putIfAbsent(contents, yangFromDependency);
+ private ContextHolder createContextHolder(final ProcessorModuleReactor reactor) throws MojoFailureException,
+ IOException, YangParserException {
+ /**
+ * Set contains all modules generated from input sources. Number of
+ * modules may differ from number of sources due to submodules
+ * (parsed submodule's data are added to its parent module). Set
+ * cannot contains null values.
+ */
+ if (inspectDependencies) {
+ final List<YangTextSchemaSource> sourcesInDependencies = Util.findYangFilesInDependenciesAsStream(
+ project);
+ for (YangTextSchemaSource s : toUniqueSources(sourcesInDependencies)) {
+ reactor.registerSourceFromDependency(s);
}
-
- }
- List<InputStream> inputs = new ArrayList<>(byContent.size());
- for (YangSourceFromDependency entry : byContent.values()) {
- inputs.add(entry.openStream());
}
- return inputs;
- }
-
- static class YangProvider {
- private static final Logger LOG = LoggerFactory.getLogger(YangProvider.class);
-
- void addYangsToMetaInf(MavenProject project, File yangFilesRootDir, File[] excludedFiles)
- throws MojoFailureException {
-
- // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
- File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
- addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, generatedYangDir);
-
- // Also copy to the actual build output dir if different than "target". When running in
- // Eclipse this can differ (eg "target-ide").
+ return reactor.toContext();
+ }
- File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
- CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
- if(!actualGeneratedYangDir.equals(generatedYangDir)) {
- addYangsToMetaInf(project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
- }
+ private static Collection<File> listFiles(final File root, final Collection<File> excludedFiles)
+ throws IOException {
+ if (!root.isDirectory()) {
+ LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
+ return ImmutableList.of();
}
- private void addYangsToMetaInf(MavenProject project, File yangFilesRootDir,
- File[] excludedFiles, File generatedYangDir)
- throws MojoFailureException {
-
- File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
- withMetaInf.mkdirs();
-
- try {
- Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles);
- for (File file : files) {
- org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
- }
- } catch (IOException e) {
- LOG.warn("Failed to generate files into root {}", yangFilesRootDir, e);
- throw new MojoFailureException("Unable to list yang files into resource folder", e);
+ return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
+ if (excludedFiles.contains(f)) {
+ LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
+ return false;
}
+ return true;
+ }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
+ }
- setResource(generatedYangDir, project);
-
- LOG.debug("{} Yang files from: {} marked as resources: {}", LOG_PREFIX, yangFilesRootDir,
- META_INF_YANG_STRING_JAR);
- }
-
- private static void setResource(File targetYangDir, MavenProject project) {
- Resource res = new Resource();
- res.setDirectory(targetYangDir.getPath());
- project.addResource(res);
+ private static Collection<YangTextSchemaSource> toUniqueSources(final Collection<YangTextSchemaSource> sources)
+ throws IOException {
+ final Map<String, YangTextSchemaSource> byContent = new HashMap<>();
+ for (YangTextSchemaSource s : sources) {
+ try (Reader reader = s.asCharSource(StandardCharsets.UTF_8).openStream()) {
+ final String contents = CharStreams.toString(reader);
+ byContent.putIfAbsent(contents, s);
+ }
}
+ return byContent.values();
}
/**
- * Call generate on every generator from plugin configuration
+ * Call generate on every generator from plugin configuration.
*/
- private void generateSources(ContextHolder context) throws MojoFailureException {
- if (codeGenerators.size() == 0) {
+ @SuppressWarnings("checkstyle:illegalCatch")
+ private void generateSources(final ContextHolder context) throws MojoFailureException {
+ if (codeGenerators.isEmpty()) {
LOG.warn("{} No code generators provided", LOG_PREFIX);
return;
}
- Map<String, String> thrown = Maps.newHashMap();
+ final Map<String, String> thrown = new HashMap<>();
for (CodeGeneratorArg codeGenerator : codeGenerators) {
try {
generateSourcesWithOneGenerator(context, codeGenerator);
if (!thrown.isEmpty()) {
String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
- LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
+ LOG.error("{}{}{}", LOG_PREFIX, message, thrown.toString());
throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
}
}
/**
- * Instantiate generator from class and call required method
+ * Instantiate generator from class and call required method.
*/
- private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
+ private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
codeGeneratorCfg.check();
- BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
+ final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
- File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
+ final File outputDir = requireNonNull(codeGeneratorCfg.getOutputBaseDir(project),
+ "outputBaseDir is null. Please provide a valid outputBaseDir value in pom.xml");
- if (outputDir != null) {
- project.addCompileSourceRoot(outputDir.getAbsolutePath());
- } else {
- throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " +
- "pom.xml");
- }
+ project.addCompileSourceRoot(outputDir.getAbsolutePath());
LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
codeGeneratorCfg.getCodeGeneratorClass());
- Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
+ if (outputDir.exists()) {
+ Files.walk(outputDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
+ LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
+ }
+ Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
+ context::moduleToResourcePath);
LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
}
+ /**
+ * Instantiate object from fully qualified class name.
+ */
+ private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
+ ClassNotFoundException, InstantiationException, IllegalAccessException {
+ final Class<?> clazz = Class.forName(codeGeneratorClass);
+ checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz, baseType);
+ return baseType.cast(clazz.newInstance());
+ }
}