Ejemplo n.º 1
0
  private void guardaRes(String resu, CliGol cliGol)
      throws ParserConfigurationException, SAXException, IOException {

    String[] nodos = {"NoHit", "Hit", "Buro"};

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(resu));
    Document xml = db.parse(is);

    Element raiz = xml.getDocumentElement();

    String nombre = obtenerNombre(raiz);

    for (String s : nodos) {

      Node nodo =
          raiz.getElementsByTagName(s) == null ? null : raiz.getElementsByTagName(s).item(0);

      if (nodo != null) {
        String informacion = sustraerInformacionNodo(cliGol, nodo);

        guardarEnListas(nodo.getNodeName(), nombre + "," + informacion);
      }
    }
  }
Ejemplo n.º 2
0
  // read all defense missile from given defense destructor
  protected void readDefenseDestructorFromGivenDestructor(Element destructor) {
    NamedNodeMap attributes = destructor.getAttributes();
    String id = "";
    String type;

    Attr attr = (Attr) attributes.item(0);

    String name = attr.getNodeName();

    // if it's iron dome
    if (name.equals("id")) {
      id = attr.getNodeValue();

      // update id's in the war
      IdGenerator.updateIronDomeId(id);
      // add to war
      war.addIronDome(id);

      NodeList destructdMissiles = destructor.getElementsByTagName("destructdMissile");
      readDefensDestructoreMissiles(destructdMissiles, id);

      // if it's launcher destructor
    } else {
      if (name.equals("type")) {
        type = attr.getNodeValue();

        // add to war
        id = war.addDefenseLauncherDestructor(type);

        NodeList destructedLanuchers = destructor.getElementsByTagName("destructedLanucher");
        readDefensDestructoreMissiles(destructedLanuchers, id);
      }
    }
  }
Ejemplo n.º 3
0
  // Lee la configuracion que se encuentra en conf/RegistryConf
  private void readConfXml() {
    try {
      File inputFile = new File("src/java/Conf/RegistryConf.xml");
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(inputFile);
      doc.getDocumentElement().normalize();
      NodeList nList = doc.getElementsByTagName("RegistryConf");
      for (int i = 0; i < nList.getLength(); i++) {
        Node nNode = nList.item(i);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
          Element eElement = (Element) nNode;
          RegistryConf reg = new RegistryConf();
          String aux;
          int idSensor;
          int value;
          aux = eElement.getElementsByTagName("idSensor").item(0).getTextContent();
          idSensor = Integer.parseInt(aux);
          reg.setIdSensor(idSensor);

          aux = eElement.getElementsByTagName("saveType").item(0).getTextContent();
          reg.setSaveTypeString(aux);

          aux = eElement.getElementsByTagName("value").item(0).getTextContent();
          value = Integer.parseInt(aux);
          reg.setValue(value);

          registryConf.add(reg);
          lastRead.put(idSensor, 0);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 4
0
  public List parsePage(String pageCode) {
    List sections = new ArrayList();
    List folders = new ArrayList();
    List files = new ArrayList();
    int start = pageCode.indexOf("<div id=\"list-view\" class=\"view\"");
    int end = pageCode.indexOf("<div id=\"gallery-view\" class=\"view\"");
    String usefulSection = "";
    if (start != -1 && end != -1) {
      usefulSection = pageCode.substring(start, end);
    } else {
      debug("Could not parse page");
    }
    try {
      DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(usefulSection));
      Document doc = db.parse(is);

      NodeList divs = doc.getElementsByTagName("div");
      for (int i = 0; i < divs.getLength(); i++) {
        Element div = (Element) divs.item(i);
        boolean isFolder = false;
        if (div.getAttribute("class").equals("filename")) {
          NodeList imgs = div.getElementsByTagName("img");
          for (int j = 0; j < imgs.getLength(); j++) {
            Element img = (Element) imgs.item(j);
            if (img.getAttribute("class").indexOf("folder") > 0) {
              isFolder = true;
            } else {
              isFolder = false; // it's a file
            }
          }

          NodeList anchors = div.getElementsByTagName("a");
          Element anchor = (Element) anchors.item(0);
          String attr = anchor.getAttribute("href");
          String fileName = anchor.getAttribute("title");
          String fileURL;
          if (isFolder && !attr.equals("#")) {
            folders.add(attr);
            folders.add(fileName);
          } else if (!isFolder && !attr.equals("#")) {
            // Dropbox uses ajax to get the file for download, so the url isn't enough. We must be
            // sneaky here.
            fileURL = "https://dl.dropbox.com" + attr.substring(23) + "?dl=1";
            files.add(fileURL);
            files.add(fileName);
          }
        }
      }
    } catch (Exception e) {
      debug(e.toString());
    }

    sections.add(files);
    sections.add(folders);

    return sections;
  }
Ejemplo n.º 5
0
  @Override
  public VPackage parse() {

    logger.debug("Starting parsing package: " + xmlFile.getAbsolutePath());

    long startParsing = System.currentTimeMillis();

    try {
      Document document = getDocument();
      Element root = document.getDocumentElement();

      _package = new VPackage(xmlFile);

      Node name = root.getElementsByTagName(EL_NAME).item(0);
      _package.setName(name.getTextContent());
      Node descr = root.getElementsByTagName(EL_DESCRIPTION).item(0);
      _package.setDescription(descr.getTextContent());

      NodeList list = root.getElementsByTagName(EL_CLASS);

      boolean initPainters = false;
      for (int i = 0; i < list.getLength(); i++) {
        PackageClass pc = parseClass((Element) list.item(i));
        if (pc.getPainterName() != null) {
          initPainters = true;
        }
      }

      if (initPainters) {
        _package.initPainters();
      }

      logger.info(
          "Parsing the package '{}' finished in {}ms.\n",
          _package.getName(),
          (System.currentTimeMillis() - startParsing));
    } catch (Exception e) {
      collector.collectDiagnostic(e.getMessage(), true);
      if (RuntimeProperties.isLogDebugEnabled()) {
        e.printStackTrace();
      }
    }

    try {
      checkProblems("Error parsing package file " + xmlFile.getName());
    } catch (Exception e) {
      return null;
    }

    return _package;
  }
  public ArrayList<String> parseXML() throws Exception {
    ArrayList<String> ret = new ArrayList<String>();

    handshake();

    URL url =
        new URL(
            "http://mangaonweb.com/page.do?cdn="
                + cdn
                + "&cpn=book.xml&crcod="
                + crcod
                + "&rid="
                + (int) (Math.random() * 10000));
    String page = DownloaderUtils.getPage(url.toString(), "UTF-8", cookies);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(page));
    Document d = builder.parse(is);
    Element doc = d.getDocumentElement();

    NodeList pages = doc.getElementsByTagName("page");
    total = pages.getLength();
    for (int i = 0; i < pages.getLength(); i++) {
      Element e = (Element) pages.item(i);
      ret.add(e.getAttribute("path"));
    }

    return (ret);
  }
 /**
  * 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);
 }
 /**
  * Unmarshall a Chromosome instance from a given XML Element representation.
  *
  * @param a_activeConfiguration the current active Configuration object that is to be used during
  *     construction of the Chromosome
  * @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 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
  * @since 1.0
  */
 public static Chromosome getChromosomeFromElement(
     Configuration a_activeConfiguration, Element a_xmlElement)
     throws ImproperXMLException, InvalidConfigurationException,
         UnsupportedRepresentationException, GeneCreationException {
   // Do some sanity checking. Make sure the XML Element isn't null and
   // that in fact represents a chromosome.
   // -----------------------------------------------------------------
   if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(CHROMOSOME_TAG))) {
     throw new ImproperXMLException(
         "Unable to build Chromosome instance from XML Element: "
             + "given Element is not a 'chromosome' element.");
   }
   // Extract the nested genes element and make sure it exists.
   // ---------------------------------------------------------
   Element genesElement = (Element) a_xmlElement.getElementsByTagName(GENES_TAG).item(0);
   if (genesElement == null) {
     throw new ImproperXMLException(
         "Unable to build Chromosome instance from XML Element: "
             + "'genes' sub-element not found.");
   }
   // Construct the genes from their representations.
   // -----------------------------------------------
   Gene[] geneAlleles = getGenesFromElement(a_activeConfiguration, genesElement);
   // Construct the new Chromosome with the genes and return it.
   // ----------------------------------------------------------
   return new Chromosome(a_activeConfiguration, geneAlleles);
 }
