import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.CharStreams;
-import java.io.Closeable;
import java.io.File;
import java.io.IOException;
-import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.FileUtils;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
+import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
+import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
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.YangsInZipsResult;
import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
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 String META_INF_YANG_SERVICES_STRING_JAR = "META-INF" + "/" + "services";
+ 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 File yangFilesRootDir;
private final Set<File> excludedFiles;
private final boolean inspectDependencies;
private final BuildContext buildContext;
private final YangProvider yangProvider;
- private final YangTextSchemaContextResolver resolver;
-
- @VisibleForTesting
- 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(final BuildContext buildContext, final File yangFilesRootDir,
final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
this.codeGenerators = ImmutableList.copyOf(codeGenerators);
this.project = Preconditions.checkNotNull(project);
this.inspectDependencies = inspectDependencies;
- this.yangProvider = yangProvider;
- this.resolver = YangTextSchemaContextResolver.create("maven-plugin");
+ this.yangProvider = Preconditions.checkNotNull(yangProvider);
+ }
+
+ @VisibleForTesting
+ 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);
}
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, new YangProvider());
+ this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, YangProvider.getInstance());
}
public void execute() throws MojoExecutionException, MojoFailureException {
- ContextHolder context = processYang();
- if (context != null) {
- generateSources(context);
- yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
- }
+ conditionalExecute(false);
}
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);
+ final Optional<ProcessorModuleReactor> optReactor = createReactor();
+ if (!optReactor.isPresent()) {
+ return;
+ }
- // 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);
+ final ProcessorModuleReactor reactor = optReactor.get();
+ if (!skip) {
+ final ContextHolder holder;
+ try {
+ holder = createContextHolder(reactor);
+ } catch (SchemaSourceException | YangSyntaxErrorException 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 {
- execute();
+ 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 {
- SchemaContext resolveSchemaContext;
- List<Closeable> closeables = new ArrayList<>();
+ @SuppressWarnings("checkstyle:illegalCatch")
+ private Optional<ProcessorModuleReactor> createReactor() throws MojoExecutionException {
LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
try {
/*
if (allFiles.isEmpty()) {
LOG.info("{} No input files found", LOG_PREFIX);
- return null;
+ return Optional.empty();
}
/*
if (noChange) {
LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
- return null;
+ return Optional.empty();
}
- final List<NamedFileInputStream> yangsInProject = new ArrayList<>();
+ final YangTextSchemaContextResolver resolver = YangTextSchemaContextResolver.create("maven-plugin");
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()));
+ resolver.registerSource(YangTextSchemaSource.forFile(f));
}
- List<InputStream> all = new ArrayList<>();
- all.addAll(yangsInProject);
- closeables.addAll(yangsInProject);
+ LOG.debug("Processed project files: {}", yangFilesInProject);
+ LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
- /**
- * 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.
- */
- final Set<Module> projectYangModules = new HashSet<>();
- final Set<Module> projectYangFiles = new HashSet<>();
- 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 = YangParserTestUtils.parseYangStreams(all);
-
- Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
- for (Module module : parsedAllYangModules) {
- if (containedInFiles(yangsInProject, module)) {
- LOG.debug("Module {} belongs to current project", module);
- projectYangModules.add(module);
- projectYangFiles.add(module);
-
- for (Module sub : module.getSubmodules()) {
- if (containedInFiles(yangsInProject, sub)) {
- LOG.debug("Submodule {} belongs to current project", sub);
- projectYangFiles.add(sub);
- } else {
- LOG.warn("Submodule {} not found in input files", sub);
- }
- }
- }
- }
- } finally {
- for (AutoCloseable closeable : closeables) {
- closeable.close();
- }
- }
-
- LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
- LOG.debug("Project YANG files: {}", projectYangFiles);
-
- return new ContextHolder(resolveSchemaContext, projectYangModules, projectYangFiles);
-
- // MojoExecutionException is thrown since execution cannot continue
+ final ProcessorModuleReactor reactor = new ProcessorModuleReactor(resolver);
+ LOG.debug("Initialized reactor {}", reactor, yangFilesInProject);
+ return Optional.of(reactor);
} catch (Exception e) {
+ // MojoExecutionException is thrown since execution cannot continue
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);
+ throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from "
+ + yangFilesRootDir, rootCause);
}
}
- private static boolean containedInFiles(final List<NamedFileInputStream> files, final Module module) {
- final String path = module.getModuleSourcePath();
- if (path != null) {
- LOG.debug("Looking for source {}", path);
- for (NamedFileInputStream is : files) {
- LOG.debug("In project destination {}", is.getFileDestination());
- if (path.equals(is.getFileDestination())) {
- return true;
- }
+ private ContextHolder createContextHolder(final ProcessorModuleReactor reactor) throws MojoFailureException,
+ IOException, SchemaSourceException, YangSyntaxErrorException {
+ /**
+ * 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.registerSource(s);
}
}
- return false;
+ return reactor.toContext();
}
- private static List<InputStream> toStreamsWithoutDuplicates(final List<YangSourceFromDependency> list)
+ private static Collection<YangTextSchemaSource> toUniqueSources(final Collection<YangTextSchemaSource> sources)
throws IOException {
- final Map<String, YangSourceFromDependency> byContent = new HashMap<>();
-
- for (YangSourceFromDependency yangFromDependency : list) {
- try (Reader reader = yangFromDependency.asCharSource(StandardCharsets.UTF_8).openStream()) {
+ 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, yangFromDependency);
- } catch (IOException e) {
- throw new IOException("Exception when reading from: " + yangFromDependency.getDescription(), e);
+ byContent.putIfAbsent(contents, s);
}
-
- }
- List<InputStream> inputs = new ArrayList<>(byContent.size());
- for (YangSourceFromDependency entry : byContent.values()) {
- inputs.add(entry.openStream());
}
- return inputs;
+ return byContent.values();
}
/**
- * Call generate on every generator from plugin configuration
+ * Call generate on every generator from plugin configuration.
*/
+ @SuppressWarnings("checkstyle:illegalCatch")
private void generateSources(final ContextHolder context) throws MojoFailureException {
if (codeGenerators.size() == 0) {
LOG.warn("{} No code generators provided", LOG_PREFIX);
}
/**
- * Instantiate generator from class and call required method
+ * Instantiate generator from class and call required method.
*/
private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
codeGeneratorCfg.check();
- BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
+ final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
final File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
if (outputDir == null) {
- throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the " +
- "pom.xml");
+ throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the "
+ + "pom.xml");
}
project.addCompileSourceRoot(outputDir.getAbsolutePath());
}
/**
- * Instantiate object from fully qualified class name
+ * Instantiate object from fully qualified class name.
*/
private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
ClassNotFoundException, InstantiationException, IllegalAccessException {