blob: c174e52d0ed7d3d45ecb052cdecab1e3ab7b4cec [file] [log] [blame]
Stuart McCullochf3173222012-06-07 21:57:32 +00001package aQute.lib.codec;
2
3import java.io.*;
4import java.lang.reflect.*;
5
6public class HCodec implements Codec {
7 final Codec codec;
8
9 public HCodec(Codec codec) {
10 this.codec = codec;
11 }
12
13 public Object decode(Reader in, Type type) throws Exception {
14 return codec.decode(in, type);
15 }
16
17 public <T> T decode(InputStream in, Class<T> t) throws Exception {
Stuart McCulloch4482c702012-06-15 13:27:53 +000018 return t.cast(decode(in, (Type) t));
Stuart McCullochf3173222012-06-07 21:57:32 +000019 }
20
21 public <T> T decode(Reader in, Class<T> t) throws Exception {
22 return t.cast(decode(in, (Type) t));
23 }
24
25 public Object decode(InputStream in, Type t) throws Exception {
26 InputStreamReader r = new InputStreamReader(in, "UTF-8");
27 return codec.decode(r, t);
28 }
29
30 public void encode(Type t, Object o, Appendable out) throws Exception {
31 codec.encode(t, o, out);
32 }
33
34 public void encode(Type t, Object o, OutputStream out) throws Exception {
35 OutputStreamWriter wr = new OutputStreamWriter(out, "UTF-8");
36 try {
37 codec.encode(t, o, wr);
Stuart McCulloch4482c702012-06-15 13:27:53 +000038 }
39 finally {
Stuart McCullochf3173222012-06-07 21:57:32 +000040 wr.flush();
41 }
42 }
43
44 public <T> T decode(File in, Class<T> t) throws Exception {
45 FileInputStream fin = new FileInputStream(in);
46 try {
47 InputStreamReader rdr = new InputStreamReader(fin, "UTF-8");
48 try {
49 return t.cast(decode(rdr, t));
Stuart McCulloch4482c702012-06-15 13:27:53 +000050 }
51 finally {
Stuart McCullochf3173222012-06-07 21:57:32 +000052 rdr.close();
53 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000054 }
55 finally {
Stuart McCullochf3173222012-06-07 21:57:32 +000056 fin.close();
57 }
58
59 }
60
61 public void encode(Type t, Object o, File out) throws Exception {
62 OutputStream oout = new FileOutputStream(out);
63 try {
64 Writer wr = new OutputStreamWriter(oout, "UTF-8");
65 try {
66 codec.encode(t, o, wr);
Stuart McCulloch4482c702012-06-15 13:27:53 +000067 }
68 finally {
Stuart McCullochf3173222012-06-07 21:57:32 +000069 wr.close();
70 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000071 }
72 finally {
Stuart McCullochf3173222012-06-07 21:57:32 +000073 oout.close();
74 }
75 }
76
77}