serial/Exporter: Better zip/noZip choice
[nikiroo-utils.git] / src / be / nikiroo / utils / serial / Exporter.java
CommitLineData
db31c358
NR
1package be.nikiroo.utils.serial;
2
3import java.io.NotSerializableException;
4import java.util.HashMap;
5import java.util.Map;
6
7import 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 */
17public class Exporter {
18 private Map<Integer, Object> map;
19 private StringBuilder builder;
20
f157aed8
NR
21 /**
22 * Create a new {@link Exporter}.
23 */
db31c358
NR
24 public Exporter() {
25 map = new HashMap<Integer, Object>();
26 builder = new StringBuilder();
27 }
28
f157aed8
NR
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 */
db31c358
NR
45 public Exporter append(Object o) throws NotSerializableException {
46 SerialUtils.append(builder, o, map);
47 return this;
48 }
49
f157aed8
NR
50 /**
51 * Clear the current content.
52 */
db31c358
NR
53 public void clear() {
54 builder.setLength(0);
55 map.clear();
56 }
57
f157aed8
NR
58 /**
59 * The exported items in a serialised form.
60 *
61 * @param zip
8a5c5903
NR
62 * TRUE to have zipped (and BASE64-coded) content, FALSE to have
63 * raw content, NULL to let the system decide
f157aed8
NR
64 *
65 * @return the items currently in this {@link Exporter}
66 */
db31c358 67 public String toString(Boolean zip) {
8a5c5903
NR
68 if (zip == null && builder.length() > 128) {
69 zip = false;
db31c358
NR
70 }
71
8a5c5903
NR
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;
db31c358 77 }
cd0c27d2
NR
78
79 return builder.toString();
db31c358
NR
80 }
81
82 /**
f157aed8 83 * The exported items in a serialised form (possibly zipped).
db31c358 84 *
f157aed8 85 * @return the items currently in this {@link Exporter}
db31c358
NR
86 */
87 @Override
88 public String toString() {
89 return toString(null);
90 }
91}