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

Last change on this file since 707 was 707, checked in by jts21, 10 years ago

Implement setting tooltip attributes

File size: 27.9 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("AddToHistory", Item.class.getMethod("getLinkHistory"),
206 Item.class.getMethod("setLinkHistory", pBool));
207 _Attrib.put("Action", Item.class.getMethod("getAction"),
208 Item.class.getMethod("setActions", pList));
209 _Attrib.put("ActionMark", Item.class.getMethod("getActionMark"),
210 Item.class.getMethod("setActionMark", pBool));
211 _Attrib.put("ActionCursorEnter", Item.class.getMethod("getActionCursorEnter"),
212 Item.class.getMethod("setActionCursorEnter", pList));
213 _Attrib.put("ActionCursorLeave", Item.class.getMethod("getActionCursorLeave"),
214 Item.class.getMethod("setActionCursorLeave", pList));
215 _Attrib.put("ActionEnterFrame", Item.class.getMethod("getActionEnterFrame"),
216 Item.class.getMethod("setActionEnterFrame", pList));
217 _Attrib.put("ActionLeaveFrame", Item.class.getMethod("getActionLeaveFrame"),
218 Item.class.getMethod("setActionLeaveFrame", pList));
219 _Attrib.put("Data", Item.class.getMethod("getData"),
220 Item.class.getMethod("setData", pList));
221 _Attrib.put("Highlight", Item.class.getMethod("getHighlight"),
222 Item.class.getMethod("setHighlight", pBool));
223 _Attrib.put("FillColor", Item.class.getMethod("getFillColor"),
224 Item.class.getMethod("setFillColor", pColor));
225 _Attrib.put("GradientColor", Item.class.getMethod("getGradientColor"),
226 Item.class.getMethod("setGradientColor", pColor));
227 _Attrib.put("GradientAngle", Item.class.getMethod("getGradientAngle"),
228 Item.class.getMethod("setGradientAngle", pInt));
229 _Attrib.put("FillPattern", Item.class.getMethod("getFillPattern"),
230 Item.class.getMethod("setFillPattern", pString));
231 _Attrib.put("Owner", Item.class.getMethod("getOwner"),
232 Item.class.getMethod("setOwner", pString));
233 _Attrib.put("LinkMark", Item.class.getMethod("getLinkMark"),
234 Item.class.getMethod("setLinkMark", pBool));
235 _Attrib.put("LinkFrameset", Item.class.getMethod("getLinkFrameset"),
236 Item.class.getMethod("setLinkFrameset", pString));
237 _Attrib.put("LinkTemplate", Item.class.getMethod("getLinkTemplate"),
238 Item.class.getMethod("setLinkTemplate", pString));
239 _Attrib.put("LinePattern", Item.class.getMethod("getLinePattern"),
240 Item.class.getMethod("setLinePattern", pIntArray));
241 _Attrib.put("Arrow", Item.class.getMethod("getArrow"),
242 Item.class.getMethod("setArrow", pArrow));
243 _Attrib.put("DotType", Item.class.getMethod("getDotType"),
244 Item.class.getMethod("setDotType", pDotType));
245 _Attrib.put("Filled", Item.class.getMethod("getFilled"),
246 Item.class.getMethod("setFilled", pBool));
247 _Attrib.put("Formula", Item.class.getMethod("getFormula"),
248 Item.class.getMethod("setFormula", pString));
249 _Attrib.put("Thickness", Item.class.getMethod("getThickness"),
250 Item.class.getMethod("setThickness", pFloat));
251// _Attrib.put("LineIDs", Item.class.getMethod("getLineIDs"),
252// Item.class.getMethod("setLineIDs", pString));
253// _Attrib.put("ConstraintIDs", Item.class.getMethod("getConstraintIDs"),
254// Item.class.getMethod("setConstraintIDs", pString));
255 _Attrib.put("Size", Item.class.getMethod("getSize"),
256 Item.class.getMethod("setSize", pFloat));
257 _Attrib.put("Save", Item.class.getMethod("getSave"),
258 Item.class.getMethod("setSave", pBool));
259 _Attrib.put("AutoStamp", Item.class.getMethod("getAutoStamp"),
260 Item.class.getMethod("setAutoStamp", pFloatO));
261 _Attrib.put("Width", Item.class.getMethod("getWidthToSave"),
262 Item.class.getMethod("setWidth", pIntO));
263 _Attrib.put("X", null,
264 Item.class.getMethod("setX", pFloat));
265 _Attrib.put("Y", null,
266 Item.class.getMethod("setY", pFloat));
267 _Attrib.put("Tooltip", Item.class.getMethod("getTooltip"),
268 Item.class.getMethod("setTooltips", pList));
269
270 // Text Items
271 _Attrib.put("Family", Text.class.getMethod("getFamily"),
272 Text.class.getMethod("setFamily", pString));
273 _Attrib.put("FontStyle", Text.class.getMethod("getFontStyle"),
274 Text.class.getMethod("setFontStyle", pString));
275 _Attrib.put("Justification", Text.class.getMethod("getJustification"),
276 Text.class.getMethod("setJustification", pJustification));
277 _Attrib.put("AutoWrap", Text.class.getMethod("getAutoWrapToSave"),
278 Text.class.getMethod("setAutoWrap", pBool));
279
280 // Aliases for attribute setting
281 _Attrib.alias("pos", "position");
282 _Attrib.alias("p", "position");
283 _Attrib.alias("xy", "position");
284 _Attrib.alias("a", "action");
285 _Attrib.alias("d", "data");
286 _Attrib.alias("f", "formula");
287 _Attrib.alias("font", "family");
288 _Attrib.alias("s", "size");
289 _Attrib.alias("l", "link");
290 _Attrib.alias("ab", "anchorbottom");
291 _Attrib.alias("ar", "anchorright");
292 _Attrib.alias("t", "thickness");
293 // _Attrib.alias("c", "color"); // breaks circle creation
294 _Attrib.alias("bgc", "backgroundcolor");
295 _Attrib.alias("bc", "bordercolor");
296 _Attrib.alias("fc", "fillcolor");
297 _Attrib.alias("gc", "gradientcolor");
298 _Attrib.alias("ga", "gradientangle");
299 _Attrib.alias("fp", "fillpattern");
300 _Attrib.alias("lm", "linkmark");
301 _Attrib.alias("am", "actionmark");
302 _Attrib.alias("dt", "dottype");
303 _Attrib.alias("fill", "filled");
304 _Attrib.alias("lp", "linepattern");
305 _Attrib.alias("lf", "linkframeset");
306 _Attrib.alias("lt", "linktemplate");
307 _Attrib.alias("face", "fontstyle");
308 _Attrib.alias("j", "justification");
309 _Attrib.alias("w", "width");
310 _Attrib.alias("as", "autostamp");
311
312
313 } catch (SecurityException e) {
314 // TODO Auto-generated catch block
315 e.printStackTrace();
316 } catch (NoSuchMethodException e) {
317 // TODO Auto-generated catch block
318 e.printStackTrace();
319 }
320 }
321
322 /**
323 * Extracts a list of attributes from the given Item. Any method that
324 * starts with <code>get</code>, takes no arguments and is not found in
325 * the Ignore list will be run, All the attributes are then put into a Text
326 * Item of the form <Name>:<Value> If the value returned by the get method
327 * is null, then the attribute will not be included, unless the name of the
328 * method is found in the AllowNull list.
329 *
330 * @param toExtract
331 * The Object from which to extract the attributes
332 * @return A Text Item containing the extracted Attributes.
333 */
334 public static Item extractAttributes(Object toExtract) {
335
336 // System.out.println(toExtract);
337
338 if (toExtract == null) {
339 return null;
340 }
341
342 // Ensure the lists are populated
343 ensureReady();
344
345 AttributeSet attribSet = null;
346 if(toExtract instanceof Frame) {
347 attribSet = _FrameAttrib;
348 } else if(toExtract instanceof Item) {
349 attribSet = _Attrib;
350 } else {
351 throw new IncorrectTypeException("toExtract", "Item | Frame");
352 }
353
354 // StringBuffer to store all the extracted Attribute:Value pairs
355 StringBuffer attributes = new StringBuffer();
356
357 // iterate through the list of methods
358 for (String prop : attribSet.keys) {
359
360 Attribute a = attribSet.get(prop);
361 // Make sure the classes of the methods match the item
362 if (a != null && a.getter != null && a.getter.getDeclaringClass().isAssignableFrom(toExtract.getClass())) {
363
364 try {
365 String s = getValue(prop, a, toExtract, true);
366 if (s == null)
367 continue;
368 // Append the attributes
369 attributes.append(a.displayName)
370 .append(AttributeValuePair.SEPARATOR_STRING)
371 .append(s).append('\n');
372 } catch (Exception e) {
373 // TODO Auto-generated catch block
374 e.printStackTrace();
375 }
376 }
377 }
378
379 // if no attributes were extracted
380 if (attributes.length() <= 0)
381 return null;
382
383 while (attributes.charAt(attributes.length() - 1) == '\n')
384 attributes.delete(attributes.length() - 1, attributes.length());
385
386 // create the text Item
387 Frame current = DisplayIO.getCurrentFrame();
388 Item attribs = current.getStatsTextItem(attributes.toString());
389 return attribs;
390 }
391
392 /**
393 * Gets a string form of the value for a given item get method.
394 * @param method
395 * @param item
396 * @param ignore true if the attributes in the IGNORE list should be ignored
397 * @return
398 */
399 private static String getValue(String name, Attribute a, Object item, boolean ignore) {
400 // assert(method.getName().startsWith("get"));
401
402 Object o = null;
403 try {
404 o = a.getter.invoke(item, (Object[]) null);
405 } catch (IllegalArgumentException e) {
406 e.printStackTrace();
407 return null;
408 } catch (IllegalAccessException e) {
409 e.printStackTrace();
410 return null;
411 } catch (InvocationTargetException e) {
412 e.printStackTrace();
413 return null;
414 }
415
416 if (o == null) {
417 // methods that return null are only included if they
418 // are in the AllowNull list
419 if (_AllowNull.contains(a.getter)) {
420 if (name.equals("color"))
421 o = "default";
422 else if (name.equals("backgroundcolor"))
423 o = "transparent";
424 else if (name.equals("foregroundcolor"))
425 o = "auto";
426 else
427 o = "";
428 } else {
429 return null;
430 }
431 }
432 // skip methods that are in the ignore lists
433 if (ignore && _IgnoreGet.contains(name)) {
434 return null;
435 }
436
437 if (o instanceof Integer) {
438 Integer i = (Integer) o;
439 if (i == Item.DEFAULT_INTEGER)
440 return null;
441 if (a.getter.getName().endsWith("Justification")
442 && ((Justification) o).toString() != null)
443 o = ((Justification) o).toString();
444 // -1 indicates default value
445 else
446 o = i;
447 } else if (o instanceof Float) {
448 if (((Float) o) < -0.0001)
449 return null;
450 // Null indicates default
451 // o = Math.round((Float) o);
452 } else if (o instanceof Double) {
453 // -1 indicates default value
454 if (((Double) o) < 0.0001)
455 return null;
456 } else if (o instanceof Color) {
457 // converts the color to the Expeditee code
458 o = Conversion.getExpediteeColorCode((Color) o);
459 if (o == null)
460 return null;
461 } else if (o instanceof Point) {
462 Point p = (Point) o;
463 o = Math.round(p.getX()) + " " + Math.round(p.getY());
464 } else if (o instanceof Font) {
465 Font f = (Font) o;
466
467 String s = f.getName() + "-";
468 if (f.isPlain())
469 s += "Plain";
470
471 if (f.isBold())
472 s += "Bold";
473
474 if (f.isItalic())
475 s += "Italic";
476
477 s += "-" + f.getSize();
478 o = s;
479 } else if (o instanceof Text) {
480 o = ((Text) o).getFirstLine();
481 } else if (o instanceof List) {
482 List list = (List) o;
483 StringBuffer sb = new StringBuffer();
484 for (Object ob : list)
485 // TODO check that this works ok
486 if (sb.length() == 0) {
487 sb.append(ob);
488 } else {
489 sb.append('\n').append(a.displayName).append(AttributeValuePair.SEPARATOR_STRING).append(ob);
490 }
491 return sb.toString();
492 } else if (o instanceof int[]) {
493 StringBuffer sb = new StringBuffer();
494 int[] values = (int[]) o;
495 for (int i = 0; i < values.length; i++) {
496 sb.append(values[i]).append(' ');
497 }
498 sb.deleteCharAt(sb.length() - 1);
499 o = sb.toString();
500 } else if (o instanceof Boolean) {
501 // true is the default for boolean values
502 if (((Boolean) o).booleanValue())
503 return null;
504 }
505 return o.toString();
506 }
507
508 /**
509 * Attempts to set the attribute in the given attribute: value pair. The
510 * value string should be formatted as follows:
511 * <code> Attribute: Value </code> Multiple values can be used if they are
512 * separated by spaces
513 *
514 * @param toSet
515 * The Item or Frame to set the attribute of
516 * @param attribs
517 * The Text item that contains the list of attributes to set
518 * @return True if the attribute(s) were sucessfully set, false otherwise
519 */
520 public static boolean setAttribute(Object toSet, Text attribs) {
521 return setAttribute(toSet, attribs, 1);
522 }
523
524 public static boolean setAttribute(Object toSet, Text attribs,
525 int minAttributeLength) {
526 // error checking
527 if (toSet == null || attribs == null)
528 return false;
529
530 ensureReady();
531
532 AttributeSet attribSet = null;
533 if(toSet instanceof Frame) {
534 attribSet = _FrameAttrib;
535 } else if(toSet instanceof Item) {
536 attribSet = _Attrib;
537 } else {
538 throw new IncorrectTypeException("toExtract", "Item | Frame");
539 }
540
541 // if(attribs.isAnnotation())
542 // return false;
543
544 // get the list of attribute: value pairs
545 List<String> values = attribs.getTextList();
546 // if no pairs exist, we are done
547 if (values == null || values.size() == 0) {
548 return false;
549 }
550
551 // loop through all attribute: value pairs
552 for (int i = 0; i < values.size(); i++) {
553 AttributeValuePair avp = new AttributeValuePair(values.get(i),
554 false);
555
556 // If the first is not an attribute value pair then don't do
557 // attribute merging
558 if (!avp.hasAttribute()
559 || avp.getAttribute().length() < minAttributeLength)
560 return false;
561
562 // check if the next string is another attribute to merge or a
563 // continuation
564 for (; i < values.size() - 1; i++) {
565 AttributeValuePair nextAvp = new AttributeValuePair(values
566 .get(i + 1), false);
567
568 // if the next String has a colon, then it may be another
569 // attribute
570 if (nextAvp.hasAttribute()) {
571 // if the attribute is the same as v, then it is a
572 // continuation
573 if (nextAvp.getAttribute().equals(avp.getAttribute())) {
574 // strip the attribute from next
575 avp.appendValue(nextAvp.getValue() + "\n");
576
577 // if the attribute is not the same, then it may be a
578 // new method
579 } else {
580 break;
581 }
582 }
583
584 // v.append("\n").append(next);
585 }
586
587 try {
588 if (!setAttribute(toSet, avp, values.size() > 1)) {
589
590 String stripped = avp.getAttribute();
591 if (!avp.hasPair()) {
592 // This happens when there is an attribute at the start
593 // Then a bunch of plain text
594 return false;
595 } else if (_IgnoreSet.contains(stripped)) {
596 return false;
597 } else {
598 Attribute a = attribSet.get(stripped);
599 if(a == null || a.setter == null) {
600 return false;
601 }
602 String types = "";
603 for (Class<?> c : a.setter.getParameterTypes()) {
604 types += c.getSimpleName() + " ";
605 }
606 MessageBay.warningMessage("Wrong arguments for: '"
607 + avp.getAttribute() + "' expecting "
608 + types.trim() + " found '" + avp.getValue() + "'");
609 }
610 }
611 } catch (AttributeException e) {
612 MessageBay.errorMessage(e.getMessage());
613 }
614 }
615
616 return true;
617 }
618
619 /**
620 * Sets a single attrubute of a frame or item.
621 *
622 * @param toSet
623 * @param avp
624 * @param isAttributeList
625 * some properties are ignored when attribute list are injected
626 * into an item. These properties are ignored if this param is
627 * true
628 * @return
629 * @throws NoSuchAttributeException
630 */
631 private static boolean setAttribute(Object toSet, AttributeValuePair avp,
632 boolean isAttributeList) throws AttributeException {
633
634 assert (avp.hasAttribute());
635
636 // separate attribute and value from string
637 String attribute = avp.getAttribute().toLowerCase();
638
639 String value = avp.getValue();
640 assert (value != null);
641
642 AttributeSet attribSet = null;
643 if(toSet instanceof Frame) {
644 attribSet = _FrameAttrib;
645 } else if(toSet instanceof Item) {
646 attribSet = _Attrib;
647 } else {
648 throw new IncorrectTypeException("toExtract", "Item | Frame");
649 }
650
651 // Some properties are ignored when multiple attributes are being set on
652 // an item at the same time
653 if (isAttributeList && _IgnoreSet.contains(attribute)) {
654 // System.out.println("Attribute ignored: " + attribute);
655 return true;
656 }
657
658 // Separate multiple values if required
659
660 Attribute a = attribSet.get(attribute);
661 // if this is not the name of a method, it may be the name of an agent
662 if (a == null || a.setter == null) {
663 // System.out.println("Attrib not found for: " + attribute);
664 return false;
665 }
666
667 // if there are duplicate methods with the same name
668 List<Method> possibles = new LinkedList<Method>();
669 if (a.setter.getDeclaringClass().isInstance(toSet))
670 possibles.add(a.setter);
671 int i = 0;
672 while (attribSet.containsKey(attribute + i)) {
673 Method m = attribSet.get(attribute + i).setter;
674 if(m == null) {
675 break;
676 }
677 if (m.getDeclaringClass().isAssignableFrom(toSet.getClass())) {
678 possibles.add(m);
679 }
680 i++;
681 }
682
683 for (Method possible : possibles) {
684 Object current = invokeAttributeGetMethod(avp.getAttribute(), toSet);
685 // find the corresponding get method for this set method
686 // and get the current value of the attribute
687
688 try {
689 Object[] params = Conversion.Convert(possible, value, current);
690
691 try {
692 possible.invoke(toSet, params);
693 return true;
694 } catch (IllegalArgumentException e) {
695 // TODO Auto-generated catch block
696 e.printStackTrace();
697 } catch (IllegalAccessException e) {
698 // TODO Auto-generated catch block
699 e.printStackTrace();
700 } catch (InvocationTargetException e) {
701 MessageBay.displayMessage(toSet.getClass().getSimpleName()
702 + " type does not support that attribute.");
703 // e.printStackTrace();
704 }
705 } catch (NumberFormatException e) {
706
707 }
708 }
709
710 if(possibles.size() == 0){
711 if(invokeAttributeGetMethod(avp.getAttribute(), toSet) == null)
712 throw new NoSuchAttributeException(avp.getAttribute(), toSet.getClass().getSimpleName());
713 throw new ReadOnlyAttributeException(avp.getAttribute(), toSet.getClass().getSimpleName());
714 }
715
716 return false;
717 }
718
719 private static Object invokeAttributeGetMethod(String name, Object toSet) {
720
721 AttributeSet attribSet = null;
722 if(toSet instanceof Frame) {
723 attribSet = _FrameAttrib;
724 } else if(toSet instanceof Item) {
725 attribSet = _Attrib;
726 } else {
727 throw new IncorrectTypeException("toExtract", "Item | Frame");
728 }
729
730 Attribute a = attribSet.get(name.toLowerCase());
731 if(a == null) {
732 return null;
733 }
734 try {
735 return a.getter.invoke(toSet);
736 } catch (Exception e) {
737 e.printStackTrace();
738 }
739 return null;
740 }
741
742 /**
743 * Replaces the current value for the text item with the new value.
744 *
745 * @param text
746 * the item whos value is to be changed
747 * @param newValue
748 * the new value for the item
749 */
750 public static void replaceValue(Text text, String newValue) {
751 assert (newValue != null);
752
753 AttributeValuePair avp = new AttributeValuePair(text.getText());
754
755 if (avp.getAttribute() == null) {
756 avp.setAttribute(avp.getValue());
757 }
758 avp.setValue(newValue);
759 text.setText(avp.toString());
760 }
761
762 public static String getAttribute(Item item, String attribute) {
763
764 // ensure the lists are populated
765 ensureReady();
766
767 // separate attribute and value from string
768 String lowerAttribute = attribute.trim().toLowerCase();
769
770 Attribute a = _Attrib.get(lowerAttribute);
771 if(a == null) {
772 MessageBay.errorMessage("Could no extract unknown attribute value: " + attribute);
773 return null;
774 }
775 return a.displayName + AttributeValuePair.SEPARATOR_STRING + getValue(lowerAttribute, a, item, false);
776 }
777}
Note: See TracBrowser for help on using the repository browser.