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

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

Implemented EncryptionPermission attribute.

EncryptionPermission is a triple. When specifying the value, if you do not specify the 2nd (group) or 3rd (other) then they default to permission level zero.

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