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);
    }
  }
Example #2
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);
  }
Example #4
0
  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();
    }
  }
Example #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);
    }
  }
Example #6
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);
        }
    }
  }
  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();
  }
  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();
  }
Example #9
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;
 }
Example #10
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);
      }
    }
  }
Example #11
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();
    }
  }
Example #12
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);
 }
Example #13
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);
    }
  }
  public void exportIntroductionPuzzle(IntroductionPuzzle puzzle, OutputStream os)
      throws TransformerException, ParserConfigurationException {

    Document xmlDoc;
    synchronized (
        mDocumentBuilder) { // TODO: Figure out whether the DocumentBuilder is maybe synchronized
                            // anyway
      xmlDoc = mDOM.createDocument(null, WebOfTrust.WOT_NAME, null);
    }

    // 1.0 does not support all Unicode characters which the String class supports. To prevent us
    // from having to filter all Strings, we use 1.1
    xmlDoc.setXmlVersion("1.1");

    Element rootElement = xmlDoc.getDocumentElement();

    // We include the WoT version to have an easy way of handling bogus XML which might be created
    // by bugged versions.
    rootElement.setAttribute("Version", Long.toString(Version.getRealVersion()));

    Element puzzleElement = xmlDoc.createElement("IntroductionPuzzle");
    puzzleElement.setAttribute(
        "Version",
        Integer.toString(INTRODUCTION_XML_FORMAT_VERSION)); /* Version of the XML format */

    // This lock is actually not necessary because all values which are taken from the puzzle are
    // final. We leave it here just to make sure that it does
    // not get lost if it becomes necessary someday.
    synchronized (puzzle) {
      puzzleElement.setAttribute("ID", puzzle.getID());
      puzzleElement.setAttribute("Type", puzzle.getType().toString());
      puzzleElement.setAttribute("MimeType", puzzle.getMimeType());
      synchronized (mDateFormat) {
        puzzleElement.setAttribute("ValidUntil", mDateFormat.format(puzzle.getValidUntilDate()));
      }

      Element dataElement = xmlDoc.createElement("Data");
      dataElement.setAttribute("Value", Base64.encodeStandard(puzzle.getData()));
      puzzleElement.appendChild(dataElement);
    }

    rootElement.appendChild(puzzleElement);

    DOMSource domSource = new DOMSource(xmlDoc);
    StreamResult resultStream = new StreamResult(os);
    synchronized (mSerializer) {
      mSerializer.transform(domSource, resultStream);
    }
  }
  public void encode(WoTMessageManager messageManager, WoTOwnMessageList list, OutputStream os)
      throws TransformerException, ParserConfigurationException, NoSuchMessageException {
    synchronized (list) {
      Document xmlDoc;
      synchronized (mDocumentBuilder) {
        xmlDoc = mDOM.createDocument(null, Freetalk.PLUGIN_TITLE, null);
      }

      Element rootElement = xmlDoc.getDocumentElement();

      Element messageListTag = xmlDoc.createElement("MessageList");
      messageListTag.setAttribute(
          "Version", Integer.toString(XML_FORMAT_VERSION)); /* Version of the XML format */

      /* Important: A OwnMessageList contains a single reference for each message. A MessageList however contains a message reference
       * for each board a message is posted to. If this function is changed to be able to encode non-own MessageLists then you need
       * to ensure that each message is only listed once, the for(each MessageReference) will return duplicates if a message is posted
       * to multiple boards.*/
      for (MessageList.MessageReference ref : list) {
        OwnMessage message = messageManager.getOwnMessage(ref.getMessageID());
        if (message.wasInserted() == false)
          throw new RuntimeException(
              "Trying to convert a MessageList to XML which contains a not inserted message.");

        Element messageTag = xmlDoc.createElement("Message");
        messageTag.setAttribute("ID", message.getID());
        messageTag.setAttribute("URI", message.getFreenetURI().toString());
        synchronized (mDateFormat) {
          messageTag.setAttribute("Date", mDateFormat.format(message.getDate()));
        }

        for (Board board : message.getBoards()) {
          Element boardTag = xmlDoc.createElement("Board");
          boardTag.setAttribute("Name", board.getName());
          messageTag.appendChild(boardTag);
        }

        messageListTag.appendChild(messageTag);
      }

      rootElement.appendChild(messageListTag);

      DOMSource domSource = new DOMSource(xmlDoc);
      StreamResult resultStream = new StreamResult(os);
      synchronized (mSerializer) {
        mSerializer.transform(domSource, resultStream);
      }
    }
  }
Example #16
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;
  }
