Ejemplo n.º 1
0
 private static Document parse(LSInput input, boolean validateIfSchema) {
   DOMImplementationLS impl = getDOMImpl();
   LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
   DOMConfiguration config = parser.getDomConfig();
   config.setParameter("element-content-whitespace", false);
   config.setParameter("namespaces", true);
   config.setParameter("validate-if-schema", validateIfSchema);
   return parser.parse(input);
 }
  /**
   * Runs the test case.
   *
   * @throws Throwable Any uncaught exception causes test to fail
   */
  public void runTest() throws Throwable {
    DOMImplementation domImpl;
    Document doc;
    DOMConfiguration domConfig;
    DocumentType nullDocType = null;

    boolean canSet;
    boolean state;
    String parameter = "nAmEspace-declarations";
    domImpl = getImplementation();
    doc = domImpl.createDocument("http://www.w3.org/1999/xhtml", "html", nullDocType);
    domConfig = doc.getDomConfig();
    state = ((Boolean) domConfig.getParameter(parameter)).booleanValue();
    assertTrue("defaultFalse", state);
    canSet = domConfig.canSetParameter(parameter, Boolean.FALSE);
    assertTrue("canSetFalse", canSet);
    canSet = domConfig.canSetParameter(parameter, Boolean.TRUE);
    assertTrue("canSetTrue", canSet);
    domConfig.setParameter(parameter, Boolean.FALSE);
    state = ((Boolean) domConfig.getParameter(parameter)).booleanValue();
    assertFalse("setFalseEffective", state);
    domConfig.setParameter(parameter, Boolean.TRUE);
    state = ((Boolean) domConfig.getParameter(parameter)).booleanValue();
    assertTrue("setTrueEffective", state);
  }
Ejemplo n.º 3
0
 public static String serialize(Document document, boolean prettyPrint) {
   DOMImplementationLS impl = getDOMImpl();
   LSSerializer serializer = impl.createLSSerializer();
   // document.normalizeDocument();
   DOMConfiguration config = serializer.getDomConfig();
   if (prettyPrint && config.canSetParameter("format-pretty-print", Boolean.TRUE)) {
     config.setParameter("format-pretty-print", true);
   }
   config.setParameter("xml-declaration", true);
   LSOutput output = impl.createLSOutput();
   output.setEncoding("UTF-8");
   Writer writer = new StringWriter();
   output.setCharacterStream(writer);
   serializer.write(document, output);
   return writer.toString();
 }
Ejemplo n.º 4
0
  public String serialize() {
    String xml = null;
    Document doc;

    if (null != (doc = current_element.getOwnerDocument())) {
      DOMImplementationLS dom_impl;
      DOMConfiguration dom_conf;
      LSSerializer serializer;

      dom_impl = (DOMImplementationLS) doc.getImplementation();
      serializer = dom_impl.createLSSerializer();
      dom_conf = serializer.getDomConfig();
      dom_conf.setParameter("format-pretty-print", true);
      dom_conf.setParameter("xml-declaration", false);

      xml = serializer.writeToString(current_element);
    }

    return xml;
  }
