1 package be
.nikiroo
.utils
.serial
;
3 import java
.awt
.image
.BufferedImage
;
4 import java
.io
.IOException
;
5 import java
.io
.NotSerializableException
;
6 import java
.lang
.reflect
.Array
;
7 import java
.lang
.reflect
.Constructor
;
8 import java
.lang
.reflect
.Field
;
9 import java
.lang
.reflect
.Modifier
;
10 import java
.util
.HashMap
;
12 import java
.util
.UnknownFormatConversionException
;
14 import be
.nikiroo
.utils
.ImageUtils
;
17 * Small class to help with serialisation.
19 * Note that we do not support inner classes (but we do support nested classes)
20 * and all objects require an empty constructor to be deserialised.
22 * It is possible to add support to custom types (both the encoder and the
23 * decoder will require the custom classes) -- see {@link CustomSerializer}.
25 * Default supported types are:
27 * <li>NULL (as a null value)</li>
37 * <li>Enum (any enum whose name and value is known by the caller)</li>
38 * <li>java.awt.image.BufferedImage (as a {@link CustomSerializer})</li>
39 * <li>An array of the above (as a {@link CustomSerializer})</li>
44 public class SerialUtils
{
45 private static Map
<String
, CustomSerializer
> customTypes
;
48 customTypes
= new HashMap
<String
, CustomSerializer
>();
51 customTypes
.put("[]", new CustomSerializer() {
53 protected String
toString(Object value
) {
54 String type
= value
.getClass().getCanonicalName();
55 type
= type
.substring(0, type
.length() - 2); // remove the []
57 StringBuilder builder
= new StringBuilder();
58 builder
.append(type
).append("\n");
60 for (int i
= 0; true; i
++) {
61 Object item
= Array
.get(value
, i
);
62 // encode it normally if direct value
63 if (!SerialUtils
.encode(builder
, item
)) {
66 builder
.append(new Exporter().append(item
)
68 } catch (NotSerializableException e
) {
69 throw new UnknownFormatConversionException(e
75 } catch (ArrayIndexOutOfBoundsException e
) {
79 return builder
.toString();
83 protected String
getType() {
88 protected Object
fromString(String content
) throws IOException
{
89 String
[] tab
= content
.split("\n");
92 Object array
= Array
.newInstance(
93 SerialUtils
.getClass(tab
[0]), tab
.length
- 1);
94 for (int i
= 1; i
< tab
.length
; i
++) {
95 Object value
= new Importer().read(tab
[i
]).getValue();
96 Array
.set(array
, i
- 1, value
);
100 } catch (Exception e
) {
101 if (e
instanceof IOException
) {
102 throw (IOException
) e
;
104 throw new IOException(e
.getMessage());
109 // Images (this is currently the only supported image type by default)
110 customTypes
.put("java.awt.image.BufferedImage", new CustomSerializer() {
112 protected String
toString(Object value
) {
114 return ImageUtils
.toBase64((BufferedImage
) value
);
115 } catch (IOException e
) {
116 throw new UnknownFormatConversionException(e
.getMessage());
121 protected String
getType() {
122 return "java.awt.image.BufferedImage";
126 protected Object
fromString(String content
) {
128 return ImageUtils
.fromBase64(content
);
129 } catch (IOException e
) {
130 throw new UnknownFormatConversionException(e
.getMessage());
137 * Create an empty object of the given type.
140 * the object type (its class name)
142 * @return the new object
144 * @throws ClassNotFoundException
145 * if the class cannot be found
146 * @throws NoSuchMethodException
147 * if the given class is not compatible with this code
149 public static Object
createObject(String type
)
150 throws ClassNotFoundException
, NoSuchMethodException
{
153 Class
<?
> clazz
= getClass(type
);
154 String className
= clazz
.getName();
155 Object
[] args
= null;
156 Constructor
<?
> ctor
= null;
157 if (className
.contains("$")) {
158 Object javaParent
= createObject(className
.substring(0,
159 className
.lastIndexOf('$')));
160 args
= new Object
[] { javaParent
};
161 ctor
= clazz
.getDeclaredConstructor(new Class
[] { javaParent
164 args
= new Object
[] {};
165 ctor
= clazz
.getDeclaredConstructor();
168 ctor
.setAccessible(true);
169 return ctor
.newInstance(args
);
170 } catch (ClassNotFoundException e
) {
172 } catch (NoSuchMethodException e
) {
174 } catch (Exception e
) {
175 throw new NoSuchMethodException("Cannot instantiate: " + type
);
180 * Insert a custom serialiser that will take precedence over the default one
181 * or the target class.
184 * the custom serialiser
186 static public void addCustomSerializer(CustomSerializer serializer
) {
187 customTypes
.put(serializer
.getType(), serializer
);
191 * Serialise the given object into this {@link StringBuilder}.
193 * <b>Important: </b>If the operation fails (with a
194 * {@link NotSerializableException}), the {@link StringBuilder} will be
195 * corrupted (will contain bad, most probably not importable data).
198 * the output {@link StringBuilder} to serialise to
200 * the object to serialise
202 * the map of already serialised objects (if the given object or
203 * one of its descendant is already present in it, only an ID
204 * will be serialised)
206 * @throws NotSerializableException
207 * if the object cannot be serialised (in this case, the
208 * {@link StringBuilder} can contain bad, most probably not
211 static void append(StringBuilder builder
, Object o
, Map
<Integer
, Object
> map
)
212 throws NotSerializableException
{
214 Field
[] fields
= new Field
[] {};
219 int hash
= System
.identityHashCode(o
);
220 fields
= o
.getClass().getDeclaredFields();
221 type
= o
.getClass().getCanonicalName();
223 throw new NotSerializableException(
225 "Cannot find the class for this object: %s (it could be an inner class, which is not supported)",
228 id
= Integer
.toString(hash
);
229 if (map
.containsKey(hash
)) {
230 fields
= new Field
[] {};
236 builder
.append("{\nREF ").append(type
).append("@").append(id
)
238 if (!encode(builder
, o
)) { // check if direct value
240 for (Field field
: fields
) {
241 field
.setAccessible(true);
243 if (field
.getName().startsWith("this$")
244 || field
.isSynthetic()
245 || (field
.getModifiers() & Modifier
.STATIC
) == Modifier
.STATIC
) {
246 // Do not keep this links of nested classes
247 // Do not keep synthetic fields
248 // Do not keep final fields
252 builder
.append("\n");
253 builder
.append(field
.getName());
257 value
= field
.get(o
);
259 if (!encode(builder
, value
)) {
260 builder
.append("\n");
261 append(builder
, value
, map
);
264 } catch (IllegalArgumentException e
) {
265 e
.printStackTrace(); // should not happen (see
267 } catch (IllegalAccessException e
) {
268 e
.printStackTrace(); // should not happen (see
272 builder
.append("\n}");
276 * Encode the object into the given builder if possible (if supported).
279 * the builder to append to
281 * the object to encode (can be NULL, which will be encoded)
283 * @return TRUE if success, FALSE if not (the content of the builder won't
284 * be changed in case of failure)
286 static boolean encode(StringBuilder builder
, Object value
) {
288 builder
.append("NULL");
289 } else if (value
.getClass().getCanonicalName().endsWith("[]")) {
290 return customTypes
.get("[]").encode(builder
, value
);
291 } else if (customTypes
.containsKey(value
.getClass().getCanonicalName())) {
292 return customTypes
.get(value
.getClass().getCanonicalName())//
293 .encode(builder
, value
);
294 } else if (value
instanceof String
) {
295 encodeString(builder
, (String
) value
);
296 } else if (value
instanceof Boolean
) {
297 builder
.append(value
);
298 } else if (value
instanceof Byte
) {
299 builder
.append(value
).append('b');
300 } else if (value
instanceof Character
) {
301 encodeString(builder
, "" + value
);
303 } else if (value
instanceof Short
) {
304 builder
.append(value
).append('s');
305 } else if (value
instanceof Integer
) {
306 builder
.append(value
);
307 } else if (value
instanceof Long
) {
308 builder
.append(value
).append('L');
309 } else if (value
instanceof Float
) {
310 builder
.append(value
).append('F');
311 } else if (value
instanceof Double
) {
312 builder
.append(value
).append('d');
313 } else if (value
instanceof Enum
) {
314 String type
= value
.getClass().getCanonicalName();
315 builder
.append(type
).append(".").append(((Enum
<?
>) value
).name())
325 * Decode the data into an equivalent source object.
327 * @param encodedValue
328 * the encoded data, cannot be NULL
330 * @return the object (can be NULL for NULL encoded values)
332 * @throws IOException
333 * if the content cannot be converted
335 static Object
decode(String encodedValue
) throws IOException
{
338 if (encodedValue
.length() > 1) {
339 cut
= encodedValue
.substring(0, encodedValue
.length() - 1);
342 if (CustomSerializer
.isCustom(encodedValue
)) {
343 // custom:TYPE_NAME:"content is String-encoded"
344 String type
= CustomSerializer
.typeOf(encodedValue
);
345 if (customTypes
.containsKey(type
)) {
346 return customTypes
.get(type
).decode(encodedValue
);
348 throw new IOException("Unknown custom type: " + type
);
349 } else if (encodedValue
.equals("NULL")
350 || encodedValue
.equals("null")) {
352 } else if (encodedValue
.endsWith("\"")) {
353 return decodeString(encodedValue
);
354 } else if (encodedValue
.equals("true")) {
356 } else if (encodedValue
.equals("false")) {
358 } else if (encodedValue
.endsWith("b")) {
359 return Byte
.parseByte(cut
);
360 } else if (encodedValue
.endsWith("c")) {
361 return decodeString(cut
).charAt(0);
362 } else if (encodedValue
.endsWith("s")) {
363 return Short
.parseShort(cut
);
364 } else if (encodedValue
.endsWith("L")) {
365 return Long
.parseLong(cut
);
366 } else if (encodedValue
.endsWith("F")) {
367 return Float
.parseFloat(cut
);
368 } else if (encodedValue
.endsWith("d")) {
369 return Double
.parseDouble(cut
);
370 } else if (encodedValue
.endsWith(";")) {
371 return decodeEnum(encodedValue
);
373 return Integer
.parseInt(encodedValue
);
375 } catch (Exception e
) {
376 if (e
instanceof IOException
) {
377 throw (IOException
) e
;
379 throw new IOException(e
.getMessage());
384 * Return the corresponding class or throw an {@link Exception} if it
388 * the class name to look for
390 * @return the class (will never be NULL)
392 * @throws ClassNotFoundException
393 * if the class cannot be found
394 * @throws NoSuchMethodException
395 * if the class cannot be created (usually because it or its
396 * enclosing class doesn't have an empty constructor)
398 static private Class
<?
> getClass(String type
)
399 throws ClassNotFoundException
, NoSuchMethodException
{
400 Class
<?
> clazz
= null;
402 clazz
= Class
.forName(type
);
403 } catch (ClassNotFoundException e
) {
404 int pos
= type
.length();
405 pos
= type
.lastIndexOf(".", pos
);
407 String parentType
= type
.substring(0, pos
);
408 String nestedType
= type
.substring(pos
+ 1);
409 Class
<?
> javaParent
= null;
411 javaParent
= getClass(parentType
);
412 parentType
= javaParent
.getName();
413 clazz
= Class
.forName(parentType
+ "$" + nestedType
);
414 } catch (Exception ee
) {
417 if (javaParent
== null) {
418 throw new NoSuchMethodException(
421 + " (the enclosing class cannot be created: maybe it doesn't have an empty constructor?)");
427 throw new ClassNotFoundException("Class not found: " + type
);
433 @SuppressWarnings({ "unchecked", "rawtypes" })
434 private static Enum
<?
> decodeEnum(String escaped
) {
435 // escaped: be.xxx.EnumType.VALUE;
436 int pos
= escaped
.lastIndexOf(".");
437 String type
= escaped
.substring(0, pos
);
438 String name
= escaped
.substring(pos
+ 1, escaped
.length() - 1);
441 return Enum
.valueOf((Class
<Enum
>) getClass(type
), name
);
442 } catch (Exception e
) {
443 throw new UnknownFormatConversionException("Unknown enum: <" + type
449 private static void encodeString(StringBuilder builder
, String raw
) {
450 builder
.append('\"');
451 for (char car
: raw
.toCharArray()) {
454 builder
.append("\\\\");
457 builder
.append("\\r");
460 builder
.append("\\n");
463 builder
.append("\\\"");
470 builder
.append('\"');
474 private static String
decodeString(String escaped
) {
475 StringBuilder builder
= new StringBuilder();
477 boolean escaping
= false;
478 for (char car
: escaped
.toCharArray()) {
488 builder
.append('\\');
491 builder
.append('\r');
494 builder
.append('\n');
504 return builder
.substring(1, builder
.length() - 1).toString();