public static void exportSVG(File file, Algorithm algorithm, Config config, int width, int height)
      throws TransformerException, IOException {
    DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
    String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
    Document doc = impl.createDocument(svgNS, "svg", null);

    Element svgRoot = doc.getDocumentElement();

    svgRoot.setAttributeNS(null, "width", Integer.toString(width));
    svgRoot.setAttributeNS(null, "height", Integer.toString(height));

    SvgPainter painter = new SvgPainter(doc, svgRoot);

    AlgorithmPainter algorithmPainter = new AlgorithmPainter(algorithm, config, painter);

    algorithmPainter.setWidth(width);
    algorithmPainter.setHeight(height);
    algorithmPainter.paint();

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    FileOutputStream fos = new FileOutputStream(file);
    StreamResult result = new StreamResult(fos);

    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    transformer.transform(source, result);

    fos.close();
  }
Exemple #2
0
 /** Initializes structures necessary for the SVG output */
 protected void initializeSVGGraphics() {
   DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
   String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
   svgDoc = (SVGDocument) impl.createDocument(svgNS, "svg", null);
   svgGraphics = new SVGGraphics2D(svgDoc);
   isSVGGraphicsInitialized = true;
 }
Exemple #3
0
  private void saveChartAsSVG(JFreeChart chart, String fileName, int width, int height)
      throws KeyedException {
    Writer out = null;
    try {
      out = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8");
      String svgNS = "http://www.w3.org/2000/svg";
      DOMImplementation di =
          DOMImplementationRegistry.newInstance().getDOMImplementation("XML 1.0");
      Document document = di.createDocument(svgNS, "svg", null);

      SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
      ctx.setEmbeddedFontsOn(true);
      SVGGraphics2D svgGenerator = new CustomSVGGraphics2D(ctx, true, 100, true);
      svgGenerator.setSVGCanvasSize(new Dimension(width, height));
      chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height));
      boolean useCSS = true;
      svgGenerator.stream(out, useCSS);
      svgGenerator.dispose();
    } catch (Exception e) {
      throw K.JFC_OUTPUT_ERR.exception(e, fileName);
    } finally {
      try {
        if (out != null) out.close();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }
Exemple #4
0
  private static void exportScreenshotSVG(
      Component target, File selectedFile, boolean paintOffscreen) throws IOException {

    String format = "svg";
    selectedFile = fixFileExt(selectedFile, new String[] {format}, format);

    // Create an instance of org.w3c.dom.Document.
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
    String svgNS = "http://www.w3.org/2000/svg";
    Document document = domImpl.createDocument(svgNS, format, null);

    // Write image data into document
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

    choosePaint(target, svgGenerator, paintOffscreen);

    Writer out = null;
    try {
      // Finally, stream out SVG to the standard output using
      // UTF-8 encoding.
      boolean useCSS = true; // we want to use CSS style attributes
      out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(selectedFile), "UTF-8"));
      svgGenerator.stream(out, useCSS);
    } finally {
      if (out != null)
        try {
          out.close();
        } catch (IOException e) {
          log.error("Error closing svg file", e);
        }
    }
  }
