1 package be
.nikiroo
.utils
.serial
;
3 import java
.io
.IOException
;
4 import java
.io
.InputStream
;
5 import java
.io
.OutputStream
;
7 import be
.nikiroo
.utils
.IOUtils
;
8 import be
.nikiroo
.utils
.streams
.NextableInputStream
;
9 import be
.nikiroo
.utils
.streams
.NextableInputStreamStep
;
11 public abstract class CustomSerializer
{
13 protected abstract void toStream(OutputStream out
, Object value
)
16 protected abstract Object
fromStream(InputStream in
) throws IOException
;
18 protected abstract String
getType();
21 * Encode the object into the given {@link OutputStream} if supported.
24 * the builder to append to
26 * the object to encode
28 * @return FALSE if the value is not supported, TRUE if the operation was
29 * successful (if the value is supported by the operation was not
30 * successful, you will get an {@link IOException})
33 * in case of I/O error
35 public boolean encode(OutputStream out
, Object value
) throws IOException
{
36 SerialUtils
.write(out
, "custom^");
37 SerialUtils
.write(out
, getType());
38 SerialUtils
.write(out
, "^");
45 public Object
decode(InputStream in
) throws IOException
{
47 NextableInputStream stream
= new NextableInputStream(in
,
48 new NextableInputStreamStep('^'));
52 throw new IOException("Cannot find the first custom^ element");
55 String custom
= IOUtils
.readSmallStream(stream
);
56 if (!"custom".equals(custom
)) {
57 throw new IOException(
58 "Cannot find the first custom^ element, it is: "
63 throw new IOException("Cannot find the second custom^"
64 + getType() + " element");
67 String type
= IOUtils
.readSmallStream(stream
);
68 if (!getType().equals(type
)) {
69 throw new IOException("Cannot find the second custom^"
70 + getType() + " element, it is: custom^" + type
+ "^");
73 if (!stream
.nextAll()) {
74 throw new IOException("Cannot find the third custom^"
75 + getType() + "^value element");
79 return fromStream(stream
);
85 public static boolean isCustom(String encodedValue
) {
86 int pos1
= encodedValue
.indexOf('^');
87 int pos2
= encodedValue
.indexOf('^', pos1
+ 1);
89 return pos1
>= 0 && pos2
>= 0 && encodedValue
.startsWith("custom^");
92 public static String
typeOf(String encodedValue
) {
93 int pos1
= encodedValue
.indexOf('^');
94 int pos2
= encodedValue
.indexOf('^', pos1
+ 1);
95 String type
= encodedValue
.substring(pos1
+ 1, pos2
);
100 public static String
contentOf(String encodedValue
) {
101 int pos1
= encodedValue
.indexOf('^');
102 int pos2
= encodedValue
.indexOf('^', pos1
+ 1);
103 String encodedContent
= encodedValue
.substring(pos2
+ 1);
105 return encodedContent
;