blob: c0240900611e391b14b7945ffb3284df2bfcc489 [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
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 McCulloch2286f232012-06-15 13:27:53 +000033 }
34 finally {
Stuart McCullochbb014372012-06-07 21:57:32 +000035 fout.close();
36 }
37 return tmp;
38 }
39
40}