Get rid of commons-io
[yangtools.git] / yang / yang-maven-plugin / src / main / java / org / opendaylight / yangtools / yang2sources / plugin / YangToSourcesProcessor.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang2sources.plugin;
9
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;
16 import java.io.File;
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;
27 import java.util.Map;
28 import java.util.Optional;
29 import java.util.Set;
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;
47
48 class YangToSourcesProcessor {
49     private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
50
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";
54
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";
58
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;
66
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);
77     }
78
79     @VisibleForTesting
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);
85     }
86
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());
91     }
92
93     public void execute() throws MojoExecutionException, MojoFailureException {
94         conditionalExecute(false);
95     }
96
97     void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
98         final Optional<ProcessorModuleReactor> optReactor = createReactor();
99         if (!optReactor.isPresent()) {
100             return;
101         }
102
103         final ProcessorModuleReactor reactor = optReactor.get();
104         if (!skip) {
105             final ContextHolder holder;
106
107             try {
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);
113             }
114
115             generateSources(holder);
116         } else {
117             LOG.info("Skipping YANG code generation because property yang.skip is true");
118         }
119
120         // add META_INF/yang
121         final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
122         try {
123             yangProvider.addYangsToMetaInf(project, models);
124         } catch (IOException e) {
125             throw new MojoExecutionException("Failed write model files for " + models, e);
126         }
127
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);
133     }
134
135     @SuppressWarnings("checkstyle:illegalCatch")
136     private Optional<ProcessorModuleReactor> createReactor() throws MojoExecutionException {
137         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
138         try {
139             /*
140              * Collect all files which affect YANG context. This includes all
141              * files in current project and optionally any jars/files in the
142              * dependencies.
143              */
144             final Collection<File> yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
145
146             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
147             if (inspectDependencies) {
148                 allFiles.addAll(Util.findYangFilesInDependencies(project));
149             }
150
151             if (allFiles.isEmpty()) {
152                 LOG.info("{} No input files found", LOG_PREFIX);
153                 return Optional.empty();
154             }
155
156             /*
157              * Check if any of the listed files changed. If no changes occurred,
158              * simply return null, which indicates and of execution.
159              */
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,
164                             buildContext, f);
165                     noChange = false;
166                 }
167             }
168
169             if (noChange) {
170                 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
171                 return Optional.empty();
172             }
173
174             final YangTextSchemaContextResolver resolver = YangTextSchemaContextResolver.create("maven-plugin");
175             for (final File f : yangFilesInProject) {
176                 resolver.registerSource(YangTextSchemaSource.forFile(f));
177             }
178
179             LOG.debug("Processed project files: {}", yangFilesInProject);
180             LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
181
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,
190                 rootCause);
191         }
192     }
193
194     private ContextHolder createContextHolder(final ProcessorModuleReactor reactor) throws MojoFailureException,
195             IOException, SchemaSourceException, YangSyntaxErrorException {
196         /**
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.
201          */
202         if (inspectDependencies) {
203             final List<YangTextSchemaSource> sourcesInDependencies = Util.findYangFilesInDependenciesAsStream(
204                 project);
205             for (YangTextSchemaSource s : toUniqueSources(sourcesInDependencies)) {
206                 reactor.registerSource(s);
207             }
208         }
209
210         return reactor.toContext();
211     }
212
213     private static Collection<File> listFiles(final File root, final Collection<File> excludedFiles)
214             throws IOException {
215         if (!root.isDirectory()) {
216             LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
217             return ImmutableList.of();
218         }
219
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);
223                 return false;
224             }
225             return true;
226         }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
227     }
228
229     private static Collection<YangTextSchemaSource> toUniqueSources(final Collection<YangTextSchemaSource> sources)
230             throws IOException {
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);
236             }
237         }
238         return byContent.values();
239     }
240
241     /**
242      * Call generate on every generator from plugin configuration.
243      */
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);
248             return;
249         }
250
251         final Map<String, String> thrown = new HashMap<>();
252         for (CodeGeneratorArg codeGenerator : codeGenerators) {
253             try {
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());
260             }
261         }
262
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());
267         }
268     }
269
270     /**
271      * Instantiate generator from class and call required method.
272      */
273     private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
274             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
275
276         codeGeneratorCfg.check();
277
278         final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
279         LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
280
281         final File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
282
283         if (outputDir == null) {
284             throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the "
285                     + "pom.xml");
286         }
287
288         project.addCompileSourceRoot(outputDir.getAbsolutePath());
289
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());
294
295         if (g instanceof BuildContextAware) {
296             ((BuildContextAware)g).setBuildContext(buildContext);
297         }
298         if (g instanceof MavenProjectAware) {
299             ((MavenProjectAware)g).setMavenProject(project);
300         }
301         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
302         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
303
304         YangProvider.setResource(resourceBaseDir, project);
305         g.setResourceBaseDir(resourceBaseDir);
306         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
307                 codeGeneratorCfg.getCodeGeneratorClass());
308
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);
312         }
313         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
314             context::moduleToResourcePath);
315
316         LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
317     }
318
319     /**
320      * Instantiate object from fully qualified class name.
321      */
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);
325
326         Preconditions.checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz,
327             baseType);
328         return baseType.cast(clazz.newInstance());
329     }
330 }