| 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 possible (if |
| 18 | * supported). |
| 19 | * |
| 20 | * @param out |
| 21 | * the builder to append to |
| 22 | * @param value |
| 23 | * the object to encode |
| 24 | * |
| 25 | * @return TRUE if success, FALSE if not (the content of the builder won't |
| 26 | * be changed in case of failure) |
| 27 | * |
| 28 | * @throws IOException |
| 29 | * in case of I/O error |
| 30 | */ |
| 31 | public boolean encode(OutputStream out, Object value) throws IOException { |
| 32 | InputStream customString = toStream(out, value); |
| 33 | SerialUtils.write(out, "custom^"); |
| 34 | SerialUtils.write(out, getType()); |
| 35 | SerialUtils.write(out, "^"); |
| 36 | if (!SerialUtils.encode(out, customString)) { |
| 37 | return false; |
| 38 | } |
| 39 | |
| 40 | return true; |
| 41 | } |
| 42 | |
| 43 | public Object decode(String encodedValue) throws IOException { |
| 44 | return fromString((String) SerialUtils.decode(contentOf(encodedValue))); |
| 45 | } |
| 46 | |
| 47 | public static boolean isCustom(String encodedValue) { |
| 48 | int pos1 = encodedValue.indexOf('^'); |
| 49 | int pos2 = encodedValue.indexOf('^', pos1 + 1); |
| 50 | |
| 51 | return pos1 >= 0 && pos2 >= 0 && encodedValue.startsWith("custom^"); |
| 52 | } |
| 53 | |
| 54 | public static String typeOf(String encodedValue) { |
| 55 | int pos1 = encodedValue.indexOf('^'); |
| 56 | int pos2 = encodedValue.indexOf('^', pos1 + 1); |
| 57 | String type = encodedValue.substring(pos1 + 1, pos2); |
| 58 | |
| 59 | return type; |
| 60 | } |
| 61 | |
| 62 | public static String contentOf(String encodedValue) { |
| 63 | int pos1 = encodedValue.indexOf('^'); |
| 64 | int pos2 = encodedValue.indexOf('^', pos1 + 1); |
| 65 | String encodedContent = encodedValue.substring(pos2 + 1); |
| 66 | |
| 67 | return encodedContent; |
| 68 | } |
| 69 | } |