1 package be
.nikiroo
.utils
.serial
;
3 import java
.io
.IOException
;
4 import java
.io
.InputStream
;
5 import java
.io
.NotSerializableException
;
6 import java
.io
.OutputStream
;
7 import java
.lang
.reflect
.Array
;
8 import java
.lang
.reflect
.Constructor
;
9 import java
.lang
.reflect
.Field
;
10 import java
.lang
.reflect
.Modifier
;
12 import java
.util
.ArrayList
;
13 import java
.util
.HashMap
;
14 import java
.util
.List
;
16 import java
.util
.UnknownFormatConversionException
;
18 import be
.nikiroo
.utils
.IOUtils
;
19 import be
.nikiroo
.utils
.Image
;
20 import be
.nikiroo
.utils
.StringUtils
;
21 import be
.nikiroo
.utils
.streams
.Base64InputStream
;
22 import be
.nikiroo
.utils
.streams
.Base64OutputStream
;
23 import be
.nikiroo
.utils
.streams
.BufferedInputStream
;
24 import be
.nikiroo
.utils
.streams
.NextableInputStream
;
25 import be
.nikiroo
.utils
.streams
.NextableInputStreamStep
;
28 * Small class to help with serialisation.
30 * Note that we do not support inner classes (but we do support nested classes)
31 * and all objects require an empty constructor to be deserialised.
33 * It is possible to add support to custom types (both the encoder and the
34 * decoder will require the custom classes) -- see {@link CustomSerializer}.
36 * Default supported types are:
38 * <li>NULL (as a null value)</li>
48 * <li>Enum (any enum whose name and value is known by the caller)</li>
49 * <li>java.awt.image.BufferedImage (as a {@link CustomSerializer})</li>
50 * <li>An array of the above (as a {@link CustomSerializer})</li>
56 public class SerialUtils
{
57 private static Map
<String
, CustomSerializer
> customTypes
;
60 customTypes
= new HashMap
<String
, CustomSerializer
>();
63 customTypes
.put("[]", new CustomSerializer() {
65 protected void toStream(OutputStream out
, Object value
)
68 String type
= value
.getClass().getCanonicalName();
69 type
= type
.substring(0, type
.length() - 2); // remove the []
73 for (int i
= 0; true; i
++) {
74 Object item
= Array
.get(value
, i
);
76 // encode it normally if direct value
78 if (!SerialUtils
.encode(out
, item
)) {
81 OutputStream out64
= new Base64OutputStream(
83 new Exporter(out64
).append(item
);
85 } catch (NotSerializableException e
) {
86 throw new UnknownFormatConversionException(e
91 } catch (ArrayIndexOutOfBoundsException e
) {
97 protected Object
fromStream(InputStream in
) throws IOException
{
98 NextableInputStream stream
= new NextableInputStream(in
,
99 new NextableInputStreamStep('\r'));
102 List
<Object
> list
= new ArrayList
<Object
>();
104 String type
= IOUtils
.readSmallStream(stream
);
106 while (stream
.next()) {
107 Object value
= new Importer().read(stream
).getValue();
111 Object array
= Array
.newInstance(
112 SerialUtils
.getClass(type
), list
.size());
113 for (int i
= 0; i
< list
.size(); i
++) {
114 Array
.set(array
, i
, list
.get(i
));
118 } catch (Exception e
) {
119 if (e
instanceof IOException
) {
120 throw (IOException
) e
;
122 throw new IOException(e
.getMessage());
127 protected String
getType() {
133 customTypes
.put("java.net.URL", new CustomSerializer() {
135 protected void toStream(OutputStream out
, Object value
)
139 val
= ((URL
) value
).toString();
142 out
.write(StringUtils
.getBytes(val
));
146 protected Object
fromStream(InputStream in
) throws IOException
{
147 String val
= IOUtils
.readSmallStream(in
);
148 if (!val
.isEmpty()) {
156 protected String
getType() {
157 return "java.net.URL";
161 // Images (this is currently the only supported image type by default)
162 customTypes
.put("be.nikiroo.utils.Image", new CustomSerializer() {
164 protected void toStream(OutputStream out
, Object value
)
166 Image img
= (Image
) value
;
167 OutputStream encoded
= new Base64OutputStream(out
, true);
169 InputStream in
= img
.newInputStream();
171 IOUtils
.write(in
, encoded
);
182 protected String
getType() {
183 return "be.nikiroo.utils.Image";
187 protected Object
fromStream(InputStream in
) throws IOException
{
190 InputStream decoded
= new Base64InputStream(in
, false);
191 return new Image(decoded
);
192 } catch (IOException e
) {
193 throw new UnknownFormatConversionException(e
.getMessage());
200 * Create an empty object of the given type.
203 * the object type (its class name)
205 * @return the new object
207 * @throws ClassNotFoundException
208 * if the class cannot be found
209 * @throws NoSuchMethodException
210 * if the given class is not compatible with this code
212 public static Object
createObject(String type
)
213 throws ClassNotFoundException
, NoSuchMethodException
{
217 Class
<?
> clazz
= getClass(type
);
218 String className
= clazz
.getName();
219 List
<Object
> args
= new ArrayList
<Object
>();
220 List
<Class
<?
>> classes
= new ArrayList
<Class
<?
>>();
221 Constructor
<?
> ctor
= null;
222 if (className
.contains("$")) {
223 for (String parentName
= className
.substring(0,
224 className
.lastIndexOf('$'));; parentName
= parentName
225 .substring(0, parentName
.lastIndexOf('$'))) {
226 Object parent
= createObject(parentName
);
228 classes
.add(parent
.getClass());
230 if (!parentName
.contains("$")) {
235 // Better error description in case there is no empty
239 for (Class
<?
> parent
= clazz
; parent
!= null
240 && !parent
.equals(Object
.class); parent
= parent
242 if (!desc
.isEmpty()) {
252 ctor
= clazz
.getDeclaredConstructor(classes
253 .toArray(new Class
[] {}));
254 } catch (NoSuchMethodException nsme
) {
255 // TODO: it seems we do not always need a parameter for each
256 // level, so we currently try "ALL" levels or "FIRST" level
257 // only -> we should check the actual rule and use it
258 ctor
= clazz
.getDeclaredConstructor(classes
.get(0));
259 Object firstParent
= args
.get(0);
261 args
.add(firstParent
);
265 ctor
= clazz
.getDeclaredConstructor();
268 ctor
.setAccessible(true);
269 return ctor
.newInstance(args
.toArray());
270 } catch (ClassNotFoundException e
) {
272 } catch (NoSuchMethodException e
) {
274 throw new NoSuchMethodException("Empty constructor not found: "
278 } catch (Exception e
) {
279 throw new NoSuchMethodException("Cannot instantiate: " + type
);
284 * Insert a custom serialiser that will take precedence over the default one
285 * or the target class.
288 * the custom serialiser
290 static public void addCustomSerializer(CustomSerializer serializer
) {
291 customTypes
.put(serializer
.getType(), serializer
);
295 * Serialise the given object into this {@link OutputStream}.
297 * <b>Important: </b>If the operation fails (with a
298 * {@link NotSerializableException}), the {@link StringBuilder} will be
299 * corrupted (will contain bad, most probably not importable data).
302 * the output {@link OutputStream} to serialise to
304 * the object to serialise
306 * the map of already serialised objects (if the given object or
307 * one of its descendant is already present in it, only an ID
308 * will be serialised)
310 * @throws NotSerializableException
311 * if the object cannot be serialised (in this case, the
312 * {@link StringBuilder} can contain bad, most probably not
314 * @throws IOException
315 * in case of I/O errors
317 static void append(OutputStream out
, Object o
, Map
<Integer
, Object
> map
)
318 throws NotSerializableException
, IOException
{
320 Field
[] fields
= new Field
[] {};
325 int hash
= System
.identityHashCode(o
);
326 fields
= o
.getClass().getDeclaredFields();
327 type
= o
.getClass().getCanonicalName();
329 // Anonymous inner classes support
330 type
= o
.getClass().getName();
332 id
= Integer
.toString(hash
);
333 if (map
.containsKey(hash
)) {
334 fields
= new Field
[] {};
340 write(out
, "{\nREF ");
346 if (!encode(out
, o
)) { // check if direct value
348 for (Field field
: fields
) {
349 field
.setAccessible(true);
351 if (field
.getName().startsWith("this$")
352 || field
.isSynthetic()
353 || (field
.getModifiers() & Modifier
.STATIC
) == Modifier
.STATIC
) {
354 // Do not keep this links of nested classes
355 // Do not keep synthetic fields
356 // Do not keep final fields
361 write(out
, field
.getName());
364 Object value
= field
.get(o
);
366 if (!encode(out
, value
)) {
368 append(out
, value
, map
);
371 } catch (IllegalArgumentException e
) {
372 e
.printStackTrace(); // should not happen (see
374 } catch (IllegalAccessException e
) {
375 e
.printStackTrace(); // should not happen (see
384 * Encode the object into the given {@link OutputStream} if possible and if
387 * A supported object in this context means an object we can directly
388 * encode, like an Integer or a String. Custom objects and arrays are also
389 * considered supported, but <b>compound objects are not supported here</b>.
391 * For compound objects, you should use {@link Exporter}.
394 * the {@link OutputStream} to append to
396 * the object to encode (can be NULL, which will be encoded)
398 * @return TRUE if success, FALSE if not (the content of the
399 * {@link OutputStream} won't be changed in case of failure)
401 * @throws IOException
402 * in case of I/O error
404 static boolean encode(OutputStream out
, Object value
) throws IOException
{
407 } else if (value
.getClass().getSimpleName().endsWith("[]")) {
408 // Simple name does support [] suffix and do not return NULL for
409 // inner anonymous classes
410 customTypes
.get("[]").encode(out
, value
);
411 } else if (customTypes
.containsKey(value
.getClass().getCanonicalName())) {
412 customTypes
.get(value
.getClass().getCanonicalName())//
414 } else if (value
instanceof String
) {
415 encodeString(out
, (String
) value
);
416 } else if (value
instanceof Boolean
) {
418 } else if (value
instanceof Byte
) {
421 } else if (value
instanceof Character
) {
423 encodeString(out
, "" + value
);
424 } else if (value
instanceof Short
) {
427 } else if (value
instanceof Integer
) {
430 } else if (value
instanceof Long
) {
433 } else if (value
instanceof Float
) {
436 } else if (value
instanceof Double
) {
439 } else if (value
instanceof Enum
) {
441 String type
= value
.getClass().getCanonicalName();
444 write(out
, ((Enum
<?
>) value
).name());
453 static boolean isDirectValue(BufferedInputStream encodedValue
)
455 if (CustomSerializer
.isCustom(encodedValue
)) {
459 for (String fullValue
: new String
[] { "NULL", "null", "true", "false" }) {
460 if (encodedValue
.is(fullValue
)) {
465 for (String prefix
: new String
[] { "c\"", "\"", "b", "s", "i", "l",
467 if (encodedValue
.startsWith(prefix
)) {
476 * Decode the data into an equivalent supported source object.
478 * A supported object in this context means an object we can directly
479 * encode, like an Integer or a String (see
480 * {@link SerialUtils#decode(String)}.
482 * Custom objects and arrays are also considered supported here, but
483 * <b>compound objects are not</b>.
485 * For compound objects, you should use {@link Importer}.
487 * @param encodedValue
488 * the encoded data, cannot be NULL
490 * @return the object (can be NULL for NULL encoded values)
492 * @throws IOException
493 * if the content cannot be converted
495 static Object
decode(BufferedInputStream encodedValue
) throws IOException
{
496 if (CustomSerializer
.isCustom(encodedValue
)) {
497 // custom^TYPE^ENCODED_VALUE
498 NextableInputStream content
= new NextableInputStream(encodedValue
,
499 new NextableInputStreamStep('^'));
502 @SuppressWarnings("unused")
503 String custom
= IOUtils
.readSmallStream(content
);
505 String type
= IOUtils
.readSmallStream(content
);
507 if (customTypes
.containsKey(type
)) {
508 return customTypes
.get(type
).decode(content
);
511 throw new IOException("Unknown custom type: " + type
);
513 content
.close(false);
518 String encodedString
= IOUtils
.readSmallStream(encodedValue
);
519 return decode(encodedString
);
523 * Decode the data into an equivalent supported source object.
525 * A supported object in this context means an object we can directly
526 * encode, like an Integer or a String.
528 * For custom objects and arrays, you should use
529 * {@link SerialUtils#decode(InputStream)} or directly {@link Importer}.
531 * For compound objects, you should use {@link Importer}.
533 * @param encodedValue
534 * the encoded data, cannot be NULL
536 * @return the object (can be NULL for NULL encoded values)
538 * @throws IOException
539 * if the content cannot be converted
541 static Object
decode(String encodedValue
) throws IOException
{
544 if (encodedValue
.length() > 1) {
545 cut
= encodedValue
.substring(1);
548 if (encodedValue
.equals("NULL") || encodedValue
.equals("null")) {
550 } else if (encodedValue
.startsWith("\"")) {
551 return decodeString(encodedValue
);
552 } else if (encodedValue
.equals("true")) {
554 } else if (encodedValue
.equals("false")) {
556 } else if (encodedValue
.startsWith("b")) {
557 return Byte
.parseByte(cut
);
558 } else if (encodedValue
.startsWith("c")) {
559 return decodeString(cut
).charAt(0);
560 } else if (encodedValue
.startsWith("s")) {
561 return Short
.parseShort(cut
);
562 } else if (encodedValue
.startsWith("l")) {
563 return Long
.parseLong(cut
);
564 } else if (encodedValue
.startsWith("f")) {
565 return Float
.parseFloat(cut
);
566 } else if (encodedValue
.startsWith("d")) {
567 return Double
.parseDouble(cut
);
568 } else if (encodedValue
.startsWith("i")) {
569 return Integer
.parseInt(cut
);
570 } else if (encodedValue
.startsWith("E:")) {
571 cut
= cut
.substring(1);
572 return decodeEnum(cut
);
574 throw new IOException("Unrecognized value: " + encodedValue
);
576 } catch (Exception e
) {
577 if (e
instanceof IOException
) {
578 throw (IOException
) e
;
580 throw new IOException(e
.getMessage(), e
);
585 * Write the given {@link String} into the given {@link OutputStream} in
589 * the {@link OutputStream}
591 * the data to write, cannot be NULL
593 * @throws IOException
594 * in case of I/O error
596 static void write(OutputStream out
, Object data
) throws IOException
{
597 out
.write(StringUtils
.getBytes(data
.toString()));
601 * Return the corresponding class or throw an {@link Exception} if it
605 * the class name to look for
607 * @return the class (will never be NULL)
609 * @throws ClassNotFoundException
610 * if the class cannot be found
611 * @throws NoSuchMethodException
612 * if the class cannot be created (usually because it or its
613 * enclosing class doesn't have an empty constructor)
615 static private Class
<?
> getClass(String type
)
616 throws ClassNotFoundException
, NoSuchMethodException
{
617 Class
<?
> clazz
= null;
619 clazz
= Class
.forName(type
);
620 } catch (ClassNotFoundException e
) {
621 int pos
= type
.length();
622 pos
= type
.lastIndexOf(".", pos
);
624 String parentType
= type
.substring(0, pos
);
625 String nestedType
= type
.substring(pos
+ 1);
626 Class
<?
> javaParent
= null;
628 javaParent
= getClass(parentType
);
629 parentType
= javaParent
.getName();
630 clazz
= Class
.forName(parentType
+ "$" + nestedType
);
631 } catch (Exception ee
) {
634 if (javaParent
== null) {
635 throw new NoSuchMethodException(
638 + " (the enclosing class cannot be created: maybe it doesn't have an empty constructor?)");
644 throw new ClassNotFoundException("Class not found: " + type
);
650 @SuppressWarnings({ "unchecked", "rawtypes" })
651 static private Enum
<?
> decodeEnum(String escaped
) {
652 // escaped: be.xxx.EnumType.VALUE;
653 int pos
= escaped
.lastIndexOf(".");
654 String type
= escaped
.substring(0, pos
);
655 String name
= escaped
.substring(pos
+ 1, escaped
.length() - 1);
658 return Enum
.valueOf((Class
<Enum
>) getClass(type
), name
);
659 } catch (Exception e
) {
660 throw new UnknownFormatConversionException("Unknown enum: <" + type
666 static void encodeString(OutputStream out
, String raw
) throws IOException
{
667 // TODO: not. efficient.
669 for (char car
: raw
.toCharArray()) {
670 encodeString(out
, car
);
675 // for encoding string, NOT to encode a char by itself!
676 static void encodeString(OutputStream out
, char raw
) throws IOException
{
701 static String
decodeString(String escaped
) {
702 StringBuilder builder
= new StringBuilder();
704 boolean escaping
= false;
705 for (char car
: escaped
.toCharArray()) {
715 builder
.append('\\');
718 builder
.append('\r');
721 builder
.append('\n');
731 return builder
.substring(1, builder
.length() - 1);