3a6e025739c9faf0893fa2a65f07970012ae8f0e
[nikiroo-utils.git] / src / be / nikiroo / utils / serial / Exporter.java
1 package be.nikiroo.utils.serial;
2
3 import java.io.NotSerializableException;
4 import java.util.HashMap;
5 import java.util.Map;
6
7 import be.nikiroo.utils.StringUtils;
8
9 /**
10 * A simple class to serialise objects to {@link String}.
11 * <p>
12 * This class does not support inner classes (it does support nested classes,
13 * though).
14 *
15 * @author niki
16 */
17 public class Exporter {
18 private Map<Integer, Object> map;
19 private StringBuilder builder;
20
21 /**
22 * Create a new {@link Exporter}.
23 */
24 public Exporter() {
25 map = new HashMap<Integer, Object>();
26 builder = new StringBuilder();
27 }
28
29 /**
30 * Serialise the given object and add it to the list.
31 * <p>
32 * <b>Important: </b>If the operation fails (with a
33 * {@link NotSerializableException}), the {@link Exporter} will be corrupted
34 * (will contain bad, most probably not importable data).
35 *
36 * @param o
37 * the object to serialise
38 * @return this (for easier appending of multiple values)
39 *
40 * @throws NotSerializableException
41 * if the object cannot be serialised (in this case, the
42 * {@link Exporter} can contain bad, most probably not
43 * importable data)
44 */
45 public Exporter append(Object o) throws NotSerializableException {
46 SerialUtils.append(builder, o, map);
47 return this;
48 }
49
50 /**
51 * Clear the current content.
52 */
53 public void clear() {
54 builder.setLength(0);
55 map.clear();
56 }
57
58 /**
59 * The exported items in a serialised form.
60 *
61 * @param zip
62 * TRUE to have zipped (and BASE64-coded) content, FALSE to have
63 * raw content, NULL to let the system decide
64 *
65 * @return the items currently in this {@link Exporter}
66 */
67 public String toString(Boolean zip) {
68 if (zip == null && builder.length() > 128) {
69 zip = false;
70 }
71
72 if (zip == null || zip) {
73 String zipped = "ZIP:" + StringUtils.zip64(builder.toString());
74
75 if (zip != null || builder.length() < zipped.length())
76 return zipped;
77 }
78
79 return builder.toString();
80 }
81
82 /**
83 * The exported items in a serialised form (possibly zipped).
84 *
85 * @return the items currently in this {@link Exporter}
86 */
87 @Override
88 public String toString() {
89 return toString(null);
90 }
91 }