Exemple #5
0
  public GraphicSet importSetFromFile(File inputFile, List<String> warnings)
      throws ImportException {
    Writer out = null;
    try {
      // Get a DOMImplementation
      DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
      // Create an instance of org.w3c.dom.Document
      Document document = domImpl.createDocument(null, "svg", null);
      // Create an instance of the SVG Generator
      final SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
      svgGenerator.setTransform(new AffineTransform());
      // Open input file
      PSInputFile in = new PSInputFile(inputFile.getAbsolutePath());
      Rectangle2D bb = this.getBoundingBox(inputFile);
      svgGenerator.setTransform(AffineTransform.getTranslateInstance(-bb.getX(), -bb.getY()));
      Dimension d = new Dimension((int) bb.getWidth(), (int) bb.getHeight());
      // Create processor and associate to input and output file
      Processor processor = new Processor(svgGenerator, d, false);
      processor.setData(in);

      // Process
      processor.process();
      File tmp = File.createTempFile("temp", "svg");
      tmp.deleteOnExit();
      svgGenerator.stream(new FileWriter(tmp));
      GraphicSet result = new SVGImporter().importSetFromFile(tmp, warnings);
      // Assume the EPS has been created with 72DPI (from Inkscape)
      double px2mm = Util.inch2mm(1d / 72d);
      result.setBasicTransform(AffineTransform.getScaleInstance(px2mm, px2mm));
      return result;
    } catch (Exception ex) {
      Logger.getLogger(EPSImporter.class.getName()).log(Level.SEVERE, null, ex);
      throw new ImportException(ex);
    }
  }
  public static void main(String[] args) throws TransformerException, IOException {
    DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
    String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
    Document doc = impl.createDocument(svgNS, "svg", null);

    Element svgRoot = doc.getDocumentElement();

    svgRoot.setAttributeNS(null, "width", "400");
    svgRoot.setAttributeNS(null, "height", "450");

    Element rectangle = doc.createElementNS(svgNS, "rect");
    rectangle.setAttributeNS(null, "x", "10");
    rectangle.setAttributeNS(null, "y", "20");
    rectangle.setAttributeNS(null, "width", "100");
    rectangle.setAttributeNS(null, "height", "50");
    rectangle.setAttributeNS(null, "fill", "red");

    svgRoot.appendChild(rectangle);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    File file = new File("/home/z/foo.svg");
    FileOutputStream fos = new FileOutputStream(file);
    StreamResult result = new StreamResult(fos);

    transformer.transform(source, result);

    fos.close();
  }
