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