1 package net.sourceforge.jenesis4java.impl;
2
3 /*
4 * #%L
5 * Jenesis 4 Java Code Generator
6 * %%
7 * Copyright (C) 2000 - 2015 jenesis4java
8 * %%
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Lesser General Public License as
11 * published by the Free Software Foundation, either version 3 of the
12 * License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Lesser Public License for more details.
18 *
19 * You should have received a copy of the GNU General Lesser Public
20 * License along with this program. If not, see
21 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
22 * #L%
23 */
24
25 import java.io.*;
26
27 import net.sourceforge.jenesis4java.CodeWriter;
28 import net.sourceforge.jenesis4java.CompilationUnit;
29 import net.sourceforge.jenesis4java.CompilationUnitEncoder;
30 import net.sourceforge.jenesis4java.impl.MDeclaration.MCompilationUnit;
31
32 import static java.nio.charset.StandardCharsets.UTF_8;
33
34 public class BasicCompilationUnitEncoder implements CompilationUnitEncoder {
35
36 @Override
37 public void encode(CompilationUnit compilationUnit) {
38
39 // wrap this section for io exceptions
40 PrintWriter fout = null;
41
42 // Make a file object which corresponds to the
43 // filename which we will write to.
44 File file = new File(((MCompilationUnit) compilationUnit).getFileName());
45
46 // Get the parent file such that we can create the
47 // directory if necessary. NOTE: JDK1.2 dependency
48 // here.
49 File dir = file.getParentFile();
50
51 try {
52
53 // Make sure it exists.
54 if (!dir.exists() && !dir.mkdirs()) {
55 throw new RuntimeException("Could not create directory(s) " + dir.getCanonicalPath());
56 }
57
58 // now we want to make the stream...
59 Writer fileWriter = new OutputStreamWriter(new FileOutputStream(file), UTF_8);
60 fout = new PrintWriter(new BufferedWriter(fileWriter));
61
62 // ...wrap it with a code writer...
63 CodeWriter out = new MCodeWriter(fout);
64
65 // ...generate the code...
66 compilationUnit.toCode(out);
67
68 // ... and finally close and drop the stream
69 fout.close();
70 fout = null;
71
72 } catch (IOException ioex) {
73 ioex.printStackTrace();
74 } finally {
75 if (fout != null) {
76 try {
77 fout.close();
78 } catch (Exception ex) {
79 throw new RuntimeException(ex);
80 }
81 }
82 }
83 }
84
85 }