public Object deserialize(String xml) throws Exception { DOMDocument domDocument = new DOMDocument(xml); root = domDocument.getRootNode(); if ((classPackage == null) || (rootPath == null)) classLoaderStrategy = getClassLoaderStrategy(root.lookupNamespaceURI(nsPrefix) + "." + root.getLocalName()); else { currentPackage = classPackage; classLoaderStrategy = ClassLoaderUtil.getClassLoader( ClassLoaderUtil.FILE_SYSTEM_CLASS_LOADER, new String[] {rootPath}); } return deserialize(root, true, true); }
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; }
private Object createObject( Node node, String name, String classPackage, String type, String value, boolean setProperty) { Bean parentBean = null; if (beansStack.size() > 0) parentBean = (Bean) beansStack.peek(); Object object = null; // param is either an XSD type or a bean, // check if it can be converted to an XSD type XSDatatype dt = null; try { dt = DatatypeFactory.getTypeByName(type); } catch (DatatypeException dte) { // the type is not a valid XSD data type } // convert null value to default if ((dt != null) && (value == null)) { Class objType = dt.getJavaObjectType(); if (objType == String.class) value = ""; else if ((objType == java.math.BigInteger.class) || (objType == Long.class) || (objType == Integer.class) || (objType == Short.class) || (objType == Byte.class)) value = "0"; else if ((objType == java.math.BigDecimal.class) || (objType == Double.class) || (objType == Float.class)) value = "0.0"; else if (objType == Boolean.class) value = "false"; else if (objType == java.util.Date.class) value = DateUtils.getCurrentDate(); else if (objType == java.util.Calendar.class) value = DateUtils.getCurrentDateTime(); } // check whether the type was converted to an XSD datatype if ((dt != null) && dt.isValid(value, null)) { // create and return an XSD Java object (e.g. String, Integer, Boolean, etc) object = dt.createJavaObject(value, null); if (object instanceof java.util.Calendar) { // check that the object is truly a Calendar // because DatatypeFactory converts xsd:date // types to GregorianCalendar instead of Date. if (type.equals("date")) { java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd"); try { object = df.parse(value); } catch (java.text.ParseException pe) { object = new java.util.Date(); } } } } else { // Create a bean object if (topLevelBean == null) topLevelBean = parentBean; object = pushBeanOnStack(classPackage, type); // Check fields to see if this property is the 'value' for the object Field[] fields = object.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].isAnnotationPresent(ObjectXmlAsValue.class)) { try { StringBuffer fieldName = new StringBuffer(fields[i].getName()); char c = fieldName.charAt(0); if (c >= 'a' && c <= 'z') { c += 'A' - 'a'; } fieldName.setCharAt(0, c); fieldName.insert(0, "set"); Method method = object .getClass() .getMethod(fieldName.toString(), new Class[] {fields[i].getType()}); method.invoke(object, value); break; } catch (Exception e) { System.err.println(e.getMessage()); } } } NamedNodeMap nodeAttrs = node.getAttributes(); // iterate attributes and set field values for property attributes for (int i = 0; i < nodeAttrs.getLength(); i++) { String nodePrefix = nodeAttrs.item(i).getPrefix(); if (nodePrefix.equals(nsPrefix)) { String nodeName = nodeAttrs.item(i).getLocalName(); String nodeValue = nodeAttrs.item(i).getNodeValue(); try { Field field = object.getClass().getDeclaredField(nodeName); if (field.isAnnotationPresent(ObjectXmlAsAttribute.class)) { StringBuffer fieldName = new StringBuffer(field.getName()); char c = fieldName.charAt(0); if (c >= 'a' && c <= 'z') { c += 'A' - 'a'; } fieldName.setCharAt(0, c); fieldName.insert(0, "set"); Method method = object.getClass().getMethod(fieldName.toString(), new Class[] {field.getType()}); if (field.getType() == String.class) method.invoke(object, nodeValue); else if (field.getType() == Boolean.TYPE) method.invoke(object, StringUtils.strToBool(nodeValue, "true")); else if (field.getType() == Byte.TYPE) method.invoke(object, Byte.valueOf(nodeValue).byteValue()); else if (field.getType() == Character.TYPE) method.invoke(object, Character.valueOf(nodeValue.charAt(0))); else if (field.getType() == Double.TYPE) method.invoke(object, Double.valueOf(nodeValue).doubleValue()); else if (field.getType() == Float.TYPE) method.invoke(object, Float.valueOf(nodeValue).floatValue()); else if (field.getType() == Integer.TYPE) method.invoke(object, Integer.valueOf(nodeValue).intValue()); else if (field.getType() == Long.TYPE) method.invoke(object, Long.valueOf(nodeValue).longValue()); else if (field.getType() == Short.TYPE) method.invoke(object, Short.valueOf(nodeValue).shortValue()); } } catch (Exception e) { System.err.println(e.getMessage()); } } } } if ((parentBean != null) && (setProperty)) { parentBean.setProperty(name, object); } return object; }
public boolean runTest(Test test) throws Exception { String filename = test.file.toString(); if (this.verbose) { System.out.println( "Running " + filename + " against " + this.host + ":" + this.port + " with " + this.browser); } this.document = parseDocument(filename); if (this.baseUrl == null) { NodeList links = this.document.getElementsByTagName("link"); if (links.getLength() != 0) { Element link = (Element) links.item(0); setBaseUrl(link.getAttribute("href")); } } if (this.verbose) { System.out.println("Base URL=" + this.baseUrl); } Node body = this.document.getElementsByTagName("body").item(0); Element resultContainer = document.createElement("div"); resultContainer.setTextContent("Result: "); Element resultElt = document.createElement("span"); resultElt.setAttribute("id", "result"); resultElt.setIdAttribute("id", true); resultContainer.appendChild(resultElt); body.insertBefore(resultContainer, body.getFirstChild()); Element executionLogContainer = document.createElement("div"); executionLogContainer.setTextContent("Execution Log:"); Element executionLog = document.createElement("div"); executionLog.setAttribute("id", "log"); executionLog.setIdAttribute("id", true); executionLog.setAttribute("style", "white-space: pre;"); executionLogContainer.appendChild(executionLog); body.appendChild(executionLogContainer); NodeList tableRows = document.getElementsByTagName("tr"); Element theadRow = (Element) tableRows.item(0); test.name = theadRow.getTextContent(); appendCellToRow(theadRow, "Result"); this.commandProcessor = new HtmlCommandProcessor(this.host, this.port, this.browser, this.baseUrl); String resultState; String resultLog; test.result = true; try { this.commandProcessor.start(); test.commands = new Command[tableRows.getLength() - 1]; for (int i = 1; i < tableRows.getLength(); i++) { Element stepRow = (Element) tableRows.item(i); Command command = executeStep(stepRow); appendCellToRow(stepRow, command.result); test.commands[i - 1] = command; if (command.error) { test.result = false; } if (command.failure) { test.result = false; // break; } } resultState = test.result ? "PASSED" : "FAILED"; resultLog = (test.result ? "Test Complete" : "Error"); this.commandProcessor.stop(); } catch (Exception e) { test.result = false; resultState = "ERROR"; resultLog = "Failed to initialize session\n" + e; e.printStackTrace(); } document.getElementById("result").setTextContent(resultState); Element log = document.getElementById("log"); log.setTextContent(log.getTextContent() + resultLog + "\n"); return test.result; }