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
.Image
;
22 * Small class to help with serialisation.
24 * Note that we do not support inner classes (but we do support nested classes)
25 * and all objects require an empty constructor to be deserialised.
27 * It is possible to add support to custom types (both the encoder and the
28 * decoder will require the custom classes) -- see {@link CustomSerializer}.
30 * Default supported types are:
32 * <li>NULL (as a null value)</li>
42 * <li>Enum (any enum whose name and value is known by the caller)</li>
43 * <li>java.awt.image.BufferedImage (as a {@link CustomSerializer})</li>
44 * <li>An array of the above (as a {@link CustomSerializer})</li>
50 public class SerialUtils
{
51 private static Map
<String
, CustomSerializer
> customTypes
;
54 customTypes
= new HashMap
<String
, CustomSerializer
>();
57 customTypes
.put("[]", new CustomSerializer() {
59 protected void toStream(OutputStream out
, Object value
)
61 String type
= value
.getClass().getCanonicalName();
62 type
= type
.substring(0, type
.length() - 2); // remove the []
67 for (int i
= 0; true; i
++) {
68 Object item
= Array
.get(value
, i
);
69 // encode it normally if direct value
70 if (!SerialUtils
.encode(out
, item
)) {
72 // TODO: use ZIP: if not?
73 new Exporter(out
).append(item
);
74 } catch (NotSerializableException e
) {
75 throw new UnknownFormatConversionException(e
81 } catch (ArrayIndexOutOfBoundsException e
) {
87 protected String
getType() {
92 protected Object
fromStream(InputStream in
) throws IOException
{
97 protected Object
fromString(String content
) throws IOException
{
98 String
[] tab
= content
.split("\n");
101 Object array
= Array
.newInstance(
102 SerialUtils
.getClass(tab
[0]), tab
.length
- 1);
103 for (int i
= 1; i
< tab
.length
; i
++) {
104 Object value
= new Importer().read(tab
[i
]).getValue();
105 Array
.set(array
, i
- 1, value
);
109 } catch (Exception e
) {
110 if (e
instanceof IOException
) {
111 throw (IOException
) e
;
113 throw new IOException(e
.getMessage());
119 customTypes
.put("java.net.URL", new CustomSerializer() {
121 protected String
toString(Object value
) {
123 return ((URL
) value
).toString();
129 protected Object
fromString(String content
) throws IOException
{
130 if (content
!= null) {
131 return new URL(content
);
137 protected String
getType() {
138 return "java.net.URL";
142 // Images (this is currently the only supported image type by default)
143 customTypes
.put("be.nikiroo.utils.Image", new CustomSerializer() {
145 protected String
toString(Object value
) {
146 return ((Image
) value
).toBase64();
150 protected String
getType() {
151 return "be.nikiroo.utils.Image";
155 protected Object
fromString(String content
) {
157 return new Image(content
);
158 } catch (IOException e
) {
159 throw new UnknownFormatConversionException(e
.getMessage());
166 * Create an empty object of the given type.
169 * the object type (its class name)
171 * @return the new object
173 * @throws ClassNotFoundException
174 * if the class cannot be found
175 * @throws NoSuchMethodException
176 * if the given class is not compatible with this code
178 public static Object
createObject(String type
)
179 throws ClassNotFoundException
, NoSuchMethodException
{
183 Class
<?
> clazz
= getClass(type
);
184 String className
= clazz
.getName();
185 List
<Object
> args
= new ArrayList
<Object
>();
186 List
<Class
<?
>> classes
= new ArrayList
<Class
<?
>>();
187 Constructor
<?
> ctor
= null;
188 if (className
.contains("$")) {
189 for (String parentName
= className
.substring(0,
190 className
.lastIndexOf('$'));; parentName
= parentName
191 .substring(0, parentName
.lastIndexOf('$'))) {
192 Object parent
= createObject(parentName
);
194 classes
.add(parent
.getClass());
196 if (!parentName
.contains("$")) {
201 // Better error description in case there is no empty
205 for (Class
<?
> parent
= clazz
; parent
!= null
206 && !parent
.equals(Object
.class); parent
= parent
208 if (!desc
.isEmpty()) {
218 ctor
= clazz
.getDeclaredConstructor(classes
219 .toArray(new Class
[] {}));
220 } catch (NoSuchMethodException nsme
) {
221 // TODO: it seems e do not always need a parameter for each
222 // level, so we currently try "ALL" levels or "FIRST" level
223 // only -> we should check the actual rule and use it
224 ctor
= clazz
.getDeclaredConstructor(classes
.get(0));
225 Object firstParent
= args
.get(0);
227 args
.add(firstParent
);
231 ctor
= clazz
.getDeclaredConstructor();
234 ctor
.setAccessible(true);
235 return ctor
.newInstance(args
.toArray());
236 } catch (ClassNotFoundException e
) {
238 } catch (NoSuchMethodException e
) {
240 throw new NoSuchMethodException("Empty constructor not found: "
244 } catch (Exception e
) {
245 throw new NoSuchMethodException("Cannot instantiate: " + type
);
250 * Insert a custom serialiser that will take precedence over the default one
251 * or the target class.
254 * the custom serialiser
256 static public void addCustomSerializer(CustomSerializer serializer
) {
257 customTypes
.put(serializer
.getType(), serializer
);
261 * Serialise the given object into this {@link OutputStream}.
263 * <b>Important: </b>If the operation fails (with a
264 * {@link NotSerializableException}), the {@link StringBuilder} will be
265 * corrupted (will contain bad, most probably not importable data).
268 * the output {@link OutputStream} to serialise to
270 * the object to serialise
272 * the map of already serialised objects (if the given object or
273 * one of its descendant is already present in it, only an ID
274 * will be serialised)
276 * @throws NotSerializableException
277 * if the object cannot be serialised (in this case, the
278 * {@link StringBuilder} can contain bad, most probably not
280 * @throws IOException
281 * in case of I/O errors
283 static void append(OutputStream out
, Object o
, Map
<Integer
, Object
> map
)
284 throws NotSerializableException
, IOException
{
286 Field
[] fields
= new Field
[] {};
291 int hash
= System
.identityHashCode(o
);
292 fields
= o
.getClass().getDeclaredFields();
293 type
= o
.getClass().getCanonicalName();
295 // Anonymous inner classes support
296 type
= o
.getClass().getName();
298 id
= Integer
.toString(hash
);
299 if (map
.containsKey(hash
)) {
300 fields
= new Field
[] {};
306 write(out
, "{\nREF ");
312 if (!encode(out
, o
)) { // check if direct value
314 for (Field field
: fields
) {
315 field
.setAccessible(true);
317 if (field
.getName().startsWith("this$")
318 || field
.isSynthetic()
319 || (field
.getModifiers() & Modifier
.STATIC
) == Modifier
.STATIC
) {
320 // Do not keep this links of nested classes
321 // Do not keep synthetic fields
322 // Do not keep final fields
327 write(out
, field
.getName());
330 Object value
= field
.get(o
);
332 if (!encode(out
, value
)) {
334 append(out
, value
, map
);
337 } catch (IllegalArgumentException e
) {
338 e
.printStackTrace(); // should not happen (see
340 } catch (IllegalAccessException e
) {
341 e
.printStackTrace(); // should not happen (see
349 * Encode the object into the given {@link OutputStream} if possible and if
352 * A supported object in this context means an object we can directly
353 * encode, like an Integer or a String. Custom objects and arrays are also
354 * considered supported, but <b>compound objects are not supported here</b>.
356 * For compound objects, you should use {@link Exporter}.
359 * the {@link OutputStream} to append to
361 * the object to encode (can be NULL, which will be encoded)
363 * @return TRUE if success, FALSE if not (the content of the
364 * {@link OutputStream} won't be changed in case of failure)
366 * @throws IOException
367 * in case of I/O error
369 static boolean encode(OutputStream out
, Object value
) throws IOException
{
372 } else if (value
.getClass().getSimpleName().endsWith("[]")) {
373 // Simple name does support [] suffix and do not return NULL for
374 // inner anonymous classes
375 return customTypes
.get("[]").encode(out
, value
);
376 } else if (customTypes
.containsKey(value
.getClass().getCanonicalName())) {
377 return customTypes
.get(value
.getClass().getCanonicalName())//
379 } else if (value
instanceof String
) {
380 encodeString(out
, (String
) value
);
381 } else if (value
instanceof Boolean
) {
383 } else if (value
instanceof Byte
) {
386 } else if (value
instanceof Character
) {
387 encodeString(out
, "" + value
);
389 } else if (value
instanceof Short
) {
392 } else if (value
instanceof Integer
) {
394 } else if (value
instanceof Long
) {
397 } else if (value
instanceof Float
) {
400 } else if (value
instanceof Double
) {
403 } else if (value
instanceof Enum
) {
404 String type
= value
.getClass().getCanonicalName();
407 write(out
, ((Enum
<?
>) value
).name());
417 * Decode the data into an equivalent supported source object.
419 * A supported object in this context means an object we can directly
420 * encode, like an Integer or a String. Custom objects and arrays are also
421 * considered supported, but <b>compound objects are not supported here</b>.
423 * For compound objects, you should use {@link Importer}.
425 * @param encodedValue
426 * the encoded data, cannot be NULL
428 * @return the object (can be NULL for NULL encoded values)
430 * @throws IOException
431 * if the content cannot be converted
433 static Object
decode(String encodedValue
) throws IOException
{
436 if (encodedValue
.length() > 1) {
437 cut
= encodedValue
.substring(0, encodedValue
.length() - 1);
440 if (CustomSerializer
.isCustom(encodedValue
)) {
441 // custom:TYPE_NAME:"content is String-encoded"
442 String type
= CustomSerializer
.typeOf(encodedValue
);
443 if (customTypes
.containsKey(type
)) {
444 return customTypes
.get(type
).decode(encodedValue
);
446 throw new IOException("Unknown custom type: " + type
);
447 } else if (encodedValue
.equals("NULL")
448 || encodedValue
.equals("null")) {
450 } else if (encodedValue
.endsWith("\"")) {
451 return decodeString(encodedValue
);
452 } else if (encodedValue
.equals("true")) {
454 } else if (encodedValue
.equals("false")) {
456 } else if (encodedValue
.endsWith("b")) {
457 return Byte
.parseByte(cut
);
458 } else if (encodedValue
.endsWith("c")) {
459 return decodeString(cut
).charAt(0);
460 } else if (encodedValue
.endsWith("s")) {
461 return Short
.parseShort(cut
);
462 } else if (encodedValue
.endsWith("L")) {
463 return Long
.parseLong(cut
);
464 } else if (encodedValue
.endsWith("F")) {
465 return Float
.parseFloat(cut
);
466 } else if (encodedValue
.endsWith("d")) {
467 return Double
.parseDouble(cut
);
468 } else if (encodedValue
.endsWith(";")) {
469 return decodeEnum(encodedValue
);
471 return Integer
.parseInt(encodedValue
);
473 } catch (Exception e
) {
474 if (e
instanceof IOException
) {
475 throw (IOException
) e
;
477 throw new IOException(e
.getMessage());
482 * Write the given {@link String} into the given {@link OutputStream} in
486 * the {@link OutputStream}
488 * the data to write, cannot be NULL
490 * @throws IOException
491 * in case of I/O error
493 static void write(OutputStream out
, Object data
) throws IOException
{
495 out
.write(data
.toString().getBytes("UTF-8"));
496 } catch (UnsupportedEncodingException e
) {
497 // A conforming JVM is required to support UTF-8
503 * Return the corresponding class or throw an {@link Exception} if it
507 * the class name to look for
509 * @return the class (will never be NULL)
511 * @throws ClassNotFoundException
512 * if the class cannot be found
513 * @throws NoSuchMethodException
514 * if the class cannot be created (usually because it or its
515 * enclosing class doesn't have an empty constructor)
517 static private Class
<?
> getClass(String type
)
518 throws ClassNotFoundException
, NoSuchMethodException
{
519 Class
<?
> clazz
= null;
521 clazz
= Class
.forName(type
);
522 } catch (ClassNotFoundException e
) {
523 int pos
= type
.length();
524 pos
= type
.lastIndexOf(".", pos
);
526 String parentType
= type
.substring(0, pos
);
527 String nestedType
= type
.substring(pos
+ 1);
528 Class
<?
> javaParent
= null;
530 javaParent
= getClass(parentType
);
531 parentType
= javaParent
.getName();
532 clazz
= Class
.forName(parentType
+ "$" + nestedType
);
533 } catch (Exception ee
) {
536 if (javaParent
== null) {
537 throw new NoSuchMethodException(
540 + " (the enclosing class cannot be created: maybe it doesn't have an empty constructor?)");
546 throw new ClassNotFoundException("Class not found: " + type
);
552 @SuppressWarnings({ "unchecked", "rawtypes" })
553 static private Enum
<?
> decodeEnum(String escaped
) {
554 // escaped: be.xxx.EnumType.VALUE;
555 int pos
= escaped
.lastIndexOf(".");
556 String type
= escaped
.substring(0, pos
);
557 String name
= escaped
.substring(pos
+ 1, escaped
.length() - 1);
560 return Enum
.valueOf((Class
<Enum
>) getClass(type
), name
);
561 } catch (Exception e
) {
562 throw new UnknownFormatConversionException("Unknown enum: <" + type
568 static void encodeString(OutputStream out
, String raw
) throws IOException
{
570 // TODO !! utf-8 required
571 for (char car
: raw
.toCharArray()) {
572 encodeString(out
, car
);
578 static void encodeString(OutputStream out
, InputStream raw
)
581 byte buffer
[] = new byte[4069];
582 for (int len
= 0; (len
= raw
.read(buffer
)) > 0;) {
583 for (int i
= 0; i
< len
; i
++) {
584 // TODO: not 100% correct, look up howto for UTF-8
585 encodeString(out
, (char) buffer
[i
]);
591 // for encode string, NOT to encode a char by itself!
592 static void encodeString(OutputStream out
, char raw
) throws IOException
{
617 static String
decodeString(String escaped
) {
618 StringBuilder builder
= new StringBuilder();
620 boolean escaping
= false;
621 for (char car
: escaped
.toCharArray()) {
631 builder
.append('\\');
634 builder
.append('\r');
637 builder
.append('\n');
647 return builder
.substring(1, builder
.length() - 1);