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
.NextableInputStream
;
23 import be
.nikiroo
.utils
.NextableInputStreamStep
;
24 import be
.nikiroo
.utils
.StringUtils
;
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
)
66 // TODO: we use \n to separate, and b64 to un-\n -- but we could
68 String type
= value
.getClass().getCanonicalName();
69 type
= type
.substring(0, type
.length() - 2); // remove the []
74 for (int i
= 0; true; i
++) {
75 Object item
= Array
.get(value
, i
);
76 // encode it normally if direct value
77 if (!SerialUtils
.encode(out
, item
)) {
79 // TODO: bad escaping?
81 OutputStream bout
= StringUtils
.base64(out
,
83 new Exporter(bout
).append(item
);
84 } catch (NotSerializableException e
) {
85 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(val
.getBytes("UTF-8"));
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
= StringUtils
.base64(out
, false, false);
169 InputStream in
= img
.newInputStream();
171 IOUtils
.write(in
, encoded
);
181 protected String
getType() {
182 return "be.nikiroo.utils.Image";
186 protected Object
fromStream(InputStream in
) throws IOException
{
188 return new Image(in
);
189 } catch (IOException e
) {
190 throw new UnknownFormatConversionException(e
.getMessage());
197 * Create an empty object of the given type.
200 * the object type (its class name)
202 * @return the new object
204 * @throws ClassNotFoundException
205 * if the class cannot be found
206 * @throws NoSuchMethodException
207 * if the given class is not compatible with this code
209 public static Object
createObject(String type
)
210 throws ClassNotFoundException
, NoSuchMethodException
{
214 Class
<?
> clazz
= getClass(type
);
215 String className
= clazz
.getName();
216 List
<Object
> args
= new ArrayList
<Object
>();
217 List
<Class
<?
>> classes
= new ArrayList
<Class
<?
>>();
218 Constructor
<?
> ctor
= null;
219 if (className
.contains("$")) {
220 for (String parentName
= className
.substring(0,
221 className
.lastIndexOf('$'));; parentName
= parentName
222 .substring(0, parentName
.lastIndexOf('$'))) {
223 Object parent
= createObject(parentName
);
225 classes
.add(parent
.getClass());
227 if (!parentName
.contains("$")) {
232 // Better error description in case there is no empty
236 for (Class
<?
> parent
= clazz
; parent
!= null
237 && !parent
.equals(Object
.class); parent
= parent
239 if (!desc
.isEmpty()) {
249 ctor
= clazz
.getDeclaredConstructor(classes
250 .toArray(new Class
[] {}));
251 } catch (NoSuchMethodException nsme
) {
252 // TODO: it seems we do not always need a parameter for each
253 // level, so we currently try "ALL" levels or "FIRST" level
254 // only -> we should check the actual rule and use it
255 ctor
= clazz
.getDeclaredConstructor(classes
.get(0));
256 Object firstParent
= args
.get(0);
258 args
.add(firstParent
);
262 ctor
= clazz
.getDeclaredConstructor();
265 ctor
.setAccessible(true);
266 return ctor
.newInstance(args
.toArray());
267 } catch (ClassNotFoundException e
) {
269 } catch (NoSuchMethodException e
) {
271 throw new NoSuchMethodException("Empty constructor not found: "
275 } catch (Exception e
) {
276 throw new NoSuchMethodException("Cannot instantiate: " + type
);
281 * Insert a custom serialiser that will take precedence over the default one
282 * or the target class.
285 * the custom serialiser
287 static public void addCustomSerializer(CustomSerializer serializer
) {
288 customTypes
.put(serializer
.getType(), serializer
);
292 * Serialise the given object into this {@link OutputStream}.
294 * <b>Important: </b>If the operation fails (with a
295 * {@link NotSerializableException}), the {@link StringBuilder} will be
296 * corrupted (will contain bad, most probably not importable data).
299 * the output {@link OutputStream} to serialise to
301 * the object to serialise
303 * the map of already serialised objects (if the given object or
304 * one of its descendant is already present in it, only an ID
305 * will be serialised)
307 * @throws NotSerializableException
308 * if the object cannot be serialised (in this case, the
309 * {@link StringBuilder} can contain bad, most probably not
311 * @throws IOException
312 * in case of I/O errors
314 static void append(OutputStream out
, Object o
, Map
<Integer
, Object
> map
)
315 throws NotSerializableException
, IOException
{
317 Field
[] fields
= new Field
[] {};
322 int hash
= System
.identityHashCode(o
);
323 fields
= o
.getClass().getDeclaredFields();
324 type
= o
.getClass().getCanonicalName();
326 // Anonymous inner classes support
327 type
= o
.getClass().getName();
329 id
= Integer
.toString(hash
);
330 if (map
.containsKey(hash
)) {
331 fields
= new Field
[] {};
337 write(out
, "{\nREF ");
343 if (!encode(out
, o
)) { // check if direct value
345 for (Field field
: fields
) {
346 field
.setAccessible(true);
348 if (field
.getName().startsWith("this$")
349 || field
.isSynthetic()
350 || (field
.getModifiers() & Modifier
.STATIC
) == Modifier
.STATIC
) {
351 // Do not keep this links of nested classes
352 // Do not keep synthetic fields
353 // Do not keep final fields
358 write(out
, field
.getName());
361 Object value
= field
.get(o
);
363 if (!encode(out
, value
)) {
365 append(out
, value
, map
);
368 } catch (IllegalArgumentException e
) {
369 e
.printStackTrace(); // should not happen (see
371 } catch (IllegalAccessException e
) {
372 e
.printStackTrace(); // should not happen (see
380 * Encode the object into the given {@link OutputStream} if possible and if
383 * A supported object in this context means an object we can directly
384 * encode, like an Integer or a String. Custom objects and arrays are also
385 * considered supported, but <b>compound objects are not supported here</b>.
387 * For compound objects, you should use {@link Exporter}.
390 * the {@link OutputStream} to append to
392 * the object to encode (can be NULL, which will be encoded)
394 * @return TRUE if success, FALSE if not (the content of the
395 * {@link OutputStream} won't be changed in case of failure)
397 * @throws IOException
398 * in case of I/O error
400 static boolean encode(OutputStream out
, Object value
) throws IOException
{
403 } else if (value
.getClass().getSimpleName().endsWith("[]")) {
404 // Simple name does support [] suffix and do not return NULL for
405 // inner anonymous classes
406 return customTypes
.get("[]").encode(out
, value
);
407 } else if (customTypes
.containsKey(value
.getClass().getCanonicalName())) {
408 return customTypes
.get(value
.getClass().getCanonicalName())//
410 } else if (value
instanceof String
) {
411 encodeString(out
, (String
) value
);
412 } else if (value
instanceof Boolean
) {
414 } else if (value
instanceof Byte
) {
417 } else if (value
instanceof Character
) {
418 encodeString(out
, "" + value
);
420 } else if (value
instanceof Short
) {
423 } else if (value
instanceof Integer
) {
425 } else if (value
instanceof Long
) {
428 } else if (value
instanceof Float
) {
431 } else if (value
instanceof Double
) {
434 } else if (value
instanceof Enum
) {
435 String type
= value
.getClass().getCanonicalName();
438 write(out
, ((Enum
<?
>) value
).name());
448 * Decode the data into an equivalent supported source object.
450 * A supported object in this context means an object we can directly
451 * encode, like an Integer or a String. Custom objects and arrays are also
452 * considered supported, but <b>compound objects are not supported here</b>.
454 * For compound objects, you should use {@link Importer}.
456 * @param encodedValue
457 * the encoded data, cannot be NULL
459 * @return the object (can be NULL for NULL encoded values)
461 * @throws IOException
462 * if the content cannot be converted
464 static Object
decode(String encodedValue
) throws IOException
{
467 if (encodedValue
.length() > 1) {
468 cut
= encodedValue
.substring(0, encodedValue
.length() - 1);
471 if (CustomSerializer
.isCustom(encodedValue
)) {
472 // custom:TYPE_NAME:"content is String-encoded"
473 String type
= CustomSerializer
.typeOf(encodedValue
);
474 if (customTypes
.containsKey(type
)) {
475 // TODO: we should start with a stream
476 InputStream streamEncodedValue
= new ByteArrayInputStream(
477 encodedValue
.getBytes("UTF-8"));
479 return customTypes
.get(type
).decode(streamEncodedValue
);
481 streamEncodedValue
.close();
484 throw new IOException("Unknown custom type: " + type
);
485 } else if (encodedValue
.equals("NULL")
486 || encodedValue
.equals("null")) {
488 } else if (encodedValue
.endsWith("\"")) {
489 return decodeString(encodedValue
);
490 } else if (encodedValue
.equals("true")) {
492 } else if (encodedValue
.equals("false")) {
494 } else if (encodedValue
.endsWith("b")) {
495 return Byte
.parseByte(cut
);
496 } else if (encodedValue
.endsWith("c")) {
497 return decodeString(cut
).charAt(0);
498 } else if (encodedValue
.endsWith("s")) {
499 return Short
.parseShort(cut
);
500 } else if (encodedValue
.endsWith("L")) {
501 return Long
.parseLong(cut
);
502 } else if (encodedValue
.endsWith("F")) {
503 return Float
.parseFloat(cut
);
504 } else if (encodedValue
.endsWith("d")) {
505 return Double
.parseDouble(cut
);
506 } else if (encodedValue
.endsWith(";")) {
507 return decodeEnum(encodedValue
);
509 return Integer
.parseInt(encodedValue
);
511 } catch (Exception e
) {
512 if (e
instanceof IOException
) {
513 throw (IOException
) e
;
515 throw new IOException(e
.getMessage());
520 * Write the given {@link String} into the given {@link OutputStream} in
524 * the {@link OutputStream}
526 * the data to write, cannot be NULL
528 * @throws IOException
529 * in case of I/O error
531 static void write(OutputStream out
, Object data
) throws IOException
{
533 out
.write(data
.toString().getBytes("UTF-8"));
534 } catch (UnsupportedEncodingException e
) {
535 // A conforming JVM is required to support UTF-8
541 * Return the corresponding class or throw an {@link Exception} if it
545 * the class name to look for
547 * @return the class (will never be NULL)
549 * @throws ClassNotFoundException
550 * if the class cannot be found
551 * @throws NoSuchMethodException
552 * if the class cannot be created (usually because it or its
553 * enclosing class doesn't have an empty constructor)
555 static private Class
<?
> getClass(String type
)
556 throws ClassNotFoundException
, NoSuchMethodException
{
557 Class
<?
> clazz
= null;
559 clazz
= Class
.forName(type
);
560 } catch (ClassNotFoundException e
) {
561 int pos
= type
.length();
562 pos
= type
.lastIndexOf(".", pos
);
564 String parentType
= type
.substring(0, pos
);
565 String nestedType
= type
.substring(pos
+ 1);
566 Class
<?
> javaParent
= null;
568 javaParent
= getClass(parentType
);
569 parentType
= javaParent
.getName();
570 clazz
= Class
.forName(parentType
+ "$" + nestedType
);
571 } catch (Exception ee
) {
574 if (javaParent
== null) {
575 throw new NoSuchMethodException(
578 + " (the enclosing class cannot be created: maybe it doesn't have an empty constructor?)");
584 throw new ClassNotFoundException("Class not found: " + type
);
590 @SuppressWarnings({ "unchecked", "rawtypes" })
591 static private Enum
<?
> decodeEnum(String escaped
) {
592 // escaped: be.xxx.EnumType.VALUE;
593 int pos
= escaped
.lastIndexOf(".");
594 String type
= escaped
.substring(0, pos
);
595 String name
= escaped
.substring(pos
+ 1, escaped
.length() - 1);
598 return Enum
.valueOf((Class
<Enum
>) getClass(type
), name
);
599 } catch (Exception e
) {
600 throw new UnknownFormatConversionException("Unknown enum: <" + type
606 static void encodeString(OutputStream out
, String raw
) throws IOException
{
608 // TODO !! utf-8 required
609 for (char car
: raw
.toCharArray()) {
610 encodeString(out
, car
);
616 static void encodeString(OutputStream out
, InputStream raw
)
619 byte buffer
[] = new byte[4096];
620 for (int len
= 0; (len
= raw
.read(buffer
)) > 0;) {
621 for (int i
= 0; i
< len
; i
++) {
622 // TODO: not 100% correct, look up howto for UTF-8
623 encodeString(out
, (char) buffer
[i
]);
629 // for encode string, NOT to encode a char by itself!
630 static void encodeString(OutputStream out
, char raw
) throws IOException
{
655 static String
decodeString(String escaped
) {
656 StringBuilder builder
= new StringBuilder();
658 boolean escaping
= false;
659 for (char car
: escaped
.toCharArray()) {
669 builder
.append('\\');
672 builder
.append('\r');
675 builder
.append('\n');
685 return builder
.substring(1, builder
.length() - 1);