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

Last change on this file since 1513 was 1513, checked in by bnemhaus, 4 years ago

You now have the ability to anchor Items to the center of the frame. AnchorCenterX: 0 will anchor a item directly to the vertical center of the frame. AnchorCenterY: 0 to the horizontal center of the frame. Negative numbers go left/up from the center, positive numbers right/down.

More work to come to deal with connected items such as rectangles made up on connected dots.

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