/** * Searches the children of an element looking for a Text node. If it finds one, it returns it. * * @param element The element whose children will be searched * @return The text for the element, or null if there is none */ public static String getElementString(Element element) { NodeList nodes = element.getChildNodes(); int numNodes = nodes.getLength(); for (int i = 0; i < numNodes; i++) { Node node = nodes.item(i); if (node instanceof Text) { return ((Text) node).getData(); } } return null; }
/** * Reads the children of an XML element and matches them to properties of a bean. * * @param ob The bean to receive the values * @param element The element the corresponds to the bean * @throws IOException If there is an error reading the document */ public void readObject(Object ob, Element element) throws IOException { // If the object is null, skip the element if (ob == null) { return; } try { BeanInfo info = (BeanInfo) beanCache.get(ob.getClass()); if (info == null) { // Get the bean info for the object info = Introspector.getBeanInfo(ob.getClass(), Object.class); beanCache.put(ob.getClass(), info); } // Get the object's properties PropertyDescriptor[] props = info.getPropertyDescriptors(); // Get the attributes of the node NamedNodeMap attrs = element.getAttributes(); // Get the children of the XML element NodeList nodes = element.getChildNodes(); int numNodes = nodes.getLength(); for (int i = 0; i < props.length; i++) { // Treat indexed properties a little differently if (props[i] instanceof IndexedPropertyDescriptor) { readIndexedProperty(ob, (IndexedPropertyDescriptor) props[i], nodes, attrs); } else { readProperty(ob, props[i], nodes, attrs); } } } catch (IntrospectionException exc) { throw new IOException( "Error getting bean info for " + ob.getClass().getName() + ": " + exc.toString()); } }
private Object deserialize(Node node, boolean setProperty, boolean popBean) throws Exception { Object object = null; currentType = null; currentNode = node; currentName = node.getNodeName(); boolean isNull = false; NamedNodeMap attrs = node.getAttributes(); String arrayType = null; for (int i = 0; i < attrs.getLength(); i++) { String nodeName = attrs.item(i).getNodeName(); String nodeValue = attrs.item(i).getNodeValue(); if (nodeName.equals(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE)) currentType = new StringBuffer(nodeValue).delete(0, nodeValue.indexOf(':') + 1).toString(); else if (nodeName.equals( NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":" + Constants.ATTR_ARRAY_TYPE)) arrayType = new StringBuffer(nodeValue).delete(0, nodeValue.indexOf(':') + 1).toString(); else if (nodeName.equals(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null")) isNull = nodeValue.equals("true"); } Class cls = null; if (currentType != null) cls = getXsdTypeClass(currentType); // Handle array, Vector, ArrayList, LinkedList, Hashtable, // Properties, and HashMap data types if ((cls != null) && ((cls == java.lang.reflect.Array.class) || (cls == Vector.class) || (cls == ArrayList.class) || (cls == LinkedList.class) || (cls == Hashtable.class) || (cls == Properties.class) || (cls == HashMap.class) || (cls == SortedMap.class))) { parentNode = currentNode; String name = node.getNodeName(); // Handle arrays if (cls == java.lang.reflect.Array.class) { int a = arrayType.indexOf("["); int b = arrayType.indexOf("]"); String s = arrayType.substring(a + 1, b); int arrayLen = Integer.valueOf(s).intValue(); arrayType = arrayType.substring(0, a); // check if the array element is a standard Java class Class arrayClass = getXsdTypeClass(arrayType); // otherwise try to get the class of the bean if (arrayClass == null) arrayClass = getClassOfBean((ClassLoader) classLoaderStrategy, arrayType); object = java.lang.reflect.Array.newInstance(arrayClass, arrayLen); } else { // Construct the list or map type Constructor ct = cls.getConstructor((Class[]) null); object = ct.newInstance((Object[]) null); } // deserialize the elements of the array, list, or map NodeList childNodes = node.getChildNodes(); int arrayIndex = -1; Node childNode = null; Object nodeObj = null; for (int i = 0; i < childNodes.getLength(); i++) { childNode = childNodes.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE) { if ((cls == java.lang.reflect.Array.class) || (cls == Vector.class) || (cls == ArrayList.class) || (cls == LinkedList.class)) { nodeObj = deserialize(childNode, false, true); if (nodeObj != null) { if (cls == java.lang.reflect.Array.class) java.lang.reflect.Array.set(object, ++arrayIndex, nodeObj); else ((List) object).add(nodeObj); } } else if ((cls == Hashtable.class) || (cls == Properties.class) || (cls == HashMap.class) || (cls == SortedMap.class)) { if (childNode.getLocalName().equals("item")) { NodeList htNodes = childNode.getChildNodes(); if (htNodes.getLength() == 2) { Object hashKey = deserialize(htNodes.item(0), false, false); Object hashValue = deserialize(htNodes.item(1), false, true); ((Map) object).put(hashKey, hashValue); } } } } } setBeanProperty(name, object); // Handle everything else (primitives & POJOs) } else { // recurse on each of the child nodes NodeList childNodes = node.getChildNodes(); if ((childNodes != null) && (childNodes.getLength() > 0)) { for (int i = 0; i < childNodes.getLength(); i++) { Node childNode = childNodes.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE) { if (currentType != null) createObject( node, currentName, currentPackage, currentType, childNode.getNodeValue(), setProperty); parentNode = node; object = deserialize(childNode, true, true); } else if ((childNode.getNodeType() == Node.TEXT_NODE) && (currentType != null)) { object = createObject( node, currentName, currentPackage, currentType, childNode.getNodeValue(), setProperty); } currentType = null; } } else { if (!isNull) object = createObject(node, currentName, currentPackage, currentType, null, setProperty); } if (node.getParentNode() != parentNode) { parentNode = node.getParentNode(); if (popBean) { Object bean = popBeanOffStack(); if (bean != null) object = bean; } } } return object; }
/** * Reads XML element(s) into an indexed bean property by first locating the XML element(s) * corresponding to this property. * * @param ob The bean whose property is being set * @param desc The property that will be set * @param nodes The list of XML items that may contain the property * @throws IOException If there is an error reading the document */ public void readIndexedProperty( Object ob, IndexedPropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs) throws IOException { // Create a vector to hold the property values Vector v = new Vector(); int numAttrs = attrs.getLength(); for (int i = 0; i < numAttrs; i++) { // See if this attribute matches the property name if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) { // Get the property value Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue()); if (obValue != null) { // Add the value to the list of values to be set v.addElement(obValue); } } } int numNodes = nodes.getLength(); for (int i = 0; i < numNodes; i++) { Node node = nodes.item(i); // Skip non-element nodes if (!(node instanceof Element)) continue; Element element = (Element) node; // See if this element tag matches the property name if (namesMatch(desc.getName(), element.getTagName())) { // Get the property value Object obValue = getObjectValue(desc, element); if (obValue != null) { // Add the value to the list of values to be set v.addElement(obValue); } } } // Get the method used to set the property value Method setter = desc.getWriteMethod(); // If this property has no setter, don't write it if (setter == null) return; // Create a new array of property values Object propArray = Array.newInstance(desc.getPropertyType().getComponentType(), v.size()); // Copy the vector into the array v.copyInto((Object[]) propArray); try { // Store the array of property values setter.invoke(ob, new Object[] {propArray}); } catch (InvocationTargetException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } }
/** * Reads an XML element into a bean property by first locating the XML element corresponding to * this property. * * @param ob The bean whose property is being set * @param desc The property that will be set * @param nodes The list of XML items that may contain the property * @throws IOException If there is an error reading the document */ public void readProperty(Object ob, PropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs) throws IOException { int numAttrs = attrs.getLength(); for (int i = 0; i < numAttrs; i++) { // See if the attribute name matches the property name if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) { // Get the method used to set this property Method setter = desc.getWriteMethod(); // If this object has no setter, don't bother writing it if (setter == null) continue; // Get the value of the property Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue()); if (obValue != null) { try { // Set the property value setter.invoke(ob, new Object[] {obValue}); } catch (InvocationTargetException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } } return; } } int numNodes = nodes.getLength(); Vector arrayBuild = null; for (int i = 0; i < numNodes; i++) { Node node = nodes.item(i); // If this node isn't an element, skip it if (!(node instanceof Element)) continue; Element element = (Element) node; // See if the tag name matches the property name if (namesMatch(desc.getName(), element.getTagName())) { // Get the method used to set this property Method setter = desc.getWriteMethod(); // If this object has no setter, don't bother writing it if (setter == null) continue; // Get the value of the property Object obValue = getObjectValue(desc, element); // 070201 MAW: Modified from change submitted by Steve Poulson if (setter.getParameterTypes()[0].isArray()) { if (arrayBuild == null) { arrayBuild = new Vector(); } arrayBuild.addElement(obValue); // 070201 MAW: Go ahead and read through the rest of the nodes in case // another one matches the array. This has the effect of skipping // over the "return" statement down below continue; } if (obValue != null) { try { // Set the property value setter.invoke(ob, new Object[] {obValue}); } catch (InvocationTargetException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException( "Error setting property " + desc.getName() + ": " + exc.toString()); } } return; } } // If we build a vector of array members, convert the vector into // an array and save it in the property if (arrayBuild != null) { // Get the method used to set this property Method setter = desc.getWriteMethod(); if (setter == null) return; Object[] obValues = (Object[]) Array.newInstance(desc.getPropertyType(), arrayBuild.size()); arrayBuild.copyInto(obValues); try { setter.invoke(ob, new Object[] {obValues}); } catch (InvocationTargetException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } catch (IllegalAccessException exc) { throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString()); } return; } }