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

Last change on this file since 1296 was 1296, checked in by bln4, 5 years ago

Added placeholders as a thing for text items. You can now provide default text for a text item. Inject the property 'Placeholder: <text>' were <text> is the placeholder text. When the placeholder is being used, the font color alpha is reduced.

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