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

Last change on this file since 601 was 601, checked in by jts21, 11 years ago

Switch back to EXP format, revert changes to Picture class

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