Example #17
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));
  }
Example #18
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();
   }
 }
Example #19
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);
  }
Example #20
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;
  }
Example #21
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);
  }
Example #22
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);
  }
Example #23
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);
  }
  /**
   * 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);
    }
  }
  public void exportIntroduction(OwnIdentity identity, OutputStream os)
      throws TransformerException {
    Document xmlDoc;
    synchronized (
        mDocumentBuilder) { // TODO: Figure out whether the DocumentBuilder is maybe synchronized
                            // anyway
      xmlDoc = mDOM.createDocument(null, WebOfTrust.WOT_NAME, null);
    }

    // 1.0 does not support all Unicode characters which the String class supports. To prevent us
    // from having to filter all Strings, we use 1.1
    xmlDoc.setXmlVersion("1.1");

    Element rootElement = xmlDoc.getDocumentElement();

    // We include the WoT version to have an easy way of handling bogus XML which might be created
    // by bugged versions.
    rootElement.setAttribute("Version", Long.toString(Version.getRealVersion()));

    Element introElement = xmlDoc.createElement("IdentityIntroduction");
    introElement.setAttribute(
        "Version", Integer.toString(XML_FORMAT_VERSION)); /* Version of the XML format */

    Element identityElement = xmlDoc.createElement("Identity");
    // synchronized(mWoT) { // Not necessary according to JavaDoc of identity.getRequestURI()
    identityElement.setAttribute("URI", identity.getRequestURI().toString());
    // }
    introElement.appendChild(identityElement);

    rootElement.appendChild(introElement);

    DOMSource domSource = new DOMSource(xmlDoc);
    StreamResult resultStream = new StreamResult(os);
    synchronized (
        mSerializer) { // TODO: Figure out whether the Serializer is maybe synchronized anyway
      mSerializer.transform(domSource, resultStream);
    }
  }
  /**
   * Exports a JFreeChart to a SVG file.
   *
   * @param chart JFreeChart to export
   * @param bounds the dimensions of the viewport
   * @param svgFile the output file.
   * @throws IOException if writing the svgFile fails.
   */
  public static byte[] convertChartToSVG(JFreeChart chart, int width, int height) {
    // Get a DOMImplementation and create an XML document
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
    Document document = domImpl.createDocument(null, "svg", null);

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

    // draw the chart in the SVG generator
    chart.draw(svgGenerator, new Rectangle(width, height));

    // Write svg file
    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      Writer out = new OutputStreamWriter(baos, "UTF-8");
      svgGenerator.stream(out, true /* use css */);
      out.flush();
      out.close();
      return baos.toByteArray();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Example #28
0
  public static void main(String[] args) throws Exception {
    // Create an SVG document.
    DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
    String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
    SVGDocument doc = (SVGDocument) impl.createDocument(svgNS, "svg", null);

    // Create a converter for this document.
    SVGGraphics2D g = new SVGGraphics2D(doc);

    // Do some drawing.
    Shape circle = new Ellipse2D.Double(0, 0, 50, 50);
    g.setPaint(Color.red);
    g.fill(circle);
    g.translate(60, 0);
    g.setPaint(Color.green);
    g.fill(circle);
    g.translate(60, 0);
    g.setPaint(Color.blue);
    g.fill(circle);
    g.setSVGCanvasSize(new Dimension(180, 50));

    // Populate the document root with the generated SVG content.
    Element root = doc.getDocumentElement();
    g.getRoot(root);

    Writer out = new OutputStreamWriter(System.out, "UTF-8");
    g.stream(out, true);

    // Display the document.
    JSVGCanvas canvas = new JSVGCanvas();
    JFrame f = new JFrame();
    f.getContentPane().add(canvas);
    canvas.setSVGDocument(doc);
    f.pack();
    f.setVisible(true);
  }
Example #29
0
  public static void domWithURI() 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; however you must provide an URI if a name has a prefix
    // passing in the the URI with createDocument makes no difference.
    org.w3c.dom.Document doc = domImpl.createDocument("", "todo:todo", null);

    // DOM does not add the declaration by default: use plain attribut
    doc.getDocumentElement().setAttribute("xmlns:todo", "http://www.example.com");
    System.out.println("DOM: ");
    XMLSerializer serializer = new XMLSerializer(System.out, new OutputFormat(doc));
    serializer.serialize(doc);
    System.out.println();
  }
