Merge "changed builder generator"
[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.YangsInZipsResult;
33 import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
34
35 import com.google.common.annotations.VisibleForTesting;
36 import com.google.common.collect.Maps;
37
38 class YangToSourcesProcessor {
39     static final String LOG_PREFIX = "yang-to-sources:";
40     static final String META_INF_YANG_STRING = "META-INF" + File.separator + "yang";
41     static final String META_INF_YANG_STRING_JAR = "META-INF" + "/" + "yang";
42     static final File META_INF_YANG_DIR = new File(META_INF_YANG_STRING);
43
44     private final Log log;
45     private final File yangFilesRootDir;
46     private final File[] excludedFiles;
47     private final List<CodeGeneratorArg> codeGenerators;
48     private final MavenProject project;
49     private final boolean inspectDependencies;
50     private YangProvider yangProvider;
51
52     @VisibleForTesting
53     YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
54             MavenProject project, boolean inspectDependencies, YangProvider yangProvider) {
55         this.log = Util.checkNotNull(log, "log");
56         this.yangFilesRootDir = Util.checkNotNull(yangFilesRootDir, "yangFilesRootDir");
57         this.excludedFiles = new File[excludedFiles.length];
58         int i = 0;
59         for (File file : excludedFiles) {
60             this.excludedFiles[i++] = new File(file.getPath());
61         }
62         this.codeGenerators = Collections.unmodifiableList(Util.checkNotNull(codeGenerators, "codeGenerators"));
63         this.project = Util.checkNotNull(project, "project");
64         this.inspectDependencies = inspectDependencies;
65         this.yangProvider = yangProvider;
66     }
67
68     YangToSourcesProcessor(Log log, File yangFilesRootDir, File[] excludedFiles, List<CodeGeneratorArg> codeGenerators,
69             MavenProject project, boolean inspectDependencies) {
70         this(log, yangFilesRootDir, excludedFiles, codeGenerators, project, inspectDependencies, new YangProvider());
71     }
72
73     public void execute() throws MojoExecutionException, MojoFailureException {
74         ContextHolder context = processYang();
75         generateSources(context);
76         yangProvider.addYangsToMetaInf(log, project, yangFilesRootDir, excludedFiles);
77     }
78
79     private ContextHolder processYang() throws MojoExecutionException {
80         YangParserImpl parser = new YangParserImpl();
81         List<Closeable> closeables = new ArrayList<>();
82         log.info(Util.message("Inspecting %s", LOG_PREFIX, yangFilesRootDir));
83         try {
84             List<InputStream> yangsInProject = Util.listFilesAsStream(yangFilesRootDir, excludedFiles, log);
85             List<InputStream> all = new ArrayList<>(yangsInProject);
86             closeables.addAll(yangsInProject);
87             Map<InputStream, Module> allYangModules;
88             Set<Module> projectYangModules;
89             try {
90                 if (inspectDependencies) {
91                     YangsInZipsResult dependentYangResult = Util.findYangFilesInDependenciesAsStream(log, project);
92                     Closeable dependentYangResult1 = dependentYangResult;
93                     closeables.add(dependentYangResult1);
94                     all.addAll(dependentYangResult.getYangStreams());
95                 }
96
97                 allYangModules = parser.parseYangModelsFromStreamsMapped(all);
98
99                 projectYangModules = new HashSet<>();
100                 for (InputStream inProject : yangsInProject) {
101                     projectYangModules.add(allYangModules.get(inProject));
102                 }
103
104             } finally {
105                 for (AutoCloseable closeable : closeables) {
106                     closeable.close();
107                 }
108             }
109
110             Set<Module> parsedAllYangModules = new HashSet<>(allYangModules.values());
111             SchemaContext resolveSchemaContext = parser.resolveSchemaContext(parsedAllYangModules);
112             log.info(Util.message("%s files parsed from %s", LOG_PREFIX, Util.YANG_SUFFIX.toUpperCase(), yangsInProject));
113             return new ContextHolder(resolveSchemaContext, projectYangModules);
114
115             // MojoExecutionException is thrown since execution cannot continue
116         } catch (Exception e) {
117             String message = Util.message("Unable to parse %s files from %s", LOG_PREFIX, Util.YANG_SUFFIX,
118                     yangFilesRootDir);
119             log.error(message, e);
120             throw new MojoExecutionException(message, e);
121         }
122     }
123
124     static class YangProvider {
125
126         private static final String YANG_RESOURCE_DIR = "target" + File.separator + "yang";
127
128         void addYangsToMetaInf(Log log, MavenProject project, File yangFilesRootDir, File[] excludedFiles)
129                 throws MojoFailureException {
130             File targetYangDir = new File(project.getBasedir(), YANG_RESOURCE_DIR);
131
132             try {
133                 Collection<File> files = Util.listFiles(yangFilesRootDir, excludedFiles, null);
134                 for (File file : files) {
135                     org.apache.commons.io.FileUtils.copyFile(file, new File(targetYangDir, file.getName()));
136                 }
137             } catch (IOException e) {
138                 String message = "Unable to list yang files into resource folder";
139                 log.warn(message, e);
140                 throw new MojoFailureException(message, e);
141             }
142
143             setResource(targetYangDir, META_INF_YANG_STRING_JAR, project);
144
145             log.debug(Util.message("Yang files from: %s marked as resources: %s", LOG_PREFIX, yangFilesRootDir,
146                     META_INF_YANG_STRING_JAR));
147         }
148
149         private static void setResource(File targetYangDir, String targetPath, MavenProject project) {
150             Resource res = new Resource();
151             res.setDirectory(targetYangDir.getPath());
152             if (targetPath != null) {
153                 res.setTargetPath(targetPath);
154             }
155             project.addResource(res);
156         }
157     }
158
159     /**
160      * Call generate on every generator from plugin configuration
161      */
162     private void generateSources(ContextHolder context) throws MojoFailureException {
163         if (codeGenerators.size() == 0) {
164             log.warn(Util.message("No code generators provided", LOG_PREFIX));
165             return;
166         }
167
168         Map<String, String> thrown = Maps.newHashMap();
169         for (CodeGeneratorArg codeGenerator : codeGenerators) {
170             try {
171                 generateSourcesWithOneGenerator(context, codeGenerator);
172             } catch (Exception e) {
173                 // try other generators, exception will be thrown after
174                 log.error(
175                         Util.message("Unable to generate sources with %s generator", LOG_PREFIX,
176                                 codeGenerator.getCodeGeneratorClass()), e);
177                 thrown.put(codeGenerator.getCodeGeneratorClass(), e.getClass().getCanonicalName());
178             }
179         }
180
181         if (!thrown.isEmpty()) {
182             String message = Util.message(
183                     "One or more code generators failed, including failed list(generatorClass=exception) %s",
184                     LOG_PREFIX, thrown.toString());
185             log.error(message);
186             throw new MojoFailureException(message);
187         }
188     }
189
190     /**
191      * Instantiate generator from class and call required method
192      */
193     private void generateSourcesWithOneGenerator(ContextHolder context, CodeGeneratorArg codeGeneratorCfg)
194             throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
195
196         codeGeneratorCfg.check();
197
198         CodeGenerator g = Util.getInstance(codeGeneratorCfg.getCodeGeneratorClass(), CodeGenerator.class);
199         log.info(Util.message("Code generator instantiated from %s", LOG_PREFIX,
200                 codeGeneratorCfg.getCodeGeneratorClass()));
201
202         File outputDir = codeGeneratorCfg.getOutputBaseDir(project);
203
204         log.info(Util.message("Sources will be generated to %s", LOG_PREFIX, outputDir));
205         log.debug(Util.message("Project root dir is %s", LOG_PREFIX, project.getBasedir()));
206         log.debug(Util.message("Additional configuration picked up for : %s: %s", LOG_PREFIX,
207                 codeGeneratorCfg.getCodeGeneratorClass(), codeGeneratorCfg.getAdditionalConfiguration()));
208
209         if (outputDir != null) {
210             project.addCompileSourceRoot(outputDir.getAbsolutePath());
211         }
212         g.setLog(log);
213         g.setMavenProject(project);
214         g.setAdditionalConfig(codeGeneratorCfg.getAdditionalConfiguration());
215         File resourceBaseDir = codeGeneratorCfg.getResourceBaseDir(project);
216
217         YangProvider.setResource(resourceBaseDir, null, project);
218         g.setResourceBaseDir(resourceBaseDir);
219         log.debug(Util.message("Folder: %s marked as resources for generator: %s", LOG_PREFIX, resourceBaseDir,
220                 codeGeneratorCfg.getCodeGeneratorClass()));
221
222         Collection<File> generated = g.generateSources(context.getContext(), outputDir, context.getYangModules());
223
224         log.info(Util.message("Sources generated by %s: %s", LOG_PREFIX, codeGeneratorCfg.getCodeGeneratorClass(),
225                 generated));
226     }
227
228 }