BUG-7013: do not rely on default character encoding
[mdsal.git] / binding / maven-sal-api-gen-plugin / src / main / java / org / opendaylight / yangtools / maven / sal / api / gen / plugin / CodeGeneratorImpl.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.maven.sal.api.gen.plugin;
9
10 import com.google.common.base.Joiner;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableSet;
13 import com.google.common.collect.ImmutableSet.Builder;
14 import java.io.BufferedWriter;
15 import java.io.File;
16 import java.io.IOException;
17 import java.io.OutputStream;
18 import java.io.OutputStreamWriter;
19 import java.io.Writer;
20 import java.nio.charset.StandardCharsets;
21 import java.util.Collection;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25 import org.apache.maven.project.MavenProject;
26 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
27 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
28 import org.opendaylight.yangtools.sal.binding.generator.impl.BindingGeneratorImpl;
29 import org.opendaylight.yangtools.sal.binding.model.api.Type;
30 import org.opendaylight.yangtools.sal.java.api.generator.GeneratorJavaFile;
31 import org.opendaylight.yangtools.sal.java.api.generator.YangModuleInfoTemplate;
32 import org.opendaylight.yangtools.yang.binding.BindingMapping;
33 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
34 import org.opendaylight.yangtools.yang.model.api.Module;
35 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
36 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
37 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
38 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.sonatype.plexus.build.incremental.BuildContext;
42
43 public final class CodeGeneratorImpl implements BasicCodeGenerator, BuildContextAware, MavenProjectAware {
44     private static final Logger LOG = LoggerFactory.getLogger(CodeGeneratorImpl.class);
45     private static final String FS = File.separator;
46     private BuildContext buildContext;
47     private File projectBaseDir;
48     private Map<String, String> additionalConfig;
49     private MavenProject mavenProject;
50     private File resourceBaseDir;
51
52     @Override
53     public Collection<File> generateSources(final SchemaContext context, final File outputDir,
54             final Set<Module> yangModules) throws IOException {
55         final File outputBaseDir;
56
57         outputBaseDir = outputDir == null ? getDefaultOutputBaseDir() : outputDir;
58
59         final BindingGenerator bindingGenerator = new BindingGeneratorImpl(true);
60         final List<Type> types = bindingGenerator.generateTypes(context, yangModules);
61         final GeneratorJavaFile generator = new GeneratorJavaFile(buildContext, types);
62
63         File persistentSourcesDir = null;
64         if (additionalConfig != null) {
65             String persistenSourcesPath = additionalConfig.get("persistentSourcesDir");
66             if (persistenSourcesPath != null) {
67                 persistentSourcesDir = new File(persistenSourcesPath);
68             }
69         }
70         if (persistentSourcesDir == null) {
71             persistentSourcesDir = new File(projectBaseDir, "src" + FS + "main" + FS + "java");
72         }
73
74         List<File> result = generator.generateToFile(outputBaseDir, persistentSourcesDir);
75
76         result.addAll(generateModuleInfos(outputBaseDir, yangModules, context));
77         return result;
78     }
79
80     private Collection<? extends File> generateModuleInfos(final File outputBaseDir, final Set<Module> yangModules,
81                                                            final SchemaContext context) {
82         Builder<File> result = ImmutableSet.builder();
83         Builder<String> bindingProviders = ImmutableSet.builder();
84         for (Module module : yangModules) {
85             Builder<String> currentProvidersBuilder = ImmutableSet.builder();
86             // TODO: do not mutate parameters, output of a method is defined by its return value
87             Set<File> moduleInfoProviders = generateYangModuleInfo(outputBaseDir, module, context, currentProvidersBuilder);
88             ImmutableSet<String> currentProviders = currentProvidersBuilder.build();
89             LOG.info("Adding ModuleInfo providers {}", currentProviders);
90             bindingProviders.addAll(currentProviders);
91             result.addAll(moduleInfoProviders);
92         }
93
94         result.add(writeMetaInfServices(resourceBaseDir, YangModelBindingProvider.class, bindingProviders.build()));
95         return result.build();
96     }
97
98     private File writeMetaInfServices(final File outputBaseDir, final Class<YangModelBindingProvider> serviceClass,
99             final ImmutableSet<String> services) {
100         File metainfServicesFolder = new File(outputBaseDir, "META-INF" + File.separator + "services");
101         metainfServicesFolder.mkdirs();
102         File serviceFile = new File(metainfServicesFolder, serviceClass.getName());
103
104         String src = Joiner.on('\n').join(services);
105
106         return writeFile(serviceFile, src);
107     }
108
109     public static final String DEFAULT_OUTPUT_BASE_DIR_PATH = "target" + File.separator + "generated-sources"
110             + File.separator + "maven-sal-api-gen";
111
112     private File getDefaultOutputBaseDir() {
113         File outputBaseDir;
114         outputBaseDir = new File(DEFAULT_OUTPUT_BASE_DIR_PATH);
115         setOutputBaseDirAsSourceFolder(outputBaseDir, mavenProject);
116         LOG.debug("Adding " + outputBaseDir.getPath() + " as compile source root");
117         return outputBaseDir;
118     }
119
120     private static void setOutputBaseDirAsSourceFolder(final File outputBaseDir, final MavenProject mavenProject) {
121         Preconditions.checkNotNull(mavenProject, "Maven project needs to be set in this phase");
122         mavenProject.addCompileSourceRoot(outputBaseDir.getPath());
123     }
124
125     @Override
126     public void setAdditionalConfig(final Map<String, String> additionalConfiguration) {
127         this.additionalConfig = additionalConfiguration;
128     }
129
130     @Override
131     public void setResourceBaseDir(final File resourceBaseDir) {
132         this.resourceBaseDir = resourceBaseDir;
133     }
134
135     @Override
136     public void setMavenProject(final MavenProject project) {
137         this.mavenProject = project;
138         this.projectBaseDir = project.getBasedir();
139     }
140
141     @Override
142     public void setBuildContext(final BuildContext buildContext) {
143         this.buildContext = Preconditions.checkNotNull(buildContext);
144     }
145
146     private Set<File> generateYangModuleInfo(final File outputBaseDir, final Module module, final SchemaContext ctx,
147             final Builder<String> providerSourceSet) {
148         Builder<File> generatedFiles = ImmutableSet.<File> builder();
149
150         final YangModuleInfoTemplate template = new YangModuleInfoTemplate(module, ctx);
151         String moduleInfoSource = template.generate();
152         if (moduleInfoSource.isEmpty()) {
153             throw new IllegalStateException("Generated code should not be empty!");
154         }
155         String providerSource = template.generateModelProvider();
156
157         final File packageDir = GeneratorJavaFile.packageToDirectory(outputBaseDir,
158                 BindingGeneratorUtil.moduleNamespaceToPackageName(module));
159
160         generatedFiles.add(writeJavaSource(packageDir, BindingMapping.MODULE_INFO_CLASS_NAME, moduleInfoSource));
161         generatedFiles
162                 .add(writeJavaSource(packageDir, BindingMapping.MODEL_BINDING_PROVIDER_CLASS_NAME, providerSource));
163         providerSourceSet.add(template.getModelBindingProviderName());
164
165         return generatedFiles.build();
166
167     }
168
169     private File writeJavaSource(final File packageDir, final String className, final String source) {
170         if (!packageDir.exists()) {
171             packageDir.mkdirs();
172         }
173         final File file = new File(packageDir, className + ".java");
174         writeFile(file, source);
175         return file;
176     }
177
178     private File writeFile(final File file, final String source) {
179         try (final OutputStream stream = buildContext.newFileOutputStream(file)) {
180             try (final Writer fw = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) {
181                 try (final BufferedWriter bw = new BufferedWriter(fw)) {
182                     bw.write(source);
183                 }
184             } catch (Exception e) {
185                 LOG.error("Could not write file: {}",file,e);
186             }
187         } catch (Exception e) {
188             LOG.error("Could not create file: {}",file,e);
189         }
190         return file;
191     }
192
193 }