Version 3.1.1: fixes: ServerBridge, Import/Export
[nikiroo-utils.git] / src / be / nikiroo / utils / serial / Importer.java
1 package be.nikiroo.utils.serial;
2
3 import java.io.IOException;
4 import java.lang.reflect.Field;
5 import java.util.HashMap;
6 import java.util.Map;
7 import java.util.Scanner;
8
9 import be.nikiroo.utils.StringUtils;
10
11 /**
12 * A simple class that can accept the output of {@link Exporter} to recreate
13 * objects as they were sent to said exporter.
14 * <p>
15 * This class requires the objects (and their potential enclosing objects) to
16 * have an empty constructor, and does not support inner classes (it does
17 * support nested classes, though).
18 *
19 * @author niki
20 */
21 public class Importer {
22 private Boolean link;
23 private Object me;
24 private Importer child;
25 private Map<String, Object> map;
26
27 private String currentFieldName;
28
29 /**
30 * Create a new {@link Importer}.
31 */
32 public Importer() {
33 map = new HashMap<String, Object>();
34 map.put("NULL", null);
35 }
36
37 private Importer(Map<String, Object> map) {
38 this.map = map;
39 }
40
41 /**
42 * Read some data into this {@link Importer}: it can be the full serialised
43 * content, or a number of lines of it (any given line <b>MUST</b> be
44 * complete though) and accumulate it with the already present data.
45 *
46 * @param data
47 * the data to parse
48 *
49 * @return itself so it can be chained
50 *
51 * @throws NoSuchFieldException
52 * if the serialised data contains information about a field
53 * which does actually not exist in the class we know of
54 * @throws NoSuchMethodException
55 * if a class described in the serialised data cannot be created
56 * because it is not compatible with this code
57 * @throws ClassNotFoundException
58 * if a class described in the serialised data cannot be found
59 * @throws IOException
60 * if the content cannot be read (for instance, corrupt data)
61 */
62 public Importer read(String data) throws NoSuchFieldException,
63 NoSuchMethodException, ClassNotFoundException, IOException {
64
65 Scanner scan = new Scanner(data);
66 try {
67 scan.useDelimiter("\n");
68 while (scan.hasNext()) {
69 String line = scan.next();
70
71 if (line.startsWith("ZIP:")) {
72 try {
73 line = StringUtils.unzip64(line.substring("ZIP:"
74 .length()));
75 } catch (IOException e) {
76 throw new IOException(
77 "Internal error when decoding ZIP content: input may be corrupt");
78 }
79 read(line);
80 } else {
81 processLine(line);
82 }
83 }
84 } finally {
85 scan.close();
86 }
87
88 return this;
89 }
90
91 /**
92 * Read a single (whole) line of serialised data into this {@link Importer}
93 * and accumulate it with the already present data.
94 *
95 * @param line
96 * the line to parse
97 *
98 * @return TRUE if we are just done with one object or sub-object
99 *
100 * @throws NoSuchFieldException
101 * if the serialised data contains information about a field
102 * which does actually not exist in the class we know of
103 * @throws NoSuchMethodException
104 * if a class described in the serialised data cannot be created
105 * because it is not compatible with this code
106 * @throws ClassNotFoundException
107 * if a class described in the serialised data cannot be found
108 * @throws IOException
109 * if the content cannot be read (for instance, corrupt data)
110 */
111 private boolean processLine(String line) throws NoSuchFieldException,
112 NoSuchMethodException, ClassNotFoundException, IOException {
113 // Defer to latest child if any
114 if (child != null) {
115 if (child.processLine(line)) {
116 if (currentFieldName != null) {
117 setField(currentFieldName, child.getValue());
118 currentFieldName = null;
119 }
120 child = null;
121 }
122
123 return false;
124 }
125
126 if (line.equals("{")) { // START: new child if needed
127 if (link != null) {
128 child = new Importer(map);
129 }
130 } else if (line.equals("}")) { // STOP: report self to parent
131 return true;
132 } else if (line.startsWith("REF ")) { // REF: create/link self
133 String[] tab = line.substring("REF ".length()).split("@");
134 String type = tab[0];
135 tab = tab[1].split(":");
136 String ref = tab[0];
137
138 link = map.containsKey(ref);
139 if (link) {
140 me = map.get(ref);
141 } else {
142 if (line.endsWith(":")) {
143 // construct
144 me = SerialUtils.createObject(type);
145 } else {
146 // direct value
147 int pos = line.indexOf(":");
148 String encodedValue = line.substring(pos + 1);
149 me = SerialUtils.decode(encodedValue);
150 }
151 map.put(ref, me);
152 }
153 } else { // FIELD: new field *or* direct simple value
154 if (line.endsWith(":")) {
155 // field value is compound
156 currentFieldName = line.substring(0, line.length() - 1);
157 } else if (line.startsWith(":") || !line.contains(":")) {
158 // not a field value but a direct value
159 me = SerialUtils.decode(line);
160 } else {
161 // field value is direct
162 int pos = line.indexOf(":");
163 String fieldName = line.substring(0, pos);
164 String encodedValue = line.substring(pos + 1);
165 Object value = null;
166 value = SerialUtils.decode(encodedValue);
167
168 // To support simple types directly:
169 if (me == null) {
170 me = value;
171 } else {
172 setField(fieldName, value);
173 }
174 }
175 }
176
177 return false;
178 }
179
180 private void setField(String name, Object value)
181 throws NoSuchFieldException {
182
183 try {
184 Field field = me.getClass().getDeclaredField(name);
185
186 field.setAccessible(true);
187 field.set(me, value);
188 } catch (NoSuchFieldException e) {
189 throw new NoSuchFieldException(String.format(
190 "Field \"%s\" was not found in object of type \"%s\".",
191 name, me.getClass().getCanonicalName()));
192 } catch (Exception e) {
193 throw new NoSuchFieldException(String.format(
194 "Internal error when setting \"%s.%s\": %s", me.getClass()
195 .getCanonicalName(), name, e.getMessage()));
196 }
197 }
198
199 /**
200 * Return the current deserialised value.
201 *
202 * @return the current value
203 */
204 public Object getValue() {
205 return me;
206 }
207 }