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