Ejemplo n.º 5
0
  /**
   * Runs the test case.
   *
   * @throws Throwable Any uncaught exception causes test to fail
   */
  public void runTest() throws Throwable {
    DOMImplementation domImpl;
    Document doc;
    DOMConfiguration domConfig;
    DocumentType nullDocType = null;

    boolean canSet;
    DOMErrorHandler errorHandler = null;

    String parameter = "error-handler";
    DOMErrorHandler state;
    domImpl = getImplementation();
    doc = domImpl.createDocument("http://www.w3.org/1999/xhtml", "html", nullDocType);
    domConfig = doc.getDomConfig();
    canSet = domConfig.canSetParameter(parameter, ((Object) /*DOMErrorHandler */ errorHandler));
    assertTrue("canSetNull", canSet);
    domConfig.setParameter(parameter, ((Object) /*DOMErrorHandler */ errorHandler));
    state = (DOMErrorHandler) domConfig.getParameter(parameter);
    assertNull("errorHandlerIsNull", state);
  }
  /**
   * Runs the test case.
   *
   * @throws Throwable Any uncaught exception causes test to fail
   */
  public void runTest() throws Throwable {
    DOMImplementation domImpl;
    Document doc;
    DOMConfiguration domConfig;
    DocumentType nullDocType = null;

    boolean canSet;
    boolean state;
    String parameter = "datatype-normalization";
    domImpl = getImplementation();
    doc = domImpl.createDocument("http://www.w3.org/1999/xhtml", "html", nullDocType);
    domConfig = doc.getDomConfig();
    domConfig.setParameter("validate", Boolean.FALSE);
    canSet = domConfig.canSetParameter(parameter, Boolean.TRUE);

    if (canSet) {
      domConfig.setParameter(parameter, Boolean.TRUE);
      state = ((Boolean) domConfig.getParameter("validate")).booleanValue();
      assertTrue("validateSet", state);
    }
  }
Ejemplo n.º 7
0
 public static void validate(Document d, String schema, DOMErrorHandler handler) {
   DOMConfiguration config = d.getDomConfig();
   config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema");
   config.setParameter("validate", true);
   config.setParameter("schema-location", schema);
   config.setParameter("resource-resolver", new ClasspathResourceResolver());
   config.setParameter("error-handler", handler);
   d.normalizeDocument();
 }
Ejemplo n.º 8
0
  /**
   * Utility method for rendering an {@link Element} into a {@link Writer}.
   *
   * @param element {@link Element} to be rendered.
   * @param writer {@link Writer} instance.
   * @param omitXmlDeclaration whether to omit the XML declaration from output.
   * @throws Exception if an error occurs during serialization.
   */
  public static void renderElement(Element element, Writer writer, boolean omitXmlDeclaration)
      throws Exception {
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");

    LSSerializer lsSerializer = impl.createLSSerializer();
    {
      DOMConfiguration domConfiguration = lsSerializer.getDomConfig();
      if (domConfiguration.canSetParameter("format-pretty-print", Boolean.TRUE)) {
        domConfiguration.setParameter("format-pretty-print", Boolean.TRUE);
      }

      if (omitXmlDeclaration
          && domConfiguration.canSetParameter("xml-declaration", Boolean.FALSE)) {
        domConfiguration.setParameter("xml-declaration", Boolean.FALSE);
      }
    }

    LSOutput lsOutput = impl.createLSOutput();
    lsOutput.setEncoding("UTF-8");
    lsOutput.setCharacterStream(writer);

    lsSerializer.write(element, lsOutput);
  }
 /**
  * DOM3 method: Normalize the document with namespaces
  *
  * @param doc
  * @return
  */
 public static Document normalizeNamespaces(Document doc) {
   DOMConfiguration docConfig = doc.getDomConfig();
   docConfig.setParameter("namespaces", Boolean.TRUE);
   doc.normalizeDocument();
   return doc;
 }
