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: use ZIP: if not?
80 new Exporter(out
).append(item
);
81 } catch (NotSerializableException e
) {
82 throw new UnknownFormatConversionException(e
88 } catch (ArrayIndexOutOfBoundsException e
) {
94 protected Object
fromStream(InputStream in
) throws IOException
{
95 NextableInputStream stream
= new NextableInputStream(in
,
96 new NextableInputStreamStep('\n'));
99 List
<Object
> list
= new ArrayList
<Object
>();
101 String type
= IOUtils
.readSmallStream(stream
);
103 while (stream
.next()) {
104 Object value
= new Importer().read(stream
).getValue();
108 Object array
= Array
.newInstance(
109 SerialUtils
.getClass(type
), list
.size());
110 for (int i
= 0; i
< list
.size(); i
++) {
111 Array
.set(array
, i
, list
.get(i
));
115 } catch (Exception e
) {
116 if (e
instanceof IOException
) {
117 throw (IOException
) e
;
119 throw new IOException(e
.getMessage());
124 protected String
getType() {
130 customTypes
.put("java.net.URL", new CustomSerializer() {
133 protected void toStream(OutputStream out
, Object value
)
137 val
= ((URL
) value
).toString();
140 out
.write(val
.getBytes("UTF-8"));
144 protected Object
fromStream(InputStream in
) throws IOException
{
145 String val
= IOUtils
.readSmallStream(in
);
146 if (!val
.isEmpty()) {
154 protected String
getType() {
155 return "java.net.URL";
159 // Images (this is currently the only supported image type by default)
160 customTypes
.put("be.nikiroo.utils.Image", new CustomSerializer() {
162 protected void toStream(OutputStream out
, Object value
)
164 Image img
= (Image
) value
;
165 OutputStream encoded
= StringUtils
.base64(out
, false, false);
167 InputStream in
= img
.newInputStream();
169 IOUtils
.write(in
, encoded
);
179 protected String
getType() {
180 return "be.nikiroo.utils.Image";
184 protected Object
fromStream(InputStream in
) throws IOException
{
186 return new Image(in
);
187 } catch (IOException e
) {
188 throw new UnknownFormatConversionException(e
.getMessage());
195 * Create an empty object of the given type.
198 * the object type (its class name)
200 * @return the new object
202 * @throws ClassNotFoundException
203 * if the class cannot be found
204 * @throws NoSuchMethodException
205 * if the given class is not compatible with this code
207 public static Object
createObject(String type
)
208 throws ClassNotFoundException
, NoSuchMethodException
{
212 Class
<?
> clazz
= getClass(type
);
213 String className
= clazz
.getName();
214 List
<Object
> args
= new ArrayList
<Object
>();
215 List
<Class
<?
>> classes
= new ArrayList
<Class
<?
>>();
216 Constructor
<?
> ctor
= null;
217 if (className
.contains("$")) {
218 for (String parentName
= className
.substring(0,
219 className
.lastIndexOf('$'));; parentName
= parentName
220 .substring(0, parentName
.lastIndexOf('$'))) {
221 Object parent
= createObject(parentName
);
223 classes
.add(parent
.getClass());
225 if (!parentName
.contains("$")) {
230 // Better error description in case there is no empty
234 for (Class
<?
> parent
= clazz
; parent
!= null
235 && !parent
.equals(Object
.class); parent
= parent
237 if (!desc
.isEmpty()) {
247 ctor
= clazz
.getDeclaredConstructor(classes
248 .toArray(new Class
[] {}));
249 } catch (NoSuchMethodException nsme
) {
250 // TODO: it seems we do not always need a parameter for each
251 // level, so we currently try "ALL" levels or "FIRST" level
252 // only -> we should check the actual rule and use it
253 ctor
= clazz
.getDeclaredConstructor(classes
.get(0));
254 Object firstParent
= args
.get(0);
256 args
.add(firstParent
);
260 ctor
= clazz
.getDeclaredConstructor();
263 ctor
.setAccessible(true);
264 return ctor
.newInstance(args
.toArray());
265 } catch (ClassNotFoundException e
) {
267 } catch (NoSuchMethodException e
) {
269 throw new NoSuchMethodException("Empty constructor not found: "
273 } catch (Exception e
) {
274 throw new NoSuchMethodException("Cannot instantiate: " + type
);
279 * Insert a custom serialiser that will take precedence over the default one
280 * or the target class.
283 * the custom serialiser
285 static public void addCustomSerializer(CustomSerializer serializer
) {
286 customTypes
.put(serializer
.getType(), serializer
);
290 * Serialise the given object into this {@link OutputStream}.
292 * <b>Important: </b>If the operation fails (with a
293 * {@link NotSerializableException}), the {@link StringBuilder} will be
294 * corrupted (will contain bad, most probably not importable data).
297 * the output {@link OutputStream} to serialise to
299 * the object to serialise
301 * the map of already serialised objects (if the given object or
302 * one of its descendant is already present in it, only an ID
303 * will be serialised)
305 * @throws NotSerializableException
306 * if the object cannot be serialised (in this case, the
307 * {@link StringBuilder} can contain bad, most probably not
309 * @throws IOException
310 * in case of I/O errors
312 static void append(OutputStream out
, Object o
, Map
<Integer
, Object
> map
)
313 throws NotSerializableException
, IOException
{
315 Field
[] fields
= new Field
[] {};
320 int hash
= System
.identityHashCode(o
);
321 fields
= o
.getClass().getDeclaredFields();
322 type
= o
.getClass().getCanonicalName();
324 // Anonymous inner classes support
325 type
= o
.getClass().getName();
327 id
= Integer
.toString(hash
);
328 if (map
.containsKey(hash
)) {
329 fields
= new Field
[] {};
335 write(out
, "{\nREF ");
341 if (!encode(out
, o
)) { // check if direct value
343 for (Field field
: fields
) {
344 field
.setAccessible(true);
346 if (field
.getName().startsWith("this$")
347 || field
.isSynthetic()
348 || (field
.getModifiers() & Modifier
.STATIC
) == Modifier
.STATIC
) {
349 // Do not keep this links of nested classes
350 // Do not keep synthetic fields
351 // Do not keep final fields
356 write(out
, field
.getName());
359 Object value
= field
.get(o
);
361 if (!encode(out
, value
)) {
363 append(out
, value
, map
);
366 } catch (IllegalArgumentException e
) {
367 e
.printStackTrace(); // should not happen (see
369 } catch (IllegalAccessException e
) {
370 e
.printStackTrace(); // should not happen (see
378 * Encode the object into the given {@link OutputStream} if possible and if
381 * A supported object in this context means an object we can directly
382 * encode, like an Integer or a String. Custom objects and arrays are also
383 * considered supported, but <b>compound objects are not supported here</b>.
385 * For compound objects, you should use {@link Exporter}.
388 * the {@link OutputStream} to append to
390 * the object to encode (can be NULL, which will be encoded)
392 * @return TRUE if success, FALSE if not (the content of the
393 * {@link OutputStream} won't be changed in case of failure)
395 * @throws IOException
396 * in case of I/O error
398 static boolean encode(OutputStream out
, Object value
) throws IOException
{
401 } else if (value
.getClass().getSimpleName().endsWith("[]")) {
402 // Simple name does support [] suffix and do not return NULL for
403 // inner anonymous classes
404 return customTypes
.get("[]").encode(out
, value
);
405 } else if (customTypes
.containsKey(value
.getClass().getCanonicalName())) {
406 return customTypes
.get(value
.getClass().getCanonicalName())//
408 } else if (value
instanceof String
) {
409 encodeString(out
, (String
) value
);
410 } else if (value
instanceof Boolean
) {
412 } else if (value
instanceof Byte
) {
415 } else if (value
instanceof Character
) {
416 encodeString(out
, "" + value
);
418 } else if (value
instanceof Short
) {
421 } else if (value
instanceof Integer
) {
423 } else if (value
instanceof Long
) {
426 } else if (value
instanceof Float
) {
429 } else if (value
instanceof Double
) {
432 } else if (value
instanceof Enum
) {
433 String type
= value
.getClass().getCanonicalName();
436 write(out
, ((Enum
<?
>) value
).name());
446 * Decode the data into an equivalent supported source object.
448 * A supported object in this context means an object we can directly
449 * encode, like an Integer or a String. Custom objects and arrays are also
450 * considered supported, but <b>compound objects are not supported here</b>.
452 * For compound objects, you should use {@link Importer}.
454 * @param encodedValue
455 * the encoded data, cannot be NULL
457 * @return the object (can be NULL for NULL encoded values)
459 * @throws IOException
460 * if the content cannot be converted
462 static Object
decode(String encodedValue
) throws IOException
{
465 if (encodedValue
.length() > 1) {
466 cut
= encodedValue
.substring(0, encodedValue
.length() - 1);
469 if (CustomSerializer
.isCustom(encodedValue
)) {
470 // custom:TYPE_NAME:"content is String-encoded"
471 String type
= CustomSerializer
.typeOf(encodedValue
);
472 if (customTypes
.containsKey(type
)) {
473 // TODO: we should start with a stream
474 InputStream streamEncodedValue
= new ByteArrayInputStream(
475 encodedValue
.getBytes("UTF-8"));
477 return customTypes
.get(type
).decode(streamEncodedValue
);
479 streamEncodedValue
.close();
482 throw new IOException("Unknown custom type: " + type
);
483 } else if (encodedValue
.equals("NULL")
484 || encodedValue
.equals("null")) {
486 } else if (encodedValue
.endsWith("\"")) {
487 return decodeString(encodedValue
);
488 } else if (encodedValue
.equals("true")) {
490 } else if (encodedValue
.equals("false")) {
492 } else if (encodedValue
.endsWith("b")) {
493 return Byte
.parseByte(cut
);
494 } else if (encodedValue
.endsWith("c")) {
495 return decodeString(cut
).charAt(0);
496 } else if (encodedValue
.endsWith("s")) {
497 return Short
.parseShort(cut
);
498 } else if (encodedValue
.endsWith("L")) {
499 return Long
.parseLong(cut
);
500 } else if (encodedValue
.endsWith("F")) {
501 return Float
.parseFloat(cut
);
502 } else if (encodedValue
.endsWith("d")) {
503 return Double
.parseDouble(cut
);
504 } else if (encodedValue
.endsWith(";")) {
505 return decodeEnum(encodedValue
);
507 return Integer
.parseInt(encodedValue
);
509 } catch (Exception e
) {
510 if (e
instanceof IOException
) {
511 throw (IOException
) e
;
513 throw new IOException(e
.getMessage());
518 * Write the given {@link String} into the given {@link OutputStream} in
522 * the {@link OutputStream}
524 * the data to write, cannot be NULL
526 * @throws IOException
527 * in case of I/O error
529 static void write(OutputStream out
, Object data
) throws IOException
{
531 out
.write(data
.toString().getBytes("UTF-8"));
532 } catch (UnsupportedEncodingException e
) {
533 // A conforming JVM is required to support UTF-8
539 * Return the corresponding class or throw an {@link Exception} if it
543 * the class name to look for
545 * @return the class (will never be NULL)
547 * @throws ClassNotFoundException
548 * if the class cannot be found
549 * @throws NoSuchMethodException
550 * if the class cannot be created (usually because it or its
551 * enclosing class doesn't have an empty constructor)
553 static private Class
<?
> getClass(String type
)
554 throws ClassNotFoundException
, NoSuchMethodException
{
555 Class
<?
> clazz
= null;
557 clazz
= Class
.forName(type
);
558 } catch (ClassNotFoundException e
) {
559 int pos
= type
.length();
560 pos
= type
.lastIndexOf(".", pos
);
562 String parentType
= type
.substring(0, pos
);
563 String nestedType
= type
.substring(pos
+ 1);
564 Class
<?
> javaParent
= null;
566 javaParent
= getClass(parentType
);
567 parentType
= javaParent
.getName();
568 clazz
= Class
.forName(parentType
+ "$" + nestedType
);
569 } catch (Exception ee
) {
572 if (javaParent
== null) {
573 throw new NoSuchMethodException(
576 + " (the enclosing class cannot be created: maybe it doesn't have an empty constructor?)");
582 throw new ClassNotFoundException("Class not found: " + type
);
588 @SuppressWarnings({ "unchecked", "rawtypes" })
589 static private Enum
<?
> decodeEnum(String escaped
) {
590 // escaped: be.xxx.EnumType.VALUE;
591 int pos
= escaped
.lastIndexOf(".");
592 String type
= escaped
.substring(0, pos
);
593 String name
= escaped
.substring(pos
+ 1, escaped
.length() - 1);
596 return Enum
.valueOf((Class
<Enum
>) getClass(type
), name
);
597 } catch (Exception e
) {
598 throw new UnknownFormatConversionException("Unknown enum: <" + type
604 static void encodeString(OutputStream out
, String raw
) throws IOException
{
606 // TODO !! utf-8 required
607 for (char car
: raw
.toCharArray()) {
608 encodeString(out
, car
);
614 static void encodeString(OutputStream out
, InputStream raw
)
617 byte buffer
[] = new byte[4096];
618 for (int len
= 0; (len
= raw
.read(buffer
)) > 0;) {
619 for (int i
= 0; i
< len
; i
++) {
620 // TODO: not 100% correct, look up howto for UTF-8
621 encodeString(out
, (char) buffer
[i
]);
627 // for encode string, NOT to encode a char by itself!
628 static void encodeString(OutputStream out
, char raw
) throws IOException
{
653 static String
decodeString(String escaped
) {
654 StringBuilder builder
= new StringBuilder();
656 boolean escaping
= false;
657 for (char car
: escaped
.toCharArray()) {
667 builder
.append('\\');
670 builder
.append('\r');
673 builder
.append('\n');
683 return builder
.substring(1, builder
.length() - 1);