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

Last change on this file since 1200 was 1200, checked in by bln4, 6 years ago

org.expeditee.auth.gio.EncryptedExpReader ->
org.expeditee.auth.gio.EncryptedExpWriter ->
org.expeditee.io.DefaultFrameReader ->
org.expeditee.io.DefaultFrameWriter ->
org.expeditee.io.ExpReader ->
org.expeditee.io.ExpWriter ->

The beginnings of a authentication system for Expeditee. Frame files (.exp) can now be encrypted with a password. A login system is being developed to accompany this.


org.expeditee.gui.AttributeUtils ->
org.expeditee.gui.Frame ->
org.expeditee.gui.FrameUtils ->
org.expeditee.items.Item ->
org.expeditee.items.PermissionPair ->
org.expeditee.items.Text ->

As part of the development the login screen. Modifications to Text Items have been made. New properties are 'Mask' and 'MinWidth'. Mask allows you to set a character to use as...a mask...for example, a password field using '*'. MinWidth allows you to specify a minimum width for text boxes. A text box with a minimum width never shrinks below this width; even when it has no content.

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