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

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

Fixed bug for when there are no surrogates left for a primary.

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