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 []
74 for (int i
= 0; true; i
++) {
75 Object item
= Array
.get(value
, i
);
77 // encode it normally if direct value
79 if (!SerialUtils
.encode(out
, item
)) {
81 // TODO: bad escaping?
83 OutputStream bout
= StringUtils
.base64(out
,
85 new Exporter(bout
).append(item
);
86 } catch (NotSerializableException e
) {
87 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
);
183 protected String
getType() {
184 return "be.nikiroo.utils.Image";
188 protected Object
fromStream(InputStream in
) throws IOException
{
191 InputStream decoded
= StringUtils
.unbase64(in
, false);
192 return new Image(decoded
);
193 } catch (IOException e
) {
194 throw new UnknownFormatConversionException(e
.getMessage());
201 * Create an empty object of the given type.
204 * the object type (its class name)
206 * @return the new object
208 * @throws ClassNotFoundException
209 * if the class cannot be found
210 * @throws NoSuchMethodException
211 * if the given class is not compatible with this code
213 public static Object
createObject(String type
)
214 throws ClassNotFoundException
, NoSuchMethodException
{
218 Class
<?
> clazz
= getClass(type
);
219 String className
= clazz
.getName();
220 List
<Object
> args
= new ArrayList
<Object
>();
221 List
<Class
<?
>> classes
= new ArrayList
<Class
<?
>>();
222 Constructor
<?
> ctor
= null;
223 if (className
.contains("$")) {
224 for (String parentName
= className
.substring(0,
225 className
.lastIndexOf('$'));; parentName
= parentName
226 .substring(0, parentName
.lastIndexOf('$'))) {
227 Object parent
= createObject(parentName
);
229 classes
.add(parent
.getClass());
231 if (!parentName
.contains("$")) {
236 // Better error description in case there is no empty
240 for (Class
<?
> parent
= clazz
; parent
!= null
241 && !parent
.equals(Object
.class); parent
= parent
243 if (!desc
.isEmpty()) {
253 ctor
= clazz
.getDeclaredConstructor(classes
254 .toArray(new Class
[] {}));
255 } catch (NoSuchMethodException nsme
) {
256 // TODO: it seems we do not always need a parameter for each
257 // level, so we currently try "ALL" levels or "FIRST" level
258 // only -> we should check the actual rule and use it
259 ctor
= clazz
.getDeclaredConstructor(classes
.get(0));
260 Object firstParent
= args
.get(0);
262 args
.add(firstParent
);
266 ctor
= clazz
.getDeclaredConstructor();
269 ctor
.setAccessible(true);
270 return ctor
.newInstance(args
.toArray());
271 } catch (ClassNotFoundException e
) {
273 } catch (NoSuchMethodException e
) {
275 throw new NoSuchMethodException("Empty constructor not found: "
279 } catch (Exception e
) {
280 throw new NoSuchMethodException("Cannot instantiate: " + type
);
285 * Insert a custom serialiser that will take precedence over the default one
286 * or the target class.
289 * the custom serialiser
291 static public void addCustomSerializer(CustomSerializer serializer
) {
292 customTypes
.put(serializer
.getType(), serializer
);
296 * Serialise the given object into this {@link OutputStream}.
298 * <b>Important: </b>If the operation fails (with a
299 * {@link NotSerializableException}), the {@link StringBuilder} will be
300 * corrupted (will contain bad, most probably not importable data).
303 * the output {@link OutputStream} to serialise to
305 * the object to serialise
307 * the map of already serialised objects (if the given object or
308 * one of its descendant is already present in it, only an ID
309 * will be serialised)
311 * @throws NotSerializableException
312 * if the object cannot be serialised (in this case, the
313 * {@link StringBuilder} can contain bad, most probably not
315 * @throws IOException
316 * in case of I/O errors
318 static void append(OutputStream out
, Object o
, Map
<Integer
, Object
> map
)
319 throws NotSerializableException
, IOException
{
321 Field
[] fields
= new Field
[] {};
326 int hash
= System
.identityHashCode(o
);
327 fields
= o
.getClass().getDeclaredFields();
328 type
= o
.getClass().getCanonicalName();
330 // Anonymous inner classes support
331 type
= o
.getClass().getName();
333 id
= Integer
.toString(hash
);
334 if (map
.containsKey(hash
)) {
335 fields
= new Field
[] {};
341 write(out
, "{\nREF ");
347 if (!encode(out
, o
)) { // check if direct value
349 for (Field field
: fields
) {
350 field
.setAccessible(true);
352 if (field
.getName().startsWith("this$")
353 || field
.isSynthetic()
354 || (field
.getModifiers() & Modifier
.STATIC
) == Modifier
.STATIC
) {
355 // Do not keep this links of nested classes
356 // Do not keep synthetic fields
357 // Do not keep final fields
362 write(out
, field
.getName());
365 Object value
= field
.get(o
);
367 if (!encode(out
, value
)) {
369 append(out
, value
, map
);
372 } catch (IllegalArgumentException e
) {
373 e
.printStackTrace(); // should not happen (see
375 } catch (IllegalAccessException e
) {
376 e
.printStackTrace(); // should not happen (see
385 * Encode the object into the given {@link OutputStream} if possible and if
388 * A supported object in this context means an object we can directly
389 * encode, like an Integer or a String. Custom objects and arrays are also
390 * considered supported, but <b>compound objects are not supported here</b>.
392 * For compound objects, you should use {@link Exporter}.
395 * the {@link OutputStream} to append to
397 * the object to encode (can be NULL, which will be encoded)
399 * @return TRUE if success, FALSE if not (the content of the
400 * {@link OutputStream} won't be changed in case of failure)
402 * @throws IOException
403 * in case of I/O error
405 static boolean encode(OutputStream out
, Object value
) throws IOException
{
408 } else if (value
.getClass().getSimpleName().endsWith("[]")) {
409 // Simple name does support [] suffix and do not return NULL for
410 // inner anonymous classes
411 customTypes
.get("[]").encode(out
, value
);
412 } else if (customTypes
.containsKey(value
.getClass().getCanonicalName())) {
413 customTypes
.get(value
.getClass().getCanonicalName())//
415 } else if (value
instanceof String
) {
416 encodeString(out
, (String
) value
);
417 } else if (value
instanceof Boolean
) {
419 } else if (value
instanceof Byte
) {
422 } else if (value
instanceof Character
) {
423 encodeString(out
, "" + value
);
425 } else if (value
instanceof Short
) {
428 } 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
) {
440 String type
= value
.getClass().getCanonicalName();
443 write(out
, ((Enum
<?
>) value
).name());
453 * Decode the data into an equivalent supported source object.
455 * A supported object in this context means an object we can directly
456 * encode, like an Integer or a String. Custom objects and arrays are also
457 * considered supported, but <b>compound objects are not supported here</b>.
459 * For compound objects, you should use {@link Importer}.
461 * @param encodedValue
462 * the encoded data, cannot be NULL
464 * @return the object (can be NULL for NULL encoded values)
466 * @throws IOException
467 * if the content cannot be converted
469 static Object
decode(String encodedValue
) throws IOException
{
472 if (encodedValue
.length() > 1) {
473 cut
= encodedValue
.substring(0, encodedValue
.length() - 1);
476 if (CustomSerializer
.isCustom(encodedValue
)) {
477 // custom:TYPE_NAME:"content is String-encoded"
478 String type
= CustomSerializer
.typeOf(encodedValue
);
479 if (customTypes
.containsKey(type
)) {
480 // TODO: we should start with a stream
481 InputStream streamEncodedValue
= new ByteArrayInputStream(
482 encodedValue
.getBytes("UTF-8"));
484 return customTypes
.get(type
).decode(streamEncodedValue
);
486 streamEncodedValue
.close();
489 throw new IOException("Unknown custom type: " + type
);
490 } else if (encodedValue
.equals("NULL")
491 || encodedValue
.equals("null")) {
493 } else if (encodedValue
.endsWith("\"")) {
494 return decodeString(encodedValue
);
495 } else if (encodedValue
.equals("true")) {
497 } else if (encodedValue
.equals("false")) {
499 } else if (encodedValue
.endsWith("b")) {
500 return Byte
.parseByte(cut
);
501 } else if (encodedValue
.endsWith("c")) {
502 return decodeString(cut
).charAt(0);
503 } else if (encodedValue
.endsWith("s")) {
504 return Short
.parseShort(cut
);
505 } else if (encodedValue
.endsWith("L")) {
506 return Long
.parseLong(cut
);
507 } else if (encodedValue
.endsWith("F")) {
508 return Float
.parseFloat(cut
);
509 } else if (encodedValue
.endsWith("d")) {
510 return Double
.parseDouble(cut
);
511 } else if (encodedValue
.endsWith(";")) {
512 return decodeEnum(encodedValue
);
514 return Integer
.parseInt(encodedValue
);
516 } catch (Exception e
) {
517 if (e
instanceof IOException
) {
518 throw (IOException
) e
;
520 throw new IOException(e
.getMessage(), e
);
525 * Write the given {@link String} into the given {@link OutputStream} in
529 * the {@link OutputStream}
531 * the data to write, cannot be NULL
533 * @throws IOException
534 * in case of I/O error
536 static void write(OutputStream out
, Object data
) throws IOException
{
538 out
.write(data
.toString().getBytes("UTF-8"));
539 } catch (UnsupportedEncodingException e
) {
540 // A conforming JVM is required to support UTF-8
546 * Return the corresponding class or throw an {@link Exception} if it
550 * the class name to look for
552 * @return the class (will never be NULL)
554 * @throws ClassNotFoundException
555 * if the class cannot be found
556 * @throws NoSuchMethodException
557 * if the class cannot be created (usually because it or its
558 * enclosing class doesn't have an empty constructor)
560 static private Class
<?
> getClass(String type
)
561 throws ClassNotFoundException
, NoSuchMethodException
{
562 Class
<?
> clazz
= null;
564 clazz
= Class
.forName(type
);
565 } catch (ClassNotFoundException e
) {
566 int pos
= type
.length();
567 pos
= type
.lastIndexOf(".", pos
);
569 String parentType
= type
.substring(0, pos
);
570 String nestedType
= type
.substring(pos
+ 1);
571 Class
<?
> javaParent
= null;
573 javaParent
= getClass(parentType
);
574 parentType
= javaParent
.getName();
575 clazz
= Class
.forName(parentType
+ "$" + nestedType
);
576 } catch (Exception ee
) {
579 if (javaParent
== null) {
580 throw new NoSuchMethodException(
583 + " (the enclosing class cannot be created: maybe it doesn't have an empty constructor?)");
589 throw new ClassNotFoundException("Class not found: " + type
);
595 @SuppressWarnings({ "unchecked", "rawtypes" })
596 static private Enum
<?
> decodeEnum(String escaped
) {
597 // escaped: be.xxx.EnumType.VALUE;
598 int pos
= escaped
.lastIndexOf(".");
599 String type
= escaped
.substring(0, pos
);
600 String name
= escaped
.substring(pos
+ 1, escaped
.length() - 1);
603 return Enum
.valueOf((Class
<Enum
>) getClass(type
), name
);
604 } catch (Exception e
) {
605 throw new UnknownFormatConversionException("Unknown enum: <" + type
611 static void encodeString(OutputStream out
, String raw
) throws IOException
{
612 // TODO: not. efficient.
614 // TODO !! utf-8 required
615 for (char car
: raw
.toCharArray()) {
616 encodeString(out
, car
);
622 static void encodeString(OutputStream out
, InputStream raw
)
625 byte buffer
[] = new byte[4096];
626 for (int len
= 0; (len
= raw
.read(buffer
)) > 0;) {
627 for (int i
= 0; i
< len
; i
++) {
628 // TODO: not 100% correct, look up howto for UTF-8
629 encodeString(out
, (char) buffer
[i
]);
635 // for encode string, NOT to encode a char by itself!
636 static void encodeString(OutputStream out
, char raw
) throws IOException
{
661 static String
decodeString(String escaped
) {
662 StringBuilder builder
= new StringBuilder();
664 boolean escaping
= false;
665 for (char car
: escaped
.toCharArray()) {
675 builder
.append('\\');
678 builder
.append('\r');
681 builder
.append('\n');
691 return builder
.substring(1, builder
.length() - 1);