source: trunk/org/expeditee/io/KMSWriter.java@ 4

Last change on this file since 4 was 4, checked in by davidb, 16 years ago

Starting source code to Expeditee

File size: 14.4 KB
Line 
1package org.expeditee.io;
2
3import java.io.File;
4import java.io.FileWriter;
5import java.io.IOException;
6import java.lang.reflect.InvocationTargetException;
7import java.lang.reflect.Method;
8import java.util.Iterator;
9import java.util.LinkedHashMap;
10import java.util.LinkedList;
11import java.util.List;
12
13import org.expeditee.gui.Frame;
14import org.expeditee.items.Constraint;
15import org.expeditee.items.Dot;
16import org.expeditee.items.Item;
17import org.expeditee.items.Line;
18import org.expeditee.items.Picture;
19import org.expeditee.items.Text;
20import org.expeditee.stats.SessionStats;
21
22/**
23 * Writes a Frame out to a KMS format file.
24 *
25 * @author jdm18
26 *
27 */
28public class KMSWriter extends DefaultFrameWriter {
29
30 private ProxyWriter _writer = null;
31
32 private StringBuilder _stringWriter = null;
33
34 // keep track of methods that are put on the same line
35 private static LinkedHashMap<String, Method> _ItemTags = null;
36
37 private static LinkedHashMap<String, Method> _FrameTags = null;
38
39 private static LinkedHashMap<String, Method> _BodyTags = null;
40
41 private static final char TERMINATOR = 'Z';
42
43 private static final char DELIMITER = '+';
44
45 public KMSWriter() {
46 if (_ItemTags != null && _FrameTags != null)
47 return;
48
49 _ItemTags = new LinkedHashMap<String, Method>();
50 _FrameTags = new LinkedHashMap<String, Method>();
51 _BodyTags = new LinkedHashMap<String, Method>();
52
53 Class[] param = {};
54
55 try {
56 _FrameTags.put("A", Frame.class.getMethod("getFrameName", param));
57 _FrameTags.put("V", Frame.class.getMethod("getVersion", param));
58 _FrameTags.put("v", Frame.class
59 .getMethod("getFormatVersion", param));
60 _FrameTags.put("p", Frame.class.getMethod("getProtection", param));
61 _FrameTags.put("U", Frame.class.getMethod("getOwner", param));
62 _FrameTags.put("D", Frame.class.getMethod("getDateCreated", param));
63 _FrameTags.put("M", Frame.class.getMethod("getLastModifyUser",
64 param));
65 _FrameTags.put("d", Frame.class.getMethod("getLastModifyDate",
66 param));
67 _FrameTags.put("F", Frame.class.getMethod("getFrozenDate", param));
68
69 _BodyTags.put("O", Frame.class.getMethod("getForegroundColor",
70 param));
71 _BodyTags.put("B", Frame.class.getMethod("getBackgroundColor",
72 param));
73 _BodyTags
74 .put("v", Frame.class.getMethod("getFormatVersion", param));
75
76 _ItemTags.put("S", Item.class.getMethod("getID", param));
77 _ItemTags.put("s", Item.class.getMethod("getDateCreated", param));
78 _ItemTags.put("d", Item.class.getMethod("getColor", param));
79 _ItemTags.put("G", Item.class
80 .getMethod("getBackgroundColor", param));
81 _ItemTags.put("P", Item.class.getMethod("getPosition", param));
82 _ItemTags.put("F", Item.class.getMethod("getLink", param));
83 _ItemTags.put("X", Item.class.getMethod("getAction", param));
84 _ItemTags.put("x", Item.class.getMethod("getActionMark", param));
85 _ItemTags.put("U", Item.class.getMethod("getActionCursorEnter",
86 param));
87 _ItemTags.put("V", Item.class.getMethod("getActionCursorLeave",
88 param));
89 _ItemTags.put("W", Item.class.getMethod("getActionEnterFrame",
90 param));
91 _ItemTags.put("Y", Item.class.getMethod("getActionLeaveFrame",
92 param));
93 _ItemTags.put("D", Item.class.getMethod("getData", param));
94 _ItemTags.put("u", Item.class.getMethod("getHighlight", param));
95 _ItemTags.put("e", Item.class.getMethod("getFillColor", param));
96 _ItemTags.put("i", Item.class.getMethod("getFillPattern", param));
97 _ItemTags.put("o", Item.class.getMethod("getOwner", param));
98 _ItemTags.put("n", Item.class.getMethod("getLinkMark", param));
99 _ItemTags.put("q", Item.class.getMethod("getLinkFrameset", param));
100 _ItemTags.put("y", Item.class.getMethod("getLinkTemplate", param));
101 _ItemTags.put("g", Item.class.getMethod("getLinePattern", param));
102
103 _ItemTags.put("j", Item.class.getMethod("getArrow", param));
104
105 _ItemTags.put("f", Text.class.getMethod("getFont", param));
106 _ItemTags.put("t", Text.class.getMethod("getSpacing", param));
107 _ItemTags.put("T", Text.class.getMethod("getText", param));
108
109 _ItemTags.put("a", Text.class.getMethod("getWordSpacing", param));
110 _ItemTags.put("b", Text.class.getMethod("getLetterSpacing", param));
111 _ItemTags
112 .put("m", Text.class.getMethod("getInitialSpacing", param));
113 _ItemTags.put("w", Text.class.getMethod("getWidth", param));
114 _ItemTags.put("k", Text.class.getMethod("getJustification", param));
115
116 _ItemTags.put("h", Dot.class.getMethod("getThickness", param));
117 _ItemTags.put("l", Dot.class.getMethod("getLineIDs", param));
118 _ItemTags.put("c", Dot.class.getMethod("getConstraintIDs", param));
119
120 // Lines and constraints are created differently
121 /*
122 * _LineTags.put("L", Line.class.getMethod("getID", param));
123 * _LineTags.put("s", Line.class.getMethod("getLineEnds", param));
124 * _LineTags.put("g", Line.class.getMethod("getLinePattern",
125 * param));
126 *
127 * _ConstraintTags.put("C", Constraint.class.getMethod("getID",
128 * (Class[]) null)); _ConstraintTags.put("s",
129 * Constraint.class.getMethod("getLineEnds", (Class[]) null));
130 */
131 } catch (SecurityException e) {
132 // TODO Auto-generated catch block
133 e.printStackTrace();
134 } catch (NoSuchMethodException e) {
135 // TODO Auto-generated catch block
136 e.printStackTrace();
137 }
138 }
139
140 public void initialise(Frame start) throws IOException {
141 String name = start.getFramesetName().toLowerCase();
142
143 if (_filename == null)
144 _filename = start.path + name + File.separator + name + "."
145 + start.getFrameNumber();
146
147 _stringWriter = new StringBuilder();
148 if (_filename.toLowerCase().equals("clipboard")) {
149 _writer = new ProxyWriter(true);
150 _filename = "Clipboard";
151 } else
152 _writer = new ProxyWriter(new FileWriter(_filename));
153
154 // _writer = new BufferedWriter(new FileWriter(filepath.toLowerCase() +
155 // filename.toLowerCase()));
156 }
157
158 /**
159 * Writes the given Frame (and all items it contains) to a KMS file. Note:
160 * File path and location must be set before calling this or it will do
161 * nothing.
162 *
163 * @param frame
164 * The Frame to write out to the file.
165 * @throws IOException
166 * Any exceptions occured by the BufferedWriter.
167 */
168 public void outputFrame(Frame frame) throws IOException {
169 if (_writer == null)
170 return;
171
172 writeHeader(frame);
173 // writeBody(frame);
174
175 // write out each Item in the Frame.
176 List<Item> items = frame.getItems();
177
178 // do not write items with ID -1, also skip any lines
179 for (Item i : items) {
180 if (i.getID() >= 0 && !(i instanceof Line))
181 writeItem(i);
182 }
183
184 // write any lines or constraints
185 writeLineData();
186 writeConstraintData();
187
188 return;
189 }
190
191 private void writeHeader(Frame toWrite) throws IOException {
192 Iterator<String> it = _FrameTags.keySet().iterator();
193 Object[] param = {};
194
195 while (it.hasNext()) {
196 String tag = it.next();
197 try {
198 Object o = _FrameTags.get(tag).invoke(toWrite, param);
199 o = Conversion.ConvertToKMS(_FrameTags.get(tag), o);
200 if (o != null) {
201 writeLine(tag, (String) o);
202 }
203 } catch (IllegalArgumentException e) {
204 // TODO Auto-generated catch block
205 e.printStackTrace();
206 } catch (IllegalAccessException e) {
207 // TODO Auto-generated catch block
208 e.printStackTrace();
209 } catch (InvocationTargetException e) {
210 // TODO Auto-generated catch block
211 e.printStackTrace();
212 }
213 }
214
215 writeTerminator();
216 it = _BodyTags.keySet().iterator();
217
218 while (it.hasNext()) {
219 String tag = it.next();
220 try {
221 Object o = _BodyTags.get(tag).invoke(toWrite, param);
222 o = Conversion.ConvertToKMS(_BodyTags.get(tag), o);
223 if (o != null) {
224 writeLine(tag, (String) o);
225 }
226 } catch (IllegalArgumentException e) {
227 // TODO Auto-generated catch block
228 e.printStackTrace();
229 } catch (IllegalAccessException e) {
230 // TODO Auto-generated catch block
231 e.printStackTrace();
232 } catch (InvocationTargetException e) {
233 // TODO Auto-generated catch block
234 e.printStackTrace();
235 }
236 }
237 }
238
239 private void writeLine(String tag, String line) throws IOException {
240 writeLine(DELIMITER + tag + DELIMITER + " " + line);
241 }
242
243 private void writeTerminator() throws IOException {
244 writeLine("" + DELIMITER + TERMINATOR + DELIMITER);
245 }
246
247 // writes the given line out to the file
248 private void writeLine(String line) throws IOException {
249 // do not write empty lines
250 if (line == null)
251 return;
252
253 String toWrite = line + "\n";
254
255 _writer.write(toWrite);
256 _stringWriter.append(toWrite);
257 }
258
259 // writes the given Item out to the file
260 public void writeItem(Item item) throws IOException {
261 if (_writer == null)
262 return;
263
264 writeLine("");
265 // Pictures are saved as the corresponding text items that created them
266 if (item instanceof Picture)
267 item = ((Picture) item).getText();
268
269 /*
270 * if(item instanceof Text) writeClass(item); else if(item instanceof
271 * Dot) writeDot((Dot) item);
272 */
273 if (item.getLines().size() > 0)
274 writePoint(item);
275 else if (!(item instanceof Line))
276 writeClass(item);
277 // lines are saved at the end of the file
278 /*
279 * else if (item instanceof Line) ;
280 */
281 else
282 System.out.println("Unknown Item: " + item.getID());
283 }
284
285 private List<Item> _points = new LinkedList<Item>();
286
287 // Writes out a Dot to the file
288 protected void writePoint(Item point) throws IOException {
289 _points.add(point);
290 writeClass(point);
291 }
292
293 // writes out all lines to the file
294 private void writeLineData() throws IOException {
295 List<Line> seen = new LinkedList<Line>();
296
297 // loop through all points stored
298 for (int i = 0; i < _points.size(); i++) {
299 List<Line> lines = _points.get(i).getLines();
300
301 // if this point is part of one or more lines
302 if (lines != null && lines.size() > 0) {
303 for (Line line : lines) {
304
305 // only output new lines that have not yet been output
306 if (!seen.contains(line)) {
307 writeLine("L", line.getID() + " " + line.getLineType());
308 writeLine("s", line.getLineEnds());
309
310 // add this line to the list of lines that have been
311 // seen
312 seen.add(line);
313 }
314
315 }
316 }
317 }
318 }
319
320 // writes out any constraints to the file
321 private void writeConstraintData() throws IOException {
322 // outputs any constraints the points have
323
324 // loop through all the points
325 while (_points.size() > 0) {
326 Item i = _points.get(0);
327
328 if (i instanceof Dot) {
329 Dot p = (Dot) i;
330
331 // if there are any constraints to write
332 if (p.getConstraints() != null) {
333 List<Constraint> constraints = p.getConstraints();
334
335 // do not write constraints that have already been
336 // written
337 for (Constraint c : constraints) {
338 if (_points.contains(c.getStart())
339 && _points.contains(c.getEnd())) {
340 writeLine("C", c.getID() + " "
341 + c.getConstraintType());
342 writeLine("s", c.getLineEnds());
343 }
344
345 }
346 }
347 }
348 // remove the point from the list
349 _points.remove(0);
350
351 }
352 }
353
354 @Override
355 protected String finaliseFrame() throws IOException {
356 writeLine("" + DELIMITER + TERMINATOR + DELIMITER);
357
358 writeLine(SessionStats.getFrameEventList());
359
360 _writer.flush();
361 _writer.close();
362 _writer = null;
363
364 return "Frame successfully written to " + _filename;
365 }
366
367 private void writeClass(Object toWrite) throws IOException {
368 Iterator<String> it = _ItemTags.keySet().iterator();
369 Object[] param = {};
370
371 while (it.hasNext()) {
372 String tag = it.next();
373 Method toRun = _ItemTags.get(tag);
374 Class declarer = toRun.getDeclaringClass();
375 if (declarer == toWrite.getClass()
376 || declarer == toWrite.getClass().getSuperclass()
377 || declarer == toWrite.getClass().getSuperclass()
378 .getSuperclass()) {
379 try {
380 Object o = toRun.invoke(toWrite, param);
381 o = Conversion.ConvertToKMS(toRun, o);
382 if (o != null) {
383 if (o instanceof List) {
384 for (Object line : (List) o)
385 writeLine(tag, (String) line);
386 } else
387 writeLine(tag, (String) o);
388 }
389 } catch (IllegalArgumentException e) {
390 // TODO Auto-generated catch block
391 e.printStackTrace();
392 } catch (IllegalAccessException e) {
393 // TODO Auto-generated catch block
394 e.printStackTrace();
395 } catch (InvocationTargetException e) {
396 // TODO Auto-generated catch block
397 e.printStackTrace();
398 }
399 }
400 }
401
402 /*
403 * Method[] methods = toWrite.getClass().getMethods(); ArrayList<String>
404 * meths = new ArrayList<String>();
405 *
406 * for(Method m : methods) meths.add(m.getName());
407 *
408 * String start = _Tags.get("DelimiterStart"); String end =
409 * _Tags.get("DelimiterEnd");
410 *
411 * Iterator<String> it = _Tags.keySet().iterator();
412 *
413 * String term = null; LinkedList<Method> seen = new LinkedList<Method>();
414 *
415 * while(it.hasNext()){ String name = it.next(); String cName =
416 * className;
417 *
418 * if(writeSuper && name.startsWith(superName)) cName = superName;
419 *
420 * if(name.startsWith(cName)){ String tag = start + _Tags.get(name) +
421 * end; String output = "";
422 *
423 * //check for other methods that go on this line LinkedList<String>
424 * shared = _SharedLine.get(name); LinkedList<String> runMethods = new
425 * LinkedList<String>();
426 *
427 * if(shared != null) runMethods.addAll(shared);
428 *
429 * name = name.substring((cName + ".").length());
430 * runMethods.addFirst(name);
431 *
432 * //loop through all methods and concat their output Iterator
433 * methodIterator = runMethods.iterator();
434 *
435 * while(methodIterator.hasNext()){ name = "get" +
436 * methodIterator.next();
437 *
438 * int ind = meths.indexOf(name);
439 *
440 * if(ind >= 0){ Method m = methods[ind];
441 *
442 * if(!seen.contains(m)){ try { if(m.getParameterTypes().length == 0){
443 * Object val = m.invoke(toWrite, (Object[]) null);
444 *
445 * if(val instanceof List){ int count = 0; for(Object o : (List) val){
446 * if(count == 0) output += " " +
447 * KMSConversion.ConvertToKMS(name.substring(3), o); else output += "\n" +
448 * tag + " " + KMSConversion.ConvertToKMS(name.substring(3), o);
449 *
450 * count++; } }else{ String res =
451 * KMSConversion.ConvertToKMS(name.substring(3), val);
452 *
453 * if(res != null) output += " " + res; } } } catch (Exception e) {
454 * Logger.Log(e); }
455 *
456 * seen.add(m); } }else if(name.equals("getTerminator")){ term = start +
457 * _Tags.get(cName + ".Terminator") + end; }else System.out.println("No
458 * method found: " + cName + "." + name); }
459 *
460 * if(output.length() > 0) writeLine(tag + output); } } if(term != null)
461 * writeLine(term);
462 */
463 }
464
465 /*
466 * private void writeBody(Object toWrite) throws IOException{
467 * writeClass(toWrite, "Body", " ", false); }
468 */
469
470 /**
471 * Gets a string representation of the frame file contents.
472 */
473 public String getFileContents() {
474 return _stringWriter.toString();
475 }
476}
Note: See TracBrowser for help on using the repository browser.