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