fix changelog headers
[fanfix.git] / 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 content, FALSE to have raw content, NULL
63 * 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) {
69 zip = builder.length() > 128;
70 }
71
72 if (zip) {
73 return "ZIP:" + StringUtils.zip64(builder.toString());
74 }
75
76 return builder.toString();
77 }
78
79 /**
80 * The exported items in a serialised form (possibly zipped).
81 *
82 * @return the items currently in this {@link Exporter}
83 */
84 @Override
85 public String toString() {
86 return toString(null);
87 }
88 }