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