Exemple #7
0
  @Test
  public void testAddOrSetAttributeAttributesImplNode() throws ParserConfigurationException {
    final AttributesImpl atts = new AttributesImpl();
    final DOMImplementation dom =
        DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    final Document doc = dom.createDocument(null, "foo", null);

    doc.getDocumentElement().setAttribute("foo", "foo");
    final Attr att = (Attr) doc.getDocumentElement().getAttributeNode("foo");
    XMLUtils.addOrSetAttribute(atts, att);

    final int i = atts.getIndex(NULL_NS_URI, "foo");
    assertEquals(NULL_NS_URI, atts.getURI(i));
    assertEquals("foo", atts.getQName(i));
    assertEquals("foo", atts.getLocalName(i));
    assertEquals("foo", atts.getValue(i));

    doc.getDocumentElement().setAttributeNS(XML_NS_URI, "xml:lang", "en");
    final Attr lang = (Attr) doc.getDocumentElement().getAttributeNodeNS(XML_NS_URI, "lang");
    XMLUtils.addOrSetAttribute(atts, lang);

    final int l = atts.getIndex(XML_NS_URI, "lang");
    assertEquals(XML_NS_URI, atts.getURI(l));
    assertEquals("xml:lang", atts.getQName(l));
    assertEquals("lang", atts.getLocalName(l));
    assertEquals("en", atts.getValue(l));
  }
  /**
   * 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);
  }
  public static void main(String[] args) {

    String outputDir = "./";

    for (int i = 0; i < args.length; i++) {
      String arg = args[i];
      if ("-o".equals(arg)) {
        outputDir = args[++i];
        continue;
      } else {
        System.out.println("XMLSchemaGenerator -o <path to newly created xsd schema file>");
        return;
      }
    }

    File f = new File(outputDir, "JGroups-" + Version.major + "." + Version.minor + ".xsd");
    try {
      FileWriter fw = new FileWriter(f, false);
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      DOMImplementation impl = builder.getDOMImplementation();
      Document xmldoc = impl.createDocument("http://www.w3.org/2001/XMLSchema", "xs:schema", null);
      xmldoc.getDocumentElement().setAttribute("targetNamespace", "urn:org:jgroups");
      xmldoc.getDocumentElement().setAttribute("elementFormDefault", "qualified");

      Element xsElement = xmldoc.createElement("xs:element");
      xsElement.setAttribute("name", "config");
      xmldoc.getDocumentElement().appendChild(xsElement);

      Element complexType = xmldoc.createElement("xs:complexType");
      xsElement.appendChild(complexType);

      Element allType = xmldoc.createElement("xs:choice");
      allType.setAttribute("maxOccurs", "unbounded");
      complexType.appendChild(allType);

      Set<Class<?>> classes = getClasses("bboss.org.jgroups.protocols", Protocol.class);
      for (Class<?> clazz : classes) {
        classToXML(xmldoc, allType, clazz, "");
      }
      classes = getClasses("bboss.org.jgroups.protocols.pbcast", Protocol.class);
      for (Class<?> clazz : classes) {
        classToXML(xmldoc, allType, clazz, "pbcast.");
      }

      DOMSource domSource = new DOMSource(xmldoc);
      StreamResult streamResult = new StreamResult(fw);
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer serializer = tf.newTransformer();
      serializer.setOutputProperty(OutputKeys.METHOD, "xml");
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
      serializer.transform(domSource, streamResult);

      fw.flush();
      fw.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #10
0
  /**
   * Creates new org.w3c.dom.Document with Traversing possibility
   *
   * @param is <code>InputSource</code>
   * @return org.w3c.dom.Document
   * @throws CitationStyleManagerException
   */
  public static Document parseDocumentForTraversing(InputSource is)
      throws CitationStyleManagerException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder parser;
    try {
      parser = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      throw new CitationStyleManagerException("Cannot create DocumentBuilder:", e);
    }

    // Check for the traversal module
    DOMImplementation impl = parser.getDOMImplementation();
    if (!impl.hasFeature("traversal", "2.0")) {
      throw new CitationStyleManagerException(
          "A DOM implementation that supports traversal is required.");
    }
    Document doc;
    try {
      doc = parser.parse(is);
    } catch (Exception e) {
      throw new CitationStyleManagerException("Cannot parse InputSource to w3c document:", e);
    }

    return doc;
  }
  public void testSetNamedItemNS4() throws Throwable {
    Document doc;
    DOMImplementation domImpl;
    Document docAlt;
    DocumentType docType = null;

    NamedNodeMap attributes;
    NodeList elementList;
    Element element;
    Attr attrAlt;

    String nullNS = null;

    doc = (Document) load("staffNS", builder);
    elementList = doc.getElementsByTagNameNS("*", "address");
    element = (Element) elementList.item(1);
    attributes = element.getAttributes();
    domImpl = doc.getImplementation();
    docAlt = domImpl.createDocument(nullNS, "newDoc", docType);
    attrAlt = docAlt.createAttributeNS(nullNS, "street");

    {
      boolean success = false;
      try {
        attributes.setNamedItemNS(attrAlt);
      } catch (DOMException ex) {
        success = (ex.code == DOMException.WRONG_DOCUMENT_ERR);
      }
      assertTrue("throw_WRONG_DOCUMENT_ERR", success);
    }
  }
Exemple #12
0
 public static synchronized String domToString(Document theDoc, Node theNode) {
   DOMImplementation domI = theDoc.getImplementation();
   DOMImplementationLS domIls = (DOMImplementationLS) domI.getFeature("LS", "3.0");
   LSSerializer lss = domIls.createLSSerializer();
   String xmlstr = lss.writeToString(theNode);
   // <?xml version="1.0" encoding="UTF-16"?>
   return xmlstr;
 }