Ejemplo n.º 9
0
 private Element getElement(String eltName) {
   NodeList nodeList = docElt.getElementsByTagName(eltName);
   if (nodeList.getLength() != 0) {
     Node node = nodeList.item(0);
     if (node instanceof Element) return (Element) node;
   }
   return null;
 }
Ejemplo n.º 10
0
 public NodeList getImediateElementsByTagName(Element el, String tagname) {
   NodeList list = el.getElementsByTagName(tagname);
   SimpleNodeList result = new SimpleNodeList();
   int length = list.getLength();
   for (int i = 0; i < length; i++) {
     Node node = list.item(i);
     if ((Element) node.getParentNode() == el) {
       result.add(node);
     }
   }
   return result;
 }
Ejemplo n.º 11
0
  public static void vol(int issue_length, NodeList issue_node) {
    for (int i = 0; i < issue_length; i++) {
      Node nnode = issue_node.item(i);
      if (nnode.getNodeType() == Element.ELEMENT_NODE) {
        Element enode = (Element) nnode;

        NodeList article_node = enode.getElementsByTagName("article");
        int article_length = enode.getElementsByTagName("article").getLength();

        for (int j = 0; j < article_length; j++) {
          Node m = article_node.item(j);
          if (m.getNodeType() == Element.ELEMENT_NODE) {
            Element f = (Element) m;
            String title = f.getElementsByTagName("title").item(0).getTextContent();
            // System.out.println(title);
            if (title.equals("Research in Knowledge Base Management Systems.")) {
              // String article = f.getElementsByTagName("title").item(0).getTextContent();
              String endPage = f.getElementsByTagName("endPage").item(0).getTextContent();
              String initPage = f.getElementsByTagName("initPage").item(0).getTextContent();
              String vol_element = enode.getElementsByTagName("volume").item(0).getTextContent();
              String num_element = enode.getElementsByTagName("number").item(0).getTextContent();
              // System.out.println("Title: "+ title);
              System.out.println("Volume: " + vol_element);
              System.out.println("Number: " + num_element);
              System.out.println("Init Page: " + initPage);
              System.out.println("End Page: " + endPage);
            }
          }
        }
      }
    }
  }
