01: /*
02: * @(#)XmlUtils.java 5/8/2005
03: *
04: * Copyright 2002 - 2005 JIDE Software Inc. All rights reserved.
05: */
06: package com.jidesoft.converter;
07:
08: import com.jidesoft.swing.JideSwingUtilities;
09: import org.w3c.dom.Element;
10: import org.w3c.dom.NamedNodeMap;
11: import org.w3c.dom.Node;
12:
13: import java.lang.reflect.InvocationTargetException;
14: import java.lang.reflect.Method;
15: import java.lang.reflect.Modifier;
16: import java.util.HashMap;
17: import java.util.regex.Matcher;
18: import java.util.regex.Pattern;
19:
20: /**
21: */
22: public class XmlUtils {
23:
24: private static final Pattern mutatorPattern = Pattern
25: .compile("^set([A-Z0-9_][A-Za-z0-9_]*)$");
26:
27: private final static int MUTATOR = 2;
28: private final static int ANYOTHER = 0;
29:
30: public static void readElement(Object object, Element element) {
31: if (object == null) {
32: return;
33: }
34:
35: NamedNodeMap map = element.getAttributes();
36: HashMap<String, String> properties = new HashMap<String, String>();
37: for (int i = 0; i < map.getLength(); i++) {
38: Node node = map.item(i);
39: String name = node.getNodeName();
40: properties.put(name, node.getNodeValue());
41: }
42:
43: Method[] methods = object.getClass().getMethods();
44: for (Method method : methods) {
45: Matcher matcher;
46: int methodType = ANYOTHER;
47: Class<?> type = null;
48:
49: if (!Modifier.isPublic(method.getModifiers())
50: || Modifier.isStatic(method.getModifiers())) {
51: continue;
52: }
53:
54: if ((matcher = mutatorPattern.matcher(method.getName()))
55: .matches()) {
56: if (method.getReturnType() == void.class
57: && method.getParameterTypes().length == 1) {
58: methodType = MUTATOR;
59: type = method.getParameterTypes()[0];
60: }
61: }
62:
63: if (methodType == MUTATOR) {
64: String name = matcher.group(1);
65: if (name.equals("Class")) // don't use getClass()
66: continue;
67: name = name.substring(0, 1).toLowerCase()
68: + name.substring(1);
69: Object value = properties.get(name);
70: if (value == null) {
71: continue;
72: }
73:
74: try {
75: method.invoke(object, ObjectConverterManager
76: .fromString((String) value, type));
77: } catch (IllegalAccessException e) {
78: throw new RuntimeException(e);
79: } catch (InvocationTargetException e) {
80: JideSwingUtilities.ignoreException(e);
81: }
82: }
83: }
84: }
85: }
|