Stuart McCulloch | bb01437 | 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 | |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 11 | @Override |
| 12 | void encode(Encoder app, Object object, Map<Object,Type> visited) throws IOException, Exception { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 13 | File f = (File) object; |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 14 | if (!f.isFile()) |
| 15 | throw new RuntimeException("Encoding a file requires the file to exist and to be a normal file " + f); |
| 16 | |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 17 | FileInputStream in = new FileInputStream(f); |
| 18 | try { |
| 19 | app.append('"'); |
| 20 | Base64.encode(in, app); |
| 21 | app.append('"'); |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 22 | } |
| 23 | finally { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 24 | in.close(); |
| 25 | } |
| 26 | } |
| 27 | |
Stuart McCulloch | a21b9e8 | 2012-08-02 13:26:25 +0000 | [diff] [blame] | 28 | @Override |
| 29 | Object decode(Decoder dec, String s) throws Exception { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 30 | File tmp = File.createTempFile("json", ".bin"); |
| 31 | FileOutputStream fout = new FileOutputStream(tmp); |
| 32 | try { |
| 33 | Base64.decode(new StringReader(s), fout); |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 34 | } |
| 35 | finally { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 36 | fout.close(); |
| 37 | } |
| 38 | return tmp; |
| 39 | } |
| 40 | |
| 41 | } |