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

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

Items can now have an encryption label. New functionality using this property incoming.

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