1 package polyglot.util; 2 3 import polyglot.main.Report; 4 import polyglot.types.*; 5 6 import java.io.*; 7 import java.util.zip.*; 8 9 24 public class TypeEncoder 25 { 26 protected TypeSystem ts; 27 protected final boolean zip = true; 28 protected final boolean base64 = true; 29 protected final boolean test = false; 30 31 public TypeEncoder( TypeSystem ts) 32 { 33 this.ts = ts; 34 } 35 36 public String encode( Type t) throws IOException 37 { 38 ByteArrayOutputStream baos; 39 ObjectOutputStream oos; 40 41 if (Report.should_report(Report.serialize, 1)) { 42 Report.report(1, "Encoding type " + t); 43 } 44 45 baos = new ByteArrayOutputStream(); 46 47 if (zip) { 48 oos = new TypeOutputStream( new GZIPOutputStream( baos), ts, t); 49 } 50 else { 51 oos = new TypeOutputStream( baos, ts, t); 52 } 53 54 oos.writeObject( t); 55 oos.flush(); 56 oos.close(); 57 58 byte[] b = baos.toByteArray(); 59 60 if (Report.should_report(Report.serialize, 2)) { 61 Report.report(2, "Size of serialization (with" 62 + (zip?"":"out") + " zipping) is " + b.length + " bytes"); 63 } 64 65 String s; 66 if (base64) { 67 s = new String (Base64.encode(b)); 68 } 69 else { 70 StringBuffer sb = new StringBuffer (b.length); 71 for (int i = 0; i < b.length; i++) 72 sb.append((char) b[i]); 73 s = sb.toString(); 74 } 75 76 if (Report.should_report(Report.serialize, 2)) { 77 Report.report(2, "Size of serialization after conversion to string is " 78 + s.length() + " characters"); 79 } 80 81 if (test) { 82 try { 84 decode(s); 85 } 86 catch (Exception e) { 87 e.printStackTrace(); 88 throw new InternalCompilerError( 89 "Could not decode back to " + t + ": " + e.getMessage(), e); 90 } 91 } 92 93 return s; 94 } 95 96 public Type decode(String s) throws InvalidClassException 97 { 98 ObjectInputStream ois; 99 byte[] b; 100 101 if (base64) { 102 b = Base64.decode(s.toCharArray()); 103 } 104 else { 105 char[] source; 106 source = s.toCharArray(); 107 b = new byte[ source.length]; 108 for (int i = 0; i < source.length; i++) 109 b[i] = (byte) source[i]; 110 } 111 112 try { 113 if (zip) { 114 ois = new TypeInputStream( new GZIPInputStream( 115 new ByteArrayInputStream( b)), ts); 116 } 117 else { 118 ois = new TypeInputStream( new ByteArrayInputStream( b), ts); 119 } 120 return (Type)ois.readObject(); 121 } 122 catch (InvalidClassException e) { 123 throw e; 124 } 125 catch (IOException e) { 126 throw new InternalCompilerError("IOException thrown while " + 127 "decoding serialized type info: " + e.getMessage(), e); 128 } 129 catch (ClassNotFoundException e) { 130 throw new InternalCompilerError("Unable to find one of the classes " + 131 "for the serialized type info: " + e.getMessage(), e); 132 } 133 } 134 } 135 | Popular Tags |