source: trunk/src/org/expeditee/io/KMSReader.java@ 247

Last change on this file since 247 was 247, checked in by ra33, 16 years ago

Added more import and mail stuff... including text importer

File size: 15.7 KB
Line 
1package org.expeditee.io;
2
3import java.io.BufferedReader;
4import java.io.FileReader;
5import java.io.IOException;
6import java.lang.reflect.Constructor;
7import java.lang.reflect.InvocationTargetException;
8import java.lang.reflect.Method;
9import java.util.HashMap;
10import java.util.Iterator;
11import java.util.LinkedHashMap;
12
13import org.expeditee.gui.Frame;
14import org.expeditee.gui.MessageBay;
15import org.expeditee.items.Constraint;
16import org.expeditee.items.Dot;
17import org.expeditee.items.Item;
18import org.expeditee.items.Line;
19import org.expeditee.items.Text;
20import org.expeditee.stats.SessionStats;
21
22/**
23 * Reads in KMS format files and constructs the Frame and Item objects they
24 * contain.
25 *
26 * @author jdm18
27 *
28 */
29public class KMSReader extends FrameReader {
30
31 private BufferedReader _reader = null;
32
33 private static LinkedHashMap<String, Method> _ItemTags = null;
34
35 private static LinkedHashMap<String, Method> _FrameTags = null;
36
37 /**
38 * Does nothing, location must be set before use
39 */
40 public KMSReader() {
41 if (_ItemTags != null && _FrameTags != null)
42 return;
43
44 _ItemTags = new LinkedHashMap<String, Method>();
45 _FrameTags = new LinkedHashMap<String, Method>();
46
47 try {
48 _FrameTags.put("A", Frame.class.getMethod("setName", pString));
49 _FrameTags.put("V", Frame.class.getMethod("setVersion", pInt));
50 _FrameTags
51 .put("p", Frame.class.getMethod("setPermission", pPermission));
52 _FrameTags.put("U", Frame.class.getMethod("setOwner", pString));
53 _FrameTags.put("D", Frame.class
54 .getMethod("setDateCreated", pString));
55 _FrameTags.put("M", Frame.class.getMethod("setLastModifyUser",
56 pString));
57 _FrameTags.put("d", Frame.class.getMethod("setLastModifyDate",
58 pString));
59 _FrameTags
60 .put("F", Frame.class.getMethod("setFrozenDate", pString));
61
62 _FrameTags.put("O", Frame.class.getMethod("setForegroundColor",
63 pColor));
64 _FrameTags.put("B", Frame.class.getMethod("setBackgroundColor",
65 pColor));
66
67 _ItemTags.put("S", Item.class.getMethod("setID", pInt));
68 _ItemTags.put("s", Item.class.getMethod("setDateCreated", pString));
69 _ItemTags.put("d", Item.class.getMethod("setColor", pColor));
70 _ItemTags.put("G", Item.class.getMethod("setBackgroundColor",
71 pColor));
72 _ItemTags.put("P", Item.class.getMethod("setPosition", pPoint));
73 _ItemTags.put("F", Item.class.getMethod("setLink", pString));
74 _ItemTags.put("J", Item.class.getMethod("setFormula", pString));
75
76 _ItemTags.put("X", Item.class.getMethod("setActions", pList));
77 _ItemTags.put("x", Item.class.getMethod("setActionMark", pBool));
78 _ItemTags.put("U", Item.class.getMethod("setActionCursorEnter",
79 pList));
80 _ItemTags.put("V", Item.class.getMethod("setActionCursorLeave",
81 pList));
82 _ItemTags.put("W", Item.class.getMethod("setActionEnterFrame",
83 pList));
84 _ItemTags.put("Y", Item.class.getMethod("setActionLeaveFrame",
85 pList));
86 _ItemTags.put("D", Item.class.getMethod("setData", pList));
87 _ItemTags.put("u", Item.class.getMethod("setHighlight", pBool));
88 _ItemTags.put("e", Item.class.getMethod("setFillColor", pColor));
89 _ItemTags.put("i", Item.class.getMethod("setFillPattern", pString));
90 _ItemTags.put("o", Item.class.getMethod("setOwner", pString));
91 _ItemTags.put("n", Item.class.getMethod("setLinkMark", pBool));
92 _ItemTags
93 .put("q", Item.class.getMethod("setLinkFrameset", pString));
94 _ItemTags
95 .put("y", Item.class.getMethod("setLinkTemplate", pString));
96 _ItemTags.put("g", Item.class
97 .getMethod("setLinePattern", pIntArray));
98
99 _ItemTags.put("j", Item.class.getMethod("setArrow", pArrow));
100
101 _ItemTags.put("f", Text.class.getMethod("setFont", pFont));
102 _ItemTags.put("t", Text.class.getMethod("setSpacing", pInt));
103 _ItemTags.put("T", Text.class.getMethod("appendText", pString));
104
105 _ItemTags.put("a", Text.class.getMethod("setWordSpacing", pInt));
106 _ItemTags.put("b", Text.class.getMethod("setLetterSpacing", pInt));
107 _ItemTags.put("m", Text.class.getMethod("setInitialSpacing", pInt));
108 _ItemTags.put("w", Text.class.getMethod("setWidth", pInt));
109 _ItemTags.put("k", Text.class.getMethod("setJustification", pJustification));
110
111 _ItemTags.put("h", Item.class.getMethod("setThickness", pFloat));
112 _ItemTags.put("l", Item.class.getMethod("setLineIDs", pString));
113 _ItemTags.put("c", Item.class
114 .getMethod("setConstraintIDs", pString));
115
116 // Lines and constraints are created differently
117 _ItemTags.put("L", Line.class.getMethod("setStartItem", pItem));
118 // _ItemTags.put("g", null);
119
120 _ItemTags.put("C", Constraint.class.getMethod("getID",
121 (Class[]) null));
122 // _ItemTags.put("s2", null);
123 } catch (SecurityException e) {
124 // TODO Auto-generated catch block
125 e.printStackTrace();
126 } catch (NoSuchMethodException e) {
127 // TODO Auto-generated catch block
128 e.printStackTrace();
129 }
130 }
131
132 /**
133 * Determines whether a string begins with a KMS tag.
134 *
135 * @param s
136 * a line of text
137 * @return true if s begins with a KMS tag
138 */
139 private static boolean isValidLine(String s) {
140 return s.length() >= 3 && s.charAt(0) == '+' && s.charAt(2) == '+'
141 && Character.isLetter(s.charAt(1));
142 }
143
144 /**
145 * Reads a KMS file with the given name from disk.
146 *
147 * @param frameName
148 * the name of the Frame to read in from a file.
149 * @return A new Frame object that contains any Items described in the file.
150 * @throws IOException
151 * Any exceptions occured by the BufferedReader.
152 */
153 public Frame readFrame(String fullPath) throws IOException {
154 _reader = new BufferedReader(new FileReader(fullPath));
155 Frame newFrame = null;
156 String next = "";
157 boolean header = true;
158 // clear hashmap and line list
159 _data.clear();
160 _linePoints.clear();
161 // First read the header
162 try {
163 while (_reader.ready()) {
164 next = _reader.readLine();
165 if (isValidLine(next)) {
166 if (header) {
167 // Create the frame when the first +S+ is reached
168 // And set the flag to indicate the end of the header
169 if (getTag(next).equals("S")) {
170 newFrame = readFrameClass();
171 header = false;
172 _data.clear();
173 processBodyLine(newFrame, next);
174 } else
175 processHeaderLine(next);
176 } else
177 processBodyLine(newFrame, next);
178 } else if (next.startsWith(SessionStats.ACTIVE_TIME_ATTRIBUTE)) {
179 try {
180 String value = next.substring(SessionStats.ACTIVE_TIME_ATTRIBUTE.length()).trim();
181 newFrame.setActiveTime(value);
182 } catch (Exception e) {
183 }
184
185 } else if (next.startsWith(SessionStats.DARK_TIME_ATTRIBUTE)) {
186 try {
187 String value = next.substring(SessionStats.DARK_TIME_ATTRIBUTE.length()).trim();
188 newFrame.setDarkTime(value);
189 } catch (Exception e) {
190 }
191
192 }
193 }
194 } catch (Exception e) {
195 System.out.println("Error reading bodyLine: " + next + " "
196 + e.getMessage());
197 e.printStackTrace();
198 }
199
200 // if the frame contains no items (Default.0 does this)
201 if (newFrame == null)
202 newFrame = readFrameClass();
203
204 _reader.close();
205 if (newFrame != null) {
206 //newFrame.refreshItemPermissions();
207 newFrame.setChanged(false);
208 }
209 return newFrame;
210 }
211
212 // stores the data of the Item to be created next
213 private LinkedHashMap<String, String> _data = new LinkedHashMap<String, String>(
214 20);
215
216 // creates an item from the last batch of data read from the file
217 private Item createItem() {
218 // creates an item based on the information in the hashmap
219 try {
220 return readItemClass();
221 } catch (IOException e) {
222 // TODO Auto-generated catch block
223 e.printStackTrace();
224 }
225
226 return null;
227 }
228
229 // Stores points used when constructing lines
230 private HashMap<Integer, Item> _linePoints = new HashMap<Integer, Item>();
231
232 /**
233 * Adds any lines stored in _lineStarts and _lineEnds to the given Frame.
234 *
235 * @param frame
236 * The Frame to add the newly created Line objects to.
237 */
238 private Line createLine() {
239 String s = _data.get("L");
240 _data.remove("L");
241
242 // get the line ID and type
243 java.awt.Point idtype = separateValues(s);
244
245 // get the end points
246 s = _data.get("s");
247 _data.remove("s");
248
249 java.awt.Point startend = separateValues(s);
250
251 int start = startend.x;
252 int end = startend.y;
253
254 if (_linePoints.get(start) != null && _linePoints.get(end) != null) {
255 Line line = new Line(_linePoints.get(start), _linePoints.get(end),
256 idtype.x);
257 return line;
258 }
259
260 // System.out.println(_linePoints.size());
261 // for (int i : _linePoints.keySet())
262 // System.out.println(i + " - "
263 // + _linePoints.get(i).getClass().getSimpleName());
264 //
265 // System.out.println("Error: Line " + idtype.x
266 // + " has missing end point(s) + (Looking for: " + start + " , "
267 // + end + ")");
268 return null;
269 }
270
271 /*
272 * Creates a constraint from the data containted in _data
273 */
274 private void createConstraint() {
275 java.awt.Point idtype = separateValues(_data.get("C"));
276 java.awt.Point startend = separateValues(_data.get("s"));
277
278 Item a = _linePoints.get(startend.x);
279 Item b = _linePoints.get(startend.y);
280
281 new Constraint(a, b, idtype.x, idtype.y);
282 }
283
284 /**
285 * Processes the body section of the KMS file, which contains all Items
286 *
287 * @param frame
288 * The Frame to add any created Items to.
289 * @param line
290 * The line of text read in from the file to process.
291 */
292 private void processBodyLine(Frame frame, String line) {
293 // separate the tag from the value
294 String tag = getTag(line);
295 line = getValue(line);
296
297 // if this is the start of a new item, a line, or a constraint
298 // then add the last item to the frame
299 if (tag.charAt(0) == 'S' || tag.charAt(0) == 'L'
300 || tag.charAt(0) == 'C') {
301 frame.addItem(createItem());
302
303 _data.clear();
304 _data.put(tag, line);
305 return;
306 }
307
308 // if this is the end of the file, then add the last item to the frame
309 if (tag.charAt(0) == 'Z') {
310 frame.addItem(createItem());
311 _data.clear();
312
313 return;
314 }
315
316 // check for duplicate tags (multiple lines of text)
317 String newtag = tag;
318 int i = 0;
319
320 // only executes if there are duplicate tags for this Item
321 while (_data.containsKey(newtag)) {
322 newtag = tag + i;
323 i++;
324 }
325
326 // All values are stored in a HashMap until the end of the Item is
327 // found.
328 _data.put(newtag, line);
329 }
330
331 private static String getTag(String line) {
332 assert (line.charAt(0) == '+');
333 assert (line.length() > 2);
334 return line.substring(1, 2);
335 }
336
337 private static String getValue(String line) {
338 assert (line.charAt(0) == '+');
339 if (line.length() > 4)
340 return line.substring(4);
341 else
342 return "";
343 }
344
345 /**
346 * Reads the header section of the file, which contains information about
347 * the Frame.
348 *
349 * @param frame
350 * The Frame to assign the read values to.
351 * @param line
352 * The line from the file to process.
353 * @return False if the end of the header has been reached, True otherwise.
354 */
355 private void processHeaderLine(String line) throws IOException {
356 // first separate the tag from the text
357 String tag = getTag(line);
358 String value = getValue(line);
359
360 if (tag.equals("Z"))
361 return;
362
363 if (_FrameTags.get(tag) == null) {
364 if (!tag.equals("t") && !tag.equals("v"))
365 MessageBay.errorMessage("Tag '" + tag + "' in '" + line
366 + "' is not supported.");
367 return;
368 }
369
370 _data.put(tag, value);
371 }
372
373 // returns two ints separated by a space from the given String
374 private java.awt.Point separateValues(String line) {
375 int x = Integer.parseInt(line.substring(0, line.indexOf(" ")));
376 int y = Integer.parseInt(line.substring(line.indexOf(" ") + 1));
377
378 return new java.awt.Point(x, y);
379 }
380
381 private Frame readFrameClass() throws IOException {
382 if (_data.size() == 0) {
383 MessageBay
384 .errorMessage("IO Error: File contains no valid KMS lines.");
385 return null;
386 }
387
388 Frame toMake = new Frame();
389 Iterator<String> it = _data.keySet().iterator();
390
391 while (it.hasNext()) {
392 String datatag = it.next();
393
394 Method toRun = _FrameTags.get(datatag);
395 Object[] vals = Conversion.Convert(toRun, _data.get(datatag));
396 try {
397 toRun.invoke(toMake, vals);
398 } catch (IllegalArgumentException e) {
399 // TODO Auto-generated catch block
400 e.printStackTrace();
401 } catch (IllegalAccessException e) {
402 // TODO Auto-generated catch block
403 e.printStackTrace();
404 } catch (InvocationTargetException e) {
405 // TODO Auto-generated catch block
406 e.printStackTrace();
407 }
408 }
409
410 return toMake;
411 }
412
413 @SuppressWarnings("unchecked")
414 private Item readItemClass() throws IOException {
415 Iterator<String> tags = _data.keySet().iterator();
416 Class toCreate = null;
417
418 // loop through all attributes read in for this item
419 while (tags.hasNext()) {
420 String next = tags.next();
421 Method m = _ItemTags.get(next);
422 if (m != null && _ItemTags.get(next + "2") == null) {
423 if (!m.getDeclaringClass().getSimpleName().equals("Item")) {
424 toCreate = m.getDeclaringClass();
425 break;
426 }
427 }
428 }
429
430 if (toCreate == null) {
431 if (_data.size() > 0)
432 toCreate = Dot.class;
433 else
434 return null;
435 }
436
437 Item toMake = null;
438
439 try {
440 if (toCreate == Line.class)
441 toMake = createLine();
442 else if (toCreate == Constraint.class) {
443 createConstraint();
444 return null;
445 } else if (toCreate == Item.class && _data.size() == 2) {
446 toCreate = Dot.class;
447 } else if (toCreate == Item.class) {
448 for (String s : _data.keySet())
449 System.out.println(s + " -> " + _data.get(s));
450 return null;
451 } else {
452 Object[] params = { -1 };
453 Constructor con = toCreate.getConstructor(int.class);
454 toMake = (Item) con.newInstance(params);
455 }
456 } catch (InstantiationException e) {
457 // TODO Auto-generated catch block
458 e.printStackTrace();
459 } catch (IllegalAccessException e) {
460 // TODO Auto-generated catch block
461 e.printStackTrace();
462 } catch (IllegalArgumentException e) {
463 // TODO Auto-generated catch block
464 e.printStackTrace();
465 } catch (InvocationTargetException e) {
466 // TODO Auto-generated catch block
467 e.printStackTrace();
468 } catch (SecurityException e) {
469 // TODO Auto-generated catch block
470 e.printStackTrace();
471 } catch (NoSuchMethodException e) {
472 // TODO Auto-generated catch block
473 e.printStackTrace();
474 }
475
476 if (toMake == null)
477 return null;
478
479 Iterator<String> it = _data.keySet().iterator();
480 String last = "";
481
482 int count = 0;
483
484 while (it.hasNext()) {
485 String tag = it.next();
486 if (_data.containsKey("" + tag.charAt(0) + count)) {
487 if (last.length() == 0)
488 last = _data.get(tag);
489 else
490 last += "\n" + _data.get(tag);
491
492 count++;
493 } else {
494 Method toRun = _ItemTags.get("" + tag.charAt(0));
495 if (toRun == null)
496 System.out.println("Error accessing tag method: "
497 + tag.charAt(0));
498 Object[] vals;
499 if (last.length() > 0)
500 vals = Conversion.Convert(toRun, last + "\n"
501 + _data.get(tag));
502 else
503 vals = Conversion.Convert(toRun, _data.get(tag));
504
505 try {
506 if (vals != null) {
507 toRun.invoke(toMake, vals);
508 }
509 } catch (IllegalArgumentException e) {
510 // TODO Auto-generated catch block
511 e.printStackTrace();
512 } catch (IllegalAccessException e) {
513 // TODO Auto-generated catch block
514 e.printStackTrace();
515 } catch (InvocationTargetException e) {
516 // TODO Auto-generated catch block
517 e.printStackTrace();
518 } catch (ClassCastException e) {
519 System.out.println(toRun.getName());
520 e.printStackTrace();
521 }
522
523 count = 0;
524 last = "";
525 }
526
527 }
528
529 if (!(toMake instanceof Line))
530 _linePoints.put(toMake.getID(), toMake);
531
532 return toMake;
533 }
534
535 public static int getVersion(String fullpath) {
536 try {
537 BufferedReader reader = new BufferedReader(new FileReader(fullpath));
538 String next = "";
539 // First read the header lines until we get the version number
540 while (reader.ready() && (next = reader.readLine()) != null) {
541 if (isValidLine(next)) {
542 char tag = getTag(next).charAt(0);
543 String value = getValue(next);
544 if (tag == 'V')
545 return Integer.parseInt(value);
546 else if (tag == 'Z')
547 return 0;
548 }
549 }
550 } catch (Exception e) {
551 }
552 return 0;
553 }
554}
Note: See TracBrowser for help on using the repository browser.