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 | |
| 28 | Object decode(String s) throws Exception { |
| 29 | File tmp = File.createTempFile("json", ".bin"); |
| 30 | FileOutputStream fout = new FileOutputStream(tmp); |
| 31 | try { |
| 32 | Base64.decode(new StringReader(s), fout); |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame] | 33 | } |
| 34 | finally { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 35 | fout.close(); |
| 36 | } |
| 37 | return tmp; |
| 38 | } |
| 39 | |
| 40 | } |