Ejemplo n.º 10
0
  public TestReport runImpl() throws Exception {
    Handler h = new Handler();
    TestReport report = null;

    // cdata-sections == false
    Document doc = newSVGDoc();
    DOMConfiguration conf = ((AbstractDocument) doc).getDomConfig();
    conf.setParameter("cdata-sections", Boolean.FALSE);
    Element e = doc.getDocumentElement();
    e.appendChild(doc.createTextNode("abc"));
    e.appendChild(doc.createCDATASection("def"));
    e.appendChild(doc.createTextNode("ghi"));
    ((AbstractDocument) doc).normalizeDocument();
    if (!(e.getFirstChild().getNodeType() == Node.TEXT_NODE
        && e.getFirstChild().getNodeValue().equals("abcdefghi")
        && e.getFirstChild() == e.getLastChild())) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "cdata-sections == false");
    }

    // comments == false
    doc = newSVGDoc();
    conf = ((AbstractDocument) doc).getDomConfig();
    conf.setParameter("comments", Boolean.FALSE);
    e = doc.getDocumentElement();
    e.appendChild(doc.createTextNode("abc"));
    e.appendChild(doc.createComment("def"));
    e.appendChild(doc.createTextNode("ghi"));
    ((AbstractDocument) doc).normalizeDocument();
    if (!(e.getFirstChild().getNodeType() == Node.TEXT_NODE
        && e.getFirstChild().getNodeValue().equals("abcghi")
        && e.getFirstChild() == e.getLastChild())) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "comments == false");
    }

    // element-content-whitespace == false
    doc = newSVGDoc();
    conf = ((AbstractDocument) doc).getDomConfig();
    conf.setParameter("element-content-whitespace", Boolean.FALSE);
    e = doc.getDocumentElement();
    e.appendChild(doc.createTextNode("    "));
    e.appendChild(doc.createElementNS(SVG_NAMESPACE_URI, "g"));
    e.appendChild(doc.createTextNode("    "));
    ((AbstractDocument) doc).normalizeDocument();
    if (!(e.getFirstChild().getNodeType() == Node.ELEMENT_NODE
        && e.getFirstChild().getNodeName().equals("g")
        && e.getFirstChild() == e.getLastChild())) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry(
          "DOMConfiguration parameter", "element-content-whitespace == false");
    }

    // split-cdata-sections == true
    doc = newSVGDoc();
    conf = ((AbstractDocument) doc).getDomConfig();
    conf.setParameter("split-cdata-sections", Boolean.TRUE);
    conf.setParameter("error-handler", h);
    e = doc.getDocumentElement();
    e.appendChild(doc.createCDATASection("before ]]> after"));
    ((AbstractDocument) doc).normalizeDocument();
    if (!(e.getFirstChild().getNodeType() == Node.CDATA_SECTION_NODE
        && e.getFirstChild().getNodeValue().equals("before ]]")
        && e.getFirstChild().getNextSibling().getNodeType() == Node.CDATA_SECTION_NODE
        && e.getFirstChild().getNextSibling().getNodeValue().equals("> after")
        && e.getFirstChild().getNextSibling() == e.getLastChild()
        && h.get("cdata-sections-splitted") == 1)) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "split-cdata-sections == true");
    }

    // well-formed
    doc = newSVGDoc();
    ((AbstractDocument) doc).setStrictErrorChecking(false);
    conf = ((AbstractDocument) doc).getDomConfig();
    conf.setParameter("error-handler", h);
    e = doc.getDocumentElement();
    e.appendChild(doc.createComment("before -- after"));
    e.appendChild(doc.createComment("ends in a dash -"));
    e.setAttribute("*", "blah");
    e.appendChild(doc.createProcessingInstruction("abc", "def?>"));
    ((AbstractDocument) doc).normalizeDocument();
    if (!(h.get("wf-invalid-character-in-node-name") == 1 && h.get("wf-invalid-character") == 3)) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "well-formed == true");
    }

    // namespaces
    doc = newDoc();
    e = doc.createElementNS(null, "root");
    doc.appendChild(e);
    Element e2 = doc.createElementNS(null, "parent");
    e.appendChild(e2);
    e2.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:ns", "http://www.example.org/ns1");
    e2.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:bar", "http://www.example.org/ns2");
    Element e3 = doc.createElementNS("http://www.example.org/ns1", "ns:child1");
    e2.appendChild(e3);
    e3.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:ns", "http://www.example.org/ns2");
    e3 = doc.createElementNS("http://www.example.org/ns2", "ns:child2");
    e2.appendChild(e3);
    ((AbstractDocument) doc).normalizeDocument();
    Attr a = e3.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "ns");
    if (!(a != null
        && a.getNodeName().equals("xmlns:ns")
        && a.getNodeValue().equals("http://www.example.org/ns2"))) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "namespaces == true, test 1");
    }

    doc = newDoc();
    e = doc.createElementNS(null, "root");
    doc.appendChild(e);
    e2 = doc.createElementNS("http://www.example.org/ns1", "ns:child1");
    e.appendChild(e2);
    e2.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:ns", "http://www.example.org/ns1");
    e3 = doc.createElementNS("http://www.example.org/ns1", "ns:child2");
    e2.appendChild(e3);
    e2 =
        (Element)
            ((AbstractDocument) doc).renameNode(e2, "http://www.example.org/ns2", "ns:child1");
    ((AbstractDocument) doc).normalizeDocument();
    a = e2.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "ns");
    Attr a2 = e3.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "ns");
    if (!(a != null
        && a.getNodeName().equals("xmlns:ns")
        && a.getNodeValue().equals("http://www.example.org/ns2")
        && a2 != null
        && a2.getNodeName().equals("xmlns:ns")
        && a2.getNodeValue().equals("http://www.example.org/ns1"))) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "namespaces == true, test 2");
    }

    doc = newDoc();
    e = doc.createElementNS(null, "root");
    doc.appendChild(e);
    e2 = doc.createElementNS("http://www.example.org/ns1", "child1");
    e.appendChild(e2);
    e2.setAttributeNS("http://www.example.org/ns2", "blah", "hi");
    ((AbstractDocument) doc).normalizeDocument();
    a = e2.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "xmlns");
    a2 = e2.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "NS1");
    if (!(a != null
        && a.getNodeValue().equals("http://www.example.org/ns1")
        && a2 != null
        && a2.getNodeValue().equals("http://www.example.org/ns2"))) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "namespaces == true, test 3");
    }

    // namespace-declarations == false
    doc = newDoc();
    e = doc.createElementNS(null, "ex:root");
    e.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:ex", "http://www.example.org/ns1");
    conf = ((AbstractDocument) doc).getDomConfig();
    conf.setParameter("namespace-declarations", Boolean.FALSE);
    doc.appendChild(e);
    ((AbstractDocument) doc).normalizeDocument();
    if (!(e.getAttributeNodeNS(XMLNS_NAMESPACE_URI, "ex") == null)) {
      if (report == null) {
        report = reportError("Document.normalizeDocument test failed");
      }
      report.addDescriptionEntry("DOMConfiguration parameter", "namespace-declarations == false");
    }

    if (report == null) {
      return reportSuccess();
    }
    return report;
  }
