Exemple #1
0
  private static SetInfo parseSet(Node parent) throws XmlParserException {
    String id = "";
    String type = "";
    String measurementids = null;

    NodeList nodes = parent.getChildNodes();
    Vector<SetInfo> sets = new Vector<SetInfo>();
    for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) {
      Node node = nodes.item(nodeid);
      if (node.getNodeType() != Node.ELEMENT_NODE) continue;

      Element element = (Element) node;
      if (element.getTagName().equals("id")) id = element.getTextContent();
      else if (element.getTagName().equals("set")) sets.add(parseSet(element));
      else if (element.getTagName().equals("type")) type = element.getTextContent();
      else if (element.getTagName().equals("measurementids"))
        measurementids = element.getTextContent();
    }

    // create the set
    SetInfo set = new SetInfo(id, Integer.parseInt(type));
    if (measurementids != null) {
      int mids[] = ByteArray.toIntArray(Base64.decode(measurementids), ByteArray.ENDIAN_LITTLE, 32);
      for (int mid : mids) set.addMeasurementID(mid);
    }

    // add the children
    for (SetInfo s : sets) set.addChild(s);

    return set;
  }
Exemple #2
0
  private static MeasurementInfo parseMeasurement(Node parent) throws XmlParserException {
    String id = "";
    String label = "";
    String sampleid = "";
    Vector<FileInfo> files = null;
    Vector<ScanInfo> scans = null;

    NodeList nodes = parent.getChildNodes();
    for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) {
      Node node = nodes.item(nodeid);
      if (node.getNodeType() != Node.ELEMENT_NODE) continue;

      Element element = (Element) node;
      if (element.getTagName().equals("id")) id = element.getTextContent();
      else if (element.getTagName().equals("label")) label = element.getTextContent();
      else if (element.getTagName().equals("sampleid")) sampleid = element.getTextContent();
      else if (element.getTagName().equals("scans")) scans = parseScans(node);
      else if (element.getTagName().equals("files")) files = parseFiles(node);
    }

    MeasurementInfo measurement = new MeasurementInfo(Integer.parseInt(id), sampleid);
    measurement.setLabel(label);
    measurement.addFileInfos(files);
    if (scans != null) measurement.addScanInfos(scans);

    return measurement;
  }
Exemple #3
0
  private static Header parseHeader(Node parent) throws XmlParserException {
    Header header = new Header();

    NodeList nodes = parent.getChildNodes();
    for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) {
      Node node = nodes.item(nodeid);
      if (node.getNodeType() != Node.ELEMENT_NODE) continue;

      Element element = (Element) node;
      try {
        if (element.getTagName().equals("nrpeaks"))
          header.setNrPeaks(Integer.parseInt(element.getTextContent()));
        else if (element.getTagName().equals("date")) header.setDate(element.getTextContent());
        else if (element.getTagName().equals("owner")) header.setOwner(element.getTextContent());
        else if (element.getTagName().equals("description"))
          header.setDescription(element.getTextContent());
        else if (element.getTagName().equals("sets")) header.addSetInfos(parseSets(element));
        else if (element.getTagName().equals("measurements"))
          header.addMeasurementInfos(parseMeasurements(element));
        else if (element.getTagName().equals("annotations")) {
          Vector<Annotation> annotations = parseAnnotations(element);
          if (annotations != null)
            for (Annotation annotation : annotations) header.addAnnotation(annotation);
        }
      } catch (Exception e) {
        throw new XmlParserException(
            "Invalid value in header (" + element.getTagName() + "): '" + e.getMessage() + "'.");
      }
    }

    return header;
  }
  /**
   * WhiteboardObjectTextJabberImpl constructor.
   *
   * @param xml the XML string object to parse.
   */
  public WhiteboardObjectTextJabberImpl(String xml) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
      builder = factory.newDocumentBuilder();
      InputStream in = new ByteArrayInputStream(xml.getBytes());
      Document doc = builder.parse(in);

      Element e = doc.getDocumentElement();
      String elementName = e.getNodeName();
      if (elementName.equals("text")) {
        // we have a text
        String id = e.getAttribute("id");
        double x = Double.parseDouble(e.getAttribute("x"));
        double y = Double.parseDouble(e.getAttribute("y"));
        String fill = e.getAttribute("fill");
        String fontFamily = e.getAttribute("font-family");
        int fontSize = Integer.parseInt(e.getAttribute("font-size"));
        String text = e.getTextContent();

        this.setID(id);
        this.setWhiteboardPoint(new WhiteboardPoint(x, y));
        this.setFontName(fontFamily);
        this.setFontSize(fontSize);
        this.setText(text);
        this.setColor(Color.decode(fill).getRGB());
      }
    } catch (ParserConfigurationException ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    } catch (IOException ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    } catch (Exception ex) {
      if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml);
    }
  }