Exemple #13
0
  /** Mock object creator (for unit testing purposes) */
  public HarvesterVerb() {
    try {
      /* Load DOM Document */
      factory = DocumentBuilderFactory.newInstance();
      factory.setNamespaceAware(true);
      Thread t = Thread.currentThread();
      DocumentBuilder builder = factory.newDocumentBuilder();
      builderMap.put(t, builder);

      DOMImplementation impl = builder.getDOMImplementation();
      Document namespaceHolder =
          impl.createDocument(
              "http://www.oclc.org/research/software/oai/harvester",
              "harvester:namespaceHolder",
              null);
      namespaceElement = namespaceHolder.getDocumentElement();
      namespaceElement.setAttributeNS(
          "http://www.w3.org/2000/xmlns/",
          "xmlns:harvester",
          "http://www.oclc.org/research/software/oai/harvester");
      namespaceElement.setAttributeNS(
          "http://www.w3.org/2000/xmlns/",
          "xmlns:xsi",
          "http://www.w3.org/2001/XMLSchema-instance");
      namespaceElement.setAttributeNS(
          "http://www.w3.org/2000/xmlns/", "xmlns:oai20", "http://www.openarchives.org/OAI/2.0/");
      namespaceElement.setAttributeNS(
          "http://www.w3.org/2000/xmlns/",
          "xmlns:oai11_GetRecord",
          "http://www.openarchives.org/OAI/1.1/OAI_GetRecord");
      namespaceElement.setAttributeNS(
          "http://www.w3.org/2000/xmlns/",
          "xmlns:oai11_Identify",
          "http://www.openarchives.org/OAI/1.1/OAI_Identify");
      namespaceElement.setAttributeNS(
          "http://www.w3.org/2000/xmlns/",
          "xmlns:oai11_ListIdentifiers",
          "http://www.openarchives.org/OAI/1.1/OAI_ListIdentifiers");
      namespaceElement.setAttributeNS(
          "http://www.w3.org/2000/xmlns/",
          "xmlns:oai11_ListMetadataFormats",
          "http://www.openarchives.org/OAI/1.1/OAI_ListMetadataFormats");
      namespaceElement.setAttributeNS(
          "http://www.w3.org/2000/xmlns/",
          "xmlns:oai11_ListRecords",
          "http://www.openarchives.org/OAI/1.1/OAI_ListRecords");
      namespaceElement.setAttributeNS(
          "http://www.w3.org/2000/xmlns/",
          "xmlns:oai11_ListSets",
          "http://www.openarchives.org/OAI/1.1/OAI_ListSets");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemple #14
0
 /** Builds an <code>SVGGraphics2D</code> with a default configuration. */
 protected SVGGraphics2D buildSVGGraphics2D() {
   // CSSDocumentHandler.setParserClassName(CSS_PARSER_CLASS_NAME);
   DOMImplementation impl = GenericDOMImplementation.getDOMImplementation();
   String namespaceURI = SVGConstants.SVG_NAMESPACE_URI;
   Document domFactory = impl.createDocument(namespaceURI, SVG_SVG_TAG, null);
   SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(domFactory);
   GraphicContextDefaults defaults = new GraphicContextDefaults();
   defaults.font = new Font("Arial", Font.PLAIN, 12);
   ctx.setGraphicContextDefaults(defaults);
   ctx.setPrecision(12);
   return new SVGGraphics2D(ctx, false);
 }
Exemple #15
0
 /** Transform into formatted XML. */
 public static String getFormattedXml(Node node) {
   Document document =
       node.getOwnerDocument().getImplementation().createDocument("", "fake", null);
   Element copy = (Element) document.importNode(node, true);
   document.importNode(node, false);
   document.removeChild(document.getDocumentElement());
   document.appendChild(copy);
   DOMImplementation domImpl = document.getImplementation();
   DOMImplementationLS domImplLs = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
   LSSerializer serializer = domImplLs.createLSSerializer();
   serializer.getDomConfig().setParameter("format-pretty-print", true);
   return serializer.writeToString(document);
 }
  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);
    }
  }
  boolean testImpl(DOMImplementation impl, String features) {

    StringTokenizer st = new StringTokenizer(features);
    String feature = null;
    String version = null;

    if (st.hasMoreTokens()) {
      feature = st.nextToken();
    }
    while (feature != null) {
      boolean isVersion = false;
      if (st.hasMoreTokens()) {
        char c;
        version = st.nextToken();
        c = version.charAt(0);
        switch (c) {
          case '0':
          case '1':
          case '2':
          case '3':
          case '4':
          case '5':
          case '6':
          case '7':
          case '8':
          case '9':
            isVersion = true;
        }
      } else {
        version = null;
      }
      if (isVersion) {
        if (!impl.hasFeature(feature, version)) {
          return false;
        }
        if (st.hasMoreTokens()) {
          feature = st.nextToken();
        } else {
          feature = null;
        }
      } else {
        if (!impl.hasFeature(feature, null)) {
          return false;
        }
        feature = version;
      }
    }
    return true;
  }
  public void connectXML(String port, String user, String pass)
      throws ParserConfigurationException {
    String filename = "connect.xml";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();

    Element body = doc.createElement("Connect");
    doc.appendChild(body);

    Element e = doc.createElement("Port");
    Text t = doc.createTextNode(port);
    e.appendChild(t);
    body.appendChild(e);

    Element e1 = doc.createElement("User");
    Text t1 = doc.createTextNode(user);
    e1.appendChild(t1);
    body.appendChild(e1);

    Element e2 = doc.createElement("Pass");
    Text t2 = doc.createTextNode(pass);
    e2.appendChild(t2);
    body.appendChild(e2);

    DOMImplementation impl = doc.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer ser = implLS.createLSSerializer();
    LSOutput lsOutput = implLS.createLSOutput();
    lsOutput.setEncoding("UTF-8");
    // System.out.println(lsOutput.toString());
    Writer stringWriter = new StringWriter();
    lsOutput.setCharacterStream(stringWriter);
    ser.write(doc, lsOutput);
    String result = stringWriter.toString();
    System.out.println(result);
    // System.out.println(ser.write(doc,lsOutput));
    try {
      print(filename, result);
      System.out.println("Print Success");
      File file = new File(filename);
      System.out.println(file.getCanonicalPath());
    } catch (IOException e3) {
      // TODO Auto-generated catch block
      e3.printStackTrace();
      System.out.println("print failed");
    }
  }
