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
.io
.UnsupportedEncodingException
;
8 import java
.lang
.reflect
.Array
;
9 import java
.lang
.reflect
.Constructor
;
10 import java
.lang
.reflect
.Field
;
11 import java
.lang
.reflect
.Modifier
;
13 import java
.util
.ArrayList
;
14 import java
.util
.HashMap
;
15 import java
.util
.List
;
17 import java
.util
.UnknownFormatConversionException
;
19 import be
.nikiroo
.utils
.IOUtils
;
20 import be
.nikiroo
.utils
.Image
;
21 import be
.nikiroo
.utils
.NextableInputStream
;
22 import be
.nikiroo
.utils
.NextableInputStreamStep
;
23 import be
.nikiroo
.utils
.StringUtils
;
26 * Small class to help with serialisation.
28 * Note that we do not support inner classes (but we do support nested classes)
29 * and all objects require an empty constructor to be deserialised.
31 * It is possible to add support to custom types (both the encoder and the
32 * decoder will require the custom classes) -- see {@link CustomSerializer}.
34 * Default supported types are:
36 * <li>NULL (as a null value)</li>
46 * <li>Enum (any enum whose name and value is known by the caller)</li>
47 * <li>java.awt.image.BufferedImage (as a {@link CustomSerializer})</li>
48 * <li>An array of the above (as a {@link CustomSerializer})</li>
54 public class SerialUtils
{
55 private static Map
<String
, CustomSerializer
> customTypes
;
58 customTypes
= new HashMap
<String
, CustomSerializer
>();
61 customTypes
.put("[]", new CustomSerializer() {
63 protected void toStream(OutputStream out
, Object value
)
65 // TODO: we use \n to separate, and b64 to un-\n -- but we could
67 String type
= value
.getClass().getCanonicalName();
68 type
= type
.substring(0, type
.length() - 2); // remove the []
73 for (int i
= 0; true; i
++) {
74 Object item
= Array
.get(value
, i
);
75 // encode it normally if direct value
76 if (!SerialUtils
.encode(out
, item
)) {
78 // TODO: use ZIP: if not?
79 new Exporter(out
).append(item
);
80 } catch (NotSerializableException e
) {
81 throw new UnknownFormatConversionException(e
87 } catch (ArrayIndexOutOfBoundsException e
) {
93 protected Object
fromStream(InputStream in
) throws IOException
{
94 NextableInputStream stream
= new NextableInputStream(in
,
95 new NextableInputStreamStep('\n'));
98 List
<Object
> list
= new ArrayList
<Object
>();
100 String type
= IOUtils
.readSmallStream(stream
);
102 while (stream
.next()) {
103 Object value
= new Importer().read(stream
).getValue();
107 Object array
= Array
.newInstance(
108 SerialUtils
.getClass(type
), list
.size());
109 for (int i
= 0; i
< list
.size(); i
++) {
110 Array
.set(array
, i
, list
.get(i
));
114 } catch (Exception e
) {
115 if (e
instanceof IOException
) {
116 throw (IOException
) e
;
118 throw new IOException(e
.getMessage());
123 protected String
getType() {
129 customTypes
.put("java.net.URL", new CustomSerializer() {
132 protected void toStream(OutputStream out
, Object value
)
136 val
= ((URL
) value
).toString();
139 out
.write(val
.getBytes("UTF-8"));
143 protected Object
fromStream(InputStream in
) throws IOException
{
144 String val
= IOUtils
.readSmallStream(in
);
145 if (!val
.isEmpty()) {
153 protected String
getType() {
154 return "java.net.URL";
158 // Images (this is currently the only supported image type by default)
159 customTypes
.put("be.nikiroo.utils.Image", new CustomSerializer() {
161 protected void toStream(OutputStream out
, Object value
)
163 Image img
= (Image
) value
;
164 OutputStream encoded
= StringUtils
.base64(out
, false, false);
166 InputStream in
= img
.newInputStream();
168 IOUtils
.write(in
, encoded
);
178 protected String
getType() {
179 return "be.nikiroo.utils.Image";
183 protected Object
fromStream(InputStream in
) throws IOException
{
185 return new Image(in
);
186 } catch (IOException e
) {
187 throw new UnknownFormatConversionException(e
.getMessage());
194 * Create an empty object of the given type.
197 * the object type (its class name)
199 * @return the new object
201 * @throws ClassNotFoundException
202 * if the class cannot be found
203 * @throws NoSuchMethodException
204 * if the given class is not compatible with this code
206 public static Object
createObject(String type
)
207 throws ClassNotFoundException
, NoSuchMethodException
{
211 Class
<?
> clazz
= getClass(type
);
212 String className
= clazz
.getName();
213 List
<Object
> args
= new ArrayList
<Object
>();
214 List
<Class
<?
>> classes
= new ArrayList
<Class
<?
>>();
215 Constructor
<?
> ctor
= null;
216 if (className
.contains("$")) {
217 for (String parentName
= className
.substring(0,
218 className
.lastIndexOf('$'));; parentName
= parentName
219 .substring(0, parentName
.lastIndexOf('$'))) {
220 Object parent
= createObject(parentName
);
222 classes
.add(parent
.getClass());
224 if (!parentName
.contains("$")) {
229 // Better error description in case there is no empty
233 for (Class
<?
> parent
= clazz
; parent
!= null
234 && !parent
.equals(Object
.class); parent
= parent
236 if (!desc
.isEmpty()) {
246 ctor
= clazz
.getDeclaredConstructor(classes
247 .toArray(new Class
[] {}));
248 } catch (NoSuchMethodException nsme
) {
249 // TODO: it seems e do not always need a parameter for each
250 // level, so we currently try "ALL" levels or "FIRST" level
251 // only -> we should check the actual rule and use it
252 ctor
= clazz
.getDeclaredConstructor(classes
.get(0));
253 Object firstParent
= args
.get(0);
255 args
.add(firstParent
);
259 ctor
= clazz
.getDeclaredConstructor();
262 ctor
.setAccessible(true);
263 return ctor
.newInstance(args
.toArray());
264 } catch (ClassNotFoundException e
) {
266 } catch (NoSuchMethodException e
) {
268 throw new NoSuchMethodException("Empty constructor not found: "
272 } catch (Exception e
) {
273 throw new NoSuchMethodException("Cannot instantiate: " + type
);
278 * Insert a custom serialiser that will take precedence over the default one
279 * or the target class.
282 * the custom serialiser
284 static public void addCustomSerializer(CustomSerializer serializer
) {
285 customTypes
.put(serializer
.getType(), serializer
);
289 * Serialise the given object into this {@link OutputStream}.
291 * <b>Important: </b>If the operation fails (with a
292 * {@link NotSerializableException}), the {@link StringBuilder} will be
293 * corrupted (will contain bad, most probably not importable data).
296 * the output {@link OutputStream} to serialise to
298 * the object to serialise
300 * the map of already serialised objects (if the given object or
301 * one of its descendant is already present in it, only an ID
302 * will be serialised)
304 * @throws NotSerializableException
305 * if the object cannot be serialised (in this case, the
306 * {@link StringBuilder} can contain bad, most probably not
308 * @throws IOException
309 * in case of I/O errors
311 static void append(OutputStream out
, Object o
, Map
<Integer
, Object
> map
)
312 throws NotSerializableException
, IOException
{
314 Field
[] fields
= new Field
[] {};
319 int hash
= System
.identityHashCode(o
);
320 fields
= o
.getClass().getDeclaredFields();
321 type
= o
.getClass().getCanonicalName();
323 // Anonymous inner classes support
324 type
= o
.getClass().getName();
326 id
= Integer
.toString(hash
);
327 if (map
.containsKey(hash
)) {
328 fields
= new Field
[] {};
334 write(out
, "{\nREF ");
340 if (!encode(out
, o
)) { // check if direct value
342 for (Field field
: fields
) {
343 field
.setAccessible(true);
345 if (field
.getName().startsWith("this$")
346 || field
.isSynthetic()
347 || (field
.getModifiers() & Modifier
.STATIC
) == Modifier
.STATIC
) {
348 // Do not keep this links of nested classes
349 // Do not keep synthetic fields
350 // Do not keep final fields
355 write(out
, field
.getName());
358 Object value
= field
.get(o
);
360 if (!encode(out
, value
)) {
362 append(out
, value
, map
);
365 } catch (IllegalArgumentException e
) {
366 e
.printStackTrace(); // should not happen (see
368 } catch (IllegalAccessException e
) {
369 e
.printStackTrace(); // should not happen (see
377 * Encode the object into the given {@link OutputStream} if possible and if
380 * A supported object in this context means an object we can directly
381 * encode, like an Integer or a String. Custom objects and arrays are also
382 * considered supported, but <b>compound objects are not supported here</b>.
384 * For compound objects, you should use {@link Exporter}.
387 * the {@link OutputStream} to append to
389 * the object to encode (can be NULL, which will be encoded)
391 * @return TRUE if success, FALSE if not (the content of the
392 * {@link OutputStream} won't be changed in case of failure)
394 * @throws IOException
395 * in case of I/O error
397 static boolean encode(OutputStream out
, Object value
) throws IOException
{
400 } else if (value
.getClass().getSimpleName().endsWith("[]")) {
401 // Simple name does support [] suffix and do not return NULL for
402 // inner anonymous classes
403 return customTypes
.get("[]").encode(out
, value
);
404 } else if (customTypes
.containsKey(value
.getClass().getCanonicalName())) {
405 return customTypes
.get(value
.getClass().getCanonicalName())//
407 } else if (value
instanceof String
) {
408 encodeString(out
, (String
) value
);
409 } else if (value
instanceof Boolean
) {
411 } else if (value
instanceof Byte
) {
414 } else if (value
instanceof Character
) {
415 encodeString(out
, "" + value
);
417 } else if (value
instanceof Short
) {
420 } else if (value
instanceof Integer
) {
422 } else if (value
instanceof Long
) {
425 } else if (value
instanceof Float
) {
428 } else if (value
instanceof Double
) {
431 } else if (value
instanceof Enum
) {
432 String type
= value
.getClass().getCanonicalName();
435 write(out
, ((Enum
<?
>) value
).name());
445 * Decode the data into an equivalent supported source object.
447 * A supported object in this context means an object we can directly
448 * encode, like an Integer or a String. Custom objects and arrays are also
449 * considered supported, but <b>compound objects are not supported here</b>.
451 * For compound objects, you should use {@link Importer}.
453 * @param encodedValue
454 * the encoded data, cannot be NULL
456 * @return the object (can be NULL for NULL encoded values)
458 * @throws IOException
459 * if the content cannot be converted
461 static Object
decode(String encodedValue
) throws IOException
{
464 if (encodedValue
.length() > 1) {
465 cut
= encodedValue
.substring(0, encodedValue
.length() - 1);
468 if (CustomSerializer
.isCustom(encodedValue
)) {
469 // custom:TYPE_NAME:"content is String-encoded"
470 String type
= CustomSerializer
.typeOf(encodedValue
);
471 if (customTypes
.containsKey(type
)) {
472 return customTypes
.get(type
).decode(encodedValue
);
474 throw new IOException("Unknown custom type: " + type
);
475 } else if (encodedValue
.equals("NULL")
476 || encodedValue
.equals("null")) {
478 } else if (encodedValue
.endsWith("\"")) {
479 return decodeString(encodedValue
);
480 } else if (encodedValue
.equals("true")) {
482 } else if (encodedValue
.equals("false")) {
484 } else if (encodedValue
.endsWith("b")) {
485 return Byte
.parseByte(cut
);
486 } else if (encodedValue
.endsWith("c")) {
487 return decodeString(cut
).charAt(0);
488 } else if (encodedValue
.endsWith("s")) {
489 return Short
.parseShort(cut
);
490 } else if (encodedValue
.endsWith("L")) {
491 return Long
.parseLong(cut
);
492 } else if (encodedValue
.endsWith("F")) {
493 return Float
.parseFloat(cut
);
494 } else if (encodedValue
.endsWith("d")) {
495 return Double
.parseDouble(cut
);
496 } else if (encodedValue
.endsWith(";")) {
497 return decodeEnum(encodedValue
);
499 return Integer
.parseInt(encodedValue
);
501 } catch (Exception e
) {
502 if (e
instanceof IOException
) {
503 throw (IOException
) e
;
505 throw new IOException(e
.getMessage());
510 * Write the given {@link String} into the given {@link OutputStream} in
514 * the {@link OutputStream}
516 * the data to write, cannot be NULL
518 * @throws IOException
519 * in case of I/O error
521 static void write(OutputStream out
, Object data
) throws IOException
{
523 out
.write(data
.toString().getBytes("UTF-8"));
524 } catch (UnsupportedEncodingException e
) {
525 // A conforming JVM is required to support UTF-8
531 * Return the corresponding class or throw an {@link Exception} if it
535 * the class name to look for
537 * @return the class (will never be NULL)
539 * @throws ClassNotFoundException
540 * if the class cannot be found
541 * @throws NoSuchMethodException
542 * if the class cannot be created (usually because it or its
543 * enclosing class doesn't have an empty constructor)
545 static private Class
<?
> getClass(String type
)
546 throws ClassNotFoundException
, NoSuchMethodException
{
547 Class
<?
> clazz
= null;
549 clazz
= Class
.forName(type
);
550 } catch (ClassNotFoundException e
) {
551 int pos
= type
.length();
552 pos
= type
.lastIndexOf(".", pos
);
554 String parentType
= type
.substring(0, pos
);
555 String nestedType
= type
.substring(pos
+ 1);
556 Class
<?
> javaParent
= null;
558 javaParent
= getClass(parentType
);
559 parentType
= javaParent
.getName();
560 clazz
= Class
.forName(parentType
+ "$" + nestedType
);
561 } catch (Exception ee
) {
564 if (javaParent
== null) {
565 throw new NoSuchMethodException(
568 + " (the enclosing class cannot be created: maybe it doesn't have an empty constructor?)");
574 throw new ClassNotFoundException("Class not found: " + type
);
580 @SuppressWarnings({ "unchecked", "rawtypes" })
581 static private Enum
<?
> decodeEnum(String escaped
) {
582 // escaped: be.xxx.EnumType.VALUE;
583 int pos
= escaped
.lastIndexOf(".");
584 String type
= escaped
.substring(0, pos
);
585 String name
= escaped
.substring(pos
+ 1, escaped
.length() - 1);
588 return Enum
.valueOf((Class
<Enum
>) getClass(type
), name
);
589 } catch (Exception e
) {
590 throw new UnknownFormatConversionException("Unknown enum: <" + type
596 static void encodeString(OutputStream out
, String raw
) throws IOException
{
598 // TODO !! utf-8 required
599 for (char car
: raw
.toCharArray()) {
600 encodeString(out
, car
);
606 static void encodeString(OutputStream out
, InputStream raw
)
609 byte buffer
[] = new byte[4069];
610 for (int len
= 0; (len
= raw
.read(buffer
)) > 0;) {
611 for (int i
= 0; i
< len
; i
++) {
612 // TODO: not 100% correct, look up howto for UTF-8
613 encodeString(out
, (char) buffer
[i
]);
619 // for encode string, NOT to encode a char by itself!
620 static void encodeString(OutputStream out
, char raw
) throws IOException
{
645 static String
decodeString(String escaped
) {
646 StringBuilder builder
= new StringBuilder();
648 boolean escaping
= false;
649 for (char car
: escaped
.toCharArray()) {
659 builder
.append('\\');
662 builder
.append('\r');
665 builder
.append('\n');
675 return builder
.substring(1, builder
.length() - 1);