Exemple #5
0
 public void load(Element domElement) {
   NodeList ch_list = domElement.getElementsByTagName("OGLParameter");
   for (int i = 0; i < ch_list.getLength(); ++i) {
     Element chEle = (Element) ch_list.item(i);
     addParameter(chEle.getAttribute("name"), chEle.getTextContent());
   }
 }
 private String getNameText(Element e) // whoops;
     {
   List<String> parts = new ArrayList<String>();
   for (Element w : XML.getElementsByTagname(e, "w", false)) {
     parts.add(w.getTextContent().trim());
   }
   return StringUtils.join(parts, " ");
 }
Exemple #7
0
  private static Vector<Annotation> parseAnnotations(Node parent) throws XmlParserException {
    Vector<Annotation> annotations = new Vector<Annotation>();

    NodeList nodes = parent.getChildNodes();
    for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) {
      Node node = nodes.item(nodeid);
      if (node.getNodeType() != Node.ELEMENT_NODE) continue;

      Element element = (Element) node;
      if (element.getTagName().equals("annotation")) {
        String label = null, value = null, valuetype = null, unit = null;
        NodeList annotation_nodes = element.getChildNodes();
        for (int annotationid = 0; annotationid < annotation_nodes.getLength(); ++annotationid) {
          Node annotation_node = annotation_nodes.item(annotationid);
          if (annotation_node.getNodeType() != Node.ELEMENT_NODE) continue;

          Element annotation_element = (Element) annotation_node;
          if (annotation_element.getTagName().equals("label"))
            label = annotation_element.getTextContent();
          else if (annotation_element.getTagName().equals("value"))
            value = annotation_element.getTextContent();
          else if (annotation_element.getTagName().equals("valuetype"))
            valuetype = annotation_element.getTextContent();
        }

        if (label == null || value == null || valuetype == null)
          throw new XmlParserException("Annotation is missing either: label, value or valuetype");

        Annotation annotation =
            new Annotation(label, value, Annotation.ValueType.valueOf(valuetype));
        annotation.setUnit(unit);
        if (annotation.getValueType() == Annotation.ValueType.ONTOLOGY)
          annotation.setOntologyRef(element.getAttribute("ontologyref"));
        if (element.getAttribute("unit") != null) annotation.setUnit(element.getAttribute("unit"));
        annotations.add(annotation);
      }
    }

    return annotations;
  }
Exemple #8
0
  private static FileInfo parseFile(Node parent) throws XmlParserException {
    String label = "";
    String name = "";
    String location = "";
    Vector<Annotation> annotations = null;

    NodeList nodes = parent.getChildNodes();
    for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) {
      Node node = nodes.item(nodeid);
      if (node.getNodeType() != Node.ELEMENT_NODE) continue;

      Element element = (Element) node;
      if (element.getTagName().equals("label")) label = element.getTextContent();
      else if (element.getTagName().equals("name")) name = element.getTextContent();
      else if (element.getTagName().equals("location")) location = element.getTextContent();
      else if (element.getTagName().equals("annotations")) annotations = parseAnnotations(node);
    }

    FileInfo file = new FileInfo(label, name, location);
    if (annotations != null) file.addAnnotations(annotations);
    return file;
  }
Exemple #9
0
  private void processGeneList(Session session, Element element, HashMap additionalInformation) {

    String name = getAttribute(element, SessionAttribute.NAME.getText());

    String txt = element.getTextContent();
    String[] genes = txt.trim().split("\\s+");
    GeneList gl = new GeneList(name, Arrays.asList(genes));
    GeneListManager.getInstance().addGeneList(gl);
    session.setCurrentGeneList(gl);

    // Adjust frames
    processFrames(element);
  }
