709c5903f6b4e9e9f62515bc601432e6aad200b7
[nikiroo-utils.git] / src / be / nikiroo / utils / serial / Exporter.java
1 package be.nikiroo.utils.serial;
2
3 import java.io.IOException;
4 import java.io.NotSerializableException;
5 import java.io.OutputStream;
6 import java.util.HashMap;
7 import java.util.Map;
8
9 import be.nikiroo.utils.StringUtils;
10
11 /**
12 * A simple class to serialise objects to {@link String}.
13 * <p>
14 * This class does not support inner classes (it does support nested classes,
15 * though).
16 *
17 * @author niki
18 */
19 public class Exporter {
20 private Map<Integer, Object> map;
21 private OutputStream out;
22
23 /**
24 * Create a new {@link Exporter}.
25 */
26 public Exporter(OutputStream out) {
27 if (out == null) {
28 throw new NullPointerException(
29 "Cannot create an be.nikiroo.utils.serials.Exporter that will export to NULL");
30 }
31
32 this.out = out;
33 map = new HashMap<Integer, Object>();
34 }
35
36 /**
37 * Serialise the given object and add it to the list.
38 * <p>
39 * <b>Important: </b>If the operation fails (with a
40 * {@link NotSerializableException}), the {@link Exporter} will be corrupted
41 * (will contain bad, most probably not importable data).
42 *
43 * @param o
44 * the object to serialise
45 * @return this (for easier appending of multiple values)
46 *
47 * @throws NotSerializableException
48 * if the object cannot be serialised (in this case, the
49 * {@link Exporter} can contain bad, most probably not
50 * importable data)
51 * @throws IOException
52 * in case of I/O error
53 */
54 public Exporter append(Object o) throws NotSerializableException,
55 IOException {
56 SerialUtils.append(out, o, map);
57 return this;
58 }
59
60 /**
61 * Append the exported items in a serialised form into the given
62 * {@link OutputStream}.
63 *
64 * @param out
65 * the {@link OutputStream}
66 * @param b64
67 * TRUE to have BASE64-coded content, FALSE to have raw content,
68 * NULL to let the system decide
69 * @param zip
70 * TRUE to zip the BASE64 output if the output is indeed in
71 * BASE64 format, FALSE not to
72 */
73 public void appendTo(OutputStream out, Boolean b64, boolean zip) {
74 if (b64 == null && out.length() < 128) {
75 b64 = false;
76 }
77
78 if (b64 == null || b64) {
79 try {
80 String zipped = StringUtils.base64(out.toString(), zip);
81 if (b64 != null || zipped.length() < out.length() - 4) {
82 SerialUtils.write(out, zip ? "ZIP:" : "B64:");
83 SerialUtils.write(out, zipped);
84 return;
85 }
86 } catch (IOException e) {
87 throw new RuntimeException(
88 "Base64 conversion of data failed, maybe not enough memory?",
89 e);
90 }
91 }
92
93 out.append(out);
94 }
95 }