Fix slf4j usage errors found by checkstyle-logging
[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 static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.io.CharStreams;
18 import java.io.File;
19 import java.io.IOException;
20 import java.io.Reader;
21 import java.nio.charset.StandardCharsets;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Optional;
31 import java.util.Set;
32 import java.util.stream.Collectors;
33 import org.apache.maven.plugin.MojoExecutionException;
34 import org.apache.maven.plugin.MojoFailureException;
35 import org.apache.maven.project.MavenProject;
36 import org.opendaylight.yangtools.yang.common.YangConstants;
37 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
38 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
39 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
40 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
41 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
42 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
43 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
44 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.sonatype.plexus.build.incremental.BuildContext;
48 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
49
50 class YangToSourcesProcessor {
51     private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
52
53     static final String LOG_PREFIX = "yang-to-sources:";
54     private static final String META_INF_STR = "META-INF";
55     private static final String YANG_STR = "yang";
56
57     static final String META_INF_YANG_STRING = META_INF_STR + File.separator + YANG_STR;
58     static final String META_INF_YANG_STRING_JAR = META_INF_STR + "/" + YANG_STR;
59     static final String META_INF_YANG_SERVICES_STRING_JAR = META_INF_STR + "/" + "services";
60
61     private final File yangFilesRootDir;
62     private final Set<File> excludedFiles;
63     private final List<CodeGeneratorArg> codeGenerators;
64     private final MavenProject project;
65     private final boolean inspectDependencies;
66     private final BuildContext buildContext;
67     private final YangProvider yangProvider;
68
69     private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
70             final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
71             final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
72         this.buildContext = requireNonNull(buildContext, "buildContext");
73         this.yangFilesRootDir = requireNonNull(yangFilesRootDir, "yangFilesRootDir");
74         this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
75         this.codeGenerators = ImmutableList.copyOf(codeGenerators);
76         this.project = requireNonNull(project);
77         this.inspectDependencies = inspectDependencies;
78         this.yangProvider = requireNonNull(yangProvider);
79     }
80
81     @VisibleForTesting
82     YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
83             final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
84             final YangProvider yangProvider) {
85         this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
86                 inspectDependencies, yangProvider);
87     }
88
89     YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
90                 final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
91                 final MavenProject project, final boolean inspectDependencies) {
92         this(yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, YangProvider.getInstance());
93     }
94
95     public void execute() throws MojoExecutionException, MojoFailureException {
96         conditionalExecute(false);
97     }
98
99     void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
100         final Optional<ProcessorModuleReactor> optReactor = createReactor();
101         if (!optReactor.isPresent()) {
102             return;
103         }
104
105         final ProcessorModuleReactor reactor = optReactor.get();
106         if (!skip) {
107             final ContextHolder holder;
108
109             try {
110                 holder = createContextHolder(reactor);
111             } catch (SchemaSourceException | YangSyntaxErrorException e) {
112                 throw new MojoFailureException("Failed to process reactor " + reactor, e);
113             } catch (IOException e) {
114                 throw new MojoExecutionException("Failed to read reactor " + reactor, e);
115             }
116
117             generateSources(holder);
118         } else {
119             LOG.info("Skipping YANG code generation because property yang.skip is true");
120         }
121
122         // add META_INF/yang
123         final Collection<YangTextSchemaSource> models = reactor.getModelsInProject();
124         try {
125             yangProvider.addYangsToMetaInf(project, models);
126         } catch (IOException e) {
127             throw new MojoExecutionException("Failed write model files for " + models, e);
128         }
129
130         // add META_INF/services
131         File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
132         YangProvider.setResource(generatedServicesDir, project);
133         LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
134             META_INF_YANG_SERVICES_STRING_JAR);
135     }
136
137     @SuppressWarnings("checkstyle:illegalCatch")
138     private Optional<ProcessorModuleReactor> createReactor() throws MojoExecutionException {
139         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
140         try {
141             /*
142              * Collect all files which affect YANG context. This includes all
143              * files in current project and optionally any jars/files in the
144              * dependencies.
145              */
146             final Collection<File> yangFilesInProject = listFiles(yangFilesRootDir, excludedFiles);
147
148             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
149             if (inspectDependencies) {
150                 allFiles.addAll(Util.findYangFilesInDependencies(project));
151             }
152
153             if (allFiles.isEmpty()) {
154                 LOG.info("{} No input files found", LOG_PREFIX);
155                 return Optional.empty();
156             }
157
158             /*
159              * Check if any of the listed files changed. If no changes occurred,
160              * simply return null, which indicates and of execution.
161              */
162             if (!allFiles.stream().anyMatch(buildContext::hasDelta)) {
163                 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
164                 return Optional.empty();
165             }
166
167             final YangTextSchemaContextResolver resolver = YangTextSchemaContextResolver.create("maven-plugin");
168             for (final File f : yangFilesInProject) {
169                 resolver.registerSource(YangTextSchemaSource.forFile(f));
170             }
171
172             LOG.debug("Processed project files: {}", yangFilesInProject);
173             LOG.info("{} Project model files parsed: {}", LOG_PREFIX, yangFilesInProject.size());
174
175             final ProcessorModuleReactor reactor = new ProcessorModuleReactor(resolver);
176             LOG.debug("Initialized reactor {}", reactor, yangFilesInProject);
177             return Optional.of(reactor);
178         } catch (Exception e) {
179             // MojoExecutionException is thrown since execution cannot continue
180             LOG.error("{} Unable to parse YANG files from {}", LOG_PREFIX, yangFilesRootDir, e);
181             Throwable rootCause = Throwables.getRootCause(e);
182             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse YANG files from " + yangFilesRootDir,
183                 rootCause);
184         }
185     }
186
187     private ContextHolder createContextHolder(final ProcessorModuleReactor reactor) throws MojoFailureException,
188             IOException, SchemaSourceException, YangSyntaxErrorException {
189         /**
190          * Set contains all modules generated from input sources. Number of
191          * modules may differ from number of sources due to submodules
192          * (parsed submodule's data are added to its parent module). Set
193          * cannot contains null values.
194          */
195         if (inspectDependencies) {
196             final List<YangTextSchemaSource> sourcesInDependencies = Util.findYangFilesInDependenciesAsStream(
197                 project);
198             for (YangTextSchemaSource s : toUniqueSources(sourcesInDependencies)) {
199                 reactor.registerSource(s);
200             }
201         }
202
203         return reactor.toContext();
204     }
205
206     private static Collection<File> listFiles(final File root, final Collection<File> excludedFiles)
207             throws IOException {
208         if (!root.isDirectory()) {
209             LOG.warn("{} YANG source directory {} not found. No code will be generated.", LOG_PREFIX, root);
210             return ImmutableList.of();
211         }
212
213         return Files.walk(root.toPath()).map(Path::toFile).filter(File::isFile).filter(f -> {
214             if (excludedFiles.contains(f)) {
215                 LOG.info("{} YANG file excluded {}", LOG_PREFIX, f);
216                 return false;
217             }
218             return true;
219         }).filter(f -> f.getName().endsWith(YangConstants.RFC6020_YANG_FILE_EXTENSION)).collect(Collectors.toList());
220     }
221
222     private static Collection<YangTextSchemaSource> toUniqueSources(final Collection<YangTextSchemaSource> sources)
223             throws IOException {
224         final Map<String, YangTextSchemaSource> byContent = new HashMap<>();
225         for (YangTextSchemaSource s : sources) {
226             try (Reader reader = s.asCharSource(StandardCharsets.UTF_8).openStream()) {
227                 final String contents = CharStreams.toString(reader);
228                 byContent.putIfAbsent(contents, s);
229             }
230         }
231         return byContent.values();
232     }
233
234     /**
235      * Call generate on every generator from plugin configuration.
236      */
237     @SuppressWarnings("checkstyle:illegalCatch")
238     private void generateSources(final ContextHolder context) throws MojoFailureException {
239         if (codeGenerators.size() == 0) {
240             LOG.warn("{} No code generators provided", LOG_PREFIX);
241             return;
242         }
243
244         final Map<String, String> thrown = new HashMap<>();
245         for (CodeGeneratorArg codeGenerator : codeGenerators) {
246             try {
247                 generateSourcesWithOneGenerator(context, codeGenerator);
248             } catch (Exception e) {
249                 // try other generators, exception will be thrown after
250                 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
251                         .getCodeGeneratorClass(), e);
252                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
253             }
254         }
255
256         if (!thrown.isEmpty()) {
257             String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
258             LOG.error("{}{}{}", LOG_PREFIX, message, thrown.toString());
259             throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
260         }
261     }
262
263     /**
264      * Instantiate generator from class and call required method.
265      */
266     private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
267             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
268
269         codeGeneratorCfg.check();
270
271         final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
272         LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
273
274         final File outputDir = requireNonNull(codeGeneratorCfg.getOutputBaseDir(project),
275             "outputBaseDir is null. Please provide a valid outputBaseDir value in pom.xml");
276
277         project.addCompileSourceRoot(outputDir.getAbsolutePath());
278
279         LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
280         LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
281         LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
282                         .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
283
284         if (g instanceof BuildContextAware) {
285             ((BuildContextAware)g).setBuildContext(buildContext);
286         }
287         if (g instanceof MavenProjectAware) {
288             ((MavenProjectAware)g).setMavenProject(project);
289         }
290         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
291         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
292
293         YangProvider.setResource(resourceBaseDir, project);
294         g.setResourceBaseDir(resourceBaseDir);
295         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
296                 codeGeneratorCfg.getCodeGeneratorClass());
297
298         if (outputDir.exists()) {
299             Files.walk(outputDir.toPath()).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
300             LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
301         }
302         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
303             context::moduleToResourcePath);
304
305         LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
306     }
307
308     /**
309      * Instantiate object from fully qualified class name.
310      */
311     private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
312             ClassNotFoundException, InstantiationException, IllegalAccessException {
313         final Class<?> clazz = Class.forName(codeGeneratorClass);
314
315         Preconditions.checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz,
316             baseType);
317         return baseType.cast(clazz.newInstance());
318     }
319 }