Enforce checkstyle in maven-plugin
[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.Closeable;
17 import java.io.File;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.Reader;
21 import java.nio.charset.StandardCharsets;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
29 import org.apache.maven.plugin.MojoExecutionException;
30 import org.apache.maven.plugin.MojoFailureException;
31 import org.apache.maven.project.MavenProject;
32 import org.codehaus.plexus.util.FileUtils;
33 import org.opendaylight.yangtools.yang.model.api.Module;
34 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
35 import org.opendaylight.yangtools.yang.parser.repo.YangTextSchemaContextResolver;
36 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
37 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
38 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
39 import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
40 import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
41 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
42 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
43 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.sonatype.plexus.build.incremental.BuildContext;
47 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
48
49 class YangToSourcesProcessor {
50     private static final Logger LOG = LoggerFactory.getLogger(YangToSourcesProcessor.class);
51
52     static final String LOG_PREFIX = "yang-to-sources:";
53     static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
54     static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
55     static final String META_INF_YANG_SERVICES_STRING_JAR = "META-INF" + "/" + "services";
56
57     private final File yangFilesRootDir;
58     private final Set<File> excludedFiles;
59     private final List<CodeGeneratorArg> codeGenerators;
60     private final MavenProject project;
61     private final boolean inspectDependencies;
62     private final BuildContext buildContext;
63     private final YangProvider yangProvider;
64     private final YangTextSchemaContextResolver resolver;
65
66     @VisibleForTesting
67     YangToSourcesProcessor(final File yangFilesRootDir, final Collection<File> excludedFiles,
68             final List<CodeGeneratorArg> codeGenerators, final MavenProject project, final boolean inspectDependencies,
69             final YangProvider yangProvider) {
70         this(new DefaultBuildContext(), yangFilesRootDir, excludedFiles, codeGenerators, project,
71                 inspectDependencies, yangProvider);
72     }
73
74     private YangToSourcesProcessor(final BuildContext buildContext, final File yangFilesRootDir,
75             final Collection<File> excludedFiles, final List<CodeGeneratorArg> codeGenerators,
76             final MavenProject project, final boolean inspectDependencies, final YangProvider yangProvider) {
77         this.buildContext = Preconditions.checkNotNull(buildContext, "buildContext");
78         this.yangFilesRootDir = Preconditions.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
79         this.excludedFiles = ImmutableSet.copyOf(excludedFiles);
80         this.codeGenerators = ImmutableList.copyOf(codeGenerators);
81         this.project = Preconditions.checkNotNull(project);
82         this.inspectDependencies = inspectDependencies;
83         this.yangProvider = yangProvider;
84         this.resolver = YangTextSchemaContextResolver.create("maven-plugin");
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, new YangProvider());
91     }
92
93     public void execute() throws MojoExecutionException, MojoFailureException {
94         ContextHolder context = processYang();
95         if (context != null) {
96             generateSources(context);
97             yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
98         }
99     }
100
101     void conditionalExecute(final boolean skip) throws MojoExecutionException, MojoFailureException {
102         if (skip) {
103             LOG.info("Skipping YANG code generation because property yang.skip is true");
104
105             // But manually add resources
106             // add META_INF/yang
107             yangProvider.addYangsToMetaInf(project, yangFilesRootDir, excludedFiles);
108
109             // add META_INF/services
110             File generatedServicesDir = new GeneratedDirectories(project).getYangServicesDir();
111             YangProvider.setResource(generatedServicesDir, project);
112             LOG.debug("{} Yang services files from: {} marked as resources: {}", LOG_PREFIX, generatedServicesDir,
113                     META_INF_YANG_SERVICES_STRING_JAR);
114
115
116         } else {
117             execute();
118         }
119     }
120
121     @SuppressWarnings("checkstyle:illegalCatch")
122     private ContextHolder processYang() throws MojoExecutionException {
123         SchemaContext resolveSchemaContext;
124         List<Closeable> closeables = new ArrayList<>();
125         LOG.info("{} Inspecting {}", LOG_PREFIX, yangFilesRootDir);
126         try {
127             /*
128              * Collect all files which affect YANG context. This includes all
129              * files in current project and optionally any jars/files in the
130              * dependencies.
131              */
132             final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles);
133
134             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
135             if (inspectDependencies) {
136                 allFiles.addAll(Util.findYangFilesInDependencies(project));
137             }
138
139             if (allFiles.isEmpty()) {
140                 LOG.info("{} No input files found", LOG_PREFIX);
141                 return null;
142             }
143
144             /*
145              * Check if any of the listed files changed. If no changes occurred,
146              * simply return null, which indicates and of execution.
147              */
148             boolean noChange = true;
149             for (final File f : allFiles) {
150                 if (buildContext.hasDelta(f)) {
151                     LOG.debug("{} buildContext {} indicates {} changed, forcing regeneration", LOG_PREFIX,
152                             buildContext, f);
153                     noChange = false;
154                 }
155             }
156
157             if (noChange) {
158                 LOG.info("{} None of {} input files changed", LOG_PREFIX, allFiles.size());
159                 return null;
160             }
161
162             final List<NamedFileInputStream> yangsInProject = new ArrayList<>();
163             for (final File f : yangFilesInProject) {
164                 // FIXME: This is hack - normal path should be reported.
165                 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
166             }
167
168             List<InputStream> all = new ArrayList<>();
169             all.addAll(yangsInProject);
170             closeables.addAll(yangsInProject);
171
172             /**
173              * Set contains all modules generated from input sources. Number of
174              * modules may differ from number of sources due to submodules
175              * (parsed submodule's data are added to its parent module). Set
176              * cannot contains null values.
177              */
178             final Set<Module> projectYangModules = new HashSet<>();
179             final Set<Module> projectYangFiles = new HashSet<>();
180             try {
181                 if (inspectDependencies) {
182                     YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(project);
183                     Closeable dependentYangResult1 = dependentYangResult;
184                     closeables.add(dependentYangResult1);
185                     List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
186                     all.addAll(yangStreams);
187                     closeables.addAll(yangStreams);
188                 }
189
190                 resolveSchemaContext = YangParserTestUtils.parseYangStreams(all);
191
192                 Set<Module> parsedAllYangModules = resolveSchemaContext.getModules();
193                 for (Module module : parsedAllYangModules) {
194                     if (containedInFiles(yangsInProject, module)) {
195                         LOG.debug("Module {} belongs to current project", module);
196                         projectYangModules.add(module);
197                         projectYangFiles.add(module);
198
199                         for (Module sub : module.getSubmodules()) {
200                             if (containedInFiles(yangsInProject, sub)) {
201                                 LOG.debug("Submodule {} belongs to current project", sub);
202                                 projectYangFiles.add(sub);
203                             } else {
204                                 LOG.warn("Submodule {} not found in input files", sub);
205                             }
206                         }
207                     }
208                 }
209             } finally {
210                 for (AutoCloseable closeable : closeables) {
211                     closeable.close();
212                 }
213             }
214
215             LOG.info("{} {} files parsed from {}", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject);
216             LOG.debug("Project YANG files: {}", projectYangFiles);
217
218             return new ContextHolder(resolveSchemaContext, projectYangModules, projectYangFiles);
219
220             // MojoExecutionException is thrown since execution cannot continue
221         } catch (Exception e) {
222             LOG.error("{} Unable to parse {} files from {}", LOG_PREFIX, Util.YANG_SUFFIX, yangFilesRootDir, e);
223             Throwable rootCause = Throwables.getRootCause(e);
224             throw new MojoExecutionException(LOG_PREFIX + " Unable to parse " + Util.YANG_SUFFIX + " files from "
225                     + yangFilesRootDir, rootCause);
226         }
227     }
228
229     private static boolean containedInFiles(final List<NamedFileInputStream> files, final Module module) {
230         final String path = module.getModuleSourcePath();
231         if (path != null) {
232             LOG.debug("Looking for source {}", path);
233             for (NamedFileInputStream is : files) {
234                 LOG.debug("In project destination {}", is.getFileDestination());
235                 if (path.equals(is.getFileDestination())) {
236                     return true;
237                 }
238             }
239         }
240
241         return false;
242     }
243
244     private static List<InputStream> toStreamsWithoutDuplicates(final List<YangSourceFromDependency> list)
245             throws IOException {
246         final Map<String, YangSourceFromDependency> byContent = new HashMap<>();
247
248         for (YangSourceFromDependency yangFromDependency : list) {
249             try (Reader reader = yangFromDependency.asCharSource(StandardCharsets.UTF_8).openStream()) {
250                 final String contents = CharStreams.toString(reader);
251                 byContent.putIfAbsent(contents, yangFromDependency);
252             } catch (IOException e) {
253                 throw new IOException("Exception when reading from: " + yangFromDependency.getDescription(), e);
254             }
255
256         }
257         List<InputStream> inputs = new ArrayList<>(byContent.size());
258         for (YangSourceFromDependency entry : byContent.values()) {
259             inputs.add(entry.openStream());
260         }
261         return inputs;
262     }
263
264     /**
265      * Call generate on every generator from plugin configuration.
266      */
267     @SuppressWarnings("checkstyle:illegalCatch")
268     private void generateSources(final ContextHolder context) throws MojoFailureException {
269         if (codeGenerators.size() == 0) {
270             LOG.warn("{} No code generators provided", LOG_PREFIX);
271             return;
272         }
273
274         final Map<String, String> thrown = new HashMap<>();
275         for (CodeGeneratorArg codeGenerator : codeGenerators) {
276             try {
277                 generateSourcesWithOneGenerator(context, codeGenerator);
278             } catch (Exception e) {
279                 // try other generators, exception will be thrown after
280                 LOG.error("{} Unable to generate sources with {} generator", LOG_PREFIX, codeGenerator
281                         .getCodeGeneratorClass(), e);
282                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
283             }
284         }
285
286         if (!thrown.isEmpty()) {
287             String message = " One or more code generators failed, including failed list(generatorClass=exception) ";
288             LOG.error("{}" + message + "{}", LOG_PREFIX, thrown.toString());
289             throw new MojoFailureException(LOG_PREFIX + message + thrown.toString());
290         }
291     }
292
293     /**
294      * Instantiate generator from class and call required method.
295      */
296     private void generateSourcesWithOneGenerator(final ContextHolder context, final CodeGeneratorArg codeGeneratorCfg)
297             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
298
299         codeGeneratorCfg.check();
300
301         final BasicCodeGenerator g = getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
302         LOG.info("{} Code generator instantiated from {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass());
303
304         final File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
305
306         if (outputDir == null) {
307             throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the "
308                     + "pom.xml");
309         }
310
311         project.addCompileSourceRoot(outputDir.getAbsolutePath());
312
313         LOG.info("{} Sources will be generated to {}", LOG_PREFIX, outputDir);
314         LOG.debug("{} Project root dir is {}", LOG_PREFIX, project.getBasedir());
315         LOG.debug("{} Additional configuration picked up for : {}: {}", LOG_PREFIX, codeGeneratorCfg
316                         .getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration());
317
318         if (g instanceof BuildContextAware) {
319             ((BuildContextAware)g).setBuildContext(buildContext);
320         }
321         if (g instanceof MavenProjectAware) {
322             ((MavenProjectAware)g).setMavenProject(project);
323         }
324         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
325         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
326
327         YangProvider.setResource(resourceBaseDir, project);
328         g.setResourceBaseDir(resourceBaseDir);
329         LOG.debug("{} Folder: {} marked as resources for generator: {}", LOG_PREFIX, resourceBaseDir,
330                 codeGeneratorCfg.getCodeGeneratorClass());
331
332         FileUtils.deleteDirectory(outputDir);
333         LOG.info("{} Succesfully deleted output directory {}", LOG_PREFIX, outputDir);
334
335         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules(),
336             context::moduleToResourcePath);
337
338         LOG.info("{} Sources generated by {}: {}", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(), generated);
339     }
340
341     /**
342      * Instantiate object from fully qualified class name.
343      */
344     private static <T> T getInstance(final String codeGeneratorClass, final Class<T> baseType) throws
345             ClassNotFoundException, InstantiationException, IllegalAccessException {
346         final Class<?> clazz = Class.forName(codeGeneratorClass);
347
348         Preconditions.checkArgument(baseType.isAssignableFrom(clazz), "Code generator %s has to implement %s", clazz,
349             baseType);
350         return baseType.cast(clazz.newInstance());
351     }
352 }