2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.maven.api.gen.plugin;
10 import static java.util.Objects.requireNonNull;
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;
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;
38 import java.util.Map.Entry;
39 import java.util.Optional;
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.EffectiveModelContext;
56 import org.opendaylight.yangtools.yang.model.api.Module;
57 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
58 import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
59 import org.opendaylight.yangtools.yang2sources.spi.BuildContextAware;
60 import org.opendaylight.yangtools.yang2sources.spi.MavenProjectAware;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63 import org.sonatype.plexus.build.incremental.BuildContext;
65 public final class CodeGeneratorImpl implements BasicCodeGenerator, BuildContextAware, MavenProjectAware {
66 public static final String CONFIG_PERSISTENT_SOURCES_DIR = "persistentSourcesDir";
67 public static final String CONFIG_IGNORE_DUPLICATE_FILES = "ignoreDuplicateFiles";
69 private static final Logger LOG = LoggerFactory.getLogger(CodeGeneratorImpl.class);
70 private static final String FS = File.separator;
71 private BuildContext buildContext;
72 private File projectBaseDir;
73 private Map<String, String> additionalConfig;
74 private MavenProject mavenProject;
75 private File resourceBaseDir;
78 public Collection<File> generateSources(final EffectiveModelContext context, final File outputDir,
79 final Set<Module> yangModules, final Function<Module, Optional<String>> moduleResourcePathResolver)
81 final File outputBaseDir;
83 outputBaseDir = outputDir == null ? getDefaultOutputBaseDir() : outputDir;
85 // Step one: determine binding types which we are generating
86 final Stopwatch sw = Stopwatch.createStarted();
87 final List<Type> types = new BindingGeneratorImpl().generateTypes(context, yangModules);
88 LOG.info("Found {} Binding types in {}", types.size(), sw);
90 final GeneratorJavaFile generator = new GeneratorJavaFile(types);
92 File persistentSourcesDir = null;
93 boolean ignoreDuplicateFiles = true;
94 if (additionalConfig != null) {
95 String persistenSourcesPath = additionalConfig.get(CONFIG_PERSISTENT_SOURCES_DIR);
96 if (persistenSourcesPath != null) {
97 persistentSourcesDir = new File(persistenSourcesPath);
99 String ignoreDuplicateFilesString = additionalConfig.get(CONFIG_IGNORE_DUPLICATE_FILES);
100 if (ignoreDuplicateFilesString != null) {
101 ignoreDuplicateFiles = Boolean.parseBoolean(ignoreDuplicateFilesString);
104 if (persistentSourcesDir == null) {
105 persistentSourcesDir = new File(projectBaseDir, "src" + FS + "main" + FS + "java");
108 final Table<FileKind, String, Supplier<String>> generatedFiles = generator.generateFileContent(
109 ignoreDuplicateFiles);
111 // Step two: create generation tasks for each target file and group them by parent directory
112 final ListMultimap<Path, GenerationTask> dirs = MultimapBuilder.hashKeys().arrayListValues().build();
113 for (Cell<FileKind, String, Supplier<String>> cell : generatedFiles.cellSet()) {
115 switch (cell.getRowKey()) {
117 target = new File(persistentSourcesDir, cell.getColumnKey());
118 if (target.exists()) {
119 LOG.debug("Skipping existing persistent {}", target);
124 target = new File(outputBaseDir, cell.getColumnKey());
127 throw new IllegalStateException("Unsupported file type in " + cell);
130 dirs.put(target.getParentFile().toPath(), new GenerationTask(buildContext, target, cell.getValue()));
132 LOG.info("Generating {} Binding source files into {} directories", dirs.size(), dirs.keySet().size());
134 // Step three: wrap common FJ pool, submit parent directory creation tasks and wait for them to complete
136 final ListeningExecutorService service = MoreExecutors.listeningDecorator(ForkJoinPool.commonPool());
137 final List<ListenableFuture<Void>> parentFutures = new ArrayList<>(dirs.keySet().size());
138 for (Entry<Path, Collection<GenerationTask>> entry : dirs.asMap().entrySet()) {
139 parentFutures.add(service.submit(() -> {
140 Files.createDirectories(entry.getKey());
146 Futures.whenAllComplete(parentFutures).call(() -> {
147 for (ListenableFuture<Void> future : parentFutures) {
148 Futures.getDone(future);
151 }, MoreExecutors.directExecutor()).get();
152 } catch (InterruptedException e) {
153 throw new IOException("Interrupted while creating parent directories", e);
154 } catch (ExecutionException e) {
155 LOG.debug("Failed to create parent directories", e);
156 Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
157 throw new IOException("Failed to create parent directories", e);
159 LOG.debug("Parent directories created in {}", sw);
161 // Step four: submit all code generation tasks and wait for them to complete
163 final List<ListenableFuture<File>> futureFiles = dirs.values().stream()
164 .map(service::submit)
165 .collect(Collectors.toList());
167 final List<File> result;
169 result = Futures.whenAllComplete(futureFiles).call(() -> {
170 List<File> ret = new ArrayList<>(futureFiles.size());
171 for (ListenableFuture<File> future : futureFiles) {
172 ret.add(Futures.getDone(future));
175 }, MoreExecutors.directExecutor()).get();
176 } catch (InterruptedException e) {
177 throw new IOException("Interrupted while generating files", e);
178 } catch (ExecutionException e) {
179 LOG.error("Failed to create generated files", e);
180 Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
181 throw new IOException("Failed to create generated files", e);
183 LOG.debug("{} Binding source type files generated in {}", result.size(), sw);
185 // Step five: generate auxiliary files
186 result.addAll(generateModuleInfos(outputBaseDir, yangModules, context, moduleResourcePathResolver));
190 private Collection<? extends File> generateModuleInfos(final File outputBaseDir, final Set<Module> yangModules,
191 final SchemaContext context, final Function<Module, Optional<String>> moduleResourcePathResolver) {
192 Builder<File> result = ImmutableSet.builder();
193 Builder<String> bindingProviders = ImmutableSet.builder();
194 for (Module module : yangModules) {
195 Builder<String> currentProvidersBuilder = ImmutableSet.builder();
196 // TODO: do not mutate parameters, output of a method is defined by its return value
197 Set<File> moduleInfoProviders = generateYangModuleInfo(outputBaseDir, module, context,
198 moduleResourcePathResolver, currentProvidersBuilder);
199 ImmutableSet<String> currentProviders = currentProvidersBuilder.build();
200 LOG.debug("Adding ModuleInfo providers {}", currentProviders);
201 bindingProviders.addAll(currentProviders);
202 result.addAll(moduleInfoProviders);
205 result.add(writeMetaInfServices(resourceBaseDir, YangModelBindingProvider.class, bindingProviders.build()));
206 return result.build();
209 private File writeMetaInfServices(final File outputBaseDir, final Class<YangModelBindingProvider> serviceClass,
210 final ImmutableSet<String> services) {
211 File metainfServicesFolder = new File(outputBaseDir, "META-INF" + File.separator + "services");
212 metainfServicesFolder.mkdirs();
213 File serviceFile = new File(metainfServicesFolder, serviceClass.getName());
215 String src = Joiner.on('\n').join(services);
217 return writeFile(serviceFile, src);
220 public static final String DEFAULT_OUTPUT_BASE_DIR_PATH = "target" + File.separator + "generated-sources"
221 + File.separator + "maven-sal-api-gen";
223 private File getDefaultOutputBaseDir() {
225 outputBaseDir = new File(DEFAULT_OUTPUT_BASE_DIR_PATH);
226 setOutputBaseDirAsSourceFolder(outputBaseDir, mavenProject);
227 LOG.debug("Adding {} as compile source root", outputBaseDir.getPath());
228 return outputBaseDir;
231 private static void setOutputBaseDirAsSourceFolder(final File outputBaseDir, final MavenProject mavenProject) {
232 requireNonNull(mavenProject, "Maven project needs to be set in this phase");
233 mavenProject.addCompileSourceRoot(outputBaseDir.getPath());
237 public void setAdditionalConfig(final Map<String, String> additionalConfiguration) {
238 this.additionalConfig = additionalConfiguration;
242 public void setResourceBaseDir(final File resourceBaseDir) {
243 this.resourceBaseDir = resourceBaseDir;
247 public void setMavenProject(final MavenProject project) {
248 this.mavenProject = project;
249 this.projectBaseDir = project.getBasedir();
253 public void setBuildContext(final BuildContext buildContext) {
254 this.buildContext = requireNonNull(buildContext);
257 private Set<File> generateYangModuleInfo(final File outputBaseDir, final Module module, final SchemaContext ctx,
258 final Function<Module, Optional<String>> moduleResourcePathResolver,
259 final Builder<String> providerSourceSet) {
260 Builder<File> generatedFiles = ImmutableSet.builder();
262 final YangModuleInfoTemplate template = new YangModuleInfoTemplate(module, ctx, moduleResourcePathResolver);
263 String moduleInfoSource = template.generate();
264 if (moduleInfoSource.isEmpty()) {
265 throw new IllegalStateException("Generated code should not be empty!");
267 String providerSource = template.generateModelProvider();
269 final File packageDir = GeneratorJavaFile.packageToDirectory(outputBaseDir,
270 BindingMapping.getRootPackageName(module.getQNameModule()));
272 generatedFiles.add(writeJavaSource(packageDir, BindingMapping.MODULE_INFO_CLASS_NAME, moduleInfoSource));
274 .add(writeJavaSource(packageDir, BindingMapping.MODEL_BINDING_PROVIDER_CLASS_NAME, providerSource));
275 providerSourceSet.add(template.getModelBindingProviderName());
277 return generatedFiles.build();
281 private File writeJavaSource(final File packageDir, final String className, final String source) {
282 if (!packageDir.exists()) {
285 final File file = new File(packageDir, className + ".java");
286 writeFile(file, source);
290 @SuppressWarnings("checkstyle:illegalCatch")
291 private File writeFile(final File file, final String source) {
292 try (OutputStream stream = buildContext.newFileOutputStream(file)) {
293 try (Writer fw = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) {
294 try (BufferedWriter bw = new BufferedWriter(fw)) {
297 } catch (Exception e) {
298 LOG.error("Could not write file: {}", file, e);
300 } catch (Exception e) {
301 LOG.error("Could not create file: {}", file, e);
306 private static final class GenerationTask implements Callable<File> {
307 private final BuildContext buildContext;
308 private final Supplier<String> contentSupplier;
309 private final File target;
311 GenerationTask(final BuildContext buildContext, final File target, final Supplier<String> contentSupplier) {
312 this.buildContext = requireNonNull(buildContext);
313 this.target = requireNonNull(target);
314 this.contentSupplier = requireNonNull(contentSupplier);
318 public File call() throws IOException {
319 try (OutputStream stream = buildContext.newFileOutputStream(target)) {
320 try (Writer fw = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) {
321 try (BufferedWriter bw = new BufferedWriter(fw)) {
322 bw.write(contentSupplier.get());