| 1 | package be.nikiroo.utils.serial; |
| 2 | |
| 3 | import java.io.IOException; |
| 4 | import java.io.InputStream; |
| 5 | import java.io.OutputStream; |
| 6 | |
| 7 | public abstract class CustomSerializer { |
| 8 | |
| 9 | protected abstract void toStream(OutputStream out, Object value) |
| 10 | throws IOException; |
| 11 | |
| 12 | protected abstract Object fromStream(InputStream in) throws IOException; |
| 13 | |
| 14 | protected abstract String getType(); |
| 15 | |
| 16 | /** |
| 17 | * Encode the object into the given {@link OutputStream} if supported. |
| 18 | * |
| 19 | * @param out |
| 20 | * the builder to append to |
| 21 | * @param value |
| 22 | * the object to encode |
| 23 | * |
| 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}) |
| 27 | * |
| 28 | * @throws IOException |
| 29 | * in case of I/O error |
| 30 | */ |
| 31 | public boolean encode(OutputStream out, Object value) throws IOException { |
| 32 | if (!isSupported(value)) { |
| 33 | return false; |
| 34 | } |
| 35 | |
| 36 | SerialUtils.write(out, "custom^"); |
| 37 | SerialUtils.write(out, getType()); |
| 38 | SerialUtils.write(out, "^"); |
| 39 | toStream(out, value); |
| 40 | |
| 41 | return true; |
| 42 | } |
| 43 | |
| 44 | public Object decode(String encodedValue) throws IOException { |
| 45 | return fromString((String) SerialUtils.decode(contentOf(encodedValue))); |
| 46 | } |
| 47 | |
| 48 | public static boolean isCustom(String encodedValue) { |
| 49 | int pos1 = encodedValue.indexOf('^'); |
| 50 | int pos2 = encodedValue.indexOf('^', pos1 + 1); |
| 51 | |
| 52 | return pos1 >= 0 && pos2 >= 0 && encodedValue.startsWith("custom^"); |
| 53 | } |
| 54 | |
| 55 | public static String typeOf(String encodedValue) { |
| 56 | int pos1 = encodedValue.indexOf('^'); |
| 57 | int pos2 = encodedValue.indexOf('^', pos1 + 1); |
| 58 | String type = encodedValue.substring(pos1 + 1, pos2); |
| 59 | |
| 60 | return type; |
| 61 | } |
| 62 | |
| 63 | public static String contentOf(String encodedValue) { |
| 64 | int pos1 = encodedValue.indexOf('^'); |
| 65 | int pos2 = encodedValue.indexOf('^', pos1 + 1); |
| 66 | String encodedContent = encodedValue.substring(pos2 + 1); |
| 67 | |
| 68 | return encodedContent; |
| 69 | } |
| 70 | } |