ce34a15ffc984a6714e7103f1ad48e86775e107d
[mdsal.git] / binding / maven-sal-api-gen-plugin / src / main / java / org / opendaylight / mdsal / binding / maven / 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.mdsal.binding.maven.api.gen.plugin;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.Joiner;
13 import com.google.common.base.Stopwatch;
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.ImmutableSet.Builder;
17 import com.google.common.collect.ListMultimap;
18 import com.google.common.collect.MultimapBuilder;
19 import com.google.common.collect.Table;
20 import com.google.common.collect.Table.Cell;
21 import com.google.common.util.concurrent.Futures;
22 import com.google.common.util.concurrent.ListenableFuture;
23 import com.google.common.util.concurrent.ListeningExecutorService;
24 import com.google.common.util.concurrent.MoreExecutors;
25 import java.io.BufferedWriter;
26 import java.io.File;
27 import java.io.IOException;
28 import java.io.OutputStream;
29 import java.io.OutputStreamWriter;
30 import java.io.Writer;
31 import java.nio.charset.StandardCharsets;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Map.Entry;
39 import java.util.Optional;
40 import java.util.Set;
41 import java.util.concurrent.Callable;
42 import java.util.concurrent.ExecutionException;
43 import java.util.concurrent.ForkJoinPool;
44 import java.util.function.Function;
45 import java.util.function.Supplier;
46 import java.util.stream.Collectors;
47 import org.apache.maven.project.MavenProject;
48 import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
49 import org.opendaylight.mdsal.binding.java.api.generator.GeneratorJavaFile;
50 import org.opendaylight.mdsal.binding.java.api.generator.GeneratorJavaFile.FileKind;
51 import org.opendaylight.mdsal.binding.java.api.generator.YangModuleInfoTemplate;
52 import org.opendaylight.mdsal.binding.model.api.Type;
53 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
54 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
55 import org.opendaylight.yangtools.yang.model.api.Module;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
58 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
59 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.sonatype.plexus.build.incremental.BuildContext;
63
64 public final class CodeGeneratorImpl implements BasicCodeGenerator, BuildContextAware, MavenProjectAware {
65     public static final String CONFIG_PERSISTENT_SOURCES_DIR = "persistentSourcesDir";
66     public static final String CONFIG_IGNORE_DUPLICATE_FILES = "ignoreDuplicateFiles";
67
68     private static final Logger LOG = LoggerFactory.getLogger(CodeGeneratorImpl.class);
69     private static final String FS = File.separator;
70     private BuildContext buildContext;
71     private File projectBaseDir;
72     private Map<String, String> additionalConfig;
73     private MavenProject mavenProject;
74     private File resourceBaseDir;
75
76     @Override
77     public Collection<File> generateSources(final SchemaContext context, final File outputDir,
78             final Set<Module> yangModules, final Function<Module, Optional<String>> moduleResourcePathResolver)
79                     throws IOException {
80         final File outputBaseDir;
81
82         outputBaseDir = outputDir == null ? getDefaultOutputBaseDir() : outputDir;
83
84         // Step one: determine binding types which we are generating
85         final Stopwatch sw = Stopwatch.createStarted();
86         final List<Type> types = new BindingGeneratorImpl().generateTypes(context, yangModules);
87         LOG.info("Found {} Binding types in {}", types.size(), sw);
88
89         final GeneratorJavaFile generator = new GeneratorJavaFile(types);
90
91         File persistentSourcesDir = null;
92         boolean ignoreDuplicateFiles = true;
93         if (additionalConfig != null) {
94             String persistenSourcesPath = additionalConfig.get(CONFIG_PERSISTENT_SOURCES_DIR);
95             if (persistenSourcesPath != null) {
96                 persistentSourcesDir = new File(persistenSourcesPath);
97             }
98             String ignoreDuplicateFilesString = additionalConfig.get(CONFIG_IGNORE_DUPLICATE_FILES);
99             if (ignoreDuplicateFilesString != null) {
100                 ignoreDuplicateFiles = Boolean.parseBoolean(ignoreDuplicateFilesString);
101             }
102         }
103         if (persistentSourcesDir == null) {
104             persistentSourcesDir = new File(projectBaseDir, "src" + FS + "main" + FS + "java");
105         }
106
107         final Table<FileKind, String, Supplier<String>> generatedFiles = generator.generateFileContent(
108             ignoreDuplicateFiles);
109
110         // Step two: create generation tasks for each target file and group them by parent directory
111         final ListMultimap<Path, GenerationTask> dirs = MultimapBuilder.hashKeys().arrayListValues().build();
112         for (Cell<FileKind, String, Supplier<String>> cell : generatedFiles.cellSet()) {
113             final File target;
114             switch (cell.getRowKey()) {
115                 case PERSISTENT:
116                     target = new File(persistentSourcesDir, cell.getColumnKey());
117                     if (target.exists()) {
118                         LOG.debug("Skipping existing persistent {}", target);
119                         continue;
120                     }
121                     break;
122                 case TRANSIENT:
123                     target = new File(outputBaseDir, cell.getColumnKey());
124                     break;
125                 default:
126                     throw new IllegalStateException("Unsupported file type in " + cell);
127             }
128
129             dirs.put(target.getParentFile().toPath(), new GenerationTask(buildContext, target, cell.getValue()));
130         }
131         LOG.info("Generating {} Binding source files into {} directories", dirs.size(), dirs.keySet().size());
132
133         // Step three: wrap common FJ pool, submit parent directory creation tasks and wait for them to complete
134         sw.reset().start();
135         final ListeningExecutorService service = MoreExecutors.listeningDecorator(ForkJoinPool.commonPool());
136         final List<ListenableFuture<Void>> parentFutures = new ArrayList<>(dirs.keySet().size());
137         for (Entry<Path, Collection<GenerationTask>> entry : dirs.asMap().entrySet()) {
138             parentFutures.add(service.submit(() -> {
139                 Files.createDirectories(entry.getKey());
140                 return null;
141             }));
142         }
143
144         try {
145             Futures.whenAllComplete(parentFutures).call(() -> {
146                 for (ListenableFuture<Void> future : parentFutures) {
147                     Futures.getDone(future);
148                 }
149                 return null;
150             }, MoreExecutors.directExecutor()).get();
151         } catch (InterruptedException e) {
152             throw new IOException("Interrupted while creating parent directories", e);
153         } catch (ExecutionException e) {
154             LOG.debug("Failed to create parent directories", e);
155             Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
156             throw new IOException("Failed to create parent directories", e);
157         }
158         LOG.debug("Parent directories created in {}", sw);
159
160         // Step four: submit all code generation tasks and wait for them to complete
161         sw.reset().start();
162         final List<ListenableFuture<File>> futureFiles = dirs.values().stream()
163                 .map(service::submit)
164                 .collect(Collectors.toList());
165
166         final List<File> result;
167         try {
168             result = Futures.whenAllComplete(futureFiles).call(() -> {
169                 List<File> ret = new ArrayList<>(futureFiles.size());
170                 for (ListenableFuture<File> future : futureFiles) {
171                     ret.add(Futures.getDone(future));
172                 }
173                 return ret;
174             }, MoreExecutors.directExecutor()).get();
175         } catch (InterruptedException e) {
176             throw new IOException("Interrupted while generating files", e);
177         } catch (ExecutionException e) {
178             LOG.error("Failed to create generated files", e);
179             Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
180             throw new IOException("Failed to create generated files", e);
181         }
182         LOG.debug("{} Binding source type files generated in {}", result.size(), sw);
183
184         // Step five: generate auxiliary files
185         result.addAll(generateModuleInfos(outputBaseDir, yangModules, context, moduleResourcePathResolver));
186         return result;
187     }
188
189     private Collection<? extends File> generateModuleInfos(final File outputBaseDir, final Set<Module> yangModules,
190             final SchemaContext context, final Function<Module, Optional<String>> moduleResourcePathResolver) {
191         Builder<File> result = ImmutableSet.builder();
192         Builder<String> bindingProviders = ImmutableSet.builder();
193         for (Module module : yangModules) {
194             Builder<String> currentProvidersBuilder = ImmutableSet.builder();
195             // TODO: do not mutate parameters, output of a method is defined by its return value
196             Set<File> moduleInfoProviders = generateYangModuleInfo(outputBaseDir, module, context,
197                 moduleResourcePathResolver, currentProvidersBuilder);
198             ImmutableSet<String> currentProviders = currentProvidersBuilder.build();
199             LOG.debug("Adding ModuleInfo providers {}", currentProviders);
200             bindingProviders.addAll(currentProviders);
201             result.addAll(moduleInfoProviders);
202         }
203
204         result.add(writeMetaInfServices(resourceBaseDir, YangModelBindingProvider.class, bindingProviders.build()));
205         return result.build();
206     }
207
208     private File writeMetaInfServices(final File outputBaseDir, final Class<YangModelBindingProvider> serviceClass,
209             final ImmutableSet<String> services) {
210         File metainfServicesFolder = new File(outputBaseDir, "META-INF" + File.separator + "services");
211         metainfServicesFolder.mkdirs();
212         File serviceFile = new File(metainfServicesFolder, serviceClass.getName());
213
214         String src = Joiner.on('\n').join(services);
215
216         return writeFile(serviceFile, src);
217     }
218
219     public static final String DEFAULT_OUTPUT_BASE_DIR_PATH = "target" + File.separator + "generated-sources"
220             + File.separator + "maven-sal-api-gen";
221
222     private File getDefaultOutputBaseDir() {
223         File outputBaseDir;
224         outputBaseDir = new File(DEFAULT_OUTPUT_BASE_DIR_PATH);
225         setOutputBaseDirAsSourceFolder(outputBaseDir, mavenProject);
226         LOG.debug("Adding {} as compile source root", outputBaseDir.getPath());
227         return outputBaseDir;
228     }
229
230     private static void setOutputBaseDirAsSourceFolder(final File outputBaseDir, final MavenProject mavenProject) {
231         requireNonNull(mavenProject, "Maven project needs to be set in this phase");
232         mavenProject.addCompileSourceRoot(outputBaseDir.getPath());
233     }
234
235     @Override
236     public void setAdditionalConfig(final Map<String, String> additionalConfiguration) {
237         this.additionalConfig = additionalConfiguration;
238     }
239
240     @Override
241     public void setResourceBaseDir(final File resourceBaseDir) {
242         this.resourceBaseDir = resourceBaseDir;
243     }
244
245     @Override
246     public void setMavenProject(final MavenProject project) {
247         this.mavenProject = project;
248         this.projectBaseDir = project.getBasedir();
249     }
250
251     @Override
252     public void setBuildContext(final BuildContext buildContext) {
253         this.buildContext = requireNonNull(buildContext);
254     }
255
256     private Set<File> generateYangModuleInfo(final File outputBaseDir, final Module module, final SchemaContext ctx,
257             final Function<Module, Optional<String>> moduleResourcePathResolver,
258             final Builder<String> providerSourceSet) {
259         Builder<File> generatedFiles = ImmutableSet.builder();
260
261         final YangModuleInfoTemplate template = new YangModuleInfoTemplate(module, ctx, moduleResourcePathResolver);
262         String moduleInfoSource = template.generate();
263         if (moduleInfoSource.isEmpty()) {
264             throw new IllegalStateException("Generated code should not be empty!");
265         }
266         String providerSource = template.generateModelProvider();
267
268         final File packageDir = GeneratorJavaFile.packageToDirectory(outputBaseDir,
269             BindingMapping.getRootPackageName(module.getQNameModule()));
270
271         generatedFiles.add(writeJavaSource(packageDir, BindingMapping.MODULE_INFO_CLASS_NAME, moduleInfoSource));
272         generatedFiles
273                 .add(writeJavaSource(packageDir, BindingMapping.MODEL_BINDING_PROVIDER_CLASS_NAME, providerSource));
274         providerSourceSet.add(template.getModelBindingProviderName());
275
276         return generatedFiles.build();
277
278     }
279
280     private File writeJavaSource(final File packageDir, final String className, final String source) {
281         if (!packageDir.exists()) {
282             packageDir.mkdirs();
283         }
284         final File file = new File(packageDir, className + ".java");
285         writeFile(file, source);
286         return file;
287     }
288
289     @SuppressWarnings("checkstyle:illegalCatch")
290     private File writeFile(final File file, final String source) {
291         try (OutputStream stream = buildContext.newFileOutputStream(file)) {
292             try (Writer fw = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) {
293                 try (BufferedWriter bw = new BufferedWriter(fw)) {
294                     bw.write(source);
295                 }
296             } catch (Exception e) {
297                 LOG.error("Could not write file: {}", file, e);
298             }
299         } catch (Exception e) {
300             LOG.error("Could not create file: {}", file, e);
301         }
302         return file;
303     }
304
305     private static final class GenerationTask implements Callable<File> {
306         private final BuildContext buildContext;
307         private final Supplier<String> contentSupplier;
308         private final File target;
309
310         GenerationTask(final BuildContext buildContext, final File target, final Supplier<String> contentSupplier) {
311             this.buildContext = requireNonNull(buildContext);
312             this.target = requireNonNull(target);
313             this.contentSupplier = requireNonNull(contentSupplier);
314         }
315
316         @Override
317         public File call() throws IOException {
318             try (OutputStream stream = buildContext.newFileOutputStream(target)) {
319                 try (Writer fw = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) {
320                     try (BufferedWriter bw = new BufferedWriter(fw)) {
321                         bw.write(contentSupplier.get());
322                     }
323                 }
324             }
325             return target;
326         }
327     }
328 }