Commit | Line | Data |
---|---|---|
db31c358 NR |
1 | package be.nikiroo.utils.serial; |
2 | ||
452f38c8 | 3 | import java.io.IOException; |
68532958 NR |
4 | import java.io.InputStream; |
5 | import java.io.OutputStream; | |
452f38c8 | 6 | |
db31c358 NR |
7 | public abstract class CustomSerializer { |
8 | ||
68532958 NR |
9 | protected abstract void toStream(OutputStream out, Object value) |
10 | throws IOException; | |
db31c358 | 11 | |
68532958 | 12 | protected abstract Object fromStream(InputStream in) throws IOException; |
db31c358 NR |
13 | |
14 | protected abstract String getType(); | |
15 | ||
5bc55b51 | 16 | /** |
68532958 NR |
17 | * Encode the object into the given {@link OutputStream} if possible (if |
18 | * supported). | |
5bc55b51 | 19 | * |
68532958 | 20 | * @param out |
5bc55b51 NR |
21 | * the builder to append to |
22 | * @param value | |
23 | * the object to encode | |
68532958 | 24 | * |
5bc55b51 NR |
25 | * @return TRUE if success, FALSE if not (the content of the builder won't |
26 | * be changed in case of failure) | |
68532958 NR |
27 | * |
28 | * @throws IOException | |
29 | * in case of I/O error | |
5bc55b51 | 30 | */ |
68532958 NR |
31 | public boolean encode(OutputStream out, Object value) throws IOException { |
32 | InputStream customString = toStream(out, value); | |
33 | SerialUtils.write(out, "custom^"); | |
34 | SerialUtils.write(out, getType()); | |
35 | SerialUtils.write(out, "^"); | |
36 | if (!SerialUtils.encode(out, customString)) { | |
5bc55b51 NR |
37 | return false; |
38 | } | |
39 | ||
40 | return true; | |
db31c358 NR |
41 | } |
42 | ||
452f38c8 | 43 | public Object decode(String encodedValue) throws IOException { |
db31c358 NR |
44 | return fromString((String) SerialUtils.decode(contentOf(encodedValue))); |
45 | } | |
46 | ||
47 | public static boolean isCustom(String encodedValue) { | |
f4053377 NR |
48 | int pos1 = encodedValue.indexOf('^'); |
49 | int pos2 = encodedValue.indexOf('^', pos1 + 1); | |
db31c358 | 50 | |
f4053377 | 51 | return pos1 >= 0 && pos2 >= 0 && encodedValue.startsWith("custom^"); |
db31c358 NR |
52 | } |
53 | ||
54 | public static String typeOf(String encodedValue) { | |
f4053377 NR |
55 | int pos1 = encodedValue.indexOf('^'); |
56 | int pos2 = encodedValue.indexOf('^', pos1 + 1); | |
db31c358 NR |
57 | String type = encodedValue.substring(pos1 + 1, pos2); |
58 | ||
59 | return type; | |
60 | } | |
61 | ||
62 | public static String contentOf(String encodedValue) { | |
f4053377 NR |
63 | int pos1 = encodedValue.indexOf('^'); |
64 | int pos2 = encodedValue.indexOf('^', pos1 + 1); | |
db31c358 NR |
65 | String encodedContent = encodedValue.substring(pos2 + 1); |
66 | ||
67 | return encodedContent; | |
68 | } | |
69 | } |