Example #30
0
    /**
     * Draws a concreteDiagram as an SVG.
     *
     * <p>This approach is wholly declarative. It currently knows nothing about the on screen
     * rendering of the diagram. To make decisions based on the on screen rendering (such as better
     * label placement) we will, in future, have to build a GVT (from the Batik library) of the
     * SVGDocument.
     *
     * @returns An SVGDocument DOM structure representing the SVG.
     */
    @Override
    public SVGDocument toSVG(ConcreteDiagram cd) {
      // Get a DOMImplementation.
      DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();

      // Create an instance of org.w3c.dom.Document.
      String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
      SVGDocument document = (SVGDocument) domImpl.createDocument(svgNS, "svg", null);

      // Get the root element (the 'svg' element).
      Element svgRoot = document.getDocumentElement();

      // Set the width and height attributes on the root 'svg' element.
      svgRoot.setAttributeNS(null, "width", Integer.toString(cd.getSize()));
      svgRoot.setAttributeNS(null, "height", Integer.toString(cd.getSize()));

      // Draw the shaded zones
      for (ConcreteZone z : cd.getShadedZones()) {
        Element path = document.createElementNS(svgNS, "path");
        path.setAttributeNS(null, "d", toSVGPath(z.getShape(cd.getBox())));
        path.setAttributeNS(null, "fill", "#cccccc"); // grey
        path.setAttributeNS(null, "z-index", Integer.toString(zOrder.SHADING.ordinal()));

        svgRoot.appendChild(path);
      }

      // TODO: Concrete* should return themselves as DocumentFragments
      for (CircleContour c : cd.getCircles()) {
        // Draw the circle
        Element circle = document.createElementNS(svgNS, "circle");
        circle.setAttributeNS(null, "cx", Double.toString(c.get_cx()));
        circle.setAttributeNS(null, "cy", Double.toString(c.get_cy()));
        circle.setAttributeNS(null, "r", Double.toString(c.get_radius()));
        circle.setAttributeNS(null, "z-index", Integer.toString(zOrder.CONTOUR.ordinal()));
        // Not pretty, but it works.
        Color strokeColor = c.color();
        circle.setAttributeNS(
            null, "stroke", (null == strokeColor) ? "black" : "#" + toHexString(c.color()));
        circle.setAttributeNS(null, "stroke-width", "2");
        circle.setAttributeNS(null, "fill", "none");
        svgRoot.appendChild(circle);

        // TODO: Put this text in a path around the circle
        // alternatively come up with some better label placement
        // algorithm
        Element text = document.createElementNS(svgNS, "text");
        text.setAttributeNS(null, "x", Double.toString(c.get_cx()));
        text.setAttributeNS(null, "y", Double.toString(c.get_cy() + c.get_radius()));
        text.setAttributeNS(null, "text-anchor", "middle");
        text.setAttributeNS(
            null, "fill", (null == strokeColor) ? "black" : "#" + toHexString(c.color()));
        text.setAttributeNS(null, "z-index", Integer.toString(zOrder.LABEL.ordinal()));

        Text textNode = document.createTextNode(c.ac.getLabel().getLabel());
        text.appendChild(textNode);
        svgRoot.appendChild(text);
      }

      for (ConcreteSpider cs : cd.getSpiders()) {
        for (ConcreteSpiderFoot f : cs.feet) {
          // Draw the foot
          Element circle = document.createElementNS(svgNS, "circle");
          circle.setAttributeNS(null, "cx", Double.toString(f.getX()));
          circle.setAttributeNS(null, "cy", Double.toString(f.getY()));
          circle.setAttributeNS(null, "r", Double.toString(ConcreteSpiderFoot.FOOT_RADIUS));
          circle.setAttributeNS(null, "z-index", Integer.toString(zOrder.SPIDER.ordinal()));

          circle.setAttributeNS(null, "stroke", "black");
          circle.setAttributeNS(null, "stroke-width", "2");
          circle.setAttributeNS(null, "fill", "black");
          svgRoot.appendChild(circle);
        }

        for (ConcreteSpiderLeg l : cs.legs) {
          Element line = document.createElementNS(svgNS, "line");
          line.setAttributeNS(null, "x1", Double.toString(l.from.getX()));
          line.setAttributeNS(null, "y1", Double.toString(l.from.getY()));
          line.setAttributeNS(null, "x2", Double.toString(l.to.getX()));
          line.setAttributeNS(null, "y2", Double.toString(l.to.getY()));
          line.setAttributeNS(null, "z-index", Integer.toString(zOrder.SPIDER.ordinal()));

          line.setAttributeNS(null, "stroke", "black");
          line.setAttributeNS(null, "stroke-width", "2");
          line.setAttributeNS(null, "fill", "black");
          svgRoot.appendChild(line);
        }
      }
      return document;
    }