Ejemplo n.º 12
0
 public void load(InputStream is) throws IOException, ParserConfigurationException, SAXException {
   doc = db.parse(is);
   docElt = doc.getDocumentElement();
   if (docElt.getTagName().equals(docElementName)) {
     NodeList nl = docElt.getElementsByTagName(trackElementName);
     for (int i = 0; i < nl.getLength(); i++) {
       Element elt = (Element) nl.item(i);
       Track track = new Track(elt);
       tracks.add(track);
       hash.put(track.getKey(), track);
     }
   }
 }
Ejemplo n.º 13
0
  public apiParser(String sdkfile) {
    System.out.println(sdkfile);
    File file = new File(sdkfile);
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();

      Document doc = db.parse(file);
      NodeList apiList = doc.getElementsByTagName("n1:api");
      NodeList inputList = doc.getElementsByTagName("n1:input");
      NodeList typeList = doc.getElementsByTagName("n1:type");

      for (int i = 0; i < apiList.getLength(); i++) {
        Node api_node = apiList.item(i);
        String api_id = api_node.getAttributes().getNamedItem("id").getNodeValue();
        String api_name = api_node.getAttributes().getNamedItem("name").getNodeValue();
        String input_type_id =
            inputList.item(i).getAttributes().getNamedItem("type_ref").getNodeValue();

        // System.out.println(api_id + " : " + api_name + " : " + input_type_id);
        ArrayList<String> api_params = new ArrayList<String>();

        for (int j = 0; j < typeList.getLength(); j++) {

          if (input_type_id.equalsIgnoreCase(
              typeList.item(j).getAttributes().getNamedItem("id").getNodeValue())) {
            Element e1 = (Element) typeList.item(j);

            NodeList param_l = e1.getElementsByTagName("n1:param");

            for (int k = 0; k < param_l.getLength(); k++) {

              String param_name =
                  param_l.item(k).getAttributes().getNamedItem("name").getNodeValue();
              // String param_desc =
              // param_l.item(k).getAttributes().getNamedItem("desc").getNodeValue();
              api_params.add(param_name);
              // System.out.println(param_name +":"+param_desc);
            }

            break;
          }
        }
        apiRoom s_room = new apiRoom(api_id, api_name, api_params);
        apiRooms.add(s_room);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 14
0
  // read all defense destructors and their missiles from XML
  protected void readDefenseDestructors() {
    ;
    NodeList destructors = root.getElementsByTagName("destructor");

    int destructorsSize = destructors.getLength();
    for (int i = 0; i < destructorsSize; i++) {
      Element destructor = (Element) destructors.item(i);

      readDefenseDestructorFromGivenDestructor(destructor);
    }

    // update the id's in the war
    IdGenerator.updateFinalIronDomeId();
  }
Ejemplo n.º 15
0
  // read enemy launchers and their missiles form XML
  protected void readEnemyLaunchers() {
    NodeList launchers = root.getElementsByTagName("launcher");

    for (int i = 0; i < launchers.getLength(); i++) {
      Element tempLauncher = (Element) launchers.item(i);

      String idLauncher = tempLauncher.getAttribute("id");
      boolean isHidden = Boolean.parseBoolean(tempLauncher.getAttribute("isHidden"));

      // add to the war
      war.addEnemyLauncher(idLauncher, isHidden);
      IdGenerator.updateEnemyLauncherId(idLauncher);

      NodeList missiles = tempLauncher.getElementsByTagName("missile");

      // read all missiles
      readMissilesForGivenLauncher(missiles, idLauncher);
    }

    // update the id's in the war
    IdGenerator.updateFinalEnemyMissileId();
    IdGenerator.updateFinalEnemyLauncherId();
  }
Ejemplo n.º 16
0
  private String obtenerNombre(Element raiz) {

    String comillas = "\"";

    StringBuilder nombre = new StringBuilder(comillas);

    String[] vars = {"CliApePat", "CliApeMat", "CliNom"};

    for (String s : vars) {
      nombre.append(raiz.getElementsByTagName(s).item(0).getTextContent() + " ");
    }
    nombre.append(comillas);

    return nombre.toString();
  }
Ejemplo n.º 17
0
  public static void main(String[] args) {
    System.out.println("--------Part 1-------------------------------");
    Document xmlDoc = getDocument("SigmodRecord.xml");
    int issue_length = xmlDoc.getElementsByTagName("issue").getLength();
    NodeList issue_node = xmlDoc.getElementsByTagName("issue");

    for (int i = 0; i < issue_length; i++) {
      Node nnode = issue_node.item(i);
      if (nnode.getNodeType() == Element.ELEMENT_NODE) {
        Element enode = (Element) nnode;
        String vol_element = enode.getElementsByTagName("volume").item(0).getTextContent();
        String num_element = enode.getElementsByTagName("number").item(0).getTextContent();
        if (vol_element.equals("13") && num_element.equals("4")) {
          NodeList article_node = xmlDoc.getElementsByTagName("article");
          int article_length = xmlDoc.getElementsByTagName("article").getLength();
          for (int j = 0; j < article_length; j++) {
            Node m = article_node.item(j);
            if (m.getNodeType() == Element.ELEMENT_NODE) {
              Element f = (Element) m;
              String auth = f.getElementsByTagName("author").item(0).getTextContent();
              if (auth.equals("David Maier")) {
                String title = f.getElementsByTagName("title").item(0).getTextContent();
                System.out.println("Title: " + title);
              }
            }
          }
        }
      }
    }
    // Part 2 of the Program (Print the author names off all articles whose title contains the word
    // "database" or "Database".)
    System.out.println("--------Part 2------------------------------- ");
    NodeList article_node = xmlDoc.getElementsByTagName("article");
    int article_length = xmlDoc.getElementsByTagName("article").getLength();
    for (int j = 0; j < article_length; j++) {
      Node m = article_node.item(j);
      if (m.getNodeType() == Element.ELEMENT_NODE) {
        Element f = (Element) m;
        String article = f.getElementsByTagName("title").item(0).getTextContent();
        if (article.contains("Database") || article.contains("database")) {
          int length = f.getElementsByTagName("author").getLength();
          for (int i = 0; i < length; i++) {
            String auth = f.getElementsByTagName("author").item(i).getTextContent();
            System.out.println("Author: " + auth);
          }
        }
      }
    }
    // Part 3 of the Program (Print the volume/number and the init/end pages of the article titled
    // "Research in Knowledge Base Management Systems.".)
    System.out.println("--------Part 3------------------------------- ");
    vol(issue_length, issue_node);
  }
  // http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
  private double my_ListParser(int itIs) {

    double[] my_list = new double[3];

    try {
      File fXmlFile =
          new File("/Users/alexiaKourfali/NetBeansProjects/mav_project3_part2/web/my_list.xml");
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(fXmlFile);
      doc.getDocumentElement().normalize();

      // System.out.println("Root element " + doc.getDocumentElement().getNodeName());
      NodeList nodeLst = doc.getElementsByTagName("Entry");

      for (int s = 0; s < nodeLst.getLength(); s++) {

        Node fstNode = nodeLst.item(s);

        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
          Element fstElmnt = (Element) fstNode;

          NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("Price");
          Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
          NodeList fstNm = fstNmElmnt.getChildNodes();
          Node nV = (Node) fstNm.item(0);
          /*not sureeeee*/
          my_list[s] = Double.parseDouble(nV.getNodeValue());
        }
      }
    } catch (Exception e) {
    }

    if (itIs == 0) return my_list[0];

    if (itIs == 1) return my_list[1];
    else return my_list[2];
  }
 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;
 }
 /**
  * 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()]);
 }
Ejemplo n.º 21
0
  public ShowFileData loadShow(String s) {
    Vector<Pair> links = new Vector<Pair>();
    /*
    ShowFileData show = new ShowFileData();
    show.setSettings(new CameoSettings());
    show.setPatch(new CameoPatch(0,0));
    show.setCueList(new CueList(0));
    show.setMagicSheet(new MagicSheet());
    */
    SettingsData settingsData = new SettingsData();
    MagicSheetData magicSheetData = new MagicSheetData();
    CueListData cueListData = new CueListData();
    PatchData patchData = new PatchData();

    Document doc;
    try {
      doc = _builder.parse(s);

      Element root = doc.getDocumentElement();
      Element settings = getElement(root, _settings);
      Element patch = getElement(root, _patch);
      Element cues = getElement(root, _cues);
      Element magic = getElement(root, _magicSheet);
      // TODO test that all of these are non null and report incorrect file missing ...

      String recordMode = getElement(settings, _recordMode).getTextContent();
      settingsData.put(_recordMode, recordMode);
      /*
      if(recordMode.equals(RecordMode.TRACKING.toString()))
      	show._settings._mode = RecordMode.TRACKING;
      else if(recordMode.equals(RecordMode.CUE_ONLY.toString()))
      	show._settings._mode = RecordMode.CUE_ONLY;
      */
      settingsData.put(_totalChannels, getElement(settings, _totalChannels).getTextContent());
      settingsData.put(_totalDimmers, getElement(settings, _totalDimmers).getTextContent());
      settingsData.put(_dUpTime, getElement(settings, _dUpTime).getTextContent());
      settingsData.put(_dDownTime, getElement(settings, _dDownTime).getTextContent());
      settingsData.put(_gotoCueTime, getElement(settings, _gotoCueTime).getTextContent());
      settingsData.put(_title, getElement(settings, _title).getTextContent());
      settingsData.put(_comment, getElement(settings, _comment).getTextContent());
      settingsData.put(_channelPerLine, getElement(settings, _channelPerLine).getTextContent());
      settingsData.put(_channelHGroup, getElement(settings, _channelHGroup).getTextContent());
      settingsData.put(_channelVGroup, getElement(settings, _channelVGroup).getTextContent());

      /*
      show._settings._totalChannels = Integer.parseInt(getElement(settings, _totalChannels).getTextContent());
      show._settings._totalDimmers = Integer.parseInt(getElement(settings, _totalDimmers).getTextContent());
      show._settings._upTime = Integer.parseInt(getElement(settings, _dUpTime).getTextContent());
      show._settings._downTime = Integer.parseInt(getElement(settings, _dDownTime).getTextContent());
      show._settings._gotoCueTime = Integer.parseInt(getElement(settings, _gotoCueTime).getTextContent());
      show._settings._showTitle = getElement(settings, _title).getTextContent();
      show._settings._showComment = getElement(settings, _comment).getTextContent();

      show._settings._ChannelsPerLine = Integer.parseInt(getElement(settings, _channelPerLine).getTextContent());
      show._settings._ChannelGrouping = Integer.parseInt(getElement(settings, _channelHGroup).getTextContent());
      show._settings._LineGrouping = Integer.parseInt(getElement(settings, _channelVGroup).getTextContent());
      */

      int totalChannels = Integer.parseInt(settingsData.get(_totalChannels));

      patchData.setTotalChannels(totalChannels);
      patchData.setTotalDimmers(Integer.parseInt(settingsData.get(_totalDimmers)));

      cueListData.setTotalChannels(totalChannels);

      // show.setPatch(new CameoPatch(show._settings._totalChannels, show._settings._totalDimmers));
      // show.setCueList(new CueList(show._settings._totalChannels));

      NodeList list = patch.getElementsByTagName(_channel);
      for (int x = 0; x < list.getLength(); x++) {
        Element el = (Element) list.item(x);
        int number = Integer.parseInt(el.getAttribute(_number));
        patchDims(patchData, number, el.getTextContent());
      }

      list = cues.getElementsByTagName(_cue);
      for (int x = 0; x < list.getLength(); x++) {
        Element el = (Element) list.item(x);
        CueData cue = new CueData();
        cue.setDescription(el.getAttribute(_discription));
        NodeList list2 = el.getElementsByTagName(_channel);
        for (int y = 0; y < list2.getLength(); y++) {
          Element chan = (Element) list2.item(y);
          setLevel(cue, chan.getAttribute(_number), chan.getTextContent());
        }

        int number = Integer.parseInt(el.getAttribute(_number));

        int upTime = Integer.parseInt(el.getAttribute(_uptime));
        int downTime = Integer.parseInt(el.getAttribute(_downTime));
        int delayUpTime = Integer.parseInt(el.getAttribute(_upTimeDelay));
        int delayDownTime = Integer.parseInt(el.getAttribute(_downTimeDelay));

        FadeData fade = new FadeData(number, upTime, downTime, delayUpTime, delayDownTime, cue);

        if (el.hasAttribute(_followtime))
          fade.setFollowTime(Integer.parseInt(el.getAttribute(_followtime)));

        if (el.hasAttribute(_nextCue)) fade.setNextCue(Integer.parseInt(el.getAttribute(_nextCue)));

        cueListData.add(fade);
      }

      // TODO this needs to be done in the extractor
      // for(Pair p : links)
      //	show._cuelist.getCueNumbered(p._first).setNextCue(show._cuelist.getCueNumbered(p._second));

      list = magic.getElementsByTagName(_channel);
      for (int x = 0; x < list.getLength(); x++) {
        Element el = (Element) list.item(x);
        // Element xval = getElement(el, _x);
        // Element yval = getElement(el, _y);
        Integer number = new Integer(Integer.parseInt(el.getAttribute(_number)) - 1);
        double xpos = Double.parseDouble(el.getAttribute(_x));
        double ypos = Double.parseDouble(el.getAttribute(_y));
        magicSheetData.put(number, new MagicChannelData(xpos, ypos));
      }

    } catch (DOMException e) {
      System.err.println(e);
    } catch (SAXException e) {
      System.err.println(e);
    } catch (FileNotFoundException e) {
      JOptionPane.showMessageDialog(
          new JFrame(""), "The show file " + s + " was not found, loading default show.");
    } catch (IOException e) {
      System.err.println(e);
    }

    return new ShowFileData(settingsData, cueListData, patchData, magicSheetData);
  }
