Fix checkstyle in mdsal-binding2-java-api-generator
[mdsal.git] / binding2 / mdsal-binding2-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / javav2 / java / api / generator / GeneratorJavaFile.java
1 /*
2  * Copyright (c) 2017 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
9 package org.opendaylight.mdsal.binding.javav2.java.api.generator;
10
11 import com.google.common.annotations.Beta;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Splitter;
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.ArrayList;
22 import java.util.Collection;
23 import java.util.Iterator;
24 import java.util.List;
25 import org.opendaylight.mdsal.binding.javav2.java.api.generator.util.JavaCodePrettyPrint;
26 import org.opendaylight.mdsal.binding.javav2.model.api.CodeGenerator;
27 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject;
28 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTypeForBuilder;
29 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
30 import org.opendaylight.mdsal.binding.javav2.model.api.UnitName;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.sonatype.plexus.build.incremental.BuildContext;
34
35 /**
36  * Generates files with JAVA source code for every specified type.
37  */
38 @Beta
39 public final class GeneratorJavaFile {
40
41     private static final Logger LOG = LoggerFactory.getLogger(GeneratorJavaFile.class);
42     private static final Splitter BSDOT_SPLITTER = Splitter.on(".");
43
44     /**
45      * List of <code>CodeGenerator</code> instances.
46      */
47     private final List<CodeGenerator> generators = new ArrayList<>();
48
49     /**
50      * Set of <code>Type</code> instances for which the JAVA code is generated.
51      */
52     private final Collection<? extends Type> types;
53
54     /**
55      * BuildContext used for instantiating files.
56      */
57     private final BuildContext buildContext;
58
59     /**
60      * Creates instance of this class with the set of <code>types</code> for
61      * which the JAVA code is generated.
62      *
63      * <p>
64      * The instances of concrete JAVA code generator are created.
65      *
66      * @param buildContext
67      *            build context to use for accessing files
68      * @param types
69      *            set of types for which JAVA code should be generated
70      */
71     public GeneratorJavaFile(final BuildContext buildContext, final Collection<? extends Type> types) {
72         this.buildContext = Preconditions.checkNotNull(buildContext);
73         this.types = Preconditions.checkNotNull(types);
74         this.generators.add(new EnumGenerator());
75         this.generators.add(new InterfaceGenerator());
76         this.generators.add(new BuilderGenerator());
77         this.generators.add(new TOGenerator());
78     }
79
80     /**
81      * Generates <code>List</code> of files for collection of types. All files are stored
82      * to sub-folders of base directory <code>persistentSourcesDirectory</code>. Subdirectories
83      * are generated according to packages to which the type belongs (e. g. if
84      * type belongs to the package <i>org.pcg</i> then in <code>persistentSourcesDirectory</code>
85      * is created directory <i>org</i> which contains <i>pcg</i>).
86      *
87      * @param generatedSourcesDirectory expected output directory for generated sources configured by
88      *            user
89      * @param persistentSourcesDirectory base directory
90      * @return list of generated files
91      * @throws IOException thrown in case of I/O error
92      */
93     public List<File> generateToFile(final File generatedSourcesDirectory, final File persistentSourcesDirectory)
94             throws IOException {
95         final List<File> result = new ArrayList<>();
96         for (final Type type : this.types) {
97             if (type != null) {
98                 for (final CodeGenerator generator : this.generators) {
99                     File generatedJavaFile = null;
100                     if (type instanceof GeneratedTransferObject
101                             && ((GeneratedTransferObject) type).isUnionTypeBuilder()) {
102                         final File packageDir = packageToDirectory(persistentSourcesDirectory, type.getPackageName());
103                         final File file = new File(packageDir, generator.getUnitName(type) + ".java");
104                         if (!file.exists()) {
105                             generatedJavaFile = generateTypeToJavaFile(persistentSourcesDirectory, type, generator);
106                         }
107                     } else {
108                         generatedJavaFile = generateTypeToJavaFile(generatedSourcesDirectory, type, generator);
109                     }
110                     if (generatedJavaFile != null) {
111                         result.add(generatedJavaFile);
112                     }
113                 }
114             }
115         }
116         return result;
117     }
118
119     /**
120      * Creates the package directory path as concatenation of
121      * <code>parentDirectory</code> and parsed <code>packageName</code>. The
122      * parsing of <code>packageName</code> is realized as replacement of the
123      * package name dots with the file system separator.
124      *
125      * @param parentDirectory
126      *            <code>File</code> object with reference to parent directory
127      * @param packageName
128      *            string with the name of the package
129      * @return <code>File</code> object which refers to the new directory for
130      *         package <code>packageName</code>
131      */
132     public static File packageToDirectory(final File parentDirectory, final String packageName) {
133         if (packageName == null) {
134             throw new IllegalArgumentException("Package Name cannot be NULL!");
135         }
136
137         final StringBuilder dirPathBuilder = new StringBuilder();
138         final Iterator<String> packageElementsItr = BSDOT_SPLITTER.split(packageName).iterator();
139         if (packageElementsItr.hasNext()) {
140             dirPathBuilder.append(packageElementsItr.next());
141         }
142
143         while (packageElementsItr.hasNext()) {
144             dirPathBuilder.append(File.separator);
145             dirPathBuilder.append(packageElementsItr.next());
146         }
147
148         return new File(parentDirectory, dirPathBuilder.toString());
149     }
150
151     /**
152      * Generates <code>File</code> for <code>type</code>. All files are stored
153      * to sub-folders of base directory <code>parentDir</code>. Subdirectories
154      * are generated according to packages to which the type belongs (e. g. if
155      * type belongs to the package <i>org.pcg</i> then in <code>parentDir</code>
156      * is created directory <i>org</i> which contains <i>pcg</i>).
157      *
158      * @param parentDir
159      *            directory where should be the new file generated
160      * @param type
161      *            JAVA <code>Type</code> for which should be JAVA source code
162      *            generated
163      * @param generator
164      *            code generator which is used for generating of the source code
165      * @return file which contains JAVA source code
166      * @throws IOException
167      *             if the error during writing to the file occurs
168      * @throws IllegalArgumentException
169      *             if <code>type</code> equals <code>null</code>
170      * @throws IllegalStateException
171      *             if string with generated code is empty
172      */
173     private File generateTypeToJavaFile(final File parentDir, final Type type, final CodeGenerator generator)
174             throws IOException {
175         if (parentDir == null) {
176             LOG.warn("Parent Directory not specified, files will be generated "
177                     + "accordingly to generated Type package path.");
178         }
179         if (type == null) {
180             LOG.error("Cannot generate Type into Java File because " + "Generated Type is NULL!");
181             throw new IllegalArgumentException("Generated Type Cannot be NULL!");
182         }
183         if (generator == null) {
184             LOG.error("Cannot generate Type into Java File because " + "Code Generator instance is NULL!");
185             throw new IllegalArgumentException("Code Generator Cannot be NULL!");
186         }
187
188         if (generator.isAcceptable(type)) {
189             File packageDir;
190             if (generator instanceof BuilderGenerator) {
191                 packageDir = packageToDirectory(parentDir, ((GeneratedTypeForBuilder)type).getPackageNameForBuilder());
192             } else {
193                 packageDir = packageToDirectory(parentDir, type.getPackageName());
194             }
195
196             if (!packageDir.exists()) {
197                 packageDir.mkdirs();
198             }
199
200             final String generatedCode = JavaCodePrettyPrint.perform(generator.generate(type));
201             Preconditions.checkState(!generatedCode.isEmpty(), "Generated code should not be empty!");
202             final File file = new File(packageDir, ((UnitName) generator.getUnitName(type)).getValue() + ".java");
203
204             if (file.exists()) {
205                 LOG.warn("Naming conflict for type '{}': file with same name already exists and will not be generated.",
206                     type.getFullyQualifiedName());
207                 return null;
208             }
209
210             try (OutputStream stream = this.buildContext.newFileOutputStream(file)) {
211                 try (Writer fw = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) {
212                     try (BufferedWriter bw = new BufferedWriter(fw)) {
213                         bw.write(generatedCode);
214                     }
215                 } catch (final IOException e) {
216                     LOG.error("Failed to write generate output into {}", file.getPath(), e);
217                     throw e;
218                 }
219             }
220             return file;
221
222         }
223         return null;
224     }
225
226 }