コード例 #1
0
 /**
  * Unmarshall a Genotype instance from a given XML Element representation. Its population of
  * Chromosomes will be unmarshalled from the Chromosome sub-elements.
  *
  * @param a_activeConfiguration the current active Configuration object that is to be used during
  *     construction of the Genotype and Chromosome instances
  * @param a_xmlElement the XML Element representation of the Genotype
  * @return a new Genotype instance, complete with a population of Chromosomes, setup with the data
  *     from the XML Element representation
  * @throws ImproperXMLException if the given Element is improperly structured or missing data
  * @throws InvalidConfigurationException if the given Configuration is in an inconsistent state
  * @throws UnsupportedRepresentationException if the actively configured Gene implementation does
  *     not support the string representation of the alleles used in the given XML document
  * @throws GeneCreationException if there is a problem creating or populating a Gene instance
  * @author Neil Rotstan
  * @author Klaus Meffert
  * @since 1.0
  */
 public static Genotype getGenotypeFromElement(
     Configuration a_activeConfiguration, Element a_xmlElement)
     throws ImproperXMLException, InvalidConfigurationException,
         UnsupportedRepresentationException, GeneCreationException {
   // Sanity check. Make sure the XML element isn't null and that it
   // actually represents a genotype.
   if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(GENOTYPE_TAG))) {
     throw new ImproperXMLException(
         "Unable to build Genotype instance from XML Element: "
             + "given Element is not a 'genotype' element.");
   }
   // Fetch all of the nested chromosome elements and convert them
   // into Chromosome instances.
   // ------------------------------------------------------------
   NodeList chromosomes = a_xmlElement.getElementsByTagName(CHROMOSOME_TAG);
   int numChromosomes = chromosomes.getLength();
   Population population = new Population(a_activeConfiguration, numChromosomes);
   for (int i = 0; i < numChromosomes; i++) {
     population.addChromosome(
         getChromosomeFromElement(a_activeConfiguration, (Element) chromosomes.item(i)));
   }
   // Construct a new Genotype with the chromosomes and return it.
   // ------------------------------------------------------------
   return new Genotype(a_activeConfiguration, population);
 }
