added org.ibex.util.Encode.JavaSourceCode
[org.ibex.util.git] / src / org / ibex / util / Encode.java
1 package org.ibex.util;
2 import java.io.*;
3 import java.util.*;
4 import java.util.zip.*;
5
6 public class Encode {
7
8     public static class JavaSourceCode {
9
10         public static final int LINE_LENGTH = 80 / 4;
11         public static void main(String[] s) throws Exception { System.out.println(encode(s[0], s[1], System.in)); }
12
13         public static String encode(String packageName, String className, InputStream is) throws IOException {
14
15             // compress first, since the encoded form has more entropy
16             ByteArrayOutputStream baos;
17             OutputStream os = new GZIPOutputStream(baos = new ByteArrayOutputStream());
18
19             byte[] buf = new byte[1024];
20             while(true) {
21                 int numread = is.read(buf, 0, buf.length);
22                 if (numread == -1) break;
23                 os.write(buf, 0, numread);
24             }
25             os.close();
26             buf = baos.toByteArray();
27             
28             StringBuffer ret = new StringBuffer();
29             ret.append("// generated by " + Encode.class.getName() + "\n\n");
30             ret.append("package " + packageName + ";\n\n");
31             ret.append("public class " + className + " {\n");
32             ret.append("    public static String data = \n");
33             for(int pos = 0; pos<buf.length;) {
34                 ret.append("        \"");
35                 for(int i=0; i<LINE_LENGTH && pos<buf.length; i++) {
36                     String cs = Integer.toOctalString(buf[pos++] & 0xff);
37                     while(cs.length() < 3) cs = "0" + cs;
38                     ret.append("\\" + cs);
39                 }
40                 ret.append("\" +\n");
41             }
42             ret.append("    \"\";\n");
43             ret.append("}\n");
44             return ret.toString();
45         }
46
47     }
48
49 }
50