Exemple #19
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;
  }
Exemple #20
0
  @Test
  public void testGetStringValue() throws ParserConfigurationException {
    final DOMImplementation dom =
        DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    final Document doc = dom.createDocument(null, "foo", null);

    final Element root = doc.getDocumentElement();
    root.appendChild(doc.createTextNode("foo"));
    assertEquals("foo", XMLUtils.getStringValue(root));
    root.appendChild(doc.createTextNode(" "));
    final Element nested = doc.createElement("ph");
    nested.appendChild(doc.createTextNode("nested"));
    root.appendChild(nested);
    root.appendChild(doc.createTextNode(" bar"));
    assertEquals("foo nested bar", XMLUtils.getStringValue(root));
  }
Exemple #21
0
 UserXML(String namespaceURI, String qualifiedName, String targetUriPattern, File dir)
     throws XMLStoreException {
   //      super(new File(dir, getFileName()));
   super(new File(dir, getFileName(targetUriPattern)), false);
   this.namespaceURI = namespaceURI;
   this.qualifiedName = qualifiedName;
   this.onlyInMemory = true;
   try {
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     DocumentBuilder builder = factory.newDocumentBuilder();
     DOMImplementation impl = builder.getDOMImplementation();
     doc = impl.createDocument(namespaceURI, qualifiedName, null);
     setTargetURIPattern(targetUriPattern);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Exemple #22
0
  public static void exportSVGImage(PrintWriter pr, Component c) throws IOException {

    // Get a DOMImplementation.
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();

    // Create an instance of org.w3c.dom.Document.
    String svgNS = "http://www.w3.org/2000/svg";
    Document document = domImpl.createDocument(svgNS, "svg", null);

    // Create an instance of the SVG Generator.
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
    c.paint(svgGenerator);

    // Finally, stream out SVG to the standard output using
    // UTF-8 encoding.
    svgGenerator.stream(pr, false);
  }
Exemple #23
0
  /**
   * Part of saveInstances
   *
   * @param file - The File object representing the XML file.
   * @return The DOM document representing the XML file.
   */
  private static Document createDocument(File file) {
    Document document = null;
    if (file != null) {
      try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation impl = builder.getDOMImplementation();

        // Create the document
        document = impl.createDocument(null, SEQUOYAH_XML_ROOT, null);

      } catch (ParserConfigurationException e) {
        e.printStackTrace();
      }
    }
    return document;
  }
Exemple #24
0
  /**
   * Converts a dom element to a String
   *
   * @param node
   * @return the dom as a String
   */
  public static String writeDomToString(Element node) {
    DOMImplementation domImplementation = node.getOwnerDocument().getImplementation();
    if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) {
      DOMImplementationLS domImplementationLS =
          (DOMImplementationLS) domImplementation.getFeature("LS", "3.0");
      LSSerializer lsSerializer = domImplementationLS.createLSSerializer();

      LSOutput lsOutput = domImplementationLS.createLSOutput();
      lsOutput.setEncoding("UTF-8");

      StringWriter stringWriter = new StringWriter();
      lsOutput.setCharacterStream(stringWriter);
      lsSerializer.write(node, lsOutput);
      return stringWriter.toString();
    } else {
      throw new RuntimeException("DOM 3.0 LS and/or DOM 2.0 Core not supported.");
    }
  }
