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
;
10 import be
.nikiroo
.utils
.streams
.ReplaceInputStream
;
11 import be
.nikiroo
.utils
.streams
.ReplaceOutputStream
;
13 public abstract class CustomSerializer
{
15 protected abstract void toStream(OutputStream out
, Object value
)
18 protected abstract Object
fromStream(InputStream in
) throws IOException
;
20 protected abstract String
getType();
23 * Encode the object into the given {@link OutputStream} if supported.
26 * the builder to append to
28 * the object to encode
31 * in case of I/O error
33 public void encode(OutputStream out
, Object value
) throws IOException
{
34 ReplaceOutputStream replace
= new ReplaceOutputStream(out
, //
35 new String
[] { "\\", "\n" }, //
36 new String
[] { "\\\\", "\\n" });
39 SerialUtils
.write(replace
, "custom^");
40 SerialUtils
.write(replace
, getType());
41 SerialUtils
.write(replace
, "^");
42 toStream(replace
, value
);
48 public Object
decode(InputStream in
) throws IOException
{
49 ReplaceInputStream replace
= new ReplaceInputStream(in
, //
50 new String
[] { "\\\\", "\\n" }, //
51 new String
[] { "\\", "\n" });
54 NextableInputStream stream
= new NextableInputStream(
55 replace
.open(), new NextableInputStreamStep('^'));
58 throw new IOException(
59 "Cannot find the first custom^ element");
62 String custom
= IOUtils
.readSmallStream(stream
);
63 if (!"custom".equals(custom
)) {
64 throw new IOException(
65 "Cannot find the first custom^ element, it is: "
70 throw new IOException("Cannot find the second custom^"
71 + getType() + " element");
74 String type
= IOUtils
.readSmallStream(stream
);
75 if (!getType().equals(type
)) {
76 throw new IOException("Cannot find the second custom^"
77 + getType() + " element, it is: custom^" + type
81 if (!stream
.nextAll()) {
82 throw new IOException("Cannot find the third custom^"
83 + getType() + "^value element");
86 return fromStream(stream
);
95 public static boolean isCustom(String encodedValue
) {
96 int pos1
= encodedValue
.indexOf('^');
97 int pos2
= encodedValue
.indexOf('^', pos1
+ 1);
99 return pos1
>= 0 && pos2
>= 0 && encodedValue
.startsWith("custom^");
102 public static String
typeOf(String encodedValue
) {
103 int pos1
= encodedValue
.indexOf('^');
104 int pos2
= encodedValue
.indexOf('^', pos1
+ 1);
105 String type
= encodedValue
.substring(pos1
+ 1, pos2
);
110 public static String
contentOf(String encodedValue
) {
111 int pos1
= encodedValue
.indexOf('^');
112 int pos2
= encodedValue
.indexOf('^', pos1
+ 1);
113 String encodedContent
= encodedValue
.substring(pos2
+ 1);
115 return encodedContent
;