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 | /** |
143a64f4 | 17 | * Encode the object into the given {@link OutputStream} if supported. |
5bc55b51 | 18 | * |
68532958 | 19 | * @param out |
5bc55b51 NR |
20 | * the builder to append to |
21 | * @param value | |
22 | * the object to encode | |
68532958 | 23 | * |
143a64f4 NR |
24 | * @return FALSE if the value is not supported, TRUE if the operation was |
25 | * successful (if the value is supported by the operation was not | |
26 | * successful, you will get an {@link IOException}) | |
68532958 NR |
27 | * |
28 | * @throws IOException | |
29 | * in case of I/O error | |
5bc55b51 | 30 | */ |
68532958 | 31 | public boolean encode(OutputStream out, Object value) throws IOException { |
143a64f4 NR |
32 | if (!isSupported(value)) { |
33 | return false; | |
34 | } | |
35 | ||
68532958 NR |
36 | SerialUtils.write(out, "custom^"); |
37 | SerialUtils.write(out, getType()); | |
38 | SerialUtils.write(out, "^"); | |
143a64f4 | 39 | toStream(out, value); |
5bc55b51 NR |
40 | |
41 | return true; | |
db31c358 NR |
42 | } |
43 | ||
452f38c8 | 44 | public Object decode(String encodedValue) throws IOException { |
db31c358 NR |
45 | return fromString((String) SerialUtils.decode(contentOf(encodedValue))); |
46 | } | |
47 | ||
48 | public static boolean isCustom(String encodedValue) { | |
f4053377 NR |
49 | int pos1 = encodedValue.indexOf('^'); |
50 | int pos2 = encodedValue.indexOf('^', pos1 + 1); | |
db31c358 | 51 | |
f4053377 | 52 | return pos1 >= 0 && pos2 >= 0 && encodedValue.startsWith("custom^"); |
db31c358 NR |
53 | } |
54 | ||
55 | public static String typeOf(String encodedValue) { | |
f4053377 NR |
56 | int pos1 = encodedValue.indexOf('^'); |
57 | int pos2 = encodedValue.indexOf('^', pos1 + 1); | |
db31c358 NR |
58 | String type = encodedValue.substring(pos1 + 1, pos2); |
59 | ||
60 | return type; | |
61 | } | |
62 | ||
63 | public static String contentOf(String encodedValue) { | |
f4053377 NR |
64 | int pos1 = encodedValue.indexOf('^'); |
65 | int pos2 = encodedValue.indexOf('^', pos1 + 1); | |
db31c358 NR |
66 | String encodedContent = encodedValue.substring(pos2 + 1); |
67 | ||
68 | return encodedContent; | |
69 | } | |
70 | } |