Package nu.xom

Examples of nu.xom.Document


     * <code>Element</code> and then creates the MusicXML file (as a
     * string) from the internal <code>Document</code>
     * @return the completed MusicXML file as a String
     */
    public String getMusicXMLString()
    {  Document xomDoc = getMusicXMLDoc();
      return xomDoc.toXML();
    }
View Full Code Here


      for (int xM = 0; xM < elPartMeasures.size(); ++xM)
        if (elPartMeasures.get(xM).getChildCount() < 1)
          elDocPart.removeChild(xM);
    }
    //  create the Document
    Document xomDoc = new Document(root);
    DocType docType = new DocType("score-partwise",
            "-//Recordare//DTD MusicXML 1.1 Partwise//EN",
            "http://www.musicxml.org/dtds/partwise.dtd");
    xomDoc.insertChild(docType, 0);
    return xomDoc;
    //  GetMusicXMLDoc
View Full Code Here

      reader.require(XMLStreamConstants.START_ELEMENT, null, null);
    } else {
      reader.require(XMLStreamConstants.START_DOCUMENT, null, null);
    }
   
    Document doc = factory.startMakingDocument();
    boolean hasRootElement = false;
    boolean done = false;
    int i = 0;
   
    while (!done && reader.getEventType() != XMLStreamConstants.END_DOCUMENT) {
     
      Nodes nodes;
//      if (DEBUG) System.out.println(toString(reader.getEventType()));
      switch (reader.getEventType()) {
        case XMLStreamConstants.START_ELEMENT: {
          if (hasRootElement) throw new IllegalAddException(
            "StAX reader must not return multiple root elements");

          if (factory.getClass() == NodeFactory.class) { // fast path
            if (nodeBuilder == null) nodeBuilder = new NodeBuilder();
            Element root = readStartTag();
            addAttributes(root);
            addNamespaceDeclarations(root);
            readElement(root); // reads entire subtree
            nodes = new Nodes(root);
          } else { // slow path     
            Element root = readStartTagF(true);
            if (root == null) {
              throw new NullPointerException(
                "Factory failed to create root element.");
            }
            doc.setRootElement(root);
            addAttributesF(root);
            addNamespaceDeclarations(root);
            readElementF(root); // read entire subtree
            nodes = factory.finishMakingElement(root);
          }
          reader.require(XMLStreamConstants.END_ELEMENT, null, null);
          if (isFragmentMode) done = true;
          break;
        }
        case XMLStreamConstants.END_ELEMENT:
          throw new IllegalAddException(
            "A document must not have more than one root element");
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
          nodes = factory.makeProcessingInstruction(
              reader.getPITarget(), reader.getPIData());
          break;
        case XMLStreamConstants.CHARACTERS:
          nodes = NONE; // ignore text in prolog/epilog
          break;
        case XMLStreamConstants.COMMENT:
          nodes = factory.makeComment(reader.getText());
          break;
        case XMLStreamConstants.SPACE:
          nodes = NONE; // ignore text in prolog/epilog
          break;
        case XMLStreamConstants.START_DOCUMENT:
          nodes = NONE; // has already been handled previously
          break;
        case XMLStreamConstants.END_DOCUMENT:
          throw new IllegalStateException("unreachable");
        case XMLStreamConstants.CDATA:
          nodes = NONE; // ignore text in prolog/epilog
          break;
        case XMLStreamConstants.ATTRIBUTE:
          throw new IllegalAddException(
            "Illegal attribute in prolog/epilog");
        case XMLStreamConstants.NAMESPACE:
          throw new IllegalAddException(
            "Illegal namespace declaration in prolog/epilog");
        case XMLStreamConstants.DTD:
          nodes = readDocType(factory); // FIXME
          break;
        case XMLStreamConstants.ENTITY_DECLARATION:
          nodes = NONE; // ignore (missing StAX support)
          break;
        case XMLStreamConstants.NOTATION_DECLARATION:
          nodes = NONE; // ignore (missing StAX support)
          break;
        case XMLStreamConstants.ENTITY_REFERENCE:
          nodes = NONE; // ignore text in prolog/epilog
          break;
        default:
          throw new XMLException("Unrecognized Stax event type: "
              + reader.getEventType());
      }
     
      // append nodes:
      for (int j=0; j < nodes.size(); j++) {
        Node node = nodes.get(j);
        if (node instanceof Element) { // replace fake root with real root
          if (hasRootElement) {
            throw new IllegalAddException(
              "Factory returned multiple root elements");
          }
          doc.setRootElement((Element) node);
          hasRootElement = true;
        } else {
          doc.insertChild(node, i);
        }
        i++;
      }
     
      if (!isFragmentMode) reader.next();
    }
   
    if (!isFragmentMode) {
      reader.require(XMLStreamConstants.END_DOCUMENT, null, null);
    }
    if (!hasRootElement) {
      throw new WellformednessException(
          "Factory attempted to remove the root element");
    }
    factory.finishMakingDocument(doc);
       
    // Set baseURI unless already set previously by NodeFactory
    // to ensure exact same behaviour as nu.xom.Builder.build(InputSource)
    if ("".equals(doc.getBaseURI())) {
      Location loc = reader.getLocation();
      String baseURI = loc == null ? null : loc.getSystemId();
      if (baseURI != null && baseURI.length() > 0) {
        doc.setBaseURI(baseURI);
      }
    }
   
    return doc;
  }