Exemple #10
0
  private static ScanInfo parseScan(Node parent) throws XmlParserException {
    double retentiontime = 0;
    Polarity polarity = Polarity.NEUTRAL;
    Vector<Annotation> annotations = null;

    NodeList nodes = parent.getChildNodes();
    for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) {
      Node node = nodes.item(nodeid);
      if (node.getNodeType() != Node.ELEMENT_NODE) continue;

      Element element = (Element) node;
      if (element.getTagName().equals("polarity"))
        polarity = Polarity.valueOf(element.getTextContent());
      else if (element.getTagName().equals("retentiontime"))
        retentiontime = Double.parseDouble(element.getTextContent());
      else if (element.getTagName().equals("annotations")) annotations = parseAnnotations(element);
    }

    ScanInfo scan = new ScanInfo(retentiontime, polarity);
    if (annotations != null) scan.addAnnotations(annotations);
    return scan;
  }
  public static void main(String[] args) {
    try {
      DocumentBuilderFactory dBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dBuilderFactory.newDocumentBuilder();

      Document document = dBuilder.parse("DOMSample.xml");

      Element rootElement = document.getDocumentElement();

      System.out.println("Root Element's Value : " + rootElement.getTextContent());
    } catch (Exception e) {
      e.printStackTrace(System.err);
    }
  }
 /**
  * Runs the test case.
  *
  * @throws Throwable Any uncaught exception causes test to fail
  */
 public void runTest() throws Throwable {
   Document doc;
   NodeList elemList;
   Element elem;
   String textContent;
   doc = (Document) load("hc_staff", false);
   elemList = doc.getElementsByTagName("p");
   elem = (Element) elemList.item(2);
   textContent = elem.getTextContent();
   assertEquals(
       "nodegettextcontent13",
       "\n  EMP0003\n  Roger\n Jones\n  Department Manager\n  100,000\n  Element data\n  PO Box 27 Irving, texas 98553\n ",
       textContent);
 }
Exemple #13
0
  /**
   * Method that reads a XML-file, and returns a Model that contains the information
   *
   * @param file
   * @return
   * @return
   */
  public static Model readXML(String file) {
    // initialize table to be filled with content of XML file
    Model t = new Model();
    try {
      // Create file to be parsed by document parser
      File xmlfile = new File(file);
      // create parser
      DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      // parse the file
      Document parsedfile = parser.parse(xmlfile);
      // normalize the parsed file (make it more user-friendly)
      parsedfile.getDocumentElement().normalize();

      NodeList cells = parsedfile.getElementsByTagName("CELL");
      for (int i = 0; i < cells.getLength(); i++) {
        // Get cell at list index i
        Node currentcell = cells.item(i);
        // read the elements "location" attributes row/column
        if (Node.ELEMENT_NODE == currentcell.getNodeType()) {
          Element cellinfo = (Element) currentcell;
          // get the row number from node attribute
          int row = Integer.parseInt(cellinfo.getAttribute("row")) - 1;
          // get the column number from the node attribute
          int col = Integer.parseInt(cellinfo.getAttribute("column")) - 1;
          // get content from node
          String content = cellinfo.getTextContent();
          if (content != null) {
            content = content.replace("\n", "");
          }
          // Make the content an Integer (if it is a number), easier
          // for
          // using it later on
          // put content in table, with row/column inserted as x/y
          t.setContent(row, col, (String) content);
        }
      }

    } catch (ParserConfigurationException e) {
      System.out.println("Fileparser could not be made");
    } catch (IOException f) {
      System.out.println("File could not be parsed, did you enter the correct file name?");
    } catch (SAXException g) {
      System.out.println("Something went wrong in parsing the file");
    }
    return t;
  }
Exemple #14
0
  private static void parseIPeak(Node parent, IPeak peak) throws XmlParserException {
    // retrieve all the properties
    int scan = -1;
    double retentiontime = -1;
    double mass = -1;
    double intensity = -1;
    int patternid = -1;
    int measurementid = -1;
    //		String sha1 = null;
    Vector<Annotation> annotations = null;

    NodeList nodes = parent.getChildNodes();
    for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) {
      Node node = nodes.item(nodeid);
      if (node.getNodeType() != Node.ELEMENT_NODE) continue;

      Element element = (Element) node;
      if (element.getTagName().equals("patternid"))
        patternid = Integer.parseInt(element.getTextContent());
      else if (element.getTagName().equals("measurementid"))
        measurementid = Integer.parseInt(element.getTextContent());
      else if (element.getTagName().equals("annotations")) annotations = parseAnnotations(element);
      else if (element.getTagName().equals("scan"))
        scan = Integer.parseInt(element.getTextContent());
      else if (element.getTagName().equals("retentiontime"))
        retentiontime = Double.parseDouble(element.getTextContent());
      else if (element.getTagName().equals("mass"))
        mass = Double.parseDouble(element.getTextContent());
      else if (element.getTagName().equals("intensity"))
        intensity = Double.parseDouble(element.getTextContent());
      //			else if (element.getTagName().equals("sha1sum"))
      //				sha1 = element.getTextContent();
    }

    // check whether obligatory values are missing
    if (mass == -1 || intensity == -1)
      throw new XmlParserException("Mass and/or intensity information is missing for IPeak.");

    peak.setScanID(scan);
    peak.setRetentionTime(retentiontime);
    peak.setMass(mass);
    peak.setIntensity(intensity);
    peak.setPatternID(patternid);
    peak.setMeasurementID(measurementid);

    if (annotations != null)
      for (Annotation annotation : annotations) peak.addAnnotation(annotation);

    // check whether
    //		if (sha1!=null && !sha1.equals(peak.sha1()))
    //			throw new XmlParserException("SHA1-sum for individual ipeak element does not match.");
  }