Ejemplo n.º 22
0
 private Element getElementByName(Element root, String name) {
   return (Element) root.getElementsByTagName(name).item(0);
 }
  /**
   * Edit the properties of a resource. The updates must refer to a Document containing a WebDAV
   * propertyupdates element as the document root.
   *
   * @param updates an XML Document containing propertyupdate elements
   * @return the result of making the updates describing the edits to be made.
   * @exception com.ibm.webdav.WebDAVException
   */
  public MultiStatus setProperties(Document propertyUpdates) throws WebDAVException {
    // create a MultiStatus to hold the results. It will hold a MethodResponse
    // for each update, and one for the method as a whole
    MultiStatus multiStatus = new MultiStatus();
    boolean errorsOccurred = false;

    // first, load the properties so they can be edited
    Document propertiesDocument = resource.loadProperties();
    Element properties = (Element) propertiesDocument.getDocumentElement();

    // be sure the updates have at least one update
    Element propertyupdate = (Element) propertyUpdates.getDocumentElement();
    String tagName = propertyupdate.getNamespaceURI() + propertyupdate.getLocalName();

    if (!tagName.equals("DAV:propertyupdate")) {
      throw new WebDAVException(
          WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "missing propertyupdate element");
    }

    NodeList updates = propertyupdate.getChildNodes();

    if (updates.getLength() == 0) {
      throw new WebDAVException(WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no updates in request");
    }

    Vector propsGood = new Vector(); // a list of properties that

    // were patched correctly or would have been if another
    // property hadn't gone bad.
    // apply the updates
    Node temp = null;

    for (int i = 0; i < updates.getLength(); i++) {
      temp = updates.item(i);

      // skip any ignorable TXText elements
      if (!(temp.getNodeType() == Node.ELEMENT_NODE)) {
        continue;
      }

      Element update = (Element) temp;
      int updateCommand = -1;
      tagName = update.getNamespaceURI() + update.getLocalName();

      if (tagName.equals("DAV:set")) {
        updateCommand = set;
      } else if (tagName.equals("DAV:remove")) {
        updateCommand = remove;
      } else {
        throw new WebDAVException(
            WebDAVStatus.SC_UNPROCESSABLE_ENTITY,
            update.getTagName() + " is not a valid property update request");
      }

      // iterate through the props in the set or remove element and update the
      // properties as directed
      Element prop = (Element) update.getElementsByTagNameNS("DAV:", "prop").item(0);

      if (prop == null) {
        throw new WebDAVException(
            WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no propeprties in update request");
      }

      NodeList propsToUpdate = prop.getChildNodes();

      for (int j = 0; j < propsToUpdate.getLength(); j++) {
        temp = propsToUpdate.item(j);

        // skip any TXText elements??
        if (!(temp.getNodeType() == Node.ELEMENT_NODE)) {
          continue;
        }

        Element propToUpdate = (Element) temp;

        // find the property in the properties element
        Element property = null;
        PropertyName propertyName = new PropertyName(propToUpdate);

        if (((Element) propToUpdate).getNamespaceURI() != null) {
          property =
              (Element)
                  properties
                      .getElementsByTagNameNS(
                          propToUpdate.getNamespaceURI(), propToUpdate.getLocalName())
                      .item(0);
        } else {
          property = (Element) properties.getElementsByTagName(propToUpdate.getTagName()).item(0);
        }

        boolean liveone = isLive(propertyName.asExpandedString());

        if (liveone) {
          errorsOccurred = true;

          PropertyResponse response = new PropertyResponse(resource.getURL().toString());
          response.addProperty(propertyName, propToUpdate, WebDAVStatus.SC_FORBIDDEN);
          multiStatus.addResponse(response);
        }

        // do the update
        if (updateCommand == set) {
          if (property != null) {
            try {
              properties.removeChild(property);
            } catch (DOMException exc) {
            }
          }

          if (!liveone) {
            // I don't think we're allowed to update live properties
            //    here.  Doing so effects the cache.  A case in
            //    point is the lockdiscoveryproperty.  properties
            //    is actually the properites cache "document" of this
            //    resource.  Even though we don't "save" the request
            //    if it includes live properties, we don't remove
            //    it from the cache after we'd set it here, so it
            //    can affect other queries. (jlc 991002)
            properties.appendChild(propertiesDocument.importNode(propToUpdate, true));

            propsGood.addElement(propToUpdate);
          }
        } else if (updateCommand == remove) {
          try {
            if (property != null) {
              properties.removeChild(property);
              propsGood.addElement(propToUpdate);
            }
          } catch (DOMException exc) {
          }
        }
      }
    }

    {
      Enumeration els = propsGood.elements();

      for (; els.hasMoreElements(); ) {
        Object ob1 = els.nextElement();
        Element elProp = (Element) ob1;
        PropertyName pn = new PropertyName(elProp);
        PropertyResponse response = new PropertyResponse(resource.getURL().toString());
        response.addProperty(
            pn,
            (Element) elProp.cloneNode(false),
            (errorsOccurred ? WebDAVStatus.SC_FAILED_DEPENDENCY : WebDAVStatus.SC_OK));

        // todo: add code for responsedescription
        multiStatus.addResponse(response);
      }
    }

    // write out the properties
    if (!errorsOccurred) {
      resource.saveProperties(propertiesDocument);
    }

    return multiStatus;
  }
Ejemplo n.º 24
0
  private PackageClass parseClass(Element classNode) {
    PackageClass newClass = new PackageClass();
    _package.getClasses().add(newClass);

    newClass.setComponentType(PackageClass.ComponentType.getType(classNode.getAttribute(ATR_TYPE)));
    newClass.setStatic(Boolean.parseBoolean(classNode.getAttribute(ATR_STATIC)));
    newClass.setName(getElementByName(classNode, EL_NAME).getTextContent());
    final String source = getElementStringByName(classNode, EL_FILE);
    if (source != null) {
      newClass.setSource(source);
    }
    newClass.setTarget(getElementStringByName(classNode, EL_EXTENDS));
    newClass.setDescription(getElementByName(classNode, EL_DESCRIPTION).getTextContent());
    newClass.setIcon(getElementByName(classNode, EL_ICON).getTextContent());

    // parse all variables declared in the corresponding specification
    if (newClass.getComponentType().hasSpec()) {
      final String newClassName = newClass.getName();
      try {
        switch (RuntimeProperties.getSpecParserKind()) {
          case REGEXP:
            {
              ClassList classList = new ClassList();
              SpecParser.parseSpecClass(newClassName, getWorkingDir(), classList);
              newClass.setSpecFields(classList.getType(newClassName).getFields());
              break;
            }
          case ANTLR:
            {
              if (specificationLoader == null) {
                specificationLoader =
                    new SpecificationLoader(new PackageSpecSourceProvider(_package), null);
              }
              final AnnotatedClass annotatedClass =
                  specificationLoader.getSpecification(newClassName);
              newClass.setSpecFields(annotatedClass.getFields());
              break;
            }
          default:
            throw new IllegalStateException("Undefined specification language parser");
        }
      } catch (SpecParseException e) {
        final String msg = "Unable to parse the specification of class " + newClassName;
        logger.error(msg, e);
        collector.collectDiagnostic(msg + "\nReason: " + e.getMessage() + "\nLine: " + e.getLine());
      }
    }

    // Graphics
    Element grNode = getElementByName(classNode, EL_GRAPHICS);
    newClass.addGraphics(
        getGraphicsParser().parse(grNode/*, newClass.getComponentType() == ComponentType.REL*/ ));

    Element painter;
    if ((painter = getElementByName(grNode, EL_PAINTER)) != null) {
      newClass.setPainterName(painter.getTextContent());
    }

    // Ports
    NodeList ports = classNode.getElementsByTagName(EL_PORT);
    for (int i = 0; i < ports.getLength(); i++) {
      parsePort(newClass, (Element) ports.item(i));
    }

    // Fields
    NodeList fields = classNode.getElementsByTagName(EL_FIELD);
    for (int i = 0; i < fields.getLength(); i++) {
      parseField(newClass, (Element) fields.item(i));
    }

    return newClass;
  }
Ejemplo n.º 25
0
  /**
   * XML Circuit constructor
   *
   * @param file the file that contains the XML description of the circuit
   * @param g the graphics that will paint the node
   * @throws CircuitLoadingException if the internal circuit can not be loaded
   */
  public CircuitUI(File file, Graphics g) throws CircuitLoadingException {
    this("");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    Document doc;
    Element root;

    Hashtable<Integer, Link> linkstable = new Hashtable<Integer, Link>();

    try {
      builder = factory.newDocumentBuilder();
      doc = builder.parse(file);
    } catch (SAXException sxe) {
      throw new CircuitLoadingException("SAX exception raised, invalid XML file.");
    } catch (ParserConfigurationException pce) {
      throw new CircuitLoadingException(
          "Parser exception raised, parser configuration is invalid.");
    } catch (IOException ioe) {
      throw new CircuitLoadingException("I/O exception, file cannot be loaded.");
    }

    root = (Element) doc.getElementsByTagName("Circuit").item(0);
    this.setName(root.getAttribute("name"));

    NodeList nl = root.getElementsByTagName("Node");
    Element e;
    Node n;
    Class cl;

    for (int i = 0; i < nl.getLength(); ++i) {
      e = (Element) nl.item(i);

      try {
        cl = Class.forName(e.getAttribute("class"));
      } catch (Exception exc) {
        System.err.println(exc.getMessage());
        throw new RuntimeException("Circuit creation from xml.");
      }

      try {
        n = ((Node) cl.newInstance());
      } catch (Exception exc) {
        System.err.println(exc.getMessage());
        throw new RuntimeException("Circuit creation from xml.");
      }

      this.nodes.add(n);
      n.setLocation(new Integer(e.getAttribute("x")), new Integer(e.getAttribute("y")));

      if (n instanceof giraffe.ui.Nameable) ((Nameable) n).setNodeName(e.getAttribute("node_name"));

      if (n instanceof giraffe.ui.CompositeNode) {
        try {
          ((CompositeNode) n)
              .load(new File(file.getParent() + "/" + e.getAttribute("file_name")), g);
        } catch (Exception exc) {
          /* try to load from the lib */
          ((CompositeNode) n)
              .load(new File(giraffe.Giraffe.PATH + "/lib/" + e.getAttribute("file_name")), g);
        }
      }

      NodeList nlist = e.getElementsByTagName("Anchor");
      Element el;

      for (int j = 0; j < nlist.getLength(); ++j) {
        el = (Element) nlist.item(j);

        Anchor a = n.getAnchor(new Integer(el.getAttribute("id")));
        NodeList linklist = el.getElementsByTagName("Link");
        Element link;
        Link l;

        for (int k = 0; k < linklist.getLength(); ++k) {
          link = (Element) linklist.item(k);
          int id = new Integer(link.getAttribute("id"));
          int index = new Integer(link.getAttribute("index"));

          if (id >= this.linkID) linkID = id + 1;

          if (linkstable.containsKey(id)) {
            l = linkstable.get(id);
            l.addLinkedAnchorAt(a, index);
            a.addLink(l);
          } else {
            l = new Link(id);
            l.addLinkedAnchorAt(a, index);
            this.links.add(l);
            linkstable.put(id, l);
            a.addLink(l);
          }
        }
      }
    }
  }
Ejemplo n.º 26
0
    private ClassGraphics parse(Element grNode /*, boolean isRelation*/) {
      ClassGraphics newGraphics = new ClassGraphics();
      newGraphics.setShowFields(Boolean.parseBoolean(grNode.getAttribute(ATR_SHOW_FIELDS)));
      // newGraphics.setRelation( isRelation );

      NodeList list = grNode.getChildNodes();
      for (int k = 0; k < list.getLength(); k++) {
        if (list.item(k).getNodeType() != Node.ELEMENT_NODE) continue;
        Element node = (Element) list.item(k);
        String nodeName = node.getNodeName();

        Shape shape = null;
        if (EL_BOUNDS.equals(nodeName)) {
          Dim dim = getDim(node);
          newGraphics.setBounds(dim.x, dim.y, dim.width, dim.height);
          continue;
        } else if (EL_LINE.equals(nodeName)) {

          shape = makeLine(node, newGraphics);

        } else if (EL_RECT.equals(nodeName)) {

          Dim dim = getDim(node);
          Lineprops lp = getLineProps(node);
          shape =
              new Rect(
                  dim.x,
                  dim.y,
                  dim.width,
                  dim.height,
                  getColor(node),
                  isShapeFilled(node),
                  lp.strokeWidth,
                  lp.lineType);

        } else if (EL_OVAL.equals(nodeName)) {

          Dim dim = getDim(node);
          Lineprops lp = getLineProps(node);
          shape =
              new Oval(
                  dim.x,
                  dim.y,
                  dim.width,
                  dim.height,
                  getColor(node),
                  isShapeFilled(node),
                  lp.strokeWidth,
                  lp.lineType);

        } else if (EL_ARC.equals(nodeName)) {

          Dim dim = getDim(node);
          Lineprops lp = getLineProps(node);
          int startAngle = Integer.parseInt(node.getAttribute(ATR_START_ANGLE));
          int arcAngle = Integer.parseInt(node.getAttribute(ATR_ARC_ANGLE));
          shape =
              new Arc(
                  dim.x,
                  dim.y,
                  dim.width,
                  dim.height,
                  startAngle,
                  arcAngle,
                  getColor(node),
                  isShapeFilled(node),
                  lp.strokeWidth,
                  lp.lineType);

        } else if (EL_POLYGON.equals(nodeName)) {
          Lineprops lp = getLineProps(node);

          Polygon polygon =
              new Polygon(getColor(node), isShapeFilled(node), lp.strokeWidth, lp.lineType);

          // points
          NodeList points = node.getElementsByTagName(EL_POINT);
          int pointCount = points.getLength();
          // arrays of polygon points
          int[] xs = new int[pointCount];
          int[] ys = new int[pointCount];
          // arrays of FIXED information about polygon points
          int[] fxs = new int[pointCount];
          int[] fys = new int[pointCount];
          int width = newGraphics.getBoundWidth();
          int height = newGraphics.getBoundHeight();

          for (int j = 0; j < pointCount; j++) {
            FixedCoords fc = getFixedCoords((Element) points.item(j), width, height, null);
            xs[j] = fc.x;
            fxs[j] = fc.fx;
            ys[j] = fc.y;
            fys[j] = fc.fy;
          }

          polygon.setPoints(xs, ys, fxs, fys);
          shape = polygon;

        } else if (EL_IMAGE.equals(nodeName)) {

          Dim dim = getDim(node);
          // image path should be relative to the package xml
          String imgPath = node.getAttribute(ATR_PATH);
          String fullPath = FileFuncs.preparePathOS(getWorkingDir() + imgPath);
          shape = new Image(dim.x, dim.y, fullPath, imgPath, isShapeFixed(node));

        } else if (EL_TEXT.equals(nodeName)) {
          shape = makeText(node, newGraphics);
          /*
           * if (str.equals("*self")) newText.name = "self"; else if
           * (str.equals("*selfWithName")) newText.name = "selfName";
           */
        }

        if (shape != null) newGraphics.addShape(shape);
      }

      return newGraphics;
    }
Ejemplo n.º 27
0
  public void addPackageClass(PackageClass pClass) {

    Document doc;
    try {
      doc = getDocument();
    } catch (Exception e) {
      e.printStackTrace();
      return;
    }

    String name = pClass.getName();

    // check if such class exists and remove duplicates
    Element rootEl = doc.getDocumentElement();
    NodeList classEls = rootEl.getElementsByTagName(EL_CLASS);
    for (int i = 0; i < classEls.getLength(); i++) {
      Element nameEl = getElementByName((Element) classEls.item(i), EL_NAME);
      if (name.equals(nameEl.getTextContent())) {
        rootEl.removeChild(classEls.item(i));
      }
    }

    Element classNode = doc.createElement(EL_CLASS);
    doc.getDocumentElement().appendChild(classNode);
    classNode.setAttribute(ATR_TYPE, PackageClass.ComponentType.SCHEME.getXmlName());
    classNode.setAttribute(ATR_STATIC, "false");

    Element className = doc.createElement(EL_NAME);
    className.setTextContent(name);
    classNode.appendChild(className);

    Element desrc = doc.createElement(EL_DESCRIPTION);
    desrc.setTextContent(pClass.getDescription());
    classNode.appendChild(desrc);

    Element icon = doc.createElement(EL_ICON);
    icon.setTextContent(pClass.getIcon());
    classNode.appendChild(icon);

    // graphics
    classNode.appendChild(generateGraphicsNode(doc, pClass.getGraphics()));

    // ports
    List<Port> ports = pClass.getPorts();
    if (!ports.isEmpty()) {
      Element portsEl = doc.createElement(EL_PORTS);
      classNode.appendChild(portsEl);

      for (Port port : ports) {
        portsEl.appendChild(generatePortNode(doc, port));
      }
    }

    // fields
    Collection<ClassField> fields = pClass.getFields();
    if (!fields.isEmpty()) {
      Element fieldsEl = doc.createElement(EL_FIELDS);
      classNode.appendChild(fieldsEl);

      for (ClassField cf : fields) {
        fieldsEl.appendChild(generateFieldNode(doc, cf));
      }
    }

    // write
    try {
      writeDocument(doc, new FileOutputStream(xmlFile));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
  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;
  }
Ejemplo n.º 29
0
 private Element getElement(Element root, String name) {
   NodeList list = root.getElementsByTagName(name);
   Element el = (Element) list.item(0);
   return el;
 }
Ejemplo n.º 30
0
  // -----------------------------------------------------
  // Description: Get the value from the node.
  // YUUGAMEE!
  // -----------------------------------------------------
  String getTagValue(String sTag, Element eElement) {
    NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0);

    return nValue.getNodeValue();
  }