Ejemplo n.º 11
0
  protected boolean execute(Map<String, String> parameters) throws TransformerRunException {
    String inputXML = parameters.remove("xml");
    String factory = parameters.remove("factory");
    String out = parameters.remove("out");
    String copyReferring = parameters.remove("copyReferring");

    URL xsltURL = Stylesheets.get("dtbook2xhtml.xsl");
    File inFile = FilenameOrFileURI.toFile(inputXML);

    /*
     * Check if the doc is compound
     */
    try {
      NamespaceReporter nsr = new NamespaceReporter(inFile.toURI().toURL());
      if (nsr.getNamespaceURIs().contains(Namespaces.MATHML_NS_URI)) {
        this.sendMessage(
            i18n("CONTAINS_MATHML"), MessageEvent.Type.INFO, MessageEvent.Cause.SYSTEM);
        parameters.put("svg_mathml", "true");
      }

      if (nsr.getNamespaceURIs().contains(Namespaces.SVG_NS_URI)) {
        this.sendMessage(i18n("CONTAINS_SVG"), MessageEvent.Type.INFO, MessageEvent.Cause.SYSTEM);
        parameters.put("svg_mathml", "true");
      }
    } catch (Exception e) {
      this.sendMessage(
          i18n("ERROR", e.getMessage()), MessageEvent.Type.ERROR, MessageEvent.Cause.SYSTEM);
    }

    try {
      File outFile = FilenameOrFileURI.toFile(out);
      FileUtils.createDirectory(outFile.getParentFile());

      if ("true".equals(copyReferring)) {
        EFile eInFile = new EFile(inFile);
        String outFileName;
        Directory folder;
        if (outFile.isDirectory()) {
          folder = new Directory(outFile);
          outFileName = eInFile.getNameMinusExtension() + ".html";
        } else {
          folder = new Directory(outFile.getParentFile());
          outFileName = outFile.getName();
        }

        if (inFile.getParentFile().getCanonicalPath().equals(folder.getCanonicalPath())) {
          throw new TransformerRunException(i18n("INPUT_OUTPUT_SAME"));
        }
        Fileset fileset = this.buildFileSet(new File(inputXML));
        if (!parameters.containsKey("css_path")) {
          parameters.put("css_path", "default.css");
        }
        Map<String, Object> xslParams = new HashMap<String, Object>();
        xslParams.putAll(parameters);
        Stylesheet.apply(
            inputXML,
            xsltURL,
            new File(folder, outFileName).toString(),
            factory,
            xslParams,
            CatalogEntityResolver.getInstance());

        URL url2 = Css.get(Css.DocumentType.D202_XHTML);
        folder.writeToFile(parameters.get("css_path"), url2.openStream());

        for (Iterator<FilesetFile> it = fileset.getLocalMembers().iterator(); it.hasNext(); ) {
          FilesetFile fsf = it.next();
          if (fsf instanceof ImageFile) {
            FileUtils.copyChild(fsf.getFile(), folder, inFile.getParentFile());
          }
        }
      } else {
        Map<String, Object> xslParams = new HashMap<String, Object>();
        xslParams.putAll(parameters);
        Stylesheet.apply(
            inputXML, xsltURL, out, factory, xslParams, CatalogEntityResolver.getInstance());
      }

      if (parameters.containsKey("svg_mathml")) {
        // some post-xslt namespace cleanup.
        Map<String, Object> domConfigMap =
            LSParserPool.getInstance().getDefaultPropertyMap(Boolean.FALSE);
        domConfigMap.put("resource-resolver", CatalogEntityResolver.getInstance());
        LSParser parser = LSParserPool.getInstance().acquire(domConfigMap);
        DOMConfiguration domConfig = parser.getDomConfig();
        domConfig.setParameter("error-handler", this);
        Document doc = parser.parseURI(outFile.toURI().toString());

        SimpleNamespaceContext snc = new SimpleNamespaceContext();
        snc.declareNamespace("m", Namespaces.MATHML_NS_URI);
        NodeList math = XPathUtils.selectNodes(doc.getDocumentElement(), "//m:*", snc);
        for (int i = 0; i < math.getLength(); i++) {
          try {
            Node m = math.item(i);
            m.setPrefix("");
            if (m.getLocalName().equals("math")) {
              m.getAttributes().removeNamedItem("xmlns:dtbook");
              m.getAttributes().removeNamedItem("xmlns:m");
              Node c = m.getAttributes().getNamedItem("xmlns");
              c.setNodeValue(Namespaces.MATHML_NS_URI);
            }
          } catch (Exception e) {
            this.sendMessage(e.getMessage(), MessageEvent.Type.ERROR);
          }
        }

        Map<String, Object> props = new HashMap<String, Object>();
        props.put(
            "namespaces", Boolean.FALSE); // temp because of attributeNS bug(?) in Xerces DOM3LS				
        props.put("error-handler", this);
        // props.put("format-pretty-print", Boolean.TRUE);
        Serializer.serialize(doc, outFile, "utf-8", props);
      }

    } catch (XSLTException e) {
      throw new TransformerRunException(e.getMessage(), e);
    } catch (CatalogExceptionNotRecoverable e) {
      throw new TransformerRunException(e.getMessage(), e);
    } catch (FilesetFatalException e) {
      throw new TransformerRunException(e.getMessage(), e);
    } catch (IOException e) {
      throw new TransformerRunException(e.getMessage(), e);
    }

    return true;
  }