コード例 #2
0
ファイル: JOXBeanInput.java プロジェクト: blueocci/codes
  /**
   * 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;
  }
コード例 #3
0
ファイル: JOXBeanInput.java プロジェクト: blueocci/codes
  /**
   * 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());
    }
  }
 public Command executeStep(Element stepRow) throws Exception {
   Command command = new Command();
   NodeList stepFields = stepRow.getElementsByTagName("td");
   String cmd = stepFields.item(0).getTextContent().trim();
   command.cmd = cmd;
   ArrayList<String> argList = new ArrayList<String>();
   if (stepFields.getLength() == 1) {
     // skip comments
     command.result = "OK";
     return command;
   }
   for (int i = 1; i < stepFields.getLength(); i++) {
     String content = stepFields.item(i).getTextContent();
     content = content.replaceAll(" +", " ");
     content = content.replace('\u00A0', ' ');
     content = content.trim();
     argList.add(content);
   }
   String args[] = argList.toArray(new String[0]);
   command.args = args;
   if (this.verbose) {
     System.out.println(cmd + " " + Arrays.asList(args));
   }
   try {
     command.result = this.commandProcessor.doCommand(cmd, args);
     command.error = false;
   } catch (Exception e) {
     command.result = e.getMessage();
     command.error = true;
   }
   command.failure = command.error && !cmd.startsWith("verify");
   if (this.verbose) {
     System.out.println(command.result);
   }
   return command;
 }
コード例 #5
0
ファイル: ObjectXml.java プロジェクト: pouncilt/vps-avs
 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;
 }
  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;
  }
  public boolean runSuite(String filename) throws Exception {
    if (this.verbose) {
      System.out.println(
          "Running test suite "
              + filename
              + " against "
              + this.host
              + ":"
              + this.port
              + " with "
              + this.browser);
    }
    TestSuite suite = new TestSuite();
    long start = System.currentTimeMillis();
    suite.numTestPasses = 0;
    suite.file = new File(filename);
    File suiteDirectory = suite.file.getParentFile();
    this.document = parseDocument(filename);
    Element table = (Element) this.document.getElementsByTagName("table").item(0);
    NodeList tableRows = table.getElementsByTagName("tr");
    Element tableNameRow = (Element) tableRows.item(0);
    suite.name = tableNameRow.getTextContent();
    suite.result = true;
    suite.tests = new Test[tableRows.getLength() - 1];
    for (int i = 1; i < tableRows.getLength(); i++) {
      Element tableRow = (Element) tableRows.item(i);
      Element cell = (Element) tableRow.getElementsByTagName("td").item(0);
      Element link = (Element) cell.getElementsByTagName("a").item(0);
      Test test = new Test();
      test.label = link.getTextContent();
      test.file = new File(suiteDirectory, link.getAttribute("href"));

      SeleniumHtmlClient subclient = new SeleniumHtmlClient();
      subclient.setHost(this.host);
      subclient.setPort(this.port);
      subclient.setBrowser(this.browser);
      // subclient.setResultsWriter(this.resultsWriter);
      subclient.setBaseUrl(this.baseUrl);
      subclient.setVerbose(this.verbose);
      subclient.runTest(test);
      if (test.result) {
        suite.numTestPasses++;
      }
      suite.result &= test.result;
      suite.tests[i - 1] = test;
    }
    long end = System.currentTimeMillis();

    suite.totalTime = (end - start) / 1000;

    if (this.resultsWriter != null) {
      this.resultsWriter.write("<html><head>\n");
      this.resultsWriter.write("<style type='text/css'>\n");
      this.resultsWriter.write(
          "body, table {font-family: Verdana, Arial, sans-serif;font-size: 12;}\n");
      this.resultsWriter.write("table {border-collapse: collapse;border: 1px solid #ccc;}\n");
      this.resultsWriter.write("th, td {padding-left: 0.3em;padding-right: 0.3em;}\n");
      this.resultsWriter.write("a {text-decoration: none;}\n");
      this.resultsWriter.write(".title {font-style: italic;}");
      this.resultsWriter.write(".selected {background-color: #ffffcc;}\n");
      this.resultsWriter.write(".status_done {background-color: #eeffee;}\n");
      this.resultsWriter.write(".status_passed {background-color: #ccffcc;}\n");
      this.resultsWriter.write(".status_failed {background-color: #ffcccc;}\n");
      this.resultsWriter.write(
          ".breakpoint {background-color: #cccccc;border: 1px solid black;}\n");
      this.resultsWriter.write("</style>\n");
      this.resultsWriter.write("<title>" + suite.name + "</title>\n");
      this.resultsWriter.write("</head><body>\n");
      this.resultsWriter.write("<h1>Test suite results </h1>\n\n");
      this.resultsWriter.write("<table>\n");
      this.resultsWriter.write(
          "<tr>\n<td>result:</td>\n<td>" + (suite.result ? "passed" : "failed") + "</td>\n</tr>\n");
      this.resultsWriter.write(
          "<tr>\n<td>totalTime:</td>\n<td>" + suite.totalTime + "</td>\n</tr>\n");
      this.resultsWriter.write(
          "<tr>\n<td>numTestTotal:</td>\n<td>" + suite.tests.length + "</td>\n</tr>\n");
      this.resultsWriter.write(
          "<tr>\n<td>numTestPasses:</td>\n<td>" + suite.numTestPasses + "</td>\n</tr>\n");
      int numTestFailures = suite.tests.length - suite.numTestPasses;
      this.resultsWriter.write(
          "<tr>\n<td>numTestFailures:</td>\n<td>" + numTestFailures + "</td>\n</tr>\n");
      this.resultsWriter.write("<tr>\n<td>numCommandPasses:</td>\n<td>0</td>\n</tr>\n");
      this.resultsWriter.write("<tr>\n<td>numCommandFailures:</td>\n<td>0</td>\n</tr>\n");
      this.resultsWriter.write("<tr>\n<td>numCommandErrors:</td>\n<td>0</td>\n</tr>\n");
      this.resultsWriter.write("<tr>\n<td>Selenium Version:</td>\n<td>2.24</td>\n</tr>\n");
      this.resultsWriter.write("<tr>\n<td>Selenium Revision:</td>\n<td>.1</td>\n</tr>\n");

      // test suite
      this.resultsWriter.write("<tr>\n<td>\n");
      this.resultsWriter.write(
          "<table id=\"suiteTable\" class=\"selenium\" border=\"1\" cellpadding=\"1\" cellspacing=\"1\"><tbody>\n");
      this.resultsWriter.write(
          "<tr class=\"title "
              + (suite.result ? "status_passed" : "status_failed")
              + "\"><td><b>Test Suite</b></td></tr>\n");

      int i = 0;
      for (Test test : suite.tests) {
        this.resultsWriter.write(
            "<tr class=\""
                + (test.result ? "status_passed" : "status_failed")
                + "\"><td><a href=\"#testresult"
                + i
                + "\">"
                + test.name
                + "</a></td></tr>");
        i++;
      }
      this.resultsWriter.write(
          "</tbody></table>\n</td>\n<td>&nbsp;</td>\n</tr>\n</table>\n<table>");
      int j = 0;
      for (Test test : suite.tests) {
        this.resultsWriter.write(
            "<tr><td><a name=\"testresult" + j + "\">" + test.file + "</a><br/><div>\n");
        this.resultsWriter.write("<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\">\n");
        this.resultsWriter.write(
            "<thead>\n<tr class=\"title "
                + (test.result ? "status_passed" : "status_failed")
                + "\"><td rowspan=\"1\" colspan=\"3\">"
                + test.name
                + "</td></tr>");
        this.resultsWriter.write("</thead><tbody>\n");
        for (Command command : test.commands) {
          boolean result = command.result.startsWith("OK");
          boolean isAssert = command.cmd.startsWith("assert") || command.cmd.startsWith("verify");
          ;
          if (!isAssert) {
            this.resultsWriter.write(
                "<tr class=\"" + (result ? "status_done" : "") + "\">\n<td>\n");
          } else {
            this.resultsWriter.write(
                "<tr class=\"" + (result ? "status_passed" : "status_failed") + "\">\n<td>\n");
          }
          this.resultsWriter.write(command.cmd);
          this.resultsWriter.write("</td>\n");
          if (command.args != null) {
            for (String arg : Arrays.asList(command.args)) {
              this.resultsWriter.write("<td>" + arg + "</td>\n");
            }
          }
        }
        this.resultsWriter.write("</tr>\n");
        this.resultsWriter.write("</tbody></table>\n");
        this.resultsWriter.write("</div></td>\n<td>&nbsp;</td>\n</tr>");

        j++;
      }

      int k = 0;
      for (Test test : suite.tests) {

        k++;
      }

      this.resultsWriter.write("</tbody></table>\n</td><td>&nbsp;</td>\n</tr>\n</table>\n");
      this.resultsWriter.write("</body></html>");
    }
    return suite.result;
  }
コード例 #8
0
ファイル: JOXBeanInput.java プロジェクト: blueocci/codes
  /**
   * 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());
    }
  }
コード例 #9
0
ファイル: JOXBeanInput.java プロジェクト: blueocci/codes
  /**
   * 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;
    }
  }
コード例 #10
0
 /**
  * Unmarshall a Chromosome instance from a given XML Element representation.
  *
  * @param a_activeConfiguration current Configuration object
  * @param a_xmlElement the XML Element representation of the Chromosome
  * @return a new Chromosome instance setup with the data from the XML Element representation
  * @throws ImproperXMLException if the given Element is improperly structured or missing data
  * @throws UnsupportedRepresentationException if the actively configured Gene implementation does
  *     not support the string representation of the alleles used in the given XML document
  * @throws GeneCreationException if there is a problem creating or populating a Gene instance
  * @author Neil Rotstan
  * @since 1.0
  */
 public static Gene[] getGenesFromElement(
     Configuration a_activeConfiguration, Element a_xmlElement)
     throws ImproperXMLException, UnsupportedRepresentationException, GeneCreationException {
   // Do some sanity checking. Make sure the XML Element isn't null and
   // that it in fact represents a set of genes.
   // -----------------------------------------------------------------
   if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(GENES_TAG))) {
     throw new ImproperXMLException(
         "Unable to build Chromosome instance from XML Element: "
             + "given Element is not a 'genes' element.");
   }
   List genes = Collections.synchronizedList(new ArrayList());
   // Extract the nested gene elements.
   // ---------------------------------
   NodeList geneElements = a_xmlElement.getElementsByTagName(GENE_TAG);
   if (geneElements == null) {
     throw new ImproperXMLException(
         "Unable to build Gene instances from XML Element: "
             + "'"
             + GENE_TAG
             + "'"
             + " sub-elements not found.");
   }
   // For each gene, get the class attribute so we know what class
   // to instantiate to represent the gene instance, and then find
   // the child text node, which is where the string representation
   // of the allele is located, and extract the representation.
   // -------------------------------------------------------------
   int numberOfGeneNodes = geneElements.getLength();
   for (int i = 0; i < numberOfGeneNodes; i++) {
     Element thisGeneElement = (Element) geneElements.item(i);
     thisGeneElement.normalize();
     // Fetch the class attribute and create an instance of that
     // class to represent the current gene.
     // --------------------------------------------------------
     String geneClassName = thisGeneElement.getAttribute(CLASS_ATTRIBUTE);
     Gene thisGeneObject;
     Class geneClass = null;
     try {
       geneClass = Class.forName(geneClassName);
       try {
         Constructor constr = geneClass.getConstructor(new Class[] {Configuration.class});
         thisGeneObject = (Gene) constr.newInstance(new Object[] {a_activeConfiguration});
       } catch (NoSuchMethodException nsme) {
         // Try it by calling method newGeneInternal.
         // -----------------------------------------
         Constructor constr = geneClass.getConstructor(new Class[] {});
         thisGeneObject = (Gene) constr.newInstance(new Object[] {});
         thisGeneObject =
             (Gene)
                 PrivateAccessor.invoke(
                     thisGeneObject, "newGeneInternal", new Class[] {}, new Object[] {});
       }
     } catch (Throwable e) {
       throw new GeneCreationException(geneClass, e);
     }
     // Find the text node and fetch the string representation of
     // the allele.
     // ---------------------------------------------------------
     NodeList children = thisGeneElement.getChildNodes();
     int childrenSize = children.getLength();
     String alleleRepresentation = null;
     for (int j = 0; j < childrenSize; j++) {
       Element alleleElem = (Element) children.item(j);
       if (alleleElem.getTagName().equals(ALLELE_TAG)) {
         alleleRepresentation = alleleElem.getAttribute("value");
       }
       if (children.item(j).getNodeType() == Node.TEXT_NODE) {
         // We found the text node. Extract the representation.
         // ---------------------------------------------------
         alleleRepresentation = children.item(j).getNodeValue();
         break;
       }
     }
     // Sanity check: Make sure the representation isn't null.
     // ------------------------------------------------------
     if (alleleRepresentation == null) {
       throw new ImproperXMLException(
           "Unable to build Gene instance from XML Element: "
               + "value (allele) is missing representation.");
     }
     // Now set the value of the gene to that reflect the
     // string representation.
     // -------------------------------------------------
     try {
       thisGeneObject.setValueFromPersistentRepresentation(alleleRepresentation);
     } catch (UnsupportedOperationException e) {
       throw new GeneCreationException(
           "Unable to build Gene because it does not support the "
               + "setValueFromPersistentRepresentation() method.");
     }
     // Finally, add the current gene object to the list of genes.
     // ----------------------------------------------------------
     genes.add(thisGeneObject);
   }
   return (Gene[]) genes.toArray(new Gene[genes.size()]);
 }