Merge "Switch to using plexus-build-api for file output"
[mdsal.git] / code-generator / binding-java-api-generator / src / main / java / org / opendaylight / yangtools / sal / java / api / generator / GeneratorJavaFile.java
1 /*
2  * Copyright (c) 2013 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 package org.opendaylight.yangtools.sal.java.api.generator;
9
10 import java.io.BufferedWriter;
11 import java.io.File;
12 import java.io.IOException;
13 import java.io.OutputStream;
14 import java.io.OutputStreamWriter;
15 import java.io.Writer;
16 import java.util.ArrayList;
17 import java.util.List;
18 import java.util.Set;
19
20 import org.opendaylight.yangtools.sal.binding.model.api.CodeGenerator;
21 import org.opendaylight.yangtools.sal.binding.model.api.Type;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24 import org.sonatype.plexus.build.incremental.BuildContext;
25 import org.sonatype.plexus.build.incremental.DefaultBuildContext;
26
27 import com.google.common.base.Preconditions;
28
29 /**
30  * Generates files with JAVA source codes for every specified type.
31  *
32  */
33 public final class GeneratorJavaFile {
34
35     private static final Logger LOG = LoggerFactory.getLogger(GeneratorJavaFile.class);
36
37     /**
38      * List of <code>CodeGenerator</code> instances.
39      */
40     private final List<CodeGenerator> generators = new ArrayList<>();
41
42     /**
43      * Set of <code>Type</code> instances for which the JAVA code is generated.
44      */
45     private final Set<? extends Type> types;
46
47     /**
48      * BuildContext used for instantiating files
49      */
50     private final BuildContext buildContext;
51
52     /**
53      * Creates instance of this class with the set of <code>types</code> for
54      * which the JAVA code is generated.
55      *
56      * The instances of concrete JAVA code generator are created.
57      *
58      * @param buildContext
59      *            build context to use for accessing files
60      * @param types
61      *            set of types for which JAVA code should be generated
62      */
63     public GeneratorJavaFile(final BuildContext buildContext, final Set<? extends Type> types) {
64         this.buildContext = Preconditions.checkNotNull(buildContext);
65         this.types = Preconditions.checkNotNull(types);
66         generators.add(new InterfaceGenerator());
67         generators.add(new TOGenerator());
68         generators.add(new EnumGenerator());
69         generators.add(new BuilderGenerator());
70     }
71
72     /**
73      * Creates instance of this class with the set of <code>types</code> for
74      * which the JAVA code is generated. Generator instantiated this way uses
75      * the default build context, e.g. it will re-generate any and all files.
76      *
77      * The instances of concrete JAVA code generator are created.
78      *
79      * @param types
80      *            set of types for which JAVA code should be generated
81      */
82     public GeneratorJavaFile(final Set<? extends Type> types) {
83         this(new DefaultBuildContext(), types);
84     }
85
86     /**
87      * Generates list of files with JAVA source code. Only the suitable code
88      * generator is used to generate the source code for the concrete type.
89      *
90      * @param parentDirectory
91      *            directory to which the output source codes should be generated
92      * @return list of output files
93      * @throws IOException
94      *             if the error during writing to the file occurs
95      */
96     public List<File> generateToFile(final File parentDirectory) throws IOException {
97         final List<File> result = new ArrayList<>();
98         for (Type type : types) {
99             if (type != null) {
100                 for (CodeGenerator generator : generators) {
101                     File generatedJavaFile = generateTypeToJavaFile(parentDirectory, type, generator);
102                     if (generatedJavaFile != null) {
103                         result.add(generatedJavaFile);
104                     }
105                 }
106             }
107         }
108         return result;
109     }
110
111     /**
112      * Generates <code>File</code> for <code>type</code>. All files are stored
113      * to subfolders of base directory <code>parentDir</code>. Subdirectories
114      * are generated according to packages to which the type belongs (e. g. if
115      * type belongs to the package <i>org.pcg</i> then in <code>parentDir</code>
116      * is created directory <i>org</i> which contains <i>pcg</i>).
117      *
118      * @param parentDir
119      *            directory where should be the new file generated
120      * @param type
121      *            JAVA <code>Type</code> for which should be JAVA source code
122      *            generated
123      * @param generator
124      *            code generator which is used for generating of the source code
125      * @return file which contains JAVA source code
126      * @throws IOException
127      *             if the error during writing to the file occurs
128      * @throws IllegalArgumentException
129      *             if <code>type</code> equals <code>null</code>
130      * @throws IllegalStateException
131      *             if string with generated code is empty
132      */
133     private File generateTypeToJavaFile(final File parentDir, final Type type, final CodeGenerator generator)
134             throws IOException {
135         if (parentDir == null) {
136             LOG.warn("Parent Directory not specified, files will be generated "
137                     + "accordingly to generated Type package path.");
138         }
139         if (type == null) {
140             LOG.error("Cannot generate Type into Java File because " + "Generated Type is NULL!");
141             throw new IllegalArgumentException("Generated Type Cannot be NULL!");
142         }
143         if (generator == null) {
144             LOG.error("Cannot generate Type into Java File because " + "Code Generator instance is NULL!");
145             throw new IllegalArgumentException("Code Generator Cannot be NULL!");
146         }
147         final File packageDir = packageToDirectory(parentDir, type.getPackageName());
148
149         if (!packageDir.exists()) {
150             packageDir.mkdirs();
151         }
152
153         if (generator.isAcceptable(type)) {
154             final String generatedCode = generator.generate(type);
155             if (generatedCode.isEmpty()) {
156                 throw new IllegalStateException("Generated code should not be empty!");
157             }
158             final File file = new File(packageDir, generator.getUnitName(type) + ".java");
159             try (final OutputStream stream = buildContext.newFileOutputStream(file)) {
160                 try (final Writer fw = new OutputStreamWriter(stream)) {
161                     try (final BufferedWriter bw = new BufferedWriter(fw)) {
162                         bw.write(generatedCode);
163                     }
164                 } catch (IOException e) {
165                     LOG.error("Failed to write generate output into {}", file.getPath(), e);
166                     throw e;
167                 }
168             }
169             return file;
170         }
171         return null;
172     }
173
174     /**
175      * Creates the package directory path as concatenation of
176      * <code>parentDirectory</code> and parsed <code>packageName</code>. The
177      * parsing of <code>packageName</code> is realized as replacement of the
178      * package name dots with the file system separator.
179      *
180      * @param parentDirectory
181      *            <code>File</code> object with reference to parent directory
182      * @param packageName
183      *            string with the name of the package
184      * @return <code>File</code> object which refers to the new directory for
185      *         package <code>packageName</code>
186      */
187     private File packageToDirectory(final File parentDirectory, final String packageName) {
188         if (packageName == null) {
189             throw new IllegalArgumentException("Package Name cannot be NULL!");
190         }
191
192         final String[] subDirNames = packageName.split("\\.");
193         final StringBuilder dirPathBuilder = new StringBuilder();
194         dirPathBuilder.append(subDirNames[0]);
195         for (int i = 1; i < subDirNames.length; ++i) {
196             dirPathBuilder.append(File.separator);
197             dirPathBuilder.append(subDirNames[i]);
198         }
199         return new File(parentDirectory, dirPathBuilder.toString());
200     }
201 }