Merge "Added wildcarded contains to InstanceIdentifier"
[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 java.io.Closeable;
11 import java.io.File;
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.HashSet;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Set;
21
22 import org.apache.maven.model.Resource;
23 import org.apache.maven.plugin.MojoExecutionException;
24 import org.apache.maven.plugin.MojoFailureException;
25 import org.apache.maven.plugin.logging.Log;
26 import org.apache.maven.project.MavenProject;
27 import org.opendaylight.yangtools.yang.model.api.Module;
28 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
29 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
30 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
31 import org.opendaylight.yangtools.yang2sources.plugin.Util.ContextHolder;
32 import org.opendaylight.yangtools.yang2sources.plugin.Util.NamedFileInputStream;
33 import org.opendaylight.yangtools.yang2sources.plugin.Util.YangsInZipsResult;
34 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
35 import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
36 import org.sonatype.plexus.build.incremental.BuildContext;
37 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
38
39 import com.google.common.annotations.VisibleForTesting;
40 import com.google.common.collect.Maps;
41
42 class YangToSourcesProcessor {
43     static final String LOG_PREFIX = "yang-to-sources:";
44     static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
45     static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
46     static final File META_INF_YANG_DIR = new File(META_INF_YANG_STRING);
47
48     private final Log log;
49     private final File yangFilesRootDir;
50     private final File[] excludedFiles;
51     private final List<CodeGeneratorArg> codeGenerators;
52     private final MavenProject project;
53     private final boolean inspectDependencies;
54     private final BuildContext buildContext;
55     private YangProvider yangProvider;
56
57     @VisibleForTesting
58     YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
59             MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
60         this(new DefaultBuildContext(), log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, yangProvider);
61     }
62
63     private YangToSourcesProcessor(BuildContext buildContext,  Log log, File yangFilesRootDir, File[] excludedFiles,
64             List<CodeGeneratorArg> codeGenerators, MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
65         this.buildContext = Util.checkNotNull(buildContext, "buildContext");
66         this.log = Util.checkNotNull(log, "log");
67         this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
68         this.excludedFiles = new File[excludedFiles.length];
69         int i = 0;
70         for (File file : excludedFiles) {
71             this.excludedFiles[i++] = new File(file.getPath());
72         }
73         this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
74         this.project = Util.checkNotNull(project, "project");
75         this.inspectDependencies = inspectDependencies;
76         this.yangProvider = yangProvider;
77     }
78
79     YangToSourcesProcessor(BuildContext buildContext, Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
80             MavenProject project, boolean inspectDependencies) {
81         this(log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
82     }
83
84     public void execute() throws MojoExecutionException, MojoFailureException {
85         ContextHolder context = processYang();
86         if (context != null) {
87             generateSources(context);
88             yangProvider.addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles);
89         }
90     }
91
92     private ContextHolder processYang() throws MojoExecutionException {
93         YangParserImpl parser = new YangParserImpl();
94         List<Closeable> closeables = new ArrayList<>();
95         log.info(Util.message("Inspecting %s", LOG_PREFIX, yangFilesRootDir));
96         try {
97             /*
98              * Collect all files which affect YANG context. This includes all
99              * files in current project and optionally any jars/files in the
100              * dependencies.
101              */
102             final Collection<File> yangFilesInProject = Util.listFiles(yangFilesRootDir, excludedFiles, log);
103             final Collection<File> allFiles = new ArrayList<>(yangFilesInProject);
104             if (inspectDependencies) {
105                 allFiles.addAll(Util.findYangFilesInDependencies(log, project));
106             }
107
108             if (allFiles.isEmpty()) {
109                 log.info(Util.message("No input files found", LOG_PREFIX));
110                 return null;
111             }
112             
113             /*
114              * Check if any of the listed files changed. If no changes occurred,
115              * simply return null, which indicates and of execution.
116              */
117             boolean noChange = true;
118             for (final File f : allFiles) {
119                 if (buildContext.hasDelta(f)) {
120                     log.debug(Util.message("buildContext %s indicates %s changed, forcing regeneration", LOG_PREFIX, buildContext, f));
121                     noChange = false;
122                 }
123             }
124
125             if (noChange) {
126                 log.info(Util.message("None of %s input files changed", LOG_PREFIX, allFiles.size()));
127                 return null;
128             }
129
130             final List<InputStream> yangsInProject = new ArrayList<>();
131             for (final File f : yangFilesInProject) {
132                 yangsInProject.add(new NamedFileInputStream(f));
133             }
134
135             List<InputStream> all = new ArrayList<>(yangsInProject);
136             closeables.addAll(yangsInProject);
137             Map<InputStream, Module> allYangModules;
138             Set<Module> projectYangModules;
139             try {
140                 if (inspectDependencies) {
141                     YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
142                     Closeable dependentYangResult1 = dependentYangResult;
143                     closeables.add(dependentYangResult1);
144                     all.addAll(dependentYangResult.getYangStreams());
145                 }
146
147                 allYangModules = parser.parseYangModelsFromStreamsMapped(all);
148
149                 projectYangModules = new HashSet<>();
150                 for (InputStream inProject : yangsInProject) {
151                     projectYangModules.add(allYangModules.get(inProject));
152                 }
153
154             } finally {
155                 for (AutoCloseable closeable : closeables) {
156                     closeable.close();
157                 }
158             }
159
160             Set<Module> parsedAllYangModules = new HashSet<>(allYangModules.values());
161             SchemaContext resolveSchemaContext = parser.resolveSchemaContext(parsedAllYangModules);
162             log.info(Util.message("%s files parsed from %s", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject));
163             return new ContextHolder(resolveSchemaContext, projectYangModules);
164
165             // MojoExecutionException is thrown since execution cannot continue
166         } catch (Exception e) {
167             String message = Util.message("Unable to parse %s files from %s", LOG_PREFIX, Util.YANG_SUFFIX,
168                     yangFilesRootDir);
169             log.error(message, e);
170             throw new MojoExecutionException(message, e);
171         }
172     }
173
174     static class YangProvider {
175
176         private static final String YANG_RESOURCE_DIR = "target" + File.separator + "yang";
177
178         void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
179                 throws MojoFailureException {
180             File targetYangDir = new File(project.getBasedir(), YANG_RESOURCE_DIR);
181
182             try {
183                 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, null);
184                 for (File file : files) {
185                     org.apache.commons.io.FileUtils.copyFile(file, new File(targetYangDir, file.getName()));
186                 }
187             } catch (IOException e) {
188                 String message = "Unable to list yang files into resource folder";
189                 log.warn(message, e);
190                 throw new MojoFailureException(message, e);
191             }
192
193             setResource(targetYangDir, META_INF_YANG_STRING_JAR, project);
194
195             log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
196                     META_INF_YANG_STRING_JAR));
197         }
198
199         private static void setResource(File targetYangDir, String targetPath, MavenProject project) {
200             Resource res = new Resource();
201             res.setDirectory(targetYangDir.getPath());
202             if (targetPath != null) {
203                 res.setTargetPath(targetPath);
204             }
205             project.addResource(res);
206         }
207     }
208
209     /**
210      * Call generate on every generator from plugin configuration
211      */
212     private void generateSources(ContextHolder context) throws MojoFailureException {
213         if (codeGenerators.size() == 0) {
214             log.warn(Util.message("No code generators provided", LOG_PREFIX));
215             return;
216         }
217
218         Map<String, String> thrown = Maps.newHashMap();
219         for (CodeGeneratorArg codeGenerator : codeGenerators) {
220             try {
221                 generateSourcesWithOneGenerator(context, codeGenerator);
222             } catch (Exception e) {
223                 // try other generators, exception will be thrown after
224                 log.error(
225                         Util.message("Unable to generate sources with %s generator", LOG_PREFIX,
226                                 codeGenerator.getCodeGeneratorClass()), e);
227                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
228             }
229         }
230
231         if (!thrown.isEmpty()) {
232             String message = Util.message(
233                     "One or more code generators failed, including failed list(generatorClass=exception) %s",
234                     LOG_PREFIX, thrown.toString());
235             log.error(message);
236             throw new MojoFailureException(message);
237         }
238     }
239
240     /**
241      * Instantiate generator from class and call required method
242      */
243     private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
244             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
245
246         codeGeneratorCfg.check();
247
248         CodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), CodeGenerator.class);
249         log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX,
250                 codeGeneratorCfg.getCodeGeneratorClass()));
251
252         File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
253
254         log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir));
255         log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir()));
256         log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
257                 codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
258
259         if (outputDir != null) {
260             project.addCompileSourceRoot(outputDir.getAbsolutePath());
261         }
262
263         if (g instanceof BuildContextAware) {
264             ((BuildContextAware)g).setBuildContext(buildContext);
265         }
266         g.setLog(log);
267         g.setMavenProject(project);
268         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
269         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
270
271         YangProvider.setResource(resourceBaseDir, null, project);
272         g.setResourceBaseDir(resourceBaseDir);
273         log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir,
274                 codeGeneratorCfg.getCodeGeneratorClass()));
275
276         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
277
278         log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),
279                 generated));
280     }
281
282 }