View Javadoc
1   package at.rseiler.spbee.core.util;
2   
3   import com.sun.codemodel.CodeWriter;
4   import com.sun.codemodel.JPackage;
5   
6   import java.io.ByteArrayOutputStream;
7   import java.io.FilterOutputStream;
8   import java.io.IOException;
9   import java.io.OutputStream;
10  import java.nio.charset.Charset;
11  
12  /**
13   * Helper class to retrieve the Java code as String from the {@link com.sun.codemodel.JCodeModel}.
14   *
15   * @author Reinhard Seiler {@literal <rseiler.developer@gmail.com>}
16   */
17  public class StringCodeWriter extends CodeWriter {
18  
19      private final ByteArrayOutputStream out = new ByteArrayOutputStream();
20  
21      /**
22       * Retrieves the Java code as String.
23       *
24       * @return the Java code
25       */
26      public String getJavaCode() {
27          return new String(out.toByteArray(), Charset.defaultCharset());
28      }
29  
30      @Override
31      public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
32          return new InternalFilterOutputStream(out);
33      }
34  
35      @Override
36      public void close() throws IOException {
37          out.close();
38      }
39  
40      private static class InternalFilterOutputStream extends FilterOutputStream {
41  
42          public InternalFilterOutputStream(ByteArrayOutputStream out) {
43              super(out);
44          }
45  
46          @Override
47          public void close() {
48              // don't let this stream close
49          }
50  
51      }
52  }