blob: b2c083840f7fdccab4f2c02b07d3eb20b6431283 [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.lib.json;
2
3import java.io.*;
4import java.lang.reflect.*;
5import java.util.*;
6
7import aQute.lib.base64.*;
8
9public class FileHandler extends Handler {
10
Stuart McCulloch2286f232012-06-15 13:27:53 +000011 @Override
12 void encode(Encoder app, Object object, Map<Object,Type> visited) throws IOException, Exception {
Stuart McCullochbb014372012-06-07 21:57:32 +000013 File f = (File) object;
Stuart McCulloch2286f232012-06-15 13:27:53 +000014 if (!f.isFile())
15 throw new RuntimeException("Encoding a file requires the file to exist and to be a normal file " + f);
16
Stuart McCullochbb014372012-06-07 21:57:32 +000017 FileInputStream in = new FileInputStream(f);
18 try {
19 app.append('"');
20 Base64.encode(in, app);
21 app.append('"');
Stuart McCulloch2286f232012-06-15 13:27:53 +000022 }
23 finally {
Stuart McCullochbb014372012-06-07 21:57:32 +000024 in.close();
25 }
26 }
27
Stuart McCullocha21b9e82012-08-02 13:26:25 +000028 @Override
29 Object decode(Decoder dec, String s) throws Exception {
Stuart McCullochbb014372012-06-07 21:57:32 +000030 File tmp = File.createTempFile("json", ".bin");
31 FileOutputStream fout = new FileOutputStream(tmp);
32 try {
33 Base64.decode(new StringReader(s), fout);
Stuart McCulloch2286f232012-06-15 13:27:53 +000034 }
35 finally {
Stuart McCullochbb014372012-06-07 21:57:32 +000036 fout.close();
37 }
38 return tmp;
39 }
40
41}