Stuart McCulloch | f317322 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 1 | package aQute.lib.json; |
| 2 | |
| 3 | import java.io.*; |
| 4 | import java.lang.reflect.*; |
| 5 | import java.util.*; |
| 6 | |
| 7 | import aQute.lib.base64.*; |
| 8 | |
| 9 | public class FileHandler extends Handler { |
| 10 | |
| 11 | @Override void encode(Encoder app, Object object, Map<Object, Type> visited) |
| 12 | throws IOException, Exception { |
| 13 | File f = (File) object; |
| 14 | if ( !f.isFile()) |
| 15 | throw new RuntimeException("Encoding a file requires the file to exist and to be a normal file " + f ); |
| 16 | |
| 17 | FileInputStream in = new FileInputStream(f); |
| 18 | try { |
| 19 | app.append('"'); |
| 20 | Base64.encode(in, app); |
| 21 | app.append('"'); |
| 22 | } finally { |
| 23 | in.close(); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | Object decode(String s) throws Exception { |
| 28 | File tmp = File.createTempFile("json", ".bin"); |
| 29 | FileOutputStream fout = new FileOutputStream(tmp); |
| 30 | try { |
| 31 | Base64.decode(new StringReader(s), fout); |
| 32 | } finally { |
| 33 | fout.close(); |
| 34 | } |
| 35 | return tmp; |
| 36 | } |
| 37 | |
| 38 | } |