Exemple #15
0
 public String getFolderName(String pageCode) {
   String usefulSection =
       pageCode.substring(
           pageCode.indexOf("<h3 id=\"breadcrumb\">"),
           pageCode.indexOf("<div id=\"list-view\" class=\"view\""));
   String folderName;
   try {
     DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
     InputSource is = new InputSource();
     is.setCharacterStream(new StringReader(usefulSection));
     Document doc = db.parse(is);
     NodeList divs = doc.getElementsByTagName("h3");
     for (int i = 0; i < divs.getLength(); i++) {
       Element div = (Element) divs.item(i);
       String a = div.getTextContent();
       folderName = a.substring(a.indexOf("/>") + 2).trim();
       return folderName;
     }
   } catch (Exception e) {
     debug(e.toString());
   }
   return "Error!";
 }
Exemple #16
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);
  }
 private NEWordform createNEWordform(Element n) {
   NEWordform neWord = new NEWordform();
   neWord.wordform = n.getTextContent();
   neWord = (NEWordform) DatabaseMapping.canonical(databaseMapping.wordformMap, neWord);
   return neWord;
 }
 private String getElementStringByName(Element root, String name) {
   Element element;
   return (element = getElementByName(root, name)) != null ? element.getTextContent() : null;
 }
  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;
  }
  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;
  }
Exemple #22
0
  private static PeakData<? extends Peak> parsePeakData(Node parent) throws XmlParserException {
    // get the attributes
    Node typeattribute = parent.getAttributes().getNamedItem(PeakMLWriter.TYPE);
    if (typeattribute == null) throw new XmlParserException("Failed to locate a type attribute.");
    Node sizeattribute = parent.getAttributes().getNamedItem(PeakMLWriter.SIZE);
    if (sizeattribute == null) throw new XmlParserException("Failed to locate a size attribute.");

    int size = Integer.parseInt(sizeattribute.getNodeValue());
    String type = typeattribute.getNodeValue();

    // create the arrays
    int scanids[] = null;
    int patternids[] = null;
    int measurementids[] = null;
    double masses[] = null;
    double intensities[] = null;
    double retentiontimes[] = null;

    // retrieve all the data
    NodeList nodes = parent.getChildNodes();
    for (int nodeid = 0; nodeid < nodes.getLength(); ++nodeid) {
      Node node = nodes.item(nodeid);
      if (node.getNodeType() != Node.ELEMENT_NODE) continue;

      Element element = (Element) node;
      if (element.getTagName().equals("scanids"))
        scanids =
            ByteArray.toIntArray(
                Base64.decode(element.getTextContent()), ByteArray.ENDIAN_LITTLE, 32);
      else if (element.getTagName().equals("patternids"))
        patternids =
            ByteArray.toIntArray(
                Base64.decode(element.getTextContent()), ByteArray.ENDIAN_LITTLE, 32);
      else if (element.getTagName().equals("measurementids"))
        measurementids =
            ByteArray.toIntArray(
                Base64.decode(element.getTextContent()), ByteArray.ENDIAN_LITTLE, 32);
      else if (element.getTagName().equals("masses"))
        masses =
            ByteArray.toDoubleArray(
                Base64.decode(element.getTextContent()), ByteArray.ENDIAN_LITTLE, 32);
      else if (element.getTagName().equals("intensities"))
        intensities =
            ByteArray.toDoubleArray(
                Base64.decode(element.getTextContent()), ByteArray.ENDIAN_LITTLE, 32);
      else if (element.getTagName().equals("retentiontimes"))
        retentiontimes =
            ByteArray.toDoubleArray(
                Base64.decode(element.getTextContent()), ByteArray.ENDIAN_LITTLE, 32);
    }

    // create the PeakData instance
    if (type.equals("centroid"))
      return new PeakData<Centroid>(
          Centroid.factory,
          size,
          scanids,
          patternids,
          measurementids,
          masses,
          intensities,
          retentiontimes);
    return null;
  }
  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();
    }
  }