Exemple #25
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);
  }
  /**
   * Runs the test case.
   *
   * @throws Throwable Any uncaught exception causes test to fail
   */
  public void runTest() throws Throwable {
    org.w3c.dom.bootstrap.DOMImplementationRegistry domImplRegistry;
    DOMImplementation domImpl;
    boolean hasFeature;
    String nullVersion = null;

    DOMImplementationList domImplList;
    int length;
    domImplRegistry = org.w3c.dom.bootstrap.DOMImplementationRegistry.newInstance();
    assertNotNull("domImplRegistryNotNull", domImplRegistry);
    domImplList = domImplRegistry.getDOMImplementationList("+cOrE");
    length = (int) domImplList.getLength();
    assertTrue("atLeastOne", (length > 0));
    for (int indexN10057 = 0; indexN10057 < domImplList.getLength(); indexN10057++) {
      domImpl = (DOMImplementation) domImplList.item(indexN10057);
      hasFeature = domImpl.hasFeature("+Core", nullVersion);
      assertTrue("hasCore", hasFeature);
    }
  }
Exemple #27
0
 private LSInput getLSInput() throws Exception {
   DOMImplementationLS impl;
   DOMImplementation docImpl = builder.getDOMImplementation();
   // Try to get the DOMImplementation from doc first before
   // defaulting to the sun implementation.
   if (docImpl != null && docImpl.hasFeature("LS", "3.0")) {
     impl = (DOMImplementationLS) docImpl.getFeature("LS", "3.0");
   } else {
     DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
     impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
     if (impl == null) {
       System.setProperty(
           DOMImplementationRegistry.PROPERTY,
           "com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
       registry = DOMImplementationRegistry.newInstance();
       impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
     }
   }
   return impl.createLSInput();
 }
  /**
   * 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);
  }
Exemple #29
0
  public static void dom() throws IOException {
    javax.xml.parsers.DocumentBuilder b;
    try {
      javax.xml.parsers.DocumentBuilderFactory f =
          javax.xml.parsers.DocumentBuilderFactory.newInstance();
      f.setNamespaceAware(true); // !!!
      b = f.newDocumentBuilder();
    } catch (javax.xml.parsers.ParserConfigurationException e) {
      e.printStackTrace();
      throw new RuntimeException("parser configuration exception");
    }
    org.w3c.dom.DOMImplementation domImpl = b.getDOMImplementation();

    // DOM works similar to DOM4J
    org.w3c.dom.Document doc = domImpl.createDocument("", "todo:todo", null);
    System.out.println("DOM: ");
    XMLSerializer serializer = new XMLSerializer(System.out, new OutputFormat(doc));
    serializer.serialize(doc);
    System.out.println();
  }
  /**
   * Runs the test case.
   *
   * @throws Throwable Any uncaught exception causes test to fail
   */
  public void runTest() throws Throwable {
    Document doc;
    DOMImplementation domImpl;
    Document newDoc;
    String namespaceURI;
    DocumentType nullDocType = null;

    Element docElem;
    String rootNS;
    String rootName;
    String qname;
    doc = (Document) load("hc_staff", false);
    docElem = doc.getDocumentElement();
    rootNS = docElem.getNamespaceURI();
    rootName = docElem.getTagName();
    domImpl = doc.getImplementation();
    qname = "dom3:" + rootName;
    newDoc = domImpl.createDocument(rootNS, qname, nullDocType);
    namespaceURI = newDoc.lookupNamespaceURI("dom3");
    assertEquals("nodelookupnamespaceuri02", rootNS, namespaceURI);
  }