Version 3.1.1: fixes: ServerBridge, Import/Export
[nikiroo-utils.git] / src / be / nikiroo / utils / serial / CustomSerializer.java
1 package be.nikiroo.utils.serial;
2
3 import java.io.IOException;
4
5 public abstract class CustomSerializer {
6
7 protected abstract String toString(Object value);
8
9 protected abstract Object fromString(String content) throws IOException;
10
11 protected abstract String getType();
12
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();
25 String customString = toString(value);
26 builder.append("custom:").append(getType()).append(":");
27 if (!SerialUtils.encode(builder, customString)) {
28 builder.delete(prev, builder.length());
29 return false;
30 }
31
32 return true;
33 }
34
35 public Object decode(String encodedValue) throws IOException {
36 return fromString((String) SerialUtils.decode(contentOf(encodedValue)));
37 }
38
39 public static boolean isCustom(String encodedValue) {
40 int pos1 = encodedValue.indexOf(':');
41 int pos2 = encodedValue.indexOf(':', pos1 + 1);
42
43 return pos1 >= 0 && pos2 >= 0 && encodedValue.startsWith("custom:");
44 }
45
46 public static String typeOf(String encodedValue) {
47 int pos1 = encodedValue.indexOf(':');
48 int pos2 = encodedValue.indexOf(':', pos1 + 1);
49 String type = encodedValue.substring(pos1 + 1, pos2);
50
51 return type;
52 }
53
54 public static String contentOf(String encodedValue) {
55 int pos1 = encodedValue.indexOf(':');
56 int pos2 = encodedValue.indexOf(':', pos1 + 1);
57 String encodedContent = encodedValue.substring(pos2 + 1);
58
59 return encodedContent;
60 }
61 }