source: trunk/src/org/expeditee/gui/AttributeUtils.java@ 214

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

Added charts

File size: 24.7 KB
Line 
1package org.expeditee.gui;
2
3import java.awt.Color;
4import java.awt.Font;
5import java.awt.Point;
6import java.lang.reflect.InvocationTargetException;
7import java.lang.reflect.Method;
8import java.util.HashMap;
9import java.util.LinkedList;
10import java.util.List;
11
12import org.expeditee.io.Conversion;
13import org.expeditee.items.Item;
14import org.expeditee.items.Justification;
15import org.expeditee.items.Permission;
16import org.expeditee.items.Text;
17
18/**
19 * This class provides the methods to extract and set attributes of Items and
20 * Frames. These methods are called when a user merges a text item with
21 * <code>Attribute: Value</code> pairs.
22 *
23 * @author jdm18
24 *
25 */
26public class AttributeUtils {
27
28 public static final char SEPARATOR_CHAR = ':';
29
30 private static final String SEPARATOR_STRING = SEPARATOR_CHAR + " ";
31
32 private static final int GET_LENGTH = "get".length();
33
34 private static int SET_LENGTH = "set".length();
35
36 // List of method names to ignore when searching for a match
37 private static List<Method> _GetMethods = null;
38
39 private static HashMap<String, Method> _SetMethods = null;
40
41 // List of attributes which are ignored when copying.
42 private static List<String> _Ignore = null;
43
44 /***************************************************************************
45 * List of method names to show in extraced lists even when they return null
46 * (Null is often used to indicate the default value is used)
47 **************************************************************************/
48 private static List<Method> _AllowNull = null;
49
50 private static List<String> _ExtractIgnore = null;
51
52 // private static HashMap<String, String> _Abbreviations = null;
53
54 /**
55 * Initialises the _Ignore and _AllowNull lists.
56 */
57 private static void initLists() {
58
59 Class[] param = {};
60
61 try {
62 // TODO load these in with reflection...
63 // Set the shortcuts with annotation tags on the methods
64 _Ignore = new LinkedList<String>();
65 _Ignore.add("date");
66 _Ignore.add("datecreated");
67 _Ignore.add("d");
68 _Ignore.add("link");
69 _Ignore.add("l");
70 _Ignore.add("action");
71 _Ignore.add("a");
72 _Ignore.add("position");
73 _Ignore.add("pos");
74 _Ignore.add("p");
75 _Ignore.add("x");
76 _Ignore.add("y");
77
78 _ExtractIgnore = new LinkedList<String>();
79 _ExtractIgnore.add("x");
80 _ExtractIgnore.add("y");
81
82 _AllowNull = new LinkedList<Method>();
83 _AllowNull.add(Item.class.getMethod("getColor", param));
84 _AllowNull.add(Item.class.getMethod("getBackgroundColor", param));
85
86 _AllowNull.add(Frame.class.getMethod("getBackgroundColor", param));
87 _AllowNull.add(Frame.class.getMethod("getForegroundColor", param));
88
89 _GetMethods = new LinkedList<Method>();
90 _GetMethods.add(Item.class.getMethod("getDateCreated", param));
91
92 _GetMethods.add(Item.class.getMethod("getColor", param));
93 _GetMethods.add(Item.class.getMethod("getBorderColor", param));
94 _GetMethods.add(Item.class.getMethod("getBackgroundColor", param));
95 _GetMethods.add(Item.class.getMethod("getAction", param));
96 _GetMethods.add(Item.class.getMethod("getData", param));
97 _GetMethods.add(Item.class.getMethod("getLink", param));
98 _GetMethods.add(Item.class.getMethod("getFormula", param));
99 _GetMethods.add(Item.class.getMethod("getFillColor", param));
100 _GetMethods.add(Item.class.getMethod("getGradientColor", param));
101 _GetMethods.add(Item.class.getMethod("getFillPattern", param));
102 _GetMethods.add(Item.class.getMethod("getThickness", param));
103
104 _GetMethods.add(Item.class.getMethod("getOwner", param));
105 _GetMethods.add(Item.class.getMethod("getLinkMark", param));
106 _GetMethods.add(Item.class.getMethod("getActionMark", param));
107
108 _GetMethods
109 .add(Item.class.getMethod("getActionCursorEnter", param));
110 _GetMethods
111 .add(Item.class.getMethod("getActionCursorLeave", param));
112 _GetMethods.add(Item.class.getMethod("getActionEnterFrame", param));
113 _GetMethods.add(Item.class.getMethod("getActionLeaveFrame", param));
114
115 _GetMethods.add(Item.class.getMethod("getTopShadowColor", param));
116 _GetMethods
117 .add(Item.class.getMethod("getBottomShadowColor", param));
118 _GetMethods.add(Item.class.getMethod("getArrow", param));
119
120 _GetMethods.add(Item.class.getMethod("getLinePattern", param));
121 _GetMethods.add(Item.class.getMethod("getLinkFrameset", param));
122 _GetMethods.add(Item.class.getMethod("getLinkTemplate", param));
123 _GetMethods.add(Item.class.getMethod("getPosition", param));
124 _GetMethods.add(Item.class.getMethod("getX", param));
125 _GetMethods.add(Item.class.getMethod("getY", param));
126
127 _GetMethods.add(Item.class.getMethod("getAnchorRight", param));
128 _GetMethods.add(Item.class.getMethod("getAnchorBottom", param));
129 _GetMethods.add(Item.class.getMethod("getSize", param));
130
131 _GetMethods.add(Text.class.getMethod("getFamily", param));
132 _GetMethods.add(Text.class.getMethod("getFontStyle", param));
133 _GetMethods.add(Text.class.getMethod("getJustification", param));
134 _GetMethods.add(Text.class.getMethod("getWidth", param));
135
136 _GetMethods.add(Frame.class.getMethod("getOwner", param));
137 _GetMethods.add(Frame.class.getMethod("getPermission", param));
138 _GetMethods.add(Frame.class.getMethod("getDateCreated", param));
139 _GetMethods.add(Frame.class.getMethod("getLastModifyUser", param));
140 _GetMethods.add(Frame.class.getMethod("getLastModifyDate", param));
141 _GetMethods.add(Frame.class.getMethod("getForegroundColor", param));
142 _GetMethods.add(Frame.class.getMethod("getBackgroundColor", param));
143
144 Class[] pPoint = { Point.class };
145 Class[] pString = { String.class };
146 Class[] pInt = { int.class };
147 Class[] pFloat = { float.class };
148 Class[] pFloatO = { Float.class };
149 Class[] pColor = { Color.class };
150 Class[] pBool = { boolean.class };
151 Class[] pArrow = { float.class, double.class };
152 Class[] pList = { List.class };
153 Class[] pIntArray = { int[].class };
154 Class[] pJustification = { Justification.class };
155 Class[] pPermission = { Permission.class };
156
157 // TODO automatically load these by annotating the methods with the
158 // shortcut text
159 // Indicate to users of any symbols that clash
160
161 _SetMethods = new HashMap<String, Method>();
162 _SetMethods.put("x", Item.class.getMethod("setX", pFloat));
163 _SetMethods.put("y", Item.class.getMethod("setY", pFloat));
164 _SetMethods.put("position", Item.class.getMethod("setPosition",
165 pPoint));
166
167 _SetMethods.put("ab", Item.class.getMethod("setAnchorBottom",
168 pFloatO));
169 _SetMethods.put("ar", Item.class.getMethod("setAnchorRight",
170 pFloatO));
171 _SetMethods.put("anchorbottom", Item.class.getMethod(
172 "setAnchorBottom", pFloatO));
173 _SetMethods.put("anchorright", Item.class.getMethod(
174 "setAnchorRight", pFloatO));
175
176 _SetMethods.put("p", Item.class.getMethod("setPosition", pPoint));
177 _SetMethods.put("pos", Item.class.getMethod("setPosition", pPoint));
178 _SetMethods.put("thickness", Item.class.getMethod("setThickness",
179 pFloat));
180 _SetMethods.put("t", Item.class.getMethod("setThickness", pFloat));
181
182 _SetMethods.put("color", Item.class.getMethod("setColor", pColor));
183 _SetMethods.put("c", Item.class.getMethod("setColor", pColor));
184
185 _SetMethods.put("backgroundcolor", Item.class.getMethod(
186 "setBackgroundColor", pColor));
187 _SetMethods.put("bgc", Item.class.getMethod("setBackgroundColor",
188 pColor));
189 _SetMethods.put("bordercolor", Item.class.getMethod(
190 "setBorderColor", pColor));
191 _SetMethods.put("bc", Item.class
192 .getMethod("setBorderColor", pColor));
193
194 _SetMethods
195 .put("action", Item.class.getMethod("setActions", pList));
196 _SetMethods.put("a", Item.class.getMethod("setActions", pList));
197 _SetMethods.put("d", Item.class.getMethod("setData", pList));
198 _SetMethods.put("data", Item.class.getMethod("setData", pList));
199
200 _SetMethods.put("link", Item.class.getMethod("setLink", pString));
201 _SetMethods.put("l", Item.class.getMethod("setLink", pString));
202
203 _SetMethods.put("formula", Item.class.getMethod("calculate",
204 pString));
205 _SetMethods.put("f", Item.class.getMethod("calculate", pString));
206
207 _SetMethods.put("fillcolor", Item.class.getMethod("setFillColor",
208 pColor));
209 _SetMethods.put("fc", Item.class.getMethod("setFillColor", pColor));
210 _SetMethods.put("gc", Item.class.getMethod("setGradientColor",
211 pColor));
212 _SetMethods.put("gradientcolor", Item.class.getMethod(
213 "setGradientColor", pColor));
214
215 _SetMethods.put("fillpattern", Item.class.getMethod(
216 "setFillPattern", pString));
217 _SetMethods.put("fp", Item.class.getMethod("setFillPattern",
218 pString));
219
220 _SetMethods.put("owner", Item.class.getMethod("setOwner", pString));
221 _SetMethods.put("linkmark", Item.class.getMethod("setLinkMark",
222 pBool));
223 _SetMethods.put("lm", Item.class.getMethod("setLinkMark", pBool));
224 _SetMethods.put("actionmark", Item.class.getMethod("setActionMark",
225 pBool));
226 _SetMethods.put("am", Item.class.getMethod("setActionMark", pBool));
227
228 _SetMethods.put("actioncursorenter", Item.class.getMethod(
229 "setActionCursorEnter", pList));
230 _SetMethods.put("actioncursorleave", Item.class.getMethod(
231 "setActionCursorLeave", pList));
232 _SetMethods.put("actionenterframe", Item.class.getMethod(
233 "setActionEnterFrame", pList));
234 _SetMethods.put("actionleaveframe", Item.class.getMethod(
235 "setActionLeaveFrame", pList));
236
237 _SetMethods.put("topshadow", Item.class.getMethod(
238 "setTopShadowColor", pColor));
239 _SetMethods.put("bottomshadow", Item.class.getMethod(
240 "setBottomShadowColor", pColor));
241 _SetMethods.put("arrow", Item.class.getMethod("setArrow", pArrow));
242
243 _SetMethods.put("linepattern", Item.class.getMethod(
244 "setLinePattern", pIntArray));
245 _SetMethods.put("lp", Item.class.getMethod("setLinePattern",
246 pIntArray));
247
248 _SetMethods.put("linkframeset", Item.class.getMethod(
249 "setLinkFrameset", pString));
250 _SetMethods.put("lf", Item.class.getMethod("setLinkFrameset",
251 pString));
252 _SetMethods.put("linktemplate", Item.class.getMethod(
253 "setLinkTemplate", pString));
254 _SetMethods.put("lt", Item.class.getMethod("setLinkTemplate",
255 pString));
256
257 _SetMethods.put("family", Text.class
258 .getMethod("setFamily", pString));
259 _SetMethods.put("face", Text.class.getMethod("setFontStyle",
260 pString));
261 _SetMethods.put("fontstyle", Text.class.getMethod("setFontStyle",
262 pString));
263 _SetMethods.put("justification", Text.class.getMethod(
264 "setJustification", pJustification));
265 _SetMethods.put("j", Text.class.getMethod("setJustification",
266 pJustification));
267 _SetMethods.put("width", Text.class.getMethod("setWidth", pInt));
268 _SetMethods.put("size", Item.class.getMethod("setSize", pFloat));
269 _SetMethods.put("s", Item.class.getMethod("setSize", pFloat));
270
271 _SetMethods.put("foregroundcolor", Frame.class.getMethod(
272 "setForegroundColor", pColor));
273 _SetMethods.put("fgc", Frame.class.getMethod("setForegroundColor",
274 pColor));
275 _SetMethods.put("backgroundcolor0", Frame.class.getMethod(
276 "setBackgroundColor", pColor));
277 _SetMethods.put("bgc0", Frame.class.getMethod("setBackgroundColor",
278 pColor));
279 _SetMethods.put("permission", Frame.class.getMethod(
280 "setPermission", pPermission));
281
282 } catch (SecurityException e) {
283 // TODO Auto-generated catch block
284 e.printStackTrace();
285 } catch (NoSuchMethodException e) {
286 // TODO Auto-generated catch block
287 e.printStackTrace();
288 }
289 }
290
291 /**
292 * Extracts a list of attributes from the given Object. Any method that
293 * starts with <code>get</code>, takes no arguments and is not found in
294 * the Ignore list will be run, All the attributes are then put into a Text
295 * Item of the form <Name>:<Value> If the value returned by the get method
296 * is null, then the attribute will not be included, unless the name of the
297 * method is found in the AllowNull list.
298 *
299 * @param toExtract
300 * The Object from which to extract the attributes
301 * @return A Text Item containing the extracted Attributes.
302 */
303 public static Item extractAttributes(Object toExtract) {
304 if (toExtract == null)
305 return null;
306
307 // ensure the lists are populated
308 if (_Ignore == null)
309 initLists();
310
311 // StringBuffer to store all the extracted Attribute:Value pairs
312 StringBuffer attributes = new StringBuffer();
313
314 // iterate through the list of methods
315 for (Method m : _GetMethods) {
316
317 // Make sure the classes of the methods match the item
318 if (m.getDeclaringClass().isAssignableFrom(toExtract.getClass())) {
319 try {
320 Object o = m.invoke(toExtract, (Object[]) null);
321
322 if (o == null) {
323 // methods that return null are only included if they
324 // are in the AllowNull list
325 if (_AllowNull.contains(m)) {
326 String name = m.getName().substring(GET_LENGTH)
327 .toLowerCase();
328 if (name.equals("color"))
329 o = "default";
330 else if (name.equals("backgroundcolor"))
331 o = "transparent";
332 else if (name.equals("foregroundcolor"))
333 o = "auto";
334 else
335 o = "";
336 } else {
337 continue;
338 }
339 }
340 // skip methods that are in the ignore lists
341 if (_ExtractIgnore.contains(m.getName().substring(
342 GET_LENGTH).toLowerCase())) {
343 continue;
344 }
345
346 if (o instanceof Integer) {
347 Integer i = (Integer) o;
348 if (i == Item.DEFAULT_INTEGER)
349 continue;
350 if (m.getName().endsWith("Justification")
351 && ((Justification) o).toString() != null)
352 o = ((Justification) o).toString();
353 // -1 indicates default value
354 else
355 o = i;
356 } else if (o instanceof Float) {
357 // -1 indicates default value
358 if (((Float) o) < 0.0001)
359 continue;
360 o = Math.round((Float) o);
361 } else if (o instanceof Double) {
362 // -1 indicates default value
363 if (((Double) o) < 0.0001)
364 continue;
365 } else if (o instanceof Color) {
366 // converts the color to the Expeditee code
367 o = Conversion.getExpediteeColorCode((Color) o);
368 if (o == null)
369 continue;
370 } else if (o instanceof Point) {
371 Point p = (Point) o;
372 o = Math.round(p.getX()) + " " + Math.round(p.getY());
373 } else if (o instanceof Font) {
374 Font f = (Font) o;
375
376 String s = f.getName() + "-";
377 if (f.isPlain())
378 s += "Plain";
379
380 if (f.isBold())
381 s += "Bold";
382
383 if (f.isItalic())
384 s += "Italic";
385
386 s += "-" + f.getSize();
387 o = s;
388 } else if (o instanceof Text) {
389 o = ((Text) o).getFirstLine();
390 } else if (o instanceof List) {
391 List list = (List) o;
392 for (Object ob : list)
393 attributes
394 .append(m.getName().substring(GET_LENGTH))
395 .append(SEPARATOR_STRING).append(ob)
396 .append('\n');
397 continue;
398 } else if (o instanceof int[]) {
399 StringBuffer sb = new StringBuffer();
400 int[] values = (int[]) o;
401 for (int i = 0; i < values.length; i++) {
402 sb.append(values[i]).append(' ');
403 }
404 sb.deleteCharAt(attributes.length() - 1);
405 o = sb.toString();
406 } else if (o instanceof Boolean) {
407 // true is the default for boolean values
408 if (((Boolean) o).booleanValue())
409 continue;
410 }
411 // Append the attributes
412 attributes.append(m.getName().substring(GET_LENGTH))
413 .append(SEPARATOR_STRING).append(o).append('\n');
414 } catch (Exception e) {
415 // TODO Auto-generated catch block
416 e.printStackTrace();
417 }
418 }
419 }
420
421 // if no attributes were extracted
422 if (attributes.length() <= 0)
423 return null;
424
425 while (attributes.charAt(attributes.length() - 1) == '\n')
426 attributes.delete(attributes.length() - 1, attributes.length());
427
428 // create the text Item
429 Frame current = DisplayIO.getCurrentFrame();
430 Item attribs = current.getStatsTextItem(attributes.toString());
431 return attribs;
432 }
433
434 /**
435 * Attempts to set the attribute in the given attribute: value pair. The
436 * value string should be formatted as follows:
437 * <code> Attribute: Value </code> Multiple values can be used if they are
438 * separated by spaces
439 *
440 * @param toSet
441 * The Item or Frame to set the attribute of
442 * @param attribs
443 * The Text item that contains the list of attributes to set
444 * @return True if the attribute(s) were sucessfully set, false otherwise
445 */
446 public static boolean setAttribute(Object toSet, Text attribs) {
447 // error checking
448 if (toSet == null || attribs == null)
449 return false;
450
451 if (_Ignore == null)
452 initLists();
453
454 // get the list of attribute: value pairs
455 List<String> values = attribs.getTextList();
456 // if no pairs exist, we are done
457 if (values == null || values.size() == 0
458 || (values.size() == 1 && values.get(0).length() == 0)) {
459 return false;
460 }
461
462 // loop through all attribute: value pairs
463 for (int i = 0; i < values.size(); i++) {
464 StringBuffer v = new StringBuffer(values.get(i));
465
466 // remove the annotation mark (if applicable)
467 if (v.indexOf("@") == 0)
468 v = v.deleteCharAt(0);
469
470 // check if the next string is another attribute to merge or a
471 // continuation
472 while (i < values.size() - 1) {
473 StringBuffer next = new StringBuffer(values.get(i + 1));
474
475 // if the next String has a colon, then it may be another
476 // attribute
477 if (next.indexOf("" + SEPARATOR_CHAR) >= 0) {
478 // if the attribute is the same as v, then it is a
479 // continuation
480 if (v.indexOf(getAttribute(next.toString())) == 0) {
481 // strip the attribute from next
482 next = new StringBuffer(getValue(next.toString()));
483 // if the attribute is not the same, then it may be a
484 // new method
485 } else {
486 // if this is indeed a method, then leave the while loop
487 // if(_SetMethods.containsKey(StripFromColon(next.toString()).toLowerCase())){
488 break;
489 // }
490 }
491 }
492
493 v.append("\n").append(next);
494 i++;
495 }
496
497 if (v.length() > 0
498 && !setAttribute(toSet, v.toString(), values.size() > 1)) {
499 // if no other attributes have been set
500 if (i == 0)
501 return false;
502 // otherwise, this is a list of attributes, so continue
503 else {
504 String stripped = getAttribute(v.toString());
505 if (stripped == null) {
506 // This happens when there is an attribute at the start
507 // Then a bunch of plain text
508 return false;
509 } else if (_Ignore.contains(stripped)) {
510 return false;
511 } else if (!(_SetMethods.containsKey(stripped))) {
512 // Display an error message if its not in our list of
513 // attributes to ignore when copying
514 MessageBay.warningMessage("Attribute: '"
515 + getAttribute(v.toString())
516 + "' does not exist.");
517 } else {
518 String types = "";
519 for (Class c : _SetMethods.get(stripped)
520 .getParameterTypes())
521 types += c.getSimpleName() + " ";
522 MessageBay.warningMessage("Wrong arguments for: '"
523 + getAttribute(v.toString()) + "' expecting "
524 + types.trim() + " found '"
525 + getValue(v.toString()) + "'");
526 }
527 }
528 } else if (v.length() == 0)
529 return false;
530 }
531
532 return true;
533 }
534
535 private static boolean setAttribute(Object toSet, String value,
536 boolean isAttributeList) {
537 // separate attribute and value from string
538 String attribute = getAttribute(value);
539 // Check that an attribute was found
540 if (attribute == null)
541 return false;
542 attribute = attribute.toLowerCase();
543
544 value = getValue(value);
545 assert (value != null);
546
547 // Some properties are ignored when multiple attributes are being set on
548 // an item at the same time
549 if (isAttributeList && _Ignore.contains(attribute)) {
550 // System.out.println("Attribute ignored: " + attribute);
551 return true;
552 }
553
554 // Separate multiple values if required
555 Method toRun = _SetMethods.get(attribute);
556
557 // if this is not the name of a method, it may be the name of an agent
558 if (toRun == null) {
559 // System.out.println("Attrib not found for: " + attribute);
560 return false;
561 }
562
563 // if there are duplicate methods with the same name
564 List<Method> possibles = new LinkedList<Method>();
565 if (toRun.getDeclaringClass().isInstance(toSet))
566 possibles.add(toRun);
567 int i = 0;
568 while (_SetMethods.containsKey(attribute + i)) {
569 if (_SetMethods.get(attribute + i).getDeclaringClass()
570 .isAssignableFrom(toSet.getClass()))
571 possibles.add(_SetMethods.get(attribute + i));
572 i++;
573 }
574
575 for (Method possible : possibles) {
576 Object current = null;
577 Object[] param = {};
578 // find the corresponding get method for this set method
579 // and get the current value of the attribute
580 for (Method m : _GetMethods) {
581 if (m.getDeclaringClass().isAssignableFrom(toSet.getClass())
582 && m.getName().substring(GET_LENGTH).equals(
583 possible.getName().substring(SET_LENGTH))) {
584 try {
585 current = m.invoke(toSet, param);
586 } catch (IllegalArgumentException e) {
587 // TODO Auto-generated catch block
588 e.printStackTrace();
589 } catch (IllegalAccessException e) {
590 // TODO Auto-generated catch block
591 e.printStackTrace();
592 } catch (InvocationTargetException e) {
593 // TODO Auto-generated catch block
594 e.printStackTrace();
595 }
596 break;
597 }
598
599 }
600
601 try {
602 Object[] params = Conversion.Convert(possible, value, current);
603
604 try {
605 possible.invoke(toSet, params);
606 return true;
607 } catch (IllegalArgumentException e) {
608 // TODO Auto-generated catch block
609 e.printStackTrace();
610 } catch (IllegalAccessException e) {
611 // TODO Auto-generated catch block
612 e.printStackTrace();
613 } catch (InvocationTargetException e) {
614 MessageBay.displayMessage(toSet.getClass().getSimpleName()
615 + " type does not support that attribute.");
616 // e.printStackTrace();
617 }
618 } catch (NumberFormatException e) {
619
620 }
621 }
622
623 return false;
624 }
625
626 /**
627 * Returns the part of the given string that is after the attribute value
628 * pair separator. If that character is not there it returns empty if it is
629 * an annotation item or the entire string if it is not.
630 *
631 * @param attributeValuePair
632 * the string to get the value from.
633 * @return the value from the attribute value pair.
634 */
635 public static String getValue(String toStrip) {
636 assert (toStrip != null);
637
638 toStrip = toStrip.trim();
639 if (toStrip.length() == 0)
640 return "";
641
642 int ind = toStrip.lastIndexOf(SEPARATOR_CHAR);
643 int lineSeparator = toStrip.indexOf(Character.LINE_SEPARATOR, ind);
644 // If it is an annotation item return the empty string
645 // Annotation items can not be values only
646 if (ind < 0 && toStrip.charAt(0) == '@') {
647 return "";
648 }
649 // If its one line then our value goes to the end of the string
650 if (lineSeparator < 0)
651 lineSeparator = toStrip.length();
652
653 return toStrip.substring(ind + 1, lineSeparator).trim();
654 }
655
656 /**
657 * Returns the part of the given string that is before the attribute value
658 * pair separator, or null if the given String does not include the
659 * separator.
660 *
661 * @param attributeValuePair
662 * The String to strip
663 * @return the attribute if there is one or null if there is not
664 */
665 public static String getAttribute(String attributeValuePair) {
666 if (attributeValuePair.length() <= 1)
667 return null;
668
669 attributeValuePair = attributeValuePair.trim();
670
671 if (attributeValuePair.length() == 0)
672 return null;
673
674 int ind = attributeValuePair.indexOf(SEPARATOR_CHAR);
675 // If its an annotation there must be no space between the @ and colon
676 // and the first character after the annotation must be a letter
677 if (attributeValuePair.charAt(0) == '@') {
678 if (!Character.isLetter(attributeValuePair.charAt(1)))
679 return null;
680 for (int i = 2; i < ind; i++) {
681 if (!Character.isLetterOrDigit(attributeValuePair.charAt(i)))
682 return null;
683 }
684 if (ind < 1)
685 return attributeValuePair.substring(0);
686 } else if (ind < 1) {
687 return null;
688 }
689
690 return attributeValuePair.substring(0, ind).trim();
691 }
692
693 /**
694 * Replaces the current value for the text item with the new value.
695 *
696 * @param text
697 * the item whos value is to be changed
698 * @param newValue
699 * the new value for the item
700 */
701 public static void replaceValue(Text text, String newValue) {
702 assert (newValue != null);
703
704 String oldText = text.getFirstLine();
705 String restOfText = text.getText().substring(oldText.length());
706 String attribute = getAttribute(oldText);
707
708 if (attribute == null)
709 attribute = text.getText().trim();
710
711 text.setText(attribute + SEPARATOR_STRING + newValue + restOfText);
712 }
713
714 /**
715 * Gets the value from an attribute value pair as a double.
716 *
717 * @param attributeValuePair
718 * the text to get the value from
719 * @return the double value or null if there is none
720 */
721 public static Double getDoubleValue(String attributeValuePair) {
722 String value = getValue(attributeValuePair);
723
724 assert (value != null);
725
726 try {
727 return Double.parseDouble(value);
728 } catch (Exception e) {
729 }
730 return null;
731 }
732
733 public static AttributeValuePair getPair(String text) {
734 // TODO Make this more efficient
735 String attribute = AttributeUtils.getAttribute(text);
736 String value = AttributeUtils.getValue(text);
737 if (attribute == null || value == null)
738 return null;
739 return new AttributeValuePair(attribute, value);
740 }
741}
Note: See TracBrowser for help on using the repository browser.