it now compiles
[nikiroo-utils.git] / src / be / nikiroo / utils / serial / SerialUtils.java
1 package be.nikiroo.utils.serial;
2
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;
13 import java.net.URL;
14 import java.util.ArrayList;
15 import java.util.HashMap;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.UnknownFormatConversionException;
19
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;
25
26 /**
27 * Small class to help with serialisation.
28 * <p>
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.
31 * <p>
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}.
34 * <p>
35 * Default supported types are:
36 * <ul>
37 * <li>NULL (as a null value)</li>
38 * <li>String</li>
39 * <li>Boolean</li>
40 * <li>Byte</li>
41 * <li>Character</li>
42 * <li>Short</li>
43 * <li>Long</li>
44 * <li>Float</li>
45 * <li>Double</li>
46 * <li>Integer</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>
50 * <li>URL</li>
51 * </ul>
52 *
53 * @author niki
54 */
55 public class SerialUtils {
56 private static Map<String, CustomSerializer> customTypes;
57
58 static {
59 customTypes = new HashMap<String, CustomSerializer>();
60
61 // Array types:
62 customTypes.put("[]", new CustomSerializer() {
63 @Override
64 protected void toStream(OutputStream out, Object value)
65 throws IOException {
66 // TODO: we use \n to separate, and b64 to un-\n -- but we could
67 // use \\n ?
68 String type = value.getClass().getCanonicalName();
69 type = type.substring(0, type.length() - 2); // remove the []
70
71 write(out, type);
72 write(out, "\n");
73 try {
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)) {
78 try {
79 // TODO: use ZIP: if not?
80 new Exporter(out).append(item);
81 } catch (NotSerializableException e) {
82 throw new UnknownFormatConversionException(e
83 .getMessage());
84 }
85 }
86 write(out, "\n");
87 }
88 } catch (ArrayIndexOutOfBoundsException e) {
89 // Done.
90 }
91 }
92
93 @Override
94 protected Object fromStream(InputStream in) throws IOException {
95 NextableInputStream stream = new NextableInputStream(in,
96 new NextableInputStreamStep('\n'));
97
98 try {
99 List<Object> list = new ArrayList<Object>();
100 stream.next();
101 String type = IOUtils.readSmallStream(stream);
102
103 while (stream.next()) {
104 Object value = new Importer().read(stream).getValue();
105 list.add(value);
106 }
107
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));
112 }
113
114 return array;
115 } catch (Exception e) {
116 if (e instanceof IOException) {
117 throw (IOException) e;
118 }
119 throw new IOException(e.getMessage());
120 }
121 }
122
123 @Override
124 protected String getType() {
125 return "[]";
126 }
127 });
128
129 // URL:
130 customTypes.put("java.net.URL", new CustomSerializer() {
131
132 @Override
133 protected void toStream(OutputStream out, Object value)
134 throws IOException {
135 String val = "";
136 if (value != null) {
137 val = ((URL) value).toString();
138 }
139
140 out.write(val.getBytes("UTF-8"));
141 }
142
143 @Override
144 protected Object fromStream(InputStream in) throws IOException {
145 String val = IOUtils.readSmallStream(in);
146 if (!val.isEmpty()) {
147 return new URL(val);
148 }
149
150 return null;
151 }
152
153 @Override
154 protected String getType() {
155 return "java.net.URL";
156 }
157 });
158
159 // Images (this is currently the only supported image type by default)
160 customTypes.put("be.nikiroo.utils.Image", new CustomSerializer() {
161 @Override
162 protected void toStream(OutputStream out, Object value)
163 throws IOException {
164 Image img = (Image) value;
165 OutputStream encoded = StringUtils.base64(out, false, false);
166 try {
167 InputStream in = img.newInputStream();
168 try {
169 IOUtils.write(in, encoded);
170 } finally {
171 in.close();
172 }
173 } finally {
174 encoded.close();
175 }
176 }
177
178 @Override
179 protected String getType() {
180 return "be.nikiroo.utils.Image";
181 }
182
183 @Override
184 protected Object fromStream(InputStream in) throws IOException {
185 try {
186 return new Image(in);
187 } catch (IOException e) {
188 throw new UnknownFormatConversionException(e.getMessage());
189 }
190 }
191 });
192 }
193
194 /**
195 * Create an empty object of the given type.
196 *
197 * @param type
198 * the object type (its class name)
199 *
200 * @return the new object
201 *
202 * @throws ClassNotFoundException
203 * if the class cannot be found
204 * @throws NoSuchMethodException
205 * if the given class is not compatible with this code
206 */
207 public static Object createObject(String type)
208 throws ClassNotFoundException, NoSuchMethodException {
209
210 String desc = null;
211 try {
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);
222 args.add(parent);
223 classes.add(parent.getClass());
224
225 if (!parentName.contains("$")) {
226 break;
227 }
228 }
229
230 // Better error description in case there is no empty
231 // constructor:
232 desc = "";
233 String end = "";
234 for (Class<?> parent = clazz; parent != null
235 && !parent.equals(Object.class); parent = parent
236 .getSuperclass()) {
237 if (!desc.isEmpty()) {
238 desc += " [:";
239 end += "]";
240 }
241 desc += parent;
242 }
243 desc += end;
244 //
245
246 try {
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);
255 args.clear();
256 args.add(firstParent);
257 }
258 desc = null;
259 } else {
260 ctor = clazz.getDeclaredConstructor();
261 }
262
263 ctor.setAccessible(true);
264 return ctor.newInstance(args.toArray());
265 } catch (ClassNotFoundException e) {
266 throw e;
267 } catch (NoSuchMethodException e) {
268 if (desc != null) {
269 throw new NoSuchMethodException("Empty constructor not found: "
270 + desc);
271 }
272 throw e;
273 } catch (Exception e) {
274 throw new NoSuchMethodException("Cannot instantiate: " + type);
275 }
276 }
277
278 /**
279 * Insert a custom serialiser that will take precedence over the default one
280 * or the target class.
281 *
282 * @param serializer
283 * the custom serialiser
284 */
285 static public void addCustomSerializer(CustomSerializer serializer) {
286 customTypes.put(serializer.getType(), serializer);
287 }
288
289 /**
290 * Serialise the given object into this {@link OutputStream}.
291 * <p>
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).
295 *
296 * @param out
297 * the output {@link OutputStream} to serialise to
298 * @param o
299 * the object to serialise
300 * @param map
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)
304 *
305 * @throws NotSerializableException
306 * if the object cannot be serialised (in this case, the
307 * {@link StringBuilder} can contain bad, most probably not
308 * importable data)
309 * @throws IOException
310 * in case of I/O errors
311 */
312 static void append(OutputStream out, Object o, Map<Integer, Object> map)
313 throws NotSerializableException, IOException {
314
315 Field[] fields = new Field[] {};
316 String type = "";
317 String id = "NULL";
318
319 if (o != null) {
320 int hash = System.identityHashCode(o);
321 fields = o.getClass().getDeclaredFields();
322 type = o.getClass().getCanonicalName();
323 if (type == null) {
324 // Anonymous inner classes support
325 type = o.getClass().getName();
326 }
327 id = Integer.toString(hash);
328 if (map.containsKey(hash)) {
329 fields = new Field[] {};
330 } else {
331 map.put(hash, o);
332 }
333 }
334
335 write(out, "{\nREF ");
336 write(out, type);
337 write(out, "@");
338 write(out, id);
339 write(out, ":");
340
341 if (!encode(out, o)) { // check if direct value
342 try {
343 for (Field field : fields) {
344 field.setAccessible(true);
345
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
352 continue;
353 }
354
355 write(out, "\n");
356 write(out, field.getName());
357 write(out, ":");
358
359 Object value = field.get(o);
360
361 if (!encode(out, value)) {
362 write(out, "\n");
363 append(out, value, map);
364 }
365 }
366 } catch (IllegalArgumentException e) {
367 e.printStackTrace(); // should not happen (see
368 // setAccessible)
369 } catch (IllegalAccessException e) {
370 e.printStackTrace(); // should not happen (see
371 // setAccessible)
372 }
373 }
374 write(out, "\n}");
375 }
376
377 /**
378 * Encode the object into the given {@link OutputStream} if possible and if
379 * supported.
380 * <p>
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>.
384 * <p>
385 * For compound objects, you should use {@link Exporter}.
386 *
387 * @param out
388 * the {@link OutputStream} to append to
389 * @param value
390 * the object to encode (can be NULL, which will be encoded)
391 *
392 * @return TRUE if success, FALSE if not (the content of the
393 * {@link OutputStream} won't be changed in case of failure)
394 *
395 * @throws IOException
396 * in case of I/O error
397 */
398 static boolean encode(OutputStream out, Object value) throws IOException {
399 if (value == null) {
400 write(out, "NULL");
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())//
407 .encode(out, value);
408 } else if (value instanceof String) {
409 encodeString(out, (String) value);
410 } else if (value instanceof Boolean) {
411 write(out, value);
412 } else if (value instanceof Byte) {
413 write(out, value);
414 write(out, "b");
415 } else if (value instanceof Character) {
416 encodeString(out, "" + value);
417 write(out, "c");
418 } else if (value instanceof Short) {
419 write(out, value);
420 write(out, "s");
421 } else if (value instanceof Integer) {
422 write(out, value);
423 } else if (value instanceof Long) {
424 write(out, value);
425 write(out, "L");
426 } else if (value instanceof Float) {
427 write(out, value);
428 write(out, "F");
429 } else if (value instanceof Double) {
430 write(out, value);
431 write(out, "d");
432 } else if (value instanceof Enum) {
433 String type = value.getClass().getCanonicalName();
434 write(out, type);
435 write(out, ".");
436 write(out, ((Enum<?>) value).name());
437 write(out, ";");
438 } else {
439 return false;
440 }
441
442 return true;
443 }
444
445 /**
446 * Decode the data into an equivalent supported source object.
447 * <p>
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>.
451 * <p>
452 * For compound objects, you should use {@link Importer}.
453 *
454 * @param encodedValue
455 * the encoded data, cannot be NULL
456 *
457 * @return the object (can be NULL for NULL encoded values)
458 *
459 * @throws IOException
460 * if the content cannot be converted
461 */
462 static Object decode(String encodedValue) throws IOException {
463 try {
464 String cut = "";
465 if (encodedValue.length() > 1) {
466 cut = encodedValue.substring(0, encodedValue.length() - 1);
467 }
468
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"));
476 try {
477 return customTypes.get(type).decode(streamEncodedValue);
478 } finally {
479 streamEncodedValue.close();
480 }
481 }
482 throw new IOException("Unknown custom type: " + type);
483 } else if (encodedValue.equals("NULL")
484 || encodedValue.equals("null")) {
485 return null;
486 } else if (encodedValue.endsWith("\"")) {
487 return decodeString(encodedValue);
488 } else if (encodedValue.equals("true")) {
489 return true;
490 } else if (encodedValue.equals("false")) {
491 return 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);
506 } else {
507 return Integer.parseInt(encodedValue);
508 }
509 } catch (Exception e) {
510 if (e instanceof IOException) {
511 throw (IOException) e;
512 }
513 throw new IOException(e.getMessage());
514 }
515 }
516
517 /**
518 * Write the given {@link String} into the given {@link OutputStream} in
519 * UTF-8.
520 *
521 * @param out
522 * the {@link OutputStream}
523 * @param data
524 * the data to write, cannot be NULL
525 *
526 * @throws IOException
527 * in case of I/O error
528 */
529 static void write(OutputStream out, Object data) throws IOException {
530 try {
531 out.write(data.toString().getBytes("UTF-8"));
532 } catch (UnsupportedEncodingException e) {
533 // A conforming JVM is required to support UTF-8
534 e.printStackTrace();
535 }
536 }
537
538 /**
539 * Return the corresponding class or throw an {@link Exception} if it
540 * cannot.
541 *
542 * @param type
543 * the class name to look for
544 *
545 * @return the class (will never be NULL)
546 *
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)
552 */
553 static private Class<?> getClass(String type)
554 throws ClassNotFoundException, NoSuchMethodException {
555 Class<?> clazz = null;
556 try {
557 clazz = Class.forName(type);
558 } catch (ClassNotFoundException e) {
559 int pos = type.length();
560 pos = type.lastIndexOf(".", pos);
561 if (pos >= 0) {
562 String parentType = type.substring(0, pos);
563 String nestedType = type.substring(pos + 1);
564 Class<?> javaParent = null;
565 try {
566 javaParent = getClass(parentType);
567 parentType = javaParent.getName();
568 clazz = Class.forName(parentType + "$" + nestedType);
569 } catch (Exception ee) {
570 }
571
572 if (javaParent == null) {
573 throw new NoSuchMethodException(
574 "Class not found: "
575 + type
576 + " (the enclosing class cannot be created: maybe it doesn't have an empty constructor?)");
577 }
578 }
579 }
580
581 if (clazz == null) {
582 throw new ClassNotFoundException("Class not found: " + type);
583 }
584
585 return clazz;
586 }
587
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);
594
595 try {
596 return Enum.valueOf((Class<Enum>) getClass(type), name);
597 } catch (Exception e) {
598 throw new UnknownFormatConversionException("Unknown enum: <" + type
599 + "> " + name);
600 }
601 }
602
603 // aa bb -> "aa\tbb"
604 static void encodeString(OutputStream out, String raw) throws IOException {
605 out.write('\"');
606 // TODO !! utf-8 required
607 for (char car : raw.toCharArray()) {
608 encodeString(out, car);
609 }
610 out.write('\"');
611 }
612
613 // aa bb -> "aa\tbb"
614 static void encodeString(OutputStream out, InputStream raw)
615 throws IOException {
616 out.write('\"');
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]);
622 }
623 }
624 out.write('\"');
625 }
626
627 // for encode string, NOT to encode a char by itself!
628 static void encodeString(OutputStream out, char raw) throws IOException {
629 switch (raw) {
630 case '\\':
631 out.write('\\');
632 out.write('\\');
633 break;
634 case '\r':
635 out.write('\\');
636 out.write('r');
637 break;
638 case '\n':
639 out.write('\\');
640 out.write('n');
641 break;
642 case '"':
643 out.write('\\');
644 out.write('\"');
645 break;
646 default:
647 out.write(raw);
648 break;
649 }
650 }
651
652 // "aa\tbb" -> aa bb
653 static String decodeString(String escaped) {
654 StringBuilder builder = new StringBuilder();
655
656 boolean escaping = false;
657 for (char car : escaped.toCharArray()) {
658 if (!escaping) {
659 if (car == '\\') {
660 escaping = true;
661 } else {
662 builder.append(car);
663 }
664 } else {
665 switch (car) {
666 case '\\':
667 builder.append('\\');
668 break;
669 case 'r':
670 builder.append('\r');
671 break;
672 case 'n':
673 builder.append('\n');
674 break;
675 case '"':
676 builder.append('"');
677 break;
678 }
679 escaping = false;
680 }
681 }
682
683 return builder.substring(1, builder.length() - 1);
684 }
685 }