View Full Code Here

  private Document readDocument(ArrayByteList src, InputStream input)
      throws BinaryParsingException, IOException {
   
    if (DEBUG) System.err.println("reading document");
    readPage(src, input);
    Document doc = factory.startMakingDocument();
//    doc.setBaseURI(symbols[src.getInt()]);
    doc.setBaseURI(getInternedName(src.getInt()));
    boolean hasRootElement = false;
    int i = 0;
   
    // add children of document, retaining the exact same order found in input
    while (src.remaining() > 0) {
      Nodes nodes;
      int type = src.get(); // look ahead
      if (DEBUG) System.err.println("reading type = " + toString(type));
      switch (type & 0x07) { // three low bits indicate node type
        case TEXT: {
          throw new BinaryParsingException("Unreachable text");
        }
        case ATTRIBUTE: {
          throw new BinaryParsingException("Unreachable attribute");
        }
        case BEGIN_ELEMENT: {
          if (factory.getClass() == NodeFactory.class) { // fast path
            Element root = readStartTag(src, type);
            readElement(src, root, input); // reads entire subtree
            nodes = new Nodes(root);
          } else { // slow path
            Element root = readStartTagF(src, type, true);
            if (root == null) {
              throw new NullPointerException("Factory failed to create root element.");
            }
            doc.setRootElement(root);
            readElementF(src, root, input);
            nodes = factory.finishMakingElement(root);
          }
          break;
        }
        case END_ELEMENT: {
          throw new BinaryParsingException("Unreachable end of element");
        }
        case COMMENT: {
          nodes = readCommentF(src, type);
          break;
        }
        case NAMESPACE_DECLARATION: {
          throw new BinaryParsingException("Unreachable namespace declaration");
        }
        case PROCESSING_INSTRUCTION: {
          nodes = readProcessingInstructionF(src);
          break;
        }
        case DOC_TYPE: {
          nodes = readDocTypeF(src);
          break;
        }
        default: {
          throw new BinaryParsingException("Illegal node type code=" + type);
        }
      }

      // append nodes:
      for (int j=0; j < nodes.size(); j++) {
        Node node = nodes.get(j);
        if (node instanceof Element) { // replace fake root with real root
          if (hasRootElement) {
            throw new IllegalAddException(
              "Factory returned multiple root elements");
          }
          doc.setRootElement((Element) node);
          hasRootElement = true;
        } else {
          doc.insertChild(node, i);
        }
        i++;
      }
    }
   
View Full Code Here

 
  /** sets the XPath value of the given node to the given value */
  private static void setValue(Node node, String value) {
    if (node instanceof Document) {
      // remove all children except root element (XOM docs must have a root element)
      Document doc = (Document) node;
      Element root = doc.getRootElement();
      for (int k = doc.getChildCount(); --k >= 0; ) {
        if (doc.getChild(k) != root) doc.removeChild(k);
      }
      node = root; // replace root element's content
    }

    if (node instanceof Element) {
View Full Code Here

    return new Attribute(
      node.getDisplayName(), node.getURI(), node.getStringValue());     
  }
 
  private Document convertDocumentNodeInfo(NodeInfo node) {
    Document doc = new Document(new Element("fakeRoot"));
    doc.setBaseURI(node.getBaseURI());
   
    boolean hasRootElement = false;
    int i = 0;
    NodeInfo next;
    AxisIterator iter = node.iterateAxis(Axis.CHILD);
    while ((next = (NodeInfo) iter.next()) != null) {
      Node child = convertNodeInfo(next);
      if (child instanceof Element) { // replace fake root with real root
        if (hasRootElement) throw new IllegalAddException(
          "A XOM document must not have more than one root element.");
        doc.setRootElement((Element) child);
        hasRootElement = true;
      } else {
        doc.insertChild(child, i);
      }
      i++;
    }
    if (!hasRootElement) throw new IllegalAddException(
      "Missing document root element; A XOM document must have a root element.");
View Full Code Here

    if (args.length == 0) args = new String[] { "../xqts-0.9.4" };
    File rootDir = new File(args[0]);
    if (!rootDir.exists() || !rootDir.isDirectory()) {
      throw new IllegalArgumentException("xqts dir does not exist: " + rootDir);
    }
    Document catalog = buildDocument(new File(rootDir, "XQTSCatalog.xml"));
   
    String ns = "declare namespace ns = 'http://www.w3.org/2005/02/query-test-XQTSCatalog'; ";
//    String version = XQueryUtil.xquery(catalog, ns + "ns:test-suite/@version").get(0).getValue();
    File expectedDir = new File(rootDir,
      XQueryUtil.xquery(catalog, ns + "ns:test-suite/@ResultOffsetPath").get(0).getValue());
    File queryDir = new File(rootDir,
      XQueryUtil.xquery(catalog, ns + "ns:test-suite/@XQueryQueryOffsetPath").get(0).getValue());
    File testSourcesDir = new File(rootDir, "TestSources");   
    Nodes testCases = XQueryUtil.xquery(catalog, ns + "//ns:test-case");
   
    for (int i=0; i < testCases.size(); i++) {
      Node testCase = testCases.get(i);

//      String groupTitle = XQueryUtil.xquery(testCase, ns + "../ns:GroupInfo/ns:title").get(0).getValue();
      String path = XQueryUtil.xquery(testCase, "@FilePath").get(0).getValue();
      File query = new File(new File(queryDir, path),
        XQueryUtil.xquery(testCase, ns + "ns:query/@name").get(0).getValue() + ".xq");
      String squery = readQuery(query);
      System.out.println(i + ": " + query + " ...");
     
      if (XQueryUtil.xquery(testCase, ns + "ns:spec-citation[@section-pointer='id-validate']").size() > 0) {
        System.out.println("    ************* IGNORED SCHEMA AWARE FUNCTIONALITY *****");
        continue; // ignore validate() function (nux is not schema aware)
      }
         
      if (squery == null) {
        System.out.println("    ************* IGNORED *****");
        continue;
      }
           
      Nodes inputs = XQueryUtil.xquery(testCase, ns + "ns:input-file");
      Map vars = new HashMap();
      for (int j=0; j < inputs.size(); j++) {
        File input = new File(testSourcesDir, inputs.get(j).getValue() + ".xml");
        String varName = ((Element) inputs.get(j)).getAttributeValue("variable");
        Document inputDoc = buildDocument(input);
//        System.out.println(inputDoc.getBaseURI());
        if (true) XOMUtil.Normalizer.STRIP.normalize(inputDoc);
        vars.put(varName, inputDoc);
      }

      Nodes expectedErrors = XQueryUtil.xquery(testCase, ns + "ns:expected-error");         
      Nodes expectedOutputs = XQueryUtil.xquery(testCase, ns + "ns:output-file");
      boolean inspect = false;
      for (int k=0; !inspect && k < expectedOutputs.size(); k++) {
        String compare = ((Element)expectedOutputs.get(k)).getAttributeValue("compare");
        if ("Inspect".equals(compare)) inspect = true;
      }
       
      Nodes results = null;
      try { // here's where the query is actually executed
        XQuery xquery = new XQuery(squery, testSourcesDir.toURI());
//        XQuery xquery = new XQuery(squery, query.toURI());
//        XQuery xquery = XQueryPool.GLOBAL_POOL.getXQuery(squery, query.toURI());
        results = xquery.execute(null, null, vars).toNodes();
      } catch (Throwable t) {
        if (!inspect && expectedErrors.size() == 0) {
          System.out.println(XOMUtil.toPrettyXML(testCase));
          throw t;
        }
        if (!(t instanceof XQueryException)) throw t;
//        System.out.println("expected error:" + t);
        continue;
      }
     
      for (int k=0; k < expectedOutputs.size(); k++) {
        File expectedOutput = new File(
            new File(expectedDir, path), expectedOutputs.get(k).getValue());     
        String compare = ((Element)expectedOutputs.get(k)).getAttributeValue("compare");
        if ("Text".equals(compare)) compare = "Fragment"; // see http://www.w3.org/Bugs/Public/show_bug.cgi?id=2476
       
        try {
          if (compare.equals("Text")) {
            String expected = FileUtil.toString(
                new FileInputStream(expectedOutput), UTF8);
            String actual = serialize(results);
            assertEquals(expected, actual);
          } else if (compare.equals("XML")) {
            Document expected = buildDocument(expectedOutput);
            if (query.toString().indexOf("XQuery/UseCase/") >= 0) {
              // input doc should not have whitespace
              XOMUtil.Normalizer.STRIP.normalize(expected); // ???
            }
            Document actual = XOMUtil.toDocument(serialize(results));
            assertEquals(expected, actual);       
          } else if (compare.equals("Fragment")) {       
            Document expected = buildFromSequence(expectedOutput);
            Document actual = buildFromSequence(results);
            assertEquals(expected, actual);
          } else if (compare.equals("Ignore")) {
            ; // nothing to do
          } else if (compare.equals("Inspect")) {
            System.out.println("****************** Inspect output?");
View Full Code Here

  }
 
  private Document buildFromSequence(File file) {
    String xml = "<!DOCTYPE doc [<!ENTITY e SYSTEM '" + file.toURI() +
        "'>]><doc>&e;</doc>";
    Document doc = XOMUtil.toDocument(xml);
    if (true) XOMUtil.Normalizer.COLLAPSE.normalize(doc); // needed by SeqUnion/fn-union-node-args-004.xq et al
    return doc;
  }
View Full Code Here

    tmp = new File(tmp, "xqts-tmp.out");
    Writer out = new OutputStreamWriter(new FileOutputStream(tmp), UTF8);
    out.write(serialize(nodes));
    out.flush();
    out.close()
    Document doc = buildFromSequence(tmp); // reparse
    tmp.delete();
    return doc;
  }
View Full Code Here

            morpher = null;
          }
         
          int numSerials = 0;
          for (int j=0; j < inputFiles.length; j++) {
            Document doc = null;
            if (inputFiles[j] != null) {
              doc = docPool.getDocument(new File(inputFiles[j]));
            }
            if (explain && doc != null) {
              System.out.println("stats=" + toStatisticsString(doc));
            }

            for (int iter=0; iter < iterations; iter++) {
              Document doc2 = doc;
              if (morpher != null && doc2 != null) {
                doc2 = new Document(doc2); // immutable for multiple iterations
              }
             
              // run the query
              Nodes results;
              if (xomXPath) {
                if (doc2 == null) throw new UsageException(
                  "A context node is required by XOM's XPath engine, but missing.");
                results = doc2.query((String)query);
              } else if (xquery != null) {
                results = xquery.execute(doc2, null, variables).toNodes();
              } else {
                results = new Nodes(); // disable XQuery for benchmarking
                results.append(doc2);
View Full Code Here

TOP

Related Classes of nu.xom.Document

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.