/** @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String) */
  public void processingInstruction(String target, String data) throws SAXException {
    if (inModification && charBuf.length() > 0) {
      final String normalized = charBuf.getNormalizedString(FastStringBuffer.SUPPRESS_BOTH);
      if (normalized.length() > 0) {
        final Text text = doc.createTextNode(normalized);
        if (stack.isEmpty()) {

          if (LOG.isDebugEnabled()) {
            LOG.debug("appending text to fragment: " + text.getData());
          }

          contents.add(text);
        } else {
          final Element last = stack.peek();
          last.appendChild(text);
        }
      }
      charBuf.setLength(0);
    }
    if (inModification) {
      final ProcessingInstruction pi = doc.createProcessingInstruction(target, data);
      if (stack.isEmpty()) {
        contents.add(pi);
      } else {
        final Element last = stack.peek();
        last.appendChild(pi);
      }
    }
  }
Example #2
0
  /**
   * If available, when the disable-output-escaping attribute is used, output raw text without
   * escaping. A PI will be inserted in front of the node with the name "lotusxsl-next-is-raw" and a
   * value of "formatter-to-dom".
   *
   * @param ch Array containing the characters
   * @param start Index to start of characters in the array
   * @param length Number of characters in the array
   */
  public void charactersRaw(char ch[], int start, int length) throws org.xml.sax.SAXException {
    if (isOutsideDocElem()
        && org.apache.xml.utils.XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
      return; // avoid DOM006 Hierarchy request error

    String s = new String(ch, start, length);

    append(m_doc.createProcessingInstruction("xslt-next-is-raw", "formatter-to-dom"));
    append(m_doc.createTextNode(s));
  }
Example #3
0
  public static void main(String[] args) {

    try {

      // Find the implementation
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setNamespaceAware(true);
      DocumentBuilder builder = factory.newDocumentBuilder();
      DOMImplementation impl = builder.getDOMImplementation();

      // Create the document
      DocumentType svgDOCTYPE =
          impl.createDocumentType(
              "svg",
              "-//W3C//DTD SVG 1.0//EN",
              "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd");
      Document doc = impl.createDocument("http://www.w3.org/2000/svg", "svg", svgDOCTYPE);

      // Fill the document
      Node rootElement = doc.getDocumentElement();
      ProcessingInstruction xmlstylesheet =
          doc.createProcessingInstruction(
              "xml-stylesheet", "type=\"text/css\" href=\"standard.css\"");
      Comment comment = doc.createComment("An example from Chapter 10 of Processing XML with Java");
      doc.insertBefore(comment, rootElement);
      doc.insertBefore(xmlstylesheet, rootElement);
      Node desc = doc.createElementNS("http://www.w3.org/2000/svg", "desc");
      rootElement.appendChild(desc);
      Text descText = doc.createTextNode("An example from Processing XML with Java");
      desc.appendChild(descText);

      // Serialize the document onto System.out
      TransformerFactory xformFactory = TransformerFactory.newInstance();
      Transformer idTransform = xformFactory.newTransformer();
      Source input = new DOMSource(doc);
      Result output = new StreamResult(System.out);
      idTransform.transform(input, output);

    } catch (FactoryConfigurationError e) {
      System.out.println("Could not locate a JAXP factory class");
    } catch (ParserConfigurationException e) {
      System.out.println("Could not locate a JAXP DocumentBuilder class");
    } catch (DOMException e) {
      System.err.println(e);
    } catch (TransformerConfigurationException e) {
      System.err.println(e);
    } catch (TransformerException e) {
      System.err.println(e);
    }
  }
Example #4
0
  public static boolean saveXml(String file, Document doc) {
    if (doc == null) {
      return false;
    }
    File f = new File(file);
    BukkitLogger.info("Saving data into file: " + f.getAbsolutePath());
    try {
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();

      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

      // doc.setXmlStandalone(true);

      if (PluginInfo.settingsXml.xslt != null && !PluginInfo.settingsXml.xslt.isEmpty()) {
        ProcessingInstruction pi =
            doc.createProcessingInstruction(
                "xml-stylesheet", "type=\"text/xsl\" href=\"" + PluginInfo.settingsXml.xslt + "\"");
        doc.insertBefore(pi, doc.getDocumentElement());
      }

      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(f);
      transformer.transform(source, result);
      return true;
    } catch (TransformerFactoryConfigurationError ex) {
      BukkitLogger.warning(
          "Transform Configuration Exception while saving XML file "
              + file
              + ": "
              + ex.getMessage());
    } catch (TransformerException ex) {
      BukkitLogger.warning(
          "Transform Exception while saving XML file " + file + ": " + ex.getMessage());
    } catch (Exception ex) {
      BukkitLogger.warning(
          "Unknown Exception while saving XML file " + file + ": " + ex.getMessage());
    }
    return false;
  }
  /**
   * Generate OFX export file from the transactions in the database
   *
   * @return String containing OFX export
   * @throws ExporterException
   */
  private String generateOfxExport() throws ExporterException {
    mAccountsList = mAccountsDbAdapter.getExportableAccounts(mExportParams.getExportStartTime());

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder;
    try {
      docBuilder = docFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      throw new ExporterException(mExportParams, e);
    }

    Document document = docBuilder.newDocument();
    Element root = document.createElement("OFX");

    ProcessingInstruction pi = document.createProcessingInstruction("OFX", OfxHelper.OFX_HEADER);
    document.appendChild(pi);
    document.appendChild(root);

    generateOfx(document, root);

    boolean useXmlHeader =
        PreferenceManager.getDefaultSharedPreferences(mContext)
            .getBoolean(mContext.getString(R.string.key_xml_ofx_header), false);

    PreferencesHelper.setLastExportTime(TimestampHelper.getTimestampFromNow());

    StringWriter stringWriter = new StringWriter();
    // if we want SGML OFX headers, write first to string and then prepend header
    if (useXmlHeader) {
      write(document, stringWriter, false);
      return stringWriter.toString();
    } else {
      Node ofxNode = document.getElementsByTagName("OFX").item(0);
      write(ofxNode, stringWriter, true);
      return OfxHelper.OFX_SGML_HEADER + '\n' + stringWriter.toString();
    }
  }
  private void writeDependencyManagementFile() throws IOException {
    if (null == dependencyManagementFile) {
      return;
    }

    log("Creating dependency management file: " + dependencyManagementFile, Project.MSG_VERBOSE);

    final String prefix1 = "  ";
    final String prefix2 = prefix1 + "  ";
    final String prefix3 = prefix2 + "  ";

    final Document doc = FileUtil.createXML("KF");
    final Element root = doc.getDocumentElement();

    // Create and add the xml-stylesheet instruction
    final ProcessingInstruction pi =
        doc.createProcessingInstruction(
            "xml-stylesheet", "type='text/xsl' href='mvn_dep_mgmt.xsl'");
    doc.insertBefore(pi, root);

    root.setAttribute("version", version);
    root.setAttribute("product", product);
    root.appendChild(doc.createTextNode("\n"));

    final Element dm = doc.createElement("dependencyManagement");
    root.appendChild(dm);

    // Element hodling extra presentation data for each bundle artifact
    final Element bundles = doc.createElement("bundles");
    root.appendChild(doc.createTextNode("\n"));
    root.appendChild(bundles);

    dm.appendChild(doc.createTextNode("\n" + prefix1));
    final Element dependencies = doc.createElement("dependencies");
    dm.appendChild(dependencies);

    for (final Entry<String, SortedSet<BundleArchive>> entry : bas.bsnToBundleArchives.entrySet()) {
      final SortedSet<BundleArchive> bsnSet = entry.getValue();
      // Sorted set with bundle archives, same bsn, different versions
      for (final BundleArchive ba : bsnSet) {
        dependencies.appendChild(doc.createTextNode("\n\n" + prefix2));
        dependencies.appendChild(doc.createComment(ba.relPath));
        dependencies.appendChild(doc.createTextNode("\n" + prefix2));

        final Element dependency = doc.createElement("dependency");
        dependencies.appendChild(dependency);

        // Dummy element to read mvn coordinates from
        final Element coordinateEl = doc.createElement("dummy");
        addMavenCoordinates(coordinateEl, ba);
        addMavenCoordinates(coordinateEl, dependency, prefix3);

        dependency.appendChild(doc.createTextNode("\n" + prefix2));

        // Bundle metadata for xsl rendering
        final Element bundle = doc.createElement("bundle");
        bundles.appendChild(doc.createTextNode("\n" + prefix2));
        bundles.appendChild(bundle);

        bundle.appendChild(doc.createTextNode("\n" + prefix3));
        final Element name = doc.createElement("name");
        bundle.appendChild(name);
        name.appendChild(doc.createTextNode(ba.name));
        log("name: " + ba.name, Project.MSG_VERBOSE);

        String description = ba.getBundleDescription();
        log("description: " + description, Project.MSG_VERBOSE);
        if (null == description) {
          description = "";
        }
        bundle.appendChild(doc.createTextNode("\n" + prefix3));
        final Element descrEl = doc.createElement("description");
        bundle.appendChild(descrEl);
        descrEl.appendChild(doc.createTextNode(description));

        addMavenCoordinates(coordinateEl, bundle, prefix3);

        bundle.appendChild(doc.createTextNode("\n" + prefix3));
        String mvnPath = getMavenPath(coordinateEl);
        final String groupIdPath = groupId.replace('.', '/');
        if (mvnPath.startsWith(groupIdPath)) {
          mvnPath = mvnPath.substring(groupIdPath.length() + 1);
        } else {
          // Add one "../" to mvnPath for each level in the groupId
          mvnPath = "../" + mvnPath;
          int sPos = groupIdPath.indexOf('/');
          while (-1 < sPos) {
            mvnPath = "../" + mvnPath;
            sPos = groupIdPath.indexOf('/', sPos + 1);
          }
        }
        final Element url = doc.createElement("url");
        bundle.appendChild(url);
        log("mvnPath: " + mvnPath, Project.MSG_VERBOSE);
        url.appendChild(doc.createTextNode(mvnPath));

        bundle.appendChild(doc.createTextNode("\n" + prefix2));
      }
    }
    dependencies.appendChild(doc.createTextNode("\n" + prefix1));
    bundles.appendChild(doc.createTextNode("\n" + prefix1));
    dm.appendChild(doc.createTextNode("\n"));
    root.appendChild(doc.createTextNode("\n"));

    FileUtil.writeDocumentToFile(dependencyManagementFile, doc);
    log("wrote " + dependencyManagementFile, Project.MSG_VERBOSE);
  }
  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;
  }
Example #8
0
 public void processingInstruction(String target, String data) throws SAXException {
   Node parent = getParent();
   ProcessingInstruction pi = document.createProcessingInstruction(target, data);
   parent.appendChild(pi);
 }
Example #9
0
 /**
  * Receive notification of a processing instruction.
  *
  * <p>The Parser will invoke this method once for each processing instruction found: note that
  * processing instructions may occur before or after the main document element.
  *
  * <p>A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a text
  * declaration (XML 1.0, section 4.3.1) using this method.
  *
  * @param target The processing instruction target.
  * @param data The processing instruction data, or null if none was supplied.
  */
 public void processingInstruction(String target, String data) throws org.xml.sax.SAXException {
   append(m_doc.createProcessingInstruction(target, data));
 }
Example #10
0
 @Override
 public ProcessingInstruction createProcessingInstruction(String target, String data)
     throws DOMException {
   return doc.createProcessingInstruction(target, data);
 }