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

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

org.expeditee.auth.EncryptedExpReader ->
org.expeditee.auth.EncryptedExpWriter ->
Actions ->
AttributeUtils ->
Frame ->
FrameIO ->
UserSettings ->

Changed how reading and writing encrypted files worked. A Frame attribute is now consulted to determine what to use as key for encryption. The 'profile' attribute setting is used to signal that the users personal aes key is used. Further enhancement will mean that other labels will be able to be used.


Actions ->

MailMode action now consults the database to reaquire the mail.

File size: 30.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.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
318 // Aliases for attribute setting
319 _Attrib.alias("pos", "position");
320 _Attrib.alias("p", "position");
321 _Attrib.alias("xy", "position");
322 _Attrib.alias("a", "action");
323 _Attrib.alias("d", "data");
324 _Attrib.alias("f", "formula");
325 _Attrib.alias("font", "family");
326 _Attrib.alias("s", "size");
327 _Attrib.alias("l", "link");
328 _Attrib.alias("at", "anchortop");
329 _Attrib.alias("ab", "anchorbottom");
330 _Attrib.alias("al", "anchorleft");
331 _Attrib.alias("ar", "anchorright");
332 _Attrib.alias("t", "thickness");
333 // _Attrib.alias("c", "color"); // breaks circle creation
334 _Attrib.alias("bgc", "backgroundcolor");
335 _Attrib.alias("bc", "bordercolor");
336 _Attrib.alias("fc", "fillcolor");
337 _Attrib.alias("gc", "gradientcolor");
338 _Attrib.alias("ga", "gradientangle");
339 _Attrib.alias("fp", "fillpattern");
340 _Attrib.alias("lm", "linkmark");
341 _Attrib.alias("am", "actionmark");
342 _Attrib.alias("dt", "dottype");
343 _Attrib.alias("fill", "filled");
344 _Attrib.alias("lp", "linepattern");
345 _Attrib.alias("lf", "linkframeset");
346 _Attrib.alias("lt", "linktemplate");
347 _Attrib.alias("face", "fontstyle");
348 _Attrib.alias("j", "justification");
349 _Attrib.alias("w", "width");
350 _Attrib.alias("mw", "minwidth");
351 _Attrib.alias("as", "autostamp");
352 } catch (SecurityException e) {
353 // TODO Auto-generated catch block
354 e.printStackTrace();
355 } catch (NoSuchMethodException e) {
356 // TODO Auto-generated catch block
357 e.printStackTrace();
358 }
359 }
360
361 /**
362 * Extracts a list of attributes from the given Item. Any method that
363 * starts with <code>get</code>, takes no arguments and is not found in
364 * the Ignore list will be run, All the attributes are then put into a Text
365 * Item of the form <Name>:<Value> If the value returned by the get method
366 * is null, then the attribute will not be included, unless the name of the
367 * method is found in the AllowNull list.
368 *
369 * @param toExtract
370 * The Object from which to extract the attributes
371 * @return A Text Item containing the extracted Attributes.
372 */
373 public static Item extractAttributes(Object toExtract) {
374
375 // System.out.println(toExtract);
376
377 if (toExtract == null) {
378 return null;
379 }
380
381 // Ensure the lists are populated
382 ensureReady();
383
384 AttributeSet attribSet = null;
385 if(toExtract instanceof Frame) {
386 attribSet = _FrameAttrib;
387 } else if(toExtract instanceof Item) {
388 attribSet = _Attrib;
389 } else {
390 throw new IncorrectTypeException("toExtract", "Item | Frame");
391 }
392
393 // StringBuffer to store all the extracted Attribute:Value pairs
394 StringBuffer attributes = new StringBuffer();
395
396 // iterate through the list of methods
397 for (String prop : attribSet.keys) {
398
399 Attribute a = attribSet.get(prop);
400 // Make sure the classes of the methods match the item
401 if (a != null && a.getter != null && a.getter.getDeclaringClass().isAssignableFrom(toExtract.getClass())) {
402 try {
403 String s = getValue(prop, a, toExtract, true);
404 if (s == null) {
405 continue;
406 }
407 // Append the attributes
408 attributes.append(a.displayName)
409 .append(AttributeValuePair.SEPARATOR_STRING)
410 .append(s).append('\n');
411 } catch (Exception e) {
412 // TODO Auto-generated catch block
413 e.printStackTrace();
414 }
415 }
416 }
417
418 // if no attributes were extracted
419 if (attributes.length() <= 0) {
420 return null;
421 }
422
423 while (attributes.charAt(attributes.length() - 1) == '\n') {
424 attributes.delete(attributes.length() - 1, attributes.length());
425 }
426
427 // create the text Item
428 Frame current = DisplayController.getCurrentFrame();
429 Item attribs = current.getStatsTextItem(attributes.toString());
430 return attribs;
431 }
432
433 /**
434 * Gets a string form of the value for a given item get method.
435 * @param method
436 * @param item
437 * @param ignore true if the attributes in the IGNORE list should be ignored
438 * @return
439 */
440 private static String getValue(String name, Attribute a, Object item, boolean ignore) {
441 // assert(method.getName().startsWith("get"));
442
443 Object o = null;
444 try {
445 o = a.getter.invoke(item, (Object[]) null);
446 } catch (IllegalArgumentException e) {
447 e.printStackTrace();
448 return null;
449 } catch (IllegalAccessException e) {
450 e.printStackTrace();
451 return null;
452 } catch (InvocationTargetException e) {
453 e.printStackTrace();
454 return null;
455 }
456
457 if (o == null) {
458 // methods that return null are only included if they
459 // are in the AllowNull list
460 if (_AllowNull.contains(a.getter)) {
461 if (name.equals("color")) {
462 o = "default";
463 } else if (name.equals("backgroundcolor")) {
464 o = "transparent";
465 } else if (name.equals("foregroundcolor")) {
466 o = "auto";
467 } else {
468 o = "";
469 }
470 } else {
471 return null;
472 }
473 }
474 // skip methods that are in the ignore lists
475 if (ignore && _IgnoreGet.contains(name)) {
476 return null;
477 }
478
479 if (o instanceof Integer) {
480 Integer i = (Integer) o;
481 if (i == Item.DEFAULT_INTEGER) {
482 return null;
483 }
484 if (a.getter.getName().endsWith("Justification")
485 && ((Justification) o).toString() != null) {
486 o = ((Justification) o).toString();
487 // -1 indicates default value
488 } else {
489 o = i;
490 }
491 } else if (o instanceof Float) {
492 if (((Float) o) < -0.0001)
493 {
494 return null;
495 // Null indicates default
496 // o = Math.round((Float) o);
497 }
498 } else if (o instanceof Double) {
499 // -1 indicates default value
500 if (((Double) o) < 0.0001) {
501 return null;
502 }
503 } else if (o instanceof Colour) {
504 // converts the color to the Expeditee code
505 o = Conversion.getExpediteeColorCode((Colour) o);
506 if (o == null) {
507 return null;
508 }
509 } else if (o instanceof Point) {
510 Point p = (Point) o;
511 o = Math.round(p.getX()) + " " + Math.round(p.getY());
512 } else if (o instanceof Font) {
513 Font f = (Font) o;
514
515 String s = f.getFamilyName() + "-";
516 if (f.isPlain()) {
517 s += "Plain";
518 }
519
520 if (f.isBold()) {
521 s += "Bold";
522 }
523
524 if (f.isItalic()) {
525 s += "Italic";
526 }
527
528 s += "-" + f.getSize();
529 o = s;
530 } else if (o instanceof Text) {
531 o = ((Text) o).getFirstLine();
532 } else if (o instanceof List) {
533 List list = (List) o;
534 StringBuffer sb = new StringBuffer();
535 for (Object ob : list) {
536 // TODO check that this works ok
537 if (sb.length() == 0) {
538 sb.append(ob);
539 } else {
540 sb.append('\n').append(a.displayName).append(AttributeValuePair.SEPARATOR_STRING).append(ob);
541 }
542 }
543 return sb.toString();
544 } else if (o instanceof int[]) {
545 StringBuffer sb = new StringBuffer();
546 int[] values = (int[]) o;
547 for (int i = 0; i < values.length; i++) {
548 sb.append(values[i]).append(' ');
549 }
550 sb.deleteCharAt(sb.length() - 1);
551 o = sb.toString();
552 } else if (o instanceof Boolean) {
553 // true is the default for boolean values
554 if (((Boolean) o).booleanValue()) {
555 return null;
556 }
557 }
558 return o.toString();
559 }
560
561 /**
562 * Attempts to set the attribute in the given attribute: value pair. The
563 * value string should be formatted as follows:
564 * <code> Attribute: Value </code> Multiple values can be used if they are
565 * separated by spaces
566 *
567 * @param toSet
568 * The Item or Frame to set the attribute of
569 * @param attribs
570 * The Text item that contains the list of attributes to set
571 * @return True if the attribute(s) were sucessfully set, false otherwise
572 */
573 public static boolean setAttribute(Object toSet, Text attribs) {
574 return setAttribute(toSet, attribs, 1);
575 }
576
577 public static boolean setAttribute(Object toSet, Text attribs,
578 int minAttributeLength) {
579 // error checking
580 if (toSet == null || attribs == null) {
581 return false;
582 }
583
584 ensureReady();
585
586 AttributeSet attribSet = null;
587 if(toSet instanceof Frame) {
588 attribSet = _FrameAttrib;
589 } else if(toSet instanceof Item) {
590 attribSet = _Attrib;
591 } else {
592 throw new IncorrectTypeException("toExtract", "Item | Frame");
593 }
594
595 // if(attribs.isAnnotation())
596 // return false;
597
598 // get the list of attribute: value pairs
599 List<String> values = attribs.getTextList();
600 // if no pairs exist, we are done
601 if (values == null || values.size() == 0) {
602 return false;
603 }
604
605 // loop through all attribute: value pairs
606 for (int i = 0; i < values.size(); i++) {
607 AttributeValuePair avp = new AttributeValuePair(values.get(i),
608 false);
609
610 // If the first is not an attribute value pair then don't do
611 // attribute merging
612 if (!avp.hasAttribute()
613 || avp.getAttribute().length() < minAttributeLength) {
614 return false;
615 }
616
617 // check if the next string is another attribute to merge or a
618 // continuation
619 for (; i < values.size() - 1; i++) {
620 AttributeValuePair nextAvp = new AttributeValuePair(values
621 .get(i + 1), false);
622
623 // if the next String has a colon, then it may be another
624 // attribute
625 if (nextAvp.hasAttribute()) {
626 // if the attribute is the same as v, then it is a
627 // continuation
628 if (nextAvp.getAttribute().equals(avp.getAttribute())) {
629 // strip the attribute from next
630 avp.appendValue(nextAvp.getValue() + "\n");
631
632 // if the attribute is not the same, then it may be a
633 // new method
634 } else {
635 break;
636 }
637 }
638
639 // v.append("\n").append(next);
640 }
641
642 try {
643 if (!setAttribute(toSet, avp, values.size() > 1)) {
644
645 String stripped = avp.getAttribute();
646 if (!avp.hasPair()) {
647 // This happens when there is an attribute at the start
648 // Then a bunch of plain text
649 return false;
650 } else if (_IgnoreSet.contains(stripped)) {
651 return false;
652 } else {
653 Attribute a = attribSet.get(stripped);
654 if(a == null || a.setter == null) {
655 return false;
656 }
657 String types = "";
658 for (Class<?> c : a.setter.getParameterTypes()) {
659 types += c.getSimpleName() + " ";
660 }
661 MessageBay.warningMessage("Wrong arguments for: '"
662 + avp.getAttribute() + "' expecting "
663 + types.trim() + " found '" + avp.getValue() + "'");
664 }
665 }
666 } catch (AttributeException e) {
667 MessageBay.errorMessage(e.getMessage());
668 }
669 }
670
671 return true;
672 }
673
674 /**
675 * Sets a single attribute of a frame or item.
676 *
677 * @param toSet
678 * @param avp
679 * @param isAttributeList
680 * some properties are ignored when attribute list are injected
681 * into an item. These properties are ignored if this param is
682 * true
683 * @return
684 * @throws NoSuchAttributeException
685 */
686 private static boolean setAttribute(Object toSet, AttributeValuePair avp,
687 boolean isAttributeList) throws AttributeException {
688
689 assert (avp.hasAttribute());
690
691 // separate attribute and value from string
692 String attribute = avp.getAttribute().toLowerCase();
693
694 String value = avp.getValue();
695 assert (value != null);
696
697 AttributeSet attribSet = null;
698 if(toSet instanceof Frame) {
699 attribSet = _FrameAttrib;
700 } else if(toSet instanceof Item) {
701 attribSet = _Attrib;
702 } else {
703 throw new IncorrectTypeException("toExtract", "Item | Frame");
704 }
705
706 // Some properties are ignored when multiple attributes are being set on
707 // an item at the same time
708 if (isAttributeList && _IgnoreSet.contains(attribute)) {
709 // System.out.println("Attribute ignored: " + attribute);
710 return true;
711 }
712
713 // Separate multiple values if required
714
715 Attribute a = attribSet.get(attribute);
716 // if this is not the name of a method, it may be the name of an agent
717 if (a == null || a.setter == null) {
718 // System.out.println("Attrib not found for: " + attribute);
719 return false;
720 }
721
722 // if there are duplicate methods with the same name
723 List<Method> possibles = new LinkedList<Method>();
724 if (a.setter.getDeclaringClass().isInstance(toSet)) {
725 possibles.add(a.setter);
726 }
727 int i = 0;
728 while (attribSet.containsKey(attribute + i)) {
729 Method m = attribSet.get(attribute + i).setter;
730 if(m == null) {
731 break;
732 }
733 if (m.getDeclaringClass().isAssignableFrom(toSet.getClass())) {
734 possibles.add(m);
735 }
736 i++;
737 }
738
739 for (Method possible : possibles) {
740 Object current = invokeAttributeGetMethod(avp.getAttribute(), toSet);
741 // find the corresponding get method for this set method
742 // and get the current value of the attribute
743
744 try {
745 Object[] params = Conversion.Convert(possible, value, current);
746
747 try {
748 possible.invoke(toSet, params);
749 return true;
750 } catch (IllegalArgumentException e) {
751 // TODO Auto-generated catch block
752 e.printStackTrace();
753 } catch (IllegalAccessException e) {
754 // TODO Auto-generated catch block
755 e.printStackTrace();
756 } catch (InvocationTargetException e) {
757 MessageBay.displayMessage(toSet.getClass().getSimpleName()
758 + " type does not support that attribute.");
759 // e.printStackTrace();
760 }
761 } catch (NumberFormatException e) {
762
763 }
764 }
765
766 if(possibles.size() == 0){
767 if(invokeAttributeGetMethod(avp.getAttribute(), toSet) == null) {
768 throw new NoSuchAttributeException(avp.getAttribute(), toSet.getClass().getSimpleName());
769 }
770 throw new ReadOnlyAttributeException(avp.getAttribute(), toSet.getClass().getSimpleName());
771 }
772
773 return false;
774 }
775
776 private static Object invokeAttributeGetMethod(String name, Object toSet) {
777
778 AttributeSet attribSet = null;
779 if(toSet instanceof Frame) {
780 attribSet = _FrameAttrib;
781 } else if(toSet instanceof Item) {
782 attribSet = _Attrib;
783 } else {
784 throw new IncorrectTypeException("toExtract", "Item | Frame");
785 }
786
787 Attribute a = attribSet.get(name.toLowerCase());
788 if(a == null) {
789 return null;
790 }
791 try {
792 return a.getter.invoke(toSet);
793 } catch (Exception e) {
794 e.printStackTrace();
795 }
796 return null;
797 }
798
799 /**
800 * Replaces the current value for the text item with the new value.
801 *
802 * @param text
803 * the item whos value is to be changed
804 * @param newValue
805 * the new value for the item
806 */
807 public static void replaceValue(Text text, String newValue) {
808 assert (newValue != null);
809
810 AttributeValuePair avp = new AttributeValuePair(text.getText());
811
812 if (avp.getAttribute() == null) {
813 avp.setAttribute(avp.getValue());
814 }
815 avp.setValue(newValue);
816 text.setText(avp.toString());
817 }
818
819 public static String getAttribute(Item item, String attribute) {
820
821 // ensure the lists are populated
822 ensureReady();
823
824 // separate attribute and value from string
825 String lowerAttribute = attribute.trim().toLowerCase();
826
827 Attribute a = _Attrib.get(lowerAttribute);
828 if(a == null) {
829 MessageBay.errorMessage("Could no extract unknown attribute value: " + attribute);
830 return null;
831 }
832 return a.displayName + AttributeValuePair.SEPARATOR_STRING + getValue(lowerAttribute, a, item, false);
833 }
834}
Note: See TracBrowser for help on using the repository browser.