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

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

EXA save format working + automatically converting save files to it's own format
Pictures are no longer XRayables, working fine except for a bug with cropping, and some problems with the default image that I need to fix.
FramePicture/FrameImage/FrameBitmap are disabled because they need to be changed to work with the modified Picture format but I don't know what they do so couldn't test them (will need to look into fixing that)

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