예제 #1
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);
    }
  }
예제 #2
0
  /**
   * Create a new document with a document type using a custom document builder.
   *
   * @param aDocBuilder the document builder to be used. May not be <code>null</code>.
   * @param eVersion The XML version to use. If <code>null</code> is passed, {@link
   *     EXMLVersion#DEFAULT} will be used.
   * @param sQualifiedName The qualified name to use.
   * @param sPublicId The public ID of the document type.
   * @param sSystemId The system ID of the document type.
   * @return The created document. Never <code>null</code>.
   */
  @Nonnull
  public static Document newDocument(
      @Nonnull final DocumentBuilder aDocBuilder,
      @Nullable final EXMLVersion eVersion,
      @Nonnull final String sQualifiedName,
      @Nullable final String sPublicId,
      @Nullable final String sSystemId) {
    ValueEnforcer.notNull(aDocBuilder, "DocBuilder");

    final DOMImplementation aDomImpl = aDocBuilder.getDOMImplementation();
    final DocumentType aDocType = aDomImpl.createDocumentType(sQualifiedName, sPublicId, sSystemId);

    final Document aDoc = aDomImpl.createDocument(sSystemId, sQualifiedName, aDocType);
    aDoc.setXmlVersion((eVersion != null ? eVersion : EXMLVersion.DEFAULT).getVersion());
    return aDoc;
  }
예제 #3
0
  /**
   * Creates empty DOM Document using JAXP factoring. E.g.:
   *
   * <p>
   *
   * <pre>
   * Document doc = createDocument("book", null, null, null);
   * </pre>
   *
   * <p>creates new DOM of a well-formed document with root element named book.
   *
   * @param rootQName qualified name of root element. e.g. <code>myroot</code> or <code>ns:myroot
   *     </code>
   * @param namespaceURI URI of root element namespace or <code>null</code>
   * @param doctypePublicID public ID of DOCTYPE or <code>null</code>
   * @param doctypeSystemID system ID of DOCTYPE or <code>null</code> if no DOCTYPE required and
   *     doctypePublicID is also <code>null</code>
   * @throws DOMException if new DOM with passed parameters can not be created
   * @throws FactoryConfigurationError Application developers should never need to directly catch
   *     errors of this type.
   * @return new DOM Document
   */
  public static Document createDocument(
      String rootQName, String namespaceURI, String doctypePublicID, String doctypeSystemID)
      throws DOMException {

    DOMImplementation impl = getDOMImplementation();

    if (doctypePublicID != null && doctypeSystemID == null) {
      throw new IllegalArgumentException(
          "System ID cannot be null if public ID specified. "); // NOI18N
    }

    DocumentType dtd = null;
    if (doctypeSystemID != null) {
      dtd = impl.createDocumentType(rootQName, doctypePublicID, doctypeSystemID);
    }

    return impl.createDocument(namespaceURI, rootQName, dtd);
  }
  @Override
  public Document clean(Reader originalHtmlContent, HTMLCleanerConfiguration configuration) {
    Document result;

    // Note: Instantiation of an HtmlCleaner object is cheap so there's no need to cache an instance
    // of it,
    // especially since this makes it extra safe with regards to multithreading (even though HTML
    // Cleaner is
    // already supposed to be thread safe).
    CleanerProperties cleanerProperties = getDefaultCleanerProperties(configuration);
    HtmlCleaner cleaner = new HtmlCleaner(cleanerProperties);

    cleaner.setTransformations(getDefaultCleanerTransformations(configuration));
    TagNode cleanedNode;
    try {
      cleanedNode = cleaner.clean(originalHtmlContent);
    } catch (Exception e) {
      // This shouldn't happen since we're not doing any IO... I consider this a flaw in the design
      // of HTML
      // Cleaner.
      throw new RuntimeException("Unhandled error when cleaning HTML", e);
    }

    // Serialize the cleanedNode TagNode into a w3c dom. Ideally following code should be enough.
    // But SF's HTML Cleaner seems to omit the DocType declaration while serializing.
    // See
    // https://sourceforge.net/tracker/index.php?func=detail&aid=2062318&group_id=183053&atid=903696
    //      cleanedNode.setDocType(new DoctypeToken("html", "PUBLIC", "-//W3C//DTD XHTML 1.0
    // Strict//EN",
    //          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"));
    //      try {
    //          result = new DomSerializer(cleanerProperties, false).createDOM(cleanedNode);
    //      } catch(ParserConfigurationException ex) { }
    // As a workaround, we must serialize the cleanedNode into a temporary w3c document, create a
    // new w3c document
    // with proper DocType declaration and move the root node from the temporary document to the new
    // one.
    try {
      // Since there's a bug in SF's HTML Cleaner in that it doesn't recognize CDATA blocks we need
      // to turn off
      // character escaping (hence the false value passed) and do the escaping in
      // XMLUtils.toString(). Note that
      // this can cause problem for code not serializing the W3C DOM to a String since it won't have
      // the
      // characters escaped.
      // See
      // https://sourceforge.net/tracker/index.php?func=detail&aid=2691888&group_id=183053&atid=903696
      Document tempDoc = new XWikiDOMSerializer(cleanerProperties, false).createDOM(cleanedNode);
      DOMImplementation domImpl =
          DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
      DocumentType docType =
          domImpl.createDocumentType(
              QUALIFIED_NAME_HTML,
              "-//W3C//DTD XHTML 1.0 Strict//EN",
              "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");
      result = domImpl.createDocument(null, QUALIFIED_NAME_HTML, docType);
      result.replaceChild(
          result.adoptNode(tempDoc.getDocumentElement()), result.getDocumentElement());
    } catch (ParserConfigurationException ex) {
      throw new RuntimeException("Error while serializing TagNode into w3c dom.", ex);
    }

    // Finally apply filters.
    for (HTMLFilter filter : configuration.getFilters()) {
      filter.filter(result, configuration.getParameters());
    }

    return result;
  }
