2 * Copyright (c) 2017 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
9 package org.opendaylight.mdsal.binding.javav2.java.api.generator;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Splitter;
16 import java.io.BufferedWriter;
18 import java.io.IOException;
19 import java.io.OutputStream;
20 import java.io.OutputStreamWriter;
21 import java.io.Writer;
22 import java.nio.charset.StandardCharsets;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Iterator;
26 import java.util.List;
27 import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.JavaCodePrettyPrint;
28 import org.opendaylight.mdsal.binding.javav2.model.api.CodeGenerator;
29 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject;
30 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTypeForBuilder;
31 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
32 import org.opendaylight.mdsal.binding.javav2.model.api.UnitName;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.sonatype.plexus.build.incremental.BuildContext;
38 * Generates files with JAVA source code for every specified type.
41 public final class GeneratorJavaFile {
43 private static final Logger LOG = LoggerFactory.getLogger(GeneratorJavaFile.class);
44 private static final Splitter BSDOT_SPLITTER = Splitter.on(".");
47 * List of <code>CodeGenerator</code> instances.
49 private final List<CodeGenerator> generators = new ArrayList<>();
52 * Set of <code>Type</code> instances for which the JAVA code is generated.
54 private final Collection<? extends Type> types;
57 * BuildContext used for instantiating files.
59 private final BuildContext buildContext;
62 * Creates instance of this class with the set of <code>types</code> for
63 * which the JAVA code is generated.
66 * The instances of concrete JAVA code generator are created.
69 * build context to use for accessing files
71 * set of types for which JAVA code should be generated
73 public GeneratorJavaFile(final BuildContext buildContext, final Collection<? extends Type> types) {
74 this.buildContext = requireNonNull(buildContext);
75 this.types = requireNonNull(types);
76 this.generators.add(new EnumGenerator());
77 this.generators.add(new InterfaceGenerator());
78 this.generators.add(new BuilderGenerator());
79 this.generators.add(new TOGenerator());
83 * Generates <code>List</code> of files for collection of types. All files are stored
84 * to sub-folders of base directory <code>persistentSourcesDirectory</code>. Subdirectories
85 * are generated according to packages to which the type belongs (e. g. if
86 * type belongs to the package <i>org.pcg</i> then in <code>persistentSourcesDirectory</code>
87 * is created directory <i>org</i> which contains <i>pcg</i>).
89 * @param generatedSourcesDirectory expected output directory for generated sources configured by
91 * @param persistentSourcesDirectory base directory
92 * @return list of generated files
93 * @throws IOException thrown in case of I/O error
95 public List<File> generateToFile(final File generatedSourcesDirectory, final File persistentSourcesDirectory)
97 final List<File> result = new ArrayList<>();
98 for (final Type type : this.types) {
100 for (final CodeGenerator generator : this.generators) {
101 File generatedJavaFile = null;
102 if (type instanceof GeneratedTransferObject
103 && ((GeneratedTransferObject) type).isUnionTypeBuilder()) {
104 final File packageDir = packageToDirectory(persistentSourcesDirectory, type.getPackageName());
105 final File file = new File(packageDir, generator.getUnitName(type) + ".java");
106 if (!file.exists()) {
107 generatedJavaFile = generateTypeToJavaFile(persistentSourcesDirectory, type, generator);
110 generatedJavaFile = generateTypeToJavaFile(generatedSourcesDirectory, type, generator);
112 if (generatedJavaFile != null) {
113 result.add(generatedJavaFile);
122 * Creates the package directory path as concatenation of
123 * <code>parentDirectory</code> and parsed <code>packageName</code>. The
124 * parsing of <code>packageName</code> is realized as replacement of the
125 * package name dots with the file system separator.
127 * @param parentDirectory
128 * <code>File</code> object with reference to parent directory
130 * string with the name of the package
131 * @return <code>File</code> object which refers to the new directory for
132 * package <code>packageName</code>
134 public static File packageToDirectory(final File parentDirectory, final String packageName) {
135 if (packageName == null) {
136 throw new IllegalArgumentException("Package Name cannot be NULL!");
139 final StringBuilder dirPathBuilder = new StringBuilder();
140 final Iterator<String> packageElementsItr = BSDOT_SPLITTER.split(packageName).iterator();
141 if (packageElementsItr.hasNext()) {
142 dirPathBuilder.append(packageElementsItr.next());
145 while (packageElementsItr.hasNext()) {
146 dirPathBuilder.append(File.separator);
147 dirPathBuilder.append(packageElementsItr.next());
150 return new File(parentDirectory, dirPathBuilder.toString());
154 * Generates <code>File</code> for <code>type</code>. All files are stored
155 * to sub-folders of base directory <code>parentDir</code>. Subdirectories
156 * are generated according to packages to which the type belongs (e. g. if
157 * type belongs to the package <i>org.pcg</i> then in <code>parentDir</code>
158 * is created directory <i>org</i> which contains <i>pcg</i>).
161 * directory where should be the new file generated
163 * JAVA <code>Type</code> for which should be JAVA source code
166 * code generator which is used for generating of the source code
167 * @return file which contains JAVA source code
168 * @throws IOException
169 * if the error during writing to the file occurs
170 * @throws IllegalArgumentException
171 * if <code>type</code> equals <code>null</code>
172 * @throws IllegalStateException
173 * if string with generated code is empty
175 private File generateTypeToJavaFile(final File parentDir, final Type type, final CodeGenerator generator)
177 if (parentDir == null) {
178 LOG.warn("Parent Directory not specified, files will be generated "
179 + "accordingly to generated Type package path.");
182 LOG.error("Cannot generate Type into Java File because " + "Generated Type is NULL!");
183 throw new IllegalArgumentException("Generated Type Cannot be NULL!");
185 if (generator == null) {
186 LOG.error("Cannot generate Type into Java File because " + "Code Generator instance is NULL!");
187 throw new IllegalArgumentException("Code Generator Cannot be NULL!");
190 if (generator.isAcceptable(type)) {
192 if (generator instanceof BuilderGenerator) {
193 packageDir = packageToDirectory(parentDir, ((GeneratedTypeForBuilder)type).getPackageNameForBuilder());
195 packageDir = packageToDirectory(parentDir, type.getPackageName());
198 if (!packageDir.exists()) {
202 final String generatedCode = JavaCodePrettyPrint.perform(generator.generate(type));
203 Preconditions.checkState(!generatedCode.isEmpty(), "Generated code should not be empty!");
204 final File file = new File(packageDir, ((UnitName) generator.getUnitName(type)).getValue() + ".java");
207 LOG.warn("Naming conflict for type '{}': file with same name already exists and will not be generated.",
208 type.getFullyQualifiedName());
212 try (OutputStream stream = this.buildContext.newFileOutputStream(file)) {
213 try (Writer fw = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) {
214 try (BufferedWriter bw = new BufferedWriter(fw)) {
215 bw.write(generatedCode);
217 } catch (final IOException e) {
218 LOG.error("Failed to write generate output into {}", file.getPath(), e);