Switch to Objects.requireNonNull
[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 static java.util.Objects.requireNonNull;
12
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;
17 import java.io.File;
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;
36
37 /**
38  * Generates files with JAVA source code for every specified type.
39  */
40 @Beta
41 public final class GeneratorJavaFile {
42
43     private static final Logger LOG = LoggerFactory.getLogger(GeneratorJavaFile.class);
44     private static final Splitter BSDOT_SPLITTER = Splitter.on(".");
45
46     /**
47      * List of <code>CodeGenerator</code> instances.
48      */
49     private final List<CodeGenerator> generators = new ArrayList<>();
50
51     /**
52      * Set of <code>Type</code> instances for which the JAVA code is generated.
53      */
54     private final Collection<? extends Type> types;
55
56     /**
57      * BuildContext used for instantiating files.
58      */
59     private final BuildContext buildContext;
60
61     /**
62      * Creates instance of this class with the set of <code>types</code> for
63      * which the JAVA code is generated.
64      *
65      * <p>
66      * The instances of concrete JAVA code generator are created.
67      *
68      * @param buildContext
69      *            build context to use for accessing files
70      * @param types
71      *            set of types for which JAVA code should be generated
72      */
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());
80     }
81
82     /**
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>).
88      *
89      * @param generatedSourcesDirectory expected output directory for generated sources configured by
90      *            user
91      * @param persistentSourcesDirectory base directory
92      * @return list of generated files
93      * @throws IOException thrown in case of I/O error
94      */
95     public List<File> generateToFile(final File generatedSourcesDirectory, final File persistentSourcesDirectory)
96             throws IOException {
97         final List<File> result = new ArrayList<>();
98         for (final Type type : this.types) {
99             if (type != null) {
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);
108                         }
109                     } else {
110                         generatedJavaFile = generateTypeToJavaFile(generatedSourcesDirectory, type, generator);
111                     }
112                     if (generatedJavaFile != null) {
113                         result.add(generatedJavaFile);
114                     }
115                 }
116             }
117         }
118         return result;
119     }
120
121     /**
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.
126      *
127      * @param parentDirectory
128      *            <code>File</code> object with reference to parent directory
129      * @param packageName
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>
133      */
134     public static File packageToDirectory(final File parentDirectory, final String packageName) {
135         if (packageName == null) {
136             throw new IllegalArgumentException("Package Name cannot be NULL!");
137         }
138
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());
143         }
144
145         while (packageElementsItr.hasNext()) {
146             dirPathBuilder.append(File.separator);
147             dirPathBuilder.append(packageElementsItr.next());
148         }
149
150         return new File(parentDirectory, dirPathBuilder.toString());
151     }
152
153     /**
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>).
159      *
160      * @param parentDir
161      *            directory where should be the new file generated
162      * @param type
163      *            JAVA <code>Type</code> for which should be JAVA source code
164      *            generated
165      * @param generator
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
174      */
175     private File generateTypeToJavaFile(final File parentDir, final Type type, final CodeGenerator generator)
176             throws IOException {
177         if (parentDir == null) {
178             LOG.warn("Parent Directory not specified, files will be generated "
179                     + "accordingly to generated Type package path.");
180         }
181         if (type == null) {
182             LOG.error("Cannot generate Type into Java File because " + "Generated Type is NULL!");
183             throw new IllegalArgumentException("Generated Type Cannot be NULL!");
184         }
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!");
188         }
189
190         if (generator.isAcceptable(type)) {
191             File packageDir;
192             if (generator instanceof BuilderGenerator) {
193                 packageDir = packageToDirectory(parentDir, ((GeneratedTypeForBuilder)type).getPackageNameForBuilder());
194             } else {
195                 packageDir = packageToDirectory(parentDir, type.getPackageName());
196             }
197
198             if (!packageDir.exists()) {
199                 packageDir.mkdirs();
200             }
201
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");
205
206             if (file.exists()) {
207                 LOG.warn("Naming conflict for type '{}': file with same name already exists and will not be generated.",
208                     type.getFullyQualifiedName());
209                 return null;
210             }
211
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);
216                     }
217                 } catch (final IOException e) {
218                     LOG.error("Failed to write generate output into {}", file.getPath(), e);
219                     throw e;
220                 }
221             }
222             return file;
223
224         }
225         return null;
226     }
227
228 }