| 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 | public void encode(StringBuilder builder, Object value) { |
| 12 | String customString = toString(value); |
| 13 | builder.append("custom:").append(getType()).append(":"); |
| 14 | SerialUtils.encode(builder, customString); |
| 15 | } |
| 16 | |
| 17 | public Object decode(String encodedValue) { |
| 18 | return fromString((String) SerialUtils.decode(contentOf(encodedValue))); |
| 19 | } |
| 20 | |
| 21 | public static boolean isCustom(String encodedValue) { |
| 22 | int pos1 = encodedValue.indexOf(':'); |
| 23 | int pos2 = encodedValue.indexOf(':', pos1 + 1); |
| 24 | |
| 25 | return pos1 >= 0 && pos2 >= 0 && encodedValue.startsWith("custom:"); |
| 26 | } |
| 27 | |
| 28 | public static String typeOf(String encodedValue) { |
| 29 | int pos1 = encodedValue.indexOf(':'); |
| 30 | int pos2 = encodedValue.indexOf(':', pos1 + 1); |
| 31 | String type = encodedValue.substring(pos1 + 1, pos2); |
| 32 | |
| 33 | return type; |
| 34 | } |
| 35 | |
| 36 | public static String contentOf(String encodedValue) { |
| 37 | int pos1 = encodedValue.indexOf(':'); |
| 38 | int pos2 = encodedValue.indexOf(':', pos1 + 1); |
| 39 | String encodedContent = encodedValue.substring(pos2 + 1); |
| 40 | |
| 41 | return encodedContent; |
| 42 | } |
| 43 | } |