Commit | Line | Data |
---|---|---|
db31c358 NR |
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 | ||
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 | |
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 | */ | |
db31c358 NR |
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()); | |
db31c358 | 74 | } |
cd0c27d2 NR |
75 | |
76 | return builder.toString(); | |
db31c358 NR |
77 | } |
78 | ||
79 | /** | |
f157aed8 | 80 | * The exported items in a serialised form (possibly zipped). |
db31c358 | 81 | * |
f157aed8 | 82 | * @return the items currently in this {@link Exporter} |
db31c358 NR |
83 | */ |
84 | @Override | |
85 | public String toString() { | |
86 | return toString(null); | |
87 | } | |
88 | } |