예제 #5
0
  private Document createInfoXml(final Attributes attr) throws BuildException {
    DOMImplementation domimpl;
    try {
      domimpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException x) {
      throw new BuildException(x, getLocation());
    }
    String loc = attr.getValue("locale");
    if (loc == null) {
      throw new BuildException("Got module attributes for undefined locale", getLocation());
    } else {
      log("Creating info.xml from module attributes for locale '" + loc + "'", Project.MSG_VERBOSE);
    }

    String pub, sys;
    if (preferredupdate != null && !("".equals(preferredupdate))) {
      pub = "-//NetBeans//DTD Autoupdate Module Info 2.7//EN";
      sys = "http://www.netbeans.org/dtds/autoupdate-info-2_7.dtd";
    } else if (attr.getValue("AutoUpdate-Show-In-Client") != null
        || attr.getValue("AutoUpdate-Essential-Module") != null
        || attr.getValue("OpenIDE-Module-Recommends") != null
        || attr.getValue("OpenIDE-Module-Needs") != null) {
      pub = "-//NetBeans//DTD Autoupdate Module Info 2.5//EN";
      sys = "http://www.netbeans.org/dtds/autoupdate-info-2_5.dtd";
    } else if (targetcluster != null && !("".equals(targetcluster))) {
      pub = "-//NetBeans//DTD Autoupdate Module Info 2.4//EN";
      sys = "http://www.netbeans.org/dtds/autoupdate-info-2_4.dtd";
    } else {
      // #74866: no need for targetcluster, so keep compat w/ 5.0 AU.
      pub = "-//NetBeans//DTD Autoupdate Module Info 2.3//EN";
      sys = "http://www.netbeans.org/dtds/autoupdate-info-2_3.dtd";
    }
    Document doc =
        domimpl.createDocument(null, "module", domimpl.createDocumentType("module", pub, sys));
    String codenamebase = attr.getValue("OpenIDE-Module");
    if (codenamebase == null) {
      Iterator it = attr.keySet().iterator();
      Name key;
      String val;
      while (it.hasNext()) {
        key = (Name) it.next();
        val = attr.getValue(key);
        log(key + " is '" + val + "'", Project.MSG_VERBOSE);
      }
      throw new BuildException("invalid manifest, does not contain OpenIDE-Module", getLocation());
    }
    // Strip major release number if any.
    int idx = codenamebase.lastIndexOf('/');
    if (idx != -1) codenamebase = codenamebase.substring(0, idx);
    Element module = doc.getDocumentElement();
    module.setAttribute("codenamebase", codenamebase);
    if (homepage != null) {
      module.setAttribute("homepage", homepage);
    }
    if (distribution != null) {
      module.setAttribute("distribution", distribution);
    } else {
      throw new BuildException("NBM distribution URL is not set", getLocation());
    }
    // Here we only write a name for the license.
    if (license != null) {
      String name = license.getName();
      if (name == null) {
        throw new BuildException("Every license must have a name or file attribute", getLocation());
      }
      module.setAttribute("license", name);
    }
    module.setAttribute("downloadsize", "0");
    if (needsrestart != null) {
      module.setAttribute("needsrestart", needsrestart);
    }
    if (global != null && !("".equals(global))) {
      module.setAttribute("global", global);
    }
    if (preferredupdate != null && !("".equals(preferredupdate))) {
      module.setAttribute("preferredupdate", global);
    }
    if (targetcluster != null && !("".equals(targetcluster))) {
      module.setAttribute("targetcluster", targetcluster);
    }
    if (moduleauthor != null) {
      module.setAttribute("moduleauthor", moduleauthor);
    }
    if (releasedate == null || "".equals(releasedate)) {
      // if date is null, set today
      releasedate = DATE_FORMAT.format(new Date(System.currentTimeMillis()));
    }
    module.setAttribute("releasedate", releasedate);
    if (desc != null) {
      module.appendChild(doc.createElement("description")).appendChild(desc.getTextNode(doc));
    }
    if (notification != null) {
      module
          .appendChild(doc.createElement("module_notification"))
          .appendChild(notification.getTextNode(doc));
    }
    if (externalPackages != null) {
      Iterator<ExternalPackage> exp = externalPackages.iterator();
      while (exp.hasNext()) {
        ExternalPackage externalPackage = exp.next();
        if (externalPackage.name == null
            || externalPackage.targetName == null
            || externalPackage.startUrl == null)
          throw new BuildException("Must define name, targetname, starturl for external package");
        Element el = doc.createElement("external_package");
        el.setAttribute("name", externalPackage.name);
        el.setAttribute("target_name", externalPackage.targetName);
        el.setAttribute("start_url", externalPackage.startUrl);
        if (externalPackage.description != null) {
          el.setAttribute("description", externalPackage.description);
        }
        module.appendChild(el);
      }
    }
    // Write manifest attributes.
    Element el = doc.createElement("manifest");
    List<String> attrNames = new ArrayList<String>(attr.size());
    Iterator it = attr.keySet().iterator();
    while (it.hasNext()) {
      attrNames.add(((Attributes.Name) it.next()).toString());
    }
    Collections.sort(attrNames);
    it = attrNames.iterator();
    while (it.hasNext()) {
      String name = (String) it.next();
      if (name.matches(
          "OpenIDE-Module(|-(Name|(Specification|Implementation)-Version|(Module|Package|Java|IDE)-Dependencies|"
              + "(Short|Long)-Description|Display-Category|Provides|Requires|Recommends|Needs))|AutoUpdate-(Show-In-Client|Essential-Module)")) {
        el.setAttribute(name, attr.getValue(name));
      }
    }
    module.appendChild(el);
    // Maybe write out license text.
    if (license != null) {
      el = doc.createElement("license");
      el.setAttribute("name", license.getName());
      el.appendChild(license.getTextNode(doc));
      module.appendChild(el);
    }
    if (updaterJar != null && updaterJar.size() > 0) {
      try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLUtil.write(doc, baos);
        validateAgainstAUDTDs(
            new InputSource(new ByteArrayInputStream(baos.toByteArray())), updaterJar, this);
      } catch (Exception x) {
        throw new BuildException(
            "Could not validate Info.xml before writing: " + x, x, getLocation());
      }
    } else {
      log("No updater.jar specified, cannot validate Info.xml against DTD", Project.MSG_WARN);
    }
    return doc;
  }