| 1 |
/* |
| 2 |
* @(#)XmlUtils.java 5/8/2005 |
| 3 |
* |
| 4 |
* Copyright 2002 - 2005 JIDE Software Inc. All rights reserved. |
| 5 |
*/ |
| 6 |
package com.jidesoft.converter; |
| 7 |
|
| 8 |
import com.jidesoft.swing.JideSwingUtilities; |
| 9 |
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 = |
| 25 |
Pattern.compile("^set([A-Z0-9_][A-Za-z0-9_]*)$"); |
| 26 |
|
| 27 |
private static final int MUTATOR = 2; |
| 28 |
private static final 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()) || Modifier.isStatic(method.getModifiers())) { |
| 50 |
continue; |
| 51 |
} |
| 52 |
|
| 53 |
if ((matcher = mutatorPattern.matcher(method.getName())).matches()) { |
| 54 |
if (method.getReturnType() == void.class && method.getParameterTypes().length == 1) { |
| 55 |
methodType = MUTATOR; |
| 56 |
type = method.getParameterTypes()[0]; |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
if (methodType == MUTATOR) { |
| 61 |
String name = matcher.group(1); |
| 62 |
if (name.equals("Class")) // don't use getClass() |
| 63 |
continue; |
| 64 |
name = name.substring(0, 1).toLowerCase() + name.substring(1); |
| 65 |
Object value = properties.get(name); |
| 66 |
if (value == null) { |
| 67 |
continue; |
| 68 |
} |
| 69 |
|
| 70 |
try { |
| 71 |
method.invoke(object, ObjectConverterManager.fromString((String) value, type)); |
| 72 |
} |
| 73 |
catch (IllegalAccessException e) { |
| 74 |
throw new RuntimeException(e); |
| 75 |
} |
| 76 |
catch (InvocationTargetException e) { |
| 77 |
JideSwingUtilities.ignoreException(e); |
| 78 |
} |
| 79 |
} |
| 80 |
} |
| 81 |
} |
| 82 |
} |