BUG-865: remove MavenLogAware and CodeGenerator
[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.collect.Maps;
12 import java.io.Closeable;
13 import java.io.File;
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.HashSet;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Set;
23 import java.util.concurrent.ConcurrentMap;
24 import org.apache.commons.io.IOUtils;
25 import org.apache.maven.model.Resource;
26 import org.apache.maven.plugin.MojoExecutionException;
27 import org.apache.maven.plugin.MojoFailureException;
28 import org.apache.maven.plugin.logging.Log;
29 import org.apache.maven.project.MavenProject;
30 import org.opendaylight.yangtools.yang.model.api.Module;
31 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
32 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
33 import org.opendaylight.yangtools.yang.parser.repo.URLSchemaContextResolver;
34 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
35 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
36 import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
37 import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
38 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
39 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
40 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
41 import org.sonatype.plexus.build.incremental.BuildContext;
42 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
43
44 class YangToSourcesProcessor {
45     static final String LOG_PREFIX = "yang-to-sources:";
46     static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
47     static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
48
49     private final Log log;
50     private final File yangFilesRootDir;
51     private final File[] excludedFiles;
52     private final List<CodeGeneratorArg> codeGenerators;
53     private final MavenProject project;
54     private final boolean inspectDependencies;
55     private final BuildContext buildContext;
56     private final YangProvider yangProvider;
57     private final URLSchemaContextResolver resolver;
58
59     @VisibleForTesting
60     YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
61             MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
62         this(new DefaultBuildContext(), log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, yangProvider);
63     }
64
65     private YangToSourcesProcessor(BuildContext buildContext,  Log log, File yangFilesRootDir, File[] excludedFiles,
66             List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
67         this.buildContext = Util.checkNotNull(buildContext, "buildContext");
68         this.log = Util.checkNotNull(log, "log");
69         this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
70         this.excludedFiles = new File[excludedFiles.length];
71         int i = 0;
72         for (File file : excludedFiles) {
73             this.excludedFiles[i++] = new File(file.getPath());
74         }
75         this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
76         this.project = Util.checkNotNull(project, "project");
77         this.inspectDependencies = inspectDependencies;
78         this.yangProvider = yangProvider;
79         this.resolver = URLSchemaContextResolver.create("maven-plugin");
80     }
81
82     YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
83             MavenProject project, boolean inspectDependencies) {
84         this(log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
85     }
86
87     public void execute() throws MojoExecutionException, MojoFailureException {
88         ContextHolder context = processYang();
89         if (context != null) {
90             generateSources(context);
91             yangProvider.addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles);
92         }
93     }
94
95     private ContextHolder processYang() throws MojoExecutionException {
96         YangParserImpl parser = new YangParserImpl();
97         List<Closeable> closeables = new ArrayList<>();
98         log.info(Util.message("Inspecting %s", LOG_PREFIX, yangFilesRootDir));
99         try {
100             /*
101              * Collect all files which affect YANG context. This includes all
102              * files in current project and optionally any jars/files in the
103              * dependencies.
104              */
105             final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles, log);
106
107
108             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
109             if (inspectDependencies) {
110                 allFiles.addAll(Util.findYangFilesInDependencies(log, project));
111             }
112
113             if (allFiles.isEmpty()) {
114                 log.info(Util.message("No input files found", LOG_PREFIX));
115                 return null;
116             }
117
118             /*
119              * Check if any of the listed files changed. If no changes occurred,
120              * simply return null, which indicates and of execution.
121              */
122             boolean noChange = true;
123             for (final File f : allFiles) {
124                 if (buildContext.hasDelta(f)) {
125                     log.debug(Util.message("buildContext %s indicates %s changed, forcing regeneration", LOG_PREFIX, buildContext, f));
126                     noChange = false;
127                 }
128             }
129
130             if (noChange) {
131                 log.info(Util.message("None of %s input files changed", LOG_PREFIX, allFiles.size()));
132                 return null;
133             }
134
135             final List<InputStream> yangsInProject = new ArrayList<>();
136             for (final File f : yangFilesInProject) {
137                 // FIXME: This is hack - normal path should be reported.
138                 yangsInProject.add(new NamedFileInputStream(f, META_INF_YANG_STRING + File.separator + f.getName()));
139             }
140
141             List<InputStream> all = new ArrayList<>(yangsInProject);
142             closeables.addAll(yangsInProject);
143             Map<InputStream, Module> allYangModules;
144
145             /**
146              * Set contains all modules generated from input sources. Number of
147              * modules may differ from number of sources due to submodules
148              * (parsed submodule's data are added to its parent module). Set
149              * cannot contains null values.
150              */
151             Set<Module> projectYangModules;
152             try {
153                 if (inspectDependencies) {
154                     YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
155                     Closeable dependentYangResult1 = dependentYangResult;
156                     closeables.add(dependentYangResult1);
157                     List<InputStream> yangStreams = toStreamsWithoutDuplicates(dependentYangResult.getYangStreams());
158                     all.addAll(yangStreams);
159                     closeables.addAll(yangStreams);
160                 }
161
162                 allYangModules = parser.parseYangModelsFromStreamsMapped(all);
163
164                 projectYangModules = new HashSet<>();
165                 for (InputStream inProject : yangsInProject) {
166                     Module module = allYangModules.get(inProject);
167                     if (module != null) {
168                         projectYangModules.add(module);
169                     }
170                 }
171
172             } finally {
173                 for (AutoCloseable closeable : closeables) {
174                     closeable.close();
175                 }
176             }
177
178             Set<Module> parsedAllYangModules = new HashSet<>(allYangModules.values());
179             SchemaContext resolveSchemaContext = parser.resolveSchemaContext(parsedAllYangModules);
180             log.info(Util.message("%s files parsed from %s", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject));
181             return new ContextHolder(resolveSchemaContext, projectYangModules);
182
183             // MojoExecutionException is thrown since execution cannot continue
184         } catch (Exception e) {
185             String message = Util.message("Unable to parse %s files from %s", LOG_PREFIX, Util.YANG_SUFFIX,
186                     yangFilesRootDir);
187             log.error(message, e);
188             throw new MojoExecutionException(message, e);
189         }
190     }
191
192     private List<InputStream> toStreamsWithoutDuplicates(List<YangSourceFromDependency> list) throws IOException {
193         ConcurrentMap<String, YangSourceFromDependency> byContent = Maps.newConcurrentMap();
194
195         for (YangSourceFromDependency yangFromDependency : list) {
196             try (InputStream dataStream = yangFromDependency.openStream()) {
197                 String contents = IOUtils.toString(dataStream);
198                 byContent.putIfAbsent(contents, yangFromDependency);
199             }
200
201         }
202         List<InputStream> inputs = new ArrayList<>(byContent.size());
203         for (YangSourceFromDependency entry : byContent.values()) {
204             inputs.add(entry.openStream());
205         }
206         return inputs;
207     }
208
209     static class YangProvider {
210
211         void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
212                 throws MojoFailureException {
213
214             // copy project's src/main/yang/*.yang to target/generated-sources/yang/META-INF/yang/*.yang
215
216             File generatedYangDir = new File(project.getBasedir(), CodeGeneratorArg.YANG_GENERATED_DIR);
217             addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, generatedYangDir);
218
219             // Also copy to the actual build output dir if different than "target". When running in
220             // Eclipse this can differ (eg "target-ide").
221
222             File actualGeneratedYangDir = new File(project.getBuild().getDirectory(),
223                     CodeGeneratorArg.YANG_GENERATED_DIR.replace("target" + File.separator, ""));
224             if(!actualGeneratedYangDir.equals(generatedYangDir)) {
225                 addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles, actualGeneratedYangDir);
226             }
227         }
228
229         private void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir,
230                 File[] excludedFiles, File generatedYangDir)
231                 throws MojoFailureException {
232
233             File withMetaInf = new File(generatedYangDir, META_INF_YANG_STRING);
234             withMetaInf.mkdirs();
235
236             try {
237                 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, log);
238                 for (File file : files) {
239                     org.apache.commons.io.FileUtils.copyFile(file, new File(withMetaInf, file.getName()));
240                 }
241             } catch (IOException e) {
242                 log.warn(String.format("Failed to generate files into root %s", yangFilesRootDir), e);
243                 throw new MojoFailureException("Unable to list yang files into resource folder", e);
244             }
245
246             setResource(generatedYangDir, project);
247
248             log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
249                     META_INF_YANG_STRING_JAR));
250         }
251
252         private static void setResource(File targetYangDir, MavenProject project) {
253             Resource res = new Resource();
254             res.setDirectory(targetYangDir.getPath());
255             project.addResource(res);
256         }
257     }
258
259     /**
260      * Call generate on every generator from plugin configuration
261      */
262     private void generateSources(ContextHolder context) throws MojoFailureException {
263         if (codeGenerators.size() == 0) {
264             log.warn(Util.message("No code generators provided", LOG_PREFIX));
265             return;
266         }
267
268         Map<String, String> thrown = Maps.newHashMap();
269         for (CodeGeneratorArg codeGenerator : codeGenerators) {
270             try {
271                 generateSourcesWithOneGenerator(context, codeGenerator);
272             } catch (Exception e) {
273                 // try other generators, exception will be thrown after
274                 log.error(
275                         Util.message("Unable to generate sources with %s generator", LOG_PREFIX,
276                                 codeGenerator.getCodeGeneratorClass()), e);
277                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
278             }
279         }
280
281         if (!thrown.isEmpty()) {
282             String message = Util.message(
283                     "One or more code generators failed, including failed list(generatorClass=exception) %s",
284                     LOG_PREFIX, thrown.toString());
285             log.error(message);
286             throw new MojoFailureException(message);
287         }
288     }
289
290     /**
291      * Instantiate generator from class and call required method
292      */
293     private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
294             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
295
296         codeGeneratorCfg.check();
297
298         BasicCodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), BasicCodeGenerator.class);
299         log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX,
300                 codeGeneratorCfg.getCodeGeneratorClass()));
301
302         File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
303
304         if (outputDir != null) {
305           project.addCompileSourceRoot(outputDir.getAbsolutePath());
306         } else {
307           throw new NullPointerException("outputBaseDir is null. Please provide a valid outputBaseDir value in the pom.xml");
308         }
309
310         log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir));
311         log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir()));
312         log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
313                 codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
314
315         if (g instanceof BuildContextAware) {
316             ((BuildContextAware)g).setBuildContext(buildContext);
317         }
318         if (g instanceof MavenProjectAware) {
319             ((MavenProjectAware)g).setMavenProject(project);
320         }
321         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
322         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
323
324         YangProvider.setResource(resourceBaseDir, project);
325         g.setResourceBaseDir(resourceBaseDir);
326         log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir,
327                 codeGeneratorCfg.getCodeGeneratorClass()));
328
329         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
330
331         log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),
332                 generated));
333     }
334
335 }