X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?a=blobdiff_plain;f=yang%2Fyang-maven-plugin%2Fsrc%2Fmain%2Fjava%2Forg%2Fopendaylight%2Fyangtools%2Fyang2sources%2Fplugin%2FYangToSourcesProcessor.java;h=604fab0d13a0c0505bf25b8910237bd09d8f28c7;hb=21b3fb1ea12d1e28115f6c216bbbfd9c80b2216f;hp=321896ef3ea76a0138bb67b342da33c0338df77c;hpb=dea46b20bfec80fe9d84dd1768219b497d57cc15;p=yangtools.git diff --git a/yang/yang-maven-plugin/src/main/java/org/opendaylight/yangtools/yang2sources/plugin/YangToSourcesProcessor.java b/yang/yang-maven-plugin/src/main/java/org/opendaylight/yangtools/yang2sources/plugin/YangToSourcesProcessor.java index 321896ef3e..604fab0d13 100644 --- a/yang/yang-maven-plugin/src/main/java/org/opendaylight/yangtools/yang2sources/plugin/YangToSourcesProcessor.java +++ b/yang/yang-maven-plugin/src/main/java/org/opendaylight/yangtools/yang2sources/plugin/YangToSourcesProcessor.java @@ -7,6 +7,9 @@ */ package org.opendaylight.yangtools.yang2sources.plugin; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Throwables; +import com.google.common.collect.Maps; import java.io.Closeable; import java.io.File; import java.io.IOException; @@ -18,52 +21,56 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - +import java.util.concurrent.ConcurrentMap; +import org.apache.commons.io.IOUtils; import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugin.logging.Log; 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.impl.YangParserImpl; +import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver; +import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream; +import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils; import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg; import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder; -import org.opendaylight.yangtools.yang2sources.plugin.Util.NamedFileInputStream; 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.CodeGenerator; +import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.sonatype.plexus.build.incremental.BuildContext; import org.sonatype.plexus.build.incremental.DefaultBuildContext; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.Maps; - class YangToSourcesProcessor { + private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class); + 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"; - static final File META_INF_YANG_DIR = new File(META_INF_YANG_STRING); + static final String META_INF_YANG_SERVICES_STRING_JAR = "META-INF" + "/" + "services"; - private final Log log; private final File yangFilesRootDir; private final File[] excludedFiles; private final List codeGenerators; private final MavenProject project; private final boolean inspectDependencies; private final BuildContext buildContext; - private YangProvider yangProvider; + private final YangProvider yangProvider; + private final YangTextSchemaContextResolver resolver; @VisibleForTesting - YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List codeGenerators, - MavenProject project, boolean inspectDependencies, YangProvider yangProvider) { - this(new DefaultBuildContext(), log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, yangProvider); + YangToSourcesProcessor(final File yangFilesRootDir, final File[] excludedFiles, final List codeGenerators, + final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) { + this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project, + inspectDependencies, yangProvider); } - private YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles, - List codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider yangProvider) { + private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir, final File[] excludedFiles, + final List codeGenerators, final MavenProject project, final boolean inspectDependencies, final YangProvider + yangProvider) { this.buildContext = Util.checkNotNull(buildContext, "buildContext"); - this.log = Util.checkNotNull(log, "log"); this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir"); this.excludedFiles = new File[excludedFiles.length]; int i = 0; @@ -74,42 +81,65 @@ class YangToSourcesProcessor { this.project = Util.checkNotNull(project, "project"); this.inspectDependencies = inspectDependencies; this.yangProvider = yangProvider; + this.resolver = YangTextSchemaContextResolver.create("maven-plugin"); } - YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles, List codeGenerators, - MavenProject project, boolean inspectDependencies) { - this(log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider()); + YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir, final File[] excludedFiles, + final List codeGenerators, final MavenProject project, final boolean inspectDependencies) { + this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider()); } public void execute() throws MojoExecutionException, MojoFailureException { ContextHolder context = processYang(); if (context != null) { generateSources(context); - yangProvider.addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles); + yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles); + } + } + + void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException { + if (skip) { + LOG.info("Skipping YANG code generation because property yang.skip is true"); + + // But manually add resources + // add META_INF/yang + yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles); + + // add META_INF/services + File generatedServicesDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_SERVICES_GENERATED_DIR); + YangProvider.setResource(generatedServicesDir, project); + LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir, + META_INF_YANG_SERVICES_STRING_JAR); + + + } else { + execute(); } } private ContextHolder processYang() throws MojoExecutionException { - YangParserImpl parser = new YangParserImpl(); + SchemaContext resolveSchemaContext; List closeables = new ArrayList<>(); - log.info(Util.message("Inspecting %s", LOG_PREFIX, yangFilesRootDir)); + LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir); try { /* * Collect all files which affect YANG context. This includes all * files in current project and optionally any jars/files in the * dependencies. */ - final Collection yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles, log); + final Collection yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles); + + final Collection allFiles = new ArrayList<>(yangFilesInProject); if (inspectDependencies) { - allFiles.addAll(Util.findYangFilesInDependencies(log, project)); + allFiles.addAll(Util.findYangFilesInDependencies(project)); } if (allFiles.isEmpty()) { - log.info(Util.message("No input files found", LOG_PREFIX)); - return null; + LOG.info("{} No input files found", LOG_PREFIX); + return null; } - + /* * Check if any of the listed files changed. If no changes occurred, * simply return null, which indicates and of execution. @@ -117,91 +147,145 @@ class YangToSourcesProcessor { boolean noChange = true; for (final File f : allFiles) { if (buildContext.hasDelta(f)) { - log.debug(Util.message("buildContext %s indicates %s changed, forcing regeneration", LOG_PREFIX, buildContext, f)); + LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX, + buildContext, f); noChange = false; } } if (noChange) { - log.info(Util.message("None of %s input files changed", LOG_PREFIX, allFiles.size())); + LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size()); return null; } - final List yangsInProject = new ArrayList<>(); + final List yangsInProject = new ArrayList<>(); for (final File f : yangFilesInProject) { - yangsInProject.add(new NamedFileInputStream(f)); + // FIXME: This is hack - normal path should be reported. + yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName())); } - List all = new ArrayList<>(yangsInProject); + List all = new ArrayList<>(); + all.addAll(yangsInProject); closeables.addAll(yangsInProject); - Map allYangModules; + + /** + * 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 projectYangModules; try { if (inspectDependencies) { - YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project); + YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project); Closeable dependentYangResult1 = dependentYangResult; closeables.add(dependentYangResult1); - all.addAll(dependentYangResult.getYangStreams()); + List yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams()); + all.addAll(yangStreams); + closeables.addAll(yangStreams); } - allYangModules = parser.parseYangModelsFromStreamsMapped(all); + resolveSchemaContext = YangParserTestUtils.parseYangStreams(all); + Set parsedAllYangModules = resolveSchemaContext.getModules(); projectYangModules = new HashSet<>(); - for (InputStream inProject : yangsInProject) { - projectYangModules.add(allYangModules.get(inProject)); + for (Module module : parsedAllYangModules) { + final String path = module.getModuleSourcePath(); + if (path != null) { + LOG.debug("Looking for source {}", path); + for (NamedFileInputStream is : yangsInProject) { + LOG.debug("In project destination {}", is.getFileDestination()); + if (path.equals(is.getFileDestination())) { + LOG.debug("Module {} belongs to current project", module); + projectYangModules.add(module); + break; + } + } + } } - } finally { for (AutoCloseable closeable : closeables) { closeable.close(); } } - Set parsedAllYangModules = new HashSet<>(allYangModules.values()); - SchemaContext resolveSchemaContext = parser.resolveSchemaContext(parsedAllYangModules); - log.info(Util.message("%s files parsed from %s", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject)); + LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject); return new ContextHolder(resolveSchemaContext, projectYangModules); // MojoExecutionException is thrown since execution cannot continue } catch (Exception e) { - String message = Util.message("Unable to parse %s files from %s", LOG_PREFIX, Util.YANG_SUFFIX, - yangFilesRootDir); - log.error(message, e); - throw new MojoExecutionException(message, e); + LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e); + Throwable rootCause = Throwables.getRootCause(e); + throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from " + + yangFilesRootDir, rootCause); } } - static class YangProvider { + private static List toStreamsWithoutDuplicates(final List list) throws IOException { + ConcurrentMap byContent = Maps.newConcurrentMap(); - private static final String YANG_RESOURCE_DIR = "target" + File.separator + "yang"; + for (YangSourceFromDependency yangFromDependency : list) { + try (InputStream dataStream = yangFromDependency.openStream()) { + String contents = IOUtils.toString(dataStream); + byContent.putIfAbsent(contents, yangFromDependency); + } catch (IOException e) { + throw new IOException("Exception when reading from: " + yangFromDependency.getDescription(), e); + } - void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles) + } + List 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(final MavenProject project, final File yangFilesRootDir, final File[] excludedFiles) throws MojoFailureException { - File targetYangDir = new File(project.getBasedir(), YANG_RESOURCE_DIR); + + // 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"). + + 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 void addYangsToMetaInf(final MavenProject project, final File yangFilesRootDir, + final File[] excludedFiles, final File generatedYangDir) throws MojoFailureException { + + File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING); + withMetaInf.mkdirs(); try { - Collection files = Util.listFiles(yangFilesRootDir, excludedFiles, null); + Collection files = Util.listFiles(yangFilesRootDir, excludedFiles); for (File file : files) { - org.apache.commons.io.FileUtils.copyFile(file, new File(targetYangDir, file.getName())); + org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName())); } } catch (IOException e) { - String message = "Unable to list yang files into resource folder"; - log.warn(message, e); - throw new MojoFailureException(message, e); + LOG.warn("Failed to generate files into root {}", yangFilesRootDir, e); + throw new MojoFailureException("Unable to list yang files into resource folder", e); } - setResource(targetYangDir, META_INF_YANG_STRING_JAR, project); + setResource(generatedYangDir, project); - log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir, - META_INF_YANG_STRING_JAR)); + LOG.debug("{} Yang files from: {} marked as resources: {}", LOG_PREFIX, yangFilesRootDir, + META_INF_YANG_STRING_JAR); } - private static void setResource(File targetYangDir, String targetPath, MavenProject project) { + private static void setResource(final File targetYangDir, final MavenProject project) { Resource res = new Resource(); res.setDirectory(targetYangDir.getPath()); - if (targetPath != null) { - res.setTargetPath(targetPath); - } project.addResource(res); } } @@ -209,9 +293,9 @@ class YangToSourcesProcessor { /** * Call generate on every generator from plugin configuration */ - private void generateSources(ContextHolder context) throws MojoFailureException { + private void generateSources(final ContextHolder context) throws MojoFailureException { if (codeGenerators.size() == 0) { - log.warn(Util.message("No code generators provided", LOG_PREFIX)); + LOG.warn("{} No code generators provided", LOG_PREFIX); return; } @@ -221,62 +305,61 @@ class YangToSourcesProcessor { generateSourcesWithOneGenerator(context, codeGenerator); } catch (Exception e) { // try other generators, exception will be thrown after - log.error( - Util.message("Unable to generate sources with %s generator", LOG_PREFIX, - codeGenerator.getCodeGeneratorClass()), e); + LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator + .getCodeGeneratorClass(), e); thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName()); } } if (!thrown.isEmpty()) { - String message = Util.message( - "One or more code generators failed, including failed list(generatorClass=exception) %s", - LOG_PREFIX, thrown.toString()); - log.error(message); - throw new MojoFailureException(message); + String message = " One or more code generators failed, including failed list(generatorClass=exception) "; + LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString()); + throw new MojoFailureException(LOG_PREFIX + message + thrown.toString()); } } /** * 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(); - CodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), CodeGenerator.class); - log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX, - codeGeneratorCfg.getCodeGeneratorClass())); + BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class); + LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass()); File outputDir = codeGeneratorCfg.getOutputBaseDir(project); - log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir)); - log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir())); - log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX, - codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration())); - if (outputDir != null) { - project.addCompileSourceRoot(outputDir.getAbsolutePath()); + project.addCompileSourceRoot(outputDir.getAbsolutePath()); + } else { + throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " + + "pom.xml"); } + LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir); + LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir()); + LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg + .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()); + if (g instanceof BuildContextAware) { ((BuildContextAware)g).setBuildContext(buildContext); } - g.setLog(log); - g.setMavenProject(project); + if (g instanceof MavenProjectAware) { + ((MavenProjectAware)g).setMavenProject(project); + } g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration()); File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project); - YangProvider.setResource(resourceBaseDir, null, project); + YangProvider.setResource(resourceBaseDir, project); g.setResourceBaseDir(resourceBaseDir); - log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir, - codeGeneratorCfg.getCodeGeneratorClass())); + LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir, + codeGeneratorCfg.getCodeGeneratorClass()); Collection generated = g.generateSources(context.getContext(), outputDir, context.getYangModules()); - log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), - generated)); + LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated); } }