1 package be
.nikiroo
.utils
.serial
;
3 import java
.io
.ByteArrayInputStream
;
4 import java
.io
.IOException
;
5 import java
.io
.InputStream
;
6 import java
.io
.NotSerializableException
;
7 import java
.io
.OutputStream
;
8 import java
.io
.UnsupportedEncodingException
;
9 import java
.lang
.reflect
.Array
;
10 import java
.lang
.reflect
.Constructor
;
11 import java
.lang
.reflect
.Field
;
12 import java
.lang
.reflect
.Modifier
;
14 import java
.util
.ArrayList
;
15 import java
.util
.HashMap
;
16 import java
.util
.List
;
18 import java
.util
.UnknownFormatConversionException
;
20 import be
.nikiroo
.utils
.IOUtils
;
21 import be
.nikiroo
.utils
.Image
;
22 import be
.nikiroo
.utils
.StringUtils
;
23 import be
.nikiroo
.utils
.streams
.NextableInputStream
;
24 import be
.nikiroo
.utils
.streams
.NextableInputStreamStep
;
27 * Small class to help with serialisation.
29 * Note that we do not support inner classes (but we do support nested classes)
30 * and all objects require an empty constructor to be deserialised.
32 * It is possible to add support to custom types (both the encoder and the
33 * decoder will require the custom classes) -- see {@link CustomSerializer}.
35 * Default supported types are:
37 * <li>NULL (as a null value)</li>
47 * <li>Enum (any enum whose name and value is known by the caller)</li>
48 * <li>java.awt.image.BufferedImage (as a {@link CustomSerializer})</li>
49 * <li>An array of the above (as a {@link CustomSerializer})</li>
55 public class SerialUtils
{
56 private static Map
<String
, CustomSerializer
> customTypes
;
59 customTypes
= new HashMap
<String
, CustomSerializer
>();
62 customTypes
.put("[]", new CustomSerializer() {
64 protected void toStream(OutputStream out
, Object value
)
67 // TODO: we use \n to separate, and b64 to un-\n
68 // -- but we could use \\n ?
69 String type
= value
.getClass().getCanonicalName();
70 type
= type
.substring(0, type
.length() - 2); // remove the []
75 for (int i
= 0; true; i
++) {
76 Object item
= Array
.get(value
, i
);
77 // encode it normally if direct value
78 if (!SerialUtils
.encode(out
, item
)) {
80 // TODO: bad escaping?
82 OutputStream bout
= StringUtils
.base64(out
,
84 new Exporter(bout
).append(item
);
85 } catch (NotSerializableException e
) {
86 throw new UnknownFormatConversionException(e
92 } catch (ArrayIndexOutOfBoundsException e
) {
98 protected Object
fromStream(InputStream in
) throws IOException
{
99 NextableInputStream stream
= new NextableInputStream(in
,
100 new NextableInputStreamStep('\r'));
103 List
<Object
> list
= new ArrayList
<Object
>();
105 String type
= IOUtils
.readSmallStream(stream
);
107 while (stream
.next()) {
108 Object value
= new Importer().read(stream
).getValue();
112 Object array
= Array
.newInstance(
113 SerialUtils
.getClass(type
), list
.size());
114 for (int i
= 0; i
< list
.size(); i
++) {
115 Array
.set(array
, i
, list
.get(i
));
119 } catch (Exception e
) {
120 if (e
instanceof IOException
) {
121 throw (IOException
) e
;
123 throw new IOException(e
.getMessage());
128 protected String
getType() {
134 customTypes
.put("java.net.URL", new CustomSerializer() {
136 protected void toStream(OutputStream out
, Object value
)
140 val
= ((URL
) value
).toString();
143 out
.write(val
.getBytes("UTF-8"));
147 protected Object
fromStream(InputStream in
) throws IOException
{
148 String val
= IOUtils
.readSmallStream(in
);
149 if (!val
.isEmpty()) {
157 protected String
getType() {
158 return "java.net.URL";
162 // Images (this is currently the only supported image type by default)
163 customTypes
.put("be.nikiroo.utils.Image", new CustomSerializer() {
165 protected void toStream(OutputStream out
, Object value
)
167 Image img
= (Image
) value
;
168 OutputStream encoded
= StringUtils
.base64(out
, false, false);
170 InputStream in
= img
.newInputStream();
172 IOUtils
.write(in
, encoded
);
182 protected String
getType() {
183 return "be.nikiroo.utils.Image";
187 protected Object
fromStream(InputStream in
) throws IOException
{
189 return new Image(in
);
190 } catch (IOException e
) {
191 throw new UnknownFormatConversionException(e
.getMessage());
198 * Create an empty object of the given type.
201 * the object type (its class name)
203 * @return the new object
205 * @throws ClassNotFoundException
206 * if the class cannot be found
207 * @throws NoSuchMethodException
208 * if the given class is not compatible with this code
210 public static Object
createObject(String type
)
211 throws ClassNotFoundException
, NoSuchMethodException
{
215 Class
<?
> clazz
= getClass(type
);
216 String className
= clazz
.getName();
217 List
<Object
> args
= new ArrayList
<Object
>();
218 List
<Class
<?
>> classes
= new ArrayList
<Class
<?
>>();
219 Constructor
<?
> ctor
= null;
220 if (className
.contains("$")) {
221 for (String parentName
= className
.substring(0,
222 className
.lastIndexOf('$'));; parentName
= parentName
223 .substring(0, parentName
.lastIndexOf('$'))) {
224 Object parent
= createObject(parentName
);
226 classes
.add(parent
.getClass());
228 if (!parentName
.contains("$")) {
233 // Better error description in case there is no empty
237 for (Class
<?
> parent
= clazz
; parent
!= null
238 && !parent
.equals(Object
.class); parent
= parent
240 if (!desc
.isEmpty()) {
250 ctor
= clazz
.getDeclaredConstructor(classes
251 .toArray(new Class
[] {}));
252 } catch (NoSuchMethodException nsme
) {
253 // TODO: it seems we do not always need a parameter for each
254 // level, so we currently try "ALL" levels or "FIRST" level
255 // only -> we should check the actual rule and use it
256 ctor
= clazz
.getDeclaredConstructor(classes
.get(0));
257 Object firstParent
= args
.get(0);
259 args
.add(firstParent
);
263 ctor
= clazz
.getDeclaredConstructor();
266 ctor
.setAccessible(true);
267 return ctor
.newInstance(args
.toArray());
268 } catch (ClassNotFoundException e
) {
270 } catch (NoSuchMethodException e
) {
272 throw new NoSuchMethodException("Empty constructor not found: "
276 } catch (Exception e
) {
277 throw new NoSuchMethodException("Cannot instantiate: " + type
);
282 * Insert a custom serialiser that will take precedence over the default one
283 * or the target class.
286 * the custom serialiser
288 static public void addCustomSerializer(CustomSerializer serializer
) {
289 customTypes
.put(serializer
.getType(), serializer
);
293 * Serialise the given object into this {@link OutputStream}.
295 * <b>Important: </b>If the operation fails (with a
296 * {@link NotSerializableException}), the {@link StringBuilder} will be
297 * corrupted (will contain bad, most probably not importable data).
300 * the output {@link OutputStream} to serialise to
302 * the object to serialise
304 * the map of already serialised objects (if the given object or
305 * one of its descendant is already present in it, only an ID
306 * will be serialised)
308 * @throws NotSerializableException
309 * if the object cannot be serialised (in this case, the
310 * {@link StringBuilder} can contain bad, most probably not
312 * @throws IOException
313 * in case of I/O errors
315 static void append(OutputStream out
, Object o
, Map
<Integer
, Object
> map
)
316 throws NotSerializableException
, IOException
{
318 Field
[] fields
= new Field
[] {};
323 int hash
= System
.identityHashCode(o
);
324 fields
= o
.getClass().getDeclaredFields();
325 type
= o
.getClass().getCanonicalName();
327 // Anonymous inner classes support
328 type
= o
.getClass().getName();
330 id
= Integer
.toString(hash
);
331 if (map
.containsKey(hash
)) {
332 fields
= new Field
[] {};
338 write(out
, "{\nREF ");
344 if (!encode(out
, o
)) { // check if direct value
346 for (Field field
: fields
) {
347 field
.setAccessible(true);
349 if (field
.getName().startsWith("this$")
350 || field
.isSynthetic()
351 || (field
.getModifiers() & Modifier
.STATIC
) == Modifier
.STATIC
) {
352 // Do not keep this links of nested classes
353 // Do not keep synthetic fields
354 // Do not keep final fields
359 write(out
, field
.getName());
362 Object value
= field
.get(o
);
364 if (!encode(out
, value
)) {
366 append(out
, value
, map
);
369 } catch (IllegalArgumentException e
) {
370 e
.printStackTrace(); // should not happen (see
372 } catch (IllegalAccessException e
) {
373 e
.printStackTrace(); // should not happen (see
381 * Encode the object into the given {@link OutputStream} if possible and if
384 * A supported object in this context means an object we can directly
385 * encode, like an Integer or a String. Custom objects and arrays are also
386 * considered supported, but <b>compound objects are not supported here</b>.
388 * For compound objects, you should use {@link Exporter}.
391 * the {@link OutputStream} to append to
393 * the object to encode (can be NULL, which will be encoded)
395 * @return TRUE if success, FALSE if not (the content of the
396 * {@link OutputStream} won't be changed in case of failure)
398 * @throws IOException
399 * in case of I/O error
401 static boolean encode(OutputStream out
, Object value
) throws IOException
{
404 } else if (value
.getClass().getSimpleName().endsWith("[]")) {
405 // Simple name does support [] suffix and do not return NULL for
406 // inner anonymous classes
407 customTypes
.get("[]").encode(out
, value
);
408 } else if (customTypes
.containsKey(value
.getClass().getCanonicalName())) {
409 customTypes
.get(value
.getClass().getCanonicalName())//
411 } else if (value
instanceof String
) {
412 encodeString(out
, (String
) value
);
413 } else if (value
instanceof Boolean
) {
415 } else if (value
instanceof Byte
) {
418 } else if (value
instanceof Character
) {
419 encodeString(out
, "" + value
);
421 } else if (value
instanceof Short
) {
424 } else if (value
instanceof Integer
) {
426 } else if (value
instanceof Long
) {
429 } else if (value
instanceof Float
) {
432 } else if (value
instanceof Double
) {
435 } else if (value
instanceof Enum
) {
436 String type
= value
.getClass().getCanonicalName();
439 write(out
, ((Enum
<?
>) value
).name());
449 * Decode the data into an equivalent supported source object.
451 * A supported object in this context means an object we can directly
452 * encode, like an Integer or a String. Custom objects and arrays are also
453 * considered supported, but <b>compound objects are not supported here</b>.
455 * For compound objects, you should use {@link Importer}.
457 * @param encodedValue
458 * the encoded data, cannot be NULL
460 * @return the object (can be NULL for NULL encoded values)
462 * @throws IOException
463 * if the content cannot be converted
465 static Object
decode(String encodedValue
) throws IOException
{
468 if (encodedValue
.length() > 1) {
469 cut
= encodedValue
.substring(0, encodedValue
.length() - 1);
472 if (CustomSerializer
.isCustom(encodedValue
)) {
473 // custom:TYPE_NAME:"content is String-encoded"
474 String type
= CustomSerializer
.typeOf(encodedValue
);
475 if (customTypes
.containsKey(type
)) {
476 // TODO: we should start with a stream
477 InputStream streamEncodedValue
= new ByteArrayInputStream(
478 encodedValue
.getBytes("UTF-8"));
480 return customTypes
.get(type
).decode(streamEncodedValue
);
482 streamEncodedValue
.close();
485 throw new IOException("Unknown custom type: " + type
);
486 } else if (encodedValue
.equals("NULL")
487 || encodedValue
.equals("null")) {
489 } else if (encodedValue
.endsWith("\"")) {
490 return decodeString(encodedValue
);
491 } else if (encodedValue
.equals("true")) {
493 } else if (encodedValue
.equals("false")) {
495 } else if (encodedValue
.endsWith("b")) {
496 return Byte
.parseByte(cut
);
497 } else if (encodedValue
.endsWith("c")) {
498 return decodeString(cut
).charAt(0);
499 } else if (encodedValue
.endsWith("s")) {
500 return Short
.parseShort(cut
);
501 } else if (encodedValue
.endsWith("L")) {
502 return Long
.parseLong(cut
);
503 } else if (encodedValue
.endsWith("F")) {
504 return Float
.parseFloat(cut
);
505 } else if (encodedValue
.endsWith("d")) {
506 return Double
.parseDouble(cut
);
507 } else if (encodedValue
.endsWith(";")) {
508 return decodeEnum(encodedValue
);
510 return Integer
.parseInt(encodedValue
);
512 } catch (Exception e
) {
513 if (e
instanceof IOException
) {
514 throw (IOException
) e
;
516 throw new IOException(e
.getMessage());
521 * Write the given {@link String} into the given {@link OutputStream} in
525 * the {@link OutputStream}
527 * the data to write, cannot be NULL
529 * @throws IOException
530 * in case of I/O error
532 static void write(OutputStream out
, Object data
) throws IOException
{
534 out
.write(data
.toString().getBytes("UTF-8"));
535 } catch (UnsupportedEncodingException e
) {
536 // A conforming JVM is required to support UTF-8
542 * Return the corresponding class or throw an {@link Exception} if it
546 * the class name to look for
548 * @return the class (will never be NULL)
550 * @throws ClassNotFoundException
551 * if the class cannot be found
552 * @throws NoSuchMethodException
553 * if the class cannot be created (usually because it or its
554 * enclosing class doesn't have an empty constructor)
556 static private Class
<?
> getClass(String type
)
557 throws ClassNotFoundException
, NoSuchMethodException
{
558 Class
<?
> clazz
= null;
560 clazz
= Class
.forName(type
);
561 } catch (ClassNotFoundException e
) {
562 int pos
= type
.length();
563 pos
= type
.lastIndexOf(".", pos
);
565 String parentType
= type
.substring(0, pos
);
566 String nestedType
= type
.substring(pos
+ 1);
567 Class
<?
> javaParent
= null;
569 javaParent
= getClass(parentType
);
570 parentType
= javaParent
.getName();
571 clazz
= Class
.forName(parentType
+ "$" + nestedType
);
572 } catch (Exception ee
) {
575 if (javaParent
== null) {
576 throw new NoSuchMethodException(
579 + " (the enclosing class cannot be created: maybe it doesn't have an empty constructor?)");
585 throw new ClassNotFoundException("Class not found: " + type
);
591 @SuppressWarnings({ "unchecked", "rawtypes" })
592 static private Enum
<?
> decodeEnum(String escaped
) {
593 // escaped: be.xxx.EnumType.VALUE;
594 int pos
= escaped
.lastIndexOf(".");
595 String type
= escaped
.substring(0, pos
);
596 String name
= escaped
.substring(pos
+ 1, escaped
.length() - 1);
599 return Enum
.valueOf((Class
<Enum
>) getClass(type
), name
);
600 } catch (Exception e
) {
601 throw new UnknownFormatConversionException("Unknown enum: <" + type
607 static void encodeString(OutputStream out
, String raw
) throws IOException
{
608 // TODO: not. efficient.
610 // TODO !! utf-8 required
611 for (char car
: raw
.toCharArray()) {
612 encodeString(out
, car
);
618 static void encodeString(OutputStream out
, InputStream raw
)
621 byte buffer
[] = new byte[4096];
622 for (int len
= 0; (len
= raw
.read(buffer
)) > 0;) {
623 for (int i
= 0; i
< len
; i
++) {
624 // TODO: not 100% correct, look up howto for UTF-8
625 encodeString(out
, (char) buffer
[i
]);
631 // for encode string, NOT to encode a char by itself!
632 static void encodeString(OutputStream out
, char raw
) throws IOException
{
657 static String
decodeString(String escaped
) {
658 StringBuilder builder
= new StringBuilder();
660 boolean escaping
= false;
661 for (char car
: escaped
.toCharArray()) {
671 builder
.append('\\');
674 builder
.append('\r');
677 builder
.append('\n');
687 return builder
.substring(1, builder
.length() - 1);