Java Code Examples for javax.xml.parsers.DocumentBuilder#getDOMImplementation()

The following examples show how to use javax.xml.parsers.DocumentBuilder#getDOMImplementation() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StylerEngine.java    From android-styler with Apache License 2.0 6 votes vote down vote up
private static String createOutput(String name, List<Pair<String, String>> xmlParams) throws ParserConfigurationException, TransformerException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation impl = builder.getDOMImplementation();
    Document doc = impl.createDocument(null, // namespaceURI
            null, // qualifiedName
            null); // doctype
    Element styleElement = doc.createElement("style");
    styleElement.setAttribute("name", name);
    for (Pair<String, String> item : xmlParams) {
        Element itemElement= doc.createElement("item");
        itemElement.setAttribute("name", item.getFirst());
        itemElement.setTextContent(item.getSecond());
        styleElement.appendChild(itemElement);
    }
    doc.appendChild(styleElement);
    return docToStr(doc);
}
 
Example 2
Source File: XmlDocument.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Creates an empty XML document.
 *
 * @throws ParserConfigurationException
 *         Error creating the document builder.
 */
public XmlDocument()
        throws ParserConfigurationException {
    // Check if there is a document type specified. 
    final DocumentType prototype = getDoctype();
    final DocumentBuilder builder = LOCAL_BUILDER.get();
    if (prototype == null) {
        // If there is none, simply create a new document as usual.
        document = builder.newDocument();
        if (document != null) {
            final Node root = createRootNode();
            appendChild(root);
        }
    } else {
        // otherwise create a document with the given doctype as a
        // prototype
        final DOMImplementation impl = builder.getDOMImplementation();
        final DocumentType type =
            impl.createDocumentType(prototype.getName(),
                prototype.getPublicId(), prototype.getSystemId());
        document = impl.createDocument(getDefaultNamespaceURI(),
                prototype.getName(), type);
    }
}
 
Example 3
Source File: StorageUtils.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Write a DOM Document to an output stream.
 * 
 * @param doc
 *        The DOM Document to write.
 * @param out
 *        The output stream.
 */
public static String writeDocumentToString(Document doc)
{
	try
	{
		
		StringWriter sw = new StringWriter();
		
		  DocumentBuilder builder = dbFactory.newDocumentBuilder();
		  DOMImplementation impl = builder.getDOMImplementation();
		  
		
		DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS",
		"3.0");
		LSSerializer serializer = feature.createLSSerializer();
		LSOutput output = feature.createLSOutput();
		output.setCharacterStream(sw);
		output.setEncoding("UTF-8");
		serializer.write(doc, output);
		
		sw.flush();
		return sw.toString();
	}
	catch (Exception any)
	{
		log.warn("writeDocumentToString: " + any.toString());
		return null;
	}
}
 
Example 4
Source File: XMLFileWriter.java    From Juicebox with MIT License 5 votes vote down vote up
private static Element initXML() throws ParserConfigurationException {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation impl = builder.getDOMImplementation();

        xmlDoc = impl.createDocument(null, "SavedMaps", null);
        return xmlDoc.getDocumentElement();
    }
 
Example 5
Source File: HtmlDocumentBuilder.java    From caja with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the JAXP DOM implementation.
 * 
 * @return the JAXP DOM implementation
 */
private static DOMImplementation jaxpDOMImplementation() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    return builder.getDOMImplementation();
}
 
Example 6
Source File: Xml.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Write a DOM Document to an output stream.
 * 
 * @param doc
 *        The DOM Document to write.
 * @param out
 *        The output stream.
 */
public static String writeDocumentToString(Document doc)
{
	try
	{
		
		StringWriter sw = new StringWriter();
		
		 DocumentBuilderFactory factory 
		   = DocumentBuilderFactory.newInstance();
		  DocumentBuilder builder = factory.newDocumentBuilder();
		  DOMImplementation impl = builder.getDOMImplementation();
		  
		
		DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS",
		"3.0");
		LSSerializer serializer = feature.createLSSerializer();
		LSOutput output = feature.createLSOutput();
		output.setCharacterStream(sw);
		output.setEncoding("UTF-8");
		serializer.write(doc, output);
		
		sw.flush();
		return sw.toString();
	}
	catch (Exception any)
	{
		log.warn("writeDocumentToString: " + any.toString());
		return null;
	}
}
 
Example 7
Source File: ClassLoaderLSResourceResolver.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * @see org.w3c.dom.ls.LSResourceResolver#resolveResource(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
 */
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
    if (!type.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
        return null;
    }
    LOG.error(type);
    LOG.error(namespaceURI);
    LOG.error(publicId);
    LOG.error(systemId);
    LOG.error(baseURI);
    String path = resolveSystemId(systemId);
    if (path == null) {
        return null;
    }
    LOG.debug("Looking up resource '" + path + "' for system id '" + systemId + "'");
    InputStream is = getClass().getClassLoader().getResourceAsStream(path);
    if (is == null) {
        String message = "Unable to find schema (" + path + ") for: " + systemId;
        LOG.error(message);
        throw new RuntimeException/*SAXException*/(message);
    }
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation domImpl = builder.getDOMImplementation();
        DOMImplementationLS dils = (DOMImplementationLS) domImpl;
        LSInput input = dils.createLSInput();
        input.setByteStream(is);
        return input;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: DOMBuilder.java    From exificient with MIT License 5 votes vote down vote up
public DOMBuilder(EXIFactory factory) throws ParserConfigurationException {
	this.factory = factory;

	// setup document builder etc.
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	dbFactory.setNamespaceAware(true);
	DocumentBuilder builder = dbFactory.newDocumentBuilder();
	domImplementation = builder.getDOMImplementation();
}
 
Example 9
Source File: Xml.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Write a DOM Document to an output stream.
 * 
 * @param doc
 *        The DOM Document to write.
 * @param out
 *        The output stream.
 */
public static String writeDocumentToString(Document doc)
{
	try
	{
		
		StringWriter sw = new StringWriter();
		
		 DocumentBuilderFactory factory 
		   = DocumentBuilderFactory.newInstance();
		  DocumentBuilder builder = factory.newDocumentBuilder();
		  DOMImplementation impl = builder.getDOMImplementation();
		  
		
		DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS",
		"3.0");
		LSSerializer serializer = feature.createLSSerializer();
		LSOutput output = feature.createLSOutput();
		output.setCharacterStream(sw);
		output.setEncoding("UTF-8");
		serializer.write(doc, output);
		
		sw.flush();
		return sw.toString();
	}
	catch (Exception any)
	{
		log.warn("writeDocumentToString: " + any.toString());
		return null;
	}
}
 
Example 10
Source File: ApiListing.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public Document createWADLApplication() {
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = null;
    try {
        docBuilder = dbfac.newDocumentBuilder();
    }
    catch ( ParserConfigurationException e ) {
    }
    DOMImplementation domImpl = docBuilder.getDOMImplementation();
    Document doc = domImpl.createDocument( "http://wadl.dev.java.net/2009/02", "application", null );
    Element application = doc.getDocumentElement();

    // add additional namespace to the root element
    application.setAttributeNS( "http://www.w3.org/2000/xmlns/", "xmlns:xsi",
            "http://www.w3.org/2001/XMLSchema-instance" );
    application.setAttributeNS( "http://www.w3.org/2000/xmlns/", "xmlns:xsd", "http://www.w3.org/2001/XMLSchema" );
    application.setAttributeNS( "http://www.w3.org/2000/xmlns/", "xmlns:apigee",
            "http://api.apigee.com/wadl/2010/07/" );
    application.setAttributeNS( "http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation",
            "http://wadl.dev.java.net/2009/02 http://apigee.com/schemas/wadl-schema.xsd http://api.apigee"
                    + ".com/wadl/2010/07/ http://apigee.com/schemas/apigee-wadl-extensions.xsd" );

    if ( apis != null ) {
        Element resources = doc.createElement( "resources" );
        if ( basePath != null ) {
            resources.setAttribute( "base", basePath );
        }
        else {
            resources.setAttribute( "base", "http://api.usergrid.com" );
        }
        application.appendChild( resources );
        for ( Api api : apis ) {
            resources.appendChild( api.createWADLResource( doc, this ) );
        }
    }
    return doc;
}
 
Example 11
Source File: AbstractXmlWriter.java    From jeveassets with GNU General Public License v2.0 5 votes vote down vote up
protected Document getXmlDocument(final String rootname) throws XmlException {
	try {
		DocumentBuilder builder = getFactory().newDocumentBuilder();
		DOMImplementation impl = builder.getDOMImplementation();
		return impl.createDocument(null, rootname, null);
	} catch (ParserConfigurationException ex) {
		throw new XmlException(ex.getMessage(), ex);
	}
}
 
Example 12
Source File: ContentTypeLSResourceResolver.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
    * @see org.w3c.dom.ls.LSResourceResolver#resolveResource(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
    */
   public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
       if (!type.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
           return null;
       }

       if (!systemId.startsWith(CONTENT_TYPE_PREFIX)) {
           LOG.warn("Cannot resolve non-ContentType resources");
           return null;
       }

       NotificationContentTypeBo notificationContentType = resolveContentType(systemId);
       if (notificationContentType == null) {
    LOG.error("Unable to resolve system id '" + systemId + "' locally...delegating to default resolution strategy.");
    return null;
}

       Reader reader = new StringReader(notificationContentType.getXsd());
       try {
           DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
           DocumentBuilder builder = factory.newDocumentBuilder();
           DOMImplementation domImpl = builder.getDOMImplementation();
           DOMImplementationLS dils = (DOMImplementationLS) domImpl;
           LSInput input = dils.createLSInput();
           input.setCharacterStream(reader);
           return input;
       } catch (Exception e) {
           throw new RuntimeException(e);
       }
   }
 
Example 13
Source File: VsmResponse.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
protected void printResponse() {
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        DOMImplementationLS ls = (DOMImplementationLS)docBuilder.getDOMImplementation();
        LSSerializer lss = ls.createLSSerializer();
        System.out.println(lss.writeToString(_docResponse));
    } catch (ParserConfigurationException e) {
        s_logger.error("Error parsing the repsonse : " + e.toString());
    }
}
 
Example 14
Source File: TestDocumentEncoding.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
@Test
public void testEncoding() throws KeyManagementException, NoSuchAlgorithmException, IOException, TransformerException, ParserConfigurationException
{
  // connect the client
  DatabaseClient client = getDatabaseClient("rest-writer", "x", getConnType());

  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = factory.newDocumentBuilder();
  DOMImplementation impl = builder.getDOMImplementation();

  Document doc = impl.createDocument(null, null, null);
  Element e1 = doc.createElement("howto");
  doc.appendChild(e1);
  Element e2 = doc.createElement("java");
  e1.appendChild(e2);
  e2.setAttribute("url", "http://www.rgagnon.com/howto.html");
  Text text = doc.createTextNode("漢字");
  e2.appendChild(text);

  // transform the Document into a String
  Source domSource = new DOMSource(doc);
  TransformerFactory tf = TransformerFactory.newInstance();
  Transformer transformer = tf.newTransformer();
  transformer.setOutputProperty(OutputKeys.METHOD, "xml");
  transformer.setOutputProperty(OutputKeys.ENCODING, "Cp1252");
  transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  java.io.StringWriter sw = new java.io.StringWriter();
  StreamResult sr = new StreamResult(sw);
  transformer.transform(domSource, sr);

  String xml = sw.toString();
  System.out.println(xml);

  XMLDocumentManager docMgr = client.newXMLDocumentManager();
  StringHandle writeHandle = new StringHandle();
  writeHandle.set(xml);
  docMgr.write("/doc/foo.xml", writeHandle);

  System.out.println(docMgr.read("/doc/foo.xml", new StringHandle()).get());
  int length1 = docMgr.read("/doc/foo.xml", new BytesHandle()).get().length;
  System.out.println(length1);

  // ************************

  DocumentBuilderFactory factory2 = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder2 = factory2.newDocumentBuilder();
  DOMImplementation impl2 = builder2.getDOMImplementation();

  Document doc2 = impl2.createDocument(null, null, null);
  Element x1 = doc2.createElement("howto");
  doc2.appendChild(x1);
  Element x2 = doc2.createElement("java");
  x1.appendChild(x2);
  x2.setAttribute("url", "http://www.rgagnon.com/howto.html");
  Text text2 = doc2.createTextNode("漢字");
  x2.appendChild(text2);

  Source domSource2 = new DOMSource(doc2);
  TransformerFactory tf2 = TransformerFactory.newInstance();
  Transformer transformer2 = tf2.newTransformer();
  transformer2.setOutputProperty(OutputKeys.METHOD, "xml");
  transformer2.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  transformer2.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
  transformer2.setOutputProperty(OutputKeys.INDENT, "yes");
  java.io.StringWriter sw2 = new java.io.StringWriter();
  StreamResult sr2 = new StreamResult(sw2);
  transformer2.transform(domSource2, sr2);
  String xml2 = sw2.toString();

  System.out.println("*********** UTF-8 ************");
  System.out.println(xml2);

  StringHandle writeHandle2 = new StringHandle();
  writeHandle2.set(xml2);
  docMgr.write("/doc/bar.xml", writeHandle2);
  System.out.println(docMgr.read("/doc/bar.xml", new StringHandle()).get());
  int length2 = docMgr.read("/doc/bar.xml", new BytesHandle()).get().length;
  System.out.println(length2);

  assertEquals("Byte size is not the same", length1, length2);

  // **************************

  client.release();
}
 
Example 15
Source File: DOML3InputSourceFactoryImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public InputSource newInputSource(String filename) throws Exception {
    // Create DOMImplementationLS, and DOM L3 LSParser
    DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
    DocumentBuilder bldr = fact.newDocumentBuilder();
    DOMImplementationLS impl = (DOMImplementationLS) bldr.getDOMImplementation();
    LSParser domparser = impl.createLSParser(MODE_SYNCHRONOUS, null);
    domparser.setFilter(new MyDOMBuilderFilter());

    // Parse the xml document to create the DOM Document using
    // the DOM L3 LSParser and a LSInput (formerly LSInputSource)
    Document doc = null;
    LSInput src = impl.createLSInput();
    // register the input file with the input source...
    String systemId = filenameToURL(filename);
    src.setSystemId(systemId);
    try (Reader reader = new FileReader(filename)) {
        src.setCharacterStream(reader);
        src.setEncoding("UTF-8");
        doc = domparser.parse(src);
    }

    // Use DOM L3 LSSerializer (previously called a DOMWriter)
    // to serialize the xml doc DOM to a file stream.
    String tmpCatalog = Files.createTempFile(Paths.get(USER_DIR), "catalog.xml", null).toString();

    LSSerializer domserializer = impl.createLSSerializer();
    domserializer.setFilter(new MyDOMWriterFilter());
    domserializer.getNewLine();
    DOMConfiguration config = domserializer.getDomConfig();
    config.setParameter("xml-declaration", Boolean.TRUE);
    String result = domserializer.writeToString(doc);
    try (FileWriter os = new FileWriter(tmpCatalog, false)) {
        os.write(result);
        os.flush();
    }

    // Return the Input Source created from the Serialized DOM L3 Document.
    InputSource catsrc = new InputSource(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(tmpCatalog)))));
    catsrc.setSystemId(systemId);
    return catsrc;
}
 
Example 16
Source File: DomSerializer.java    From web-data-extractor with Apache License 2.0 4 votes vote down vote up
/**
 * @param rootNode the HTML Cleaner root node to serialize
 * @return the W3C Document object
 * @throws ParserConfigurationException if there's an error during serialization
 */
public Document createDOM(TagNode rootNode) throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation impl = builder.getDOMImplementation();


    Document document;

    //
    // Where a DOCTYPE is supplied in the input, ensure that this is in the output DOM. See issue #27
    //
    // Note that we may want to fix incorrect DOCTYPEs in future; there are some fairly
    // common patterns for errors with the older HTML4 doctypes.
    //
    if (rootNode.getDocType() != null) {
        String qualifiedName = rootNode.getDocType().getPart1();
        String publicId = rootNode.getDocType().getPublicId();
        String systemId = rootNode.getDocType().getSystemId();

        //
        // If there is no qualified name, set it to html. See bug #153.
        //
        if (qualifiedName == null) qualifiedName = "html";

        DocumentType documentType = impl.createDocumentType(qualifiedName, publicId, systemId);

        //
        // While the qualified name is "HTML" for some DocTypes, we want the actual document root name to be "html". See bug #116
        //
        if (qualifiedName.equals("HTML")) qualifiedName = "html";
        document = impl.createDocument(rootNode.getNamespaceURIOnPath(""), qualifiedName, documentType);
    } else {
        document = builder.newDocument();
        Element rootElement = document.createElement(rootNode.getName());
        document.appendChild(rootElement);
    }

    //
    // Copy across root node attributes - see issue 127. Thanks to rasifiel for the patch
    //
    Map<String, String> attributes = rootNode.getAttributes();
    Iterator<Map.Entry<String, String>> entryIterator = attributes.entrySet().iterator();
    while (entryIterator.hasNext()) {
        Map.Entry<String, String> entry = entryIterator.next();
        String attrName = entry.getKey();
        String attrValue = entry.getValue();
        if (escapeXml) {
            attrValue = Utils.escapeXml(attrValue, props, true);
        }

        document.getDocumentElement().setAttribute(attrName, attrValue);

        //
        // Flag the attribute as an ID attribute if appropriate. Thanks to Chris173
        //
        if (attrName.equalsIgnoreCase("id")) {
            document.getDocumentElement().setIdAttribute(attrName, true);
        }

    }

    createSubnodes(document, (Element) document.getDocumentElement(), rootNode.getAllChildren());

    return document;
}
 
Example 17
Source File: PrettyPrintTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testLSSerializerFormatPrettyPrint() {

    final String XML_DOCUMENT = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\n"
            + "<hello>before child element<child><children/><children/></child>after child element</hello>";
    /**JDK-8035467
     * no newline in default output
     */
    final String XML_DOCUMENT_DEFAULT_PRINT =
            "<?xml version=\"1.0\" encoding=\"UTF-16\"?>"
            + "<hello>"
            + "before child element"
            + "<child><children/><children/></child>"
            + "after child element</hello>";

    final String XML_DOCUMENT_PRETTY_PRINT = "<?xml version=\"1.0\" encoding=\"UTF-16\"?><hello>\n" +
            "    before child element\n" +
            "    <child>\n" +
            "        <children/>\n" +
            "        <children/>\n" +
            "    </child>\n" +
            "    after child element\n" +
            "</hello>\n";

    // it all begins with a Document
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException parserConfigurationException) {
        parserConfigurationException.printStackTrace();
        Assert.fail(parserConfigurationException.toString());
    }
    Document document = null;

    StringReader stringReader = new StringReader(XML_DOCUMENT);
    InputSource inputSource = new InputSource(stringReader);
    try {
        document = documentBuilder.parse(inputSource);
    } catch (SAXException saxException) {
        saxException.printStackTrace();
        Assert.fail(saxException.toString());
    } catch (IOException ioException) {
        ioException.printStackTrace();
        Assert.fail(ioException.toString());
    }

    // query DOM Interfaces to get to a LSSerializer
    DOMImplementation domImplementation = documentBuilder.getDOMImplementation();
    DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation;
    LSSerializer lsSerializer = domImplementationLS.createLSSerializer();

    System.out.println("Serializer is: " + lsSerializer.getClass().getName() + " " + lsSerializer);

    // get configuration
    DOMConfiguration domConfiguration = lsSerializer.getDomConfig();

    // query current configuration
    Boolean defaultFormatPrettyPrint = (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT);
    Boolean canSetFormatPrettyPrintFalse = (Boolean) domConfiguration.canSetParameter(DOM_FORMAT_PRETTY_PRINT, Boolean.FALSE);
    Boolean canSetFormatPrettyPrintTrue = (Boolean) domConfiguration.canSetParameter(DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);

    System.out.println(DOM_FORMAT_PRETTY_PRINT + " default/can set false/can set true = " + defaultFormatPrettyPrint + "/"
            + canSetFormatPrettyPrintFalse + "/" + canSetFormatPrettyPrintTrue);

    // test values
    assertEquals(defaultFormatPrettyPrint, Boolean.FALSE, "Default value of " + DOM_FORMAT_PRETTY_PRINT + " should be " + Boolean.FALSE);

    assertEquals(canSetFormatPrettyPrintFalse, Boolean.TRUE, "Can set " + DOM_FORMAT_PRETTY_PRINT + " to " + Boolean.FALSE + " should be "
            + Boolean.TRUE);

    assertEquals(canSetFormatPrettyPrintTrue, Boolean.TRUE, "Can set " + DOM_FORMAT_PRETTY_PRINT + " to " + Boolean.TRUE + " should be "
            + Boolean.TRUE);

    // get default serialization
    String prettyPrintDefault = lsSerializer.writeToString(document);
    System.out.println("(default) " + DOM_FORMAT_PRETTY_PRINT + "==" + (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT)
            + ": \n\"" + prettyPrintDefault + "\"");

    assertEquals(prettyPrintDefault, XML_DOCUMENT_DEFAULT_PRINT, "Invalid serialization with default value, " + DOM_FORMAT_PRETTY_PRINT + "=="
            + (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT));

    // configure LSSerializer to not format-pretty-print
    domConfiguration.setParameter(DOM_FORMAT_PRETTY_PRINT, Boolean.FALSE);
    String prettyPrintFalse = lsSerializer.writeToString(document);
    System.out.println("(FALSE) " + DOM_FORMAT_PRETTY_PRINT + "==" + (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT)
            + ": \n\"" + prettyPrintFalse + "\"");

    assertEquals(prettyPrintFalse, XML_DOCUMENT_DEFAULT_PRINT, "Invalid serialization with FALSE value, " + DOM_FORMAT_PRETTY_PRINT + "=="
            + (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT));

    // configure LSSerializer to format-pretty-print
    domConfiguration.setParameter(DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);
    String prettyPrintTrue = lsSerializer.writeToString(document);
    System.out.println("(TRUE) " + DOM_FORMAT_PRETTY_PRINT + "==" + (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT)
            + ": \n\"" + prettyPrintTrue + "\"");

    assertEquals(prettyPrintTrue, XML_DOCUMENT_PRETTY_PRINT, "Invalid serialization with TRUE value, " + DOM_FORMAT_PRETTY_PRINT + "=="
            + (Boolean) domConfiguration.getParameter(DOM_FORMAT_PRETTY_PRINT));
}
 
Example 18
Source File: LSSerializerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testEntityReference() throws Exception {
    final String XML_DOCUMENT = "<?xml version=\"1.1\" encoding=\"UTF-16\"?>\n" +
            "<!DOCTYPE author [\n" +
            " <!ENTITY name \"Jo Smith\">" +
            " <!ENTITY name1 \"&name;\">" +
            " <!ENTITY name2 \"&name1;\">" +
            "<!ENTITY ele \"<aa><bb>text</bb></aa>\">" +
            " <!ENTITY ele1 \"&ele;\">" +
            " <!ENTITY ele2 \"&ele1;\">" +
            " ]>" +
            " <author><a>&name1;</a>" +
            "<b>b &name2; &name1; b</b>" +
            "<c> &name; </c>" +
            "<d>&ele1;d</d>" +
            "<e> &ele2;eee </e>" +
            "<f>&lt;att&gt;</f>" +
            "<g> &ele; g</g>" +
            "<h>&ele2;</h></author>" ;


    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

    DOMImplementation domImplementation = documentBuilder.getDOMImplementation();
    DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation;

    LSParser domParser = domImplementationLS.createLSParser(MODE_SYNCHRONOUS, null);
    domParser.getDomConfig().setParameter("entities", Boolean.TRUE);

    LSInput src = domImplementationLS.createLSInput();
    src.setStringData(XML_DOCUMENT);
    Document document = domParser.parse(src);

    LSSerializer lsSerializer = domImplementationLS.createLSSerializer();

    lsSerializer.getDomConfig().setParameter("format-pretty-print", true);
    System.out.println("test with default entities is " + lsSerializer.getDomConfig().getParameter("entities"));
    Assert.assertEquals(lsSerializer.writeToString(document),
            "<?xml version=\"1.1\" encoding=\"UTF-16\"?><!DOCTYPE author [ \n" +
            "<!ENTITY name 'Jo Smith'>\n" +
            "<!ENTITY name1 '&name;'>\n" +
            "<!ENTITY name2 '&name1;'>\n" +
            "<!ENTITY ele '<aa><bb>text</bb></aa>'>\n" +
            "<!ENTITY ele1 '&ele;'>\n" +
            "<!ENTITY ele2 '&ele1;'>\n" +
            "]>\n" +
            "<author>\n" +
            "    <a>&name1;Jo Smith</a>\n" +
            "    <b>b &name2;Jo Smith &name1;Jo Smith b</b>\n" +
            "    <c>&name;Jo Smith </c>\n" +
            "    <d>&ele1;d</d>\n" +
            "    <e>&ele2;eee </e>\n" +
            "    <f>&lt;att&gt;</f>\n" +
            "    <g>&ele; g</g>\n" +
            "    <h>&ele2;</h>\n" +
            "</author>\n");

    lsSerializer.getDomConfig().setParameter("entities", Boolean.FALSE);
    System.out.println("test with entities is false");
    Assert.assertEquals(lsSerializer.writeToString(document),
            "<?xml version=\"1.1\" encoding=\"UTF-16\"?><!DOCTYPE author [ \n" +
            "<!ENTITY name 'Jo Smith'>\n" +
            "<!ENTITY name1 '&name;'>\n" +
            "<!ENTITY name2 '&name1;'>\n" +
            "<!ENTITY ele '<aa><bb>text</bb></aa>'>\n" +
            "<!ENTITY ele1 '&ele;'>\n" +
            "<!ENTITY ele2 '&ele1;'>\n" +
            "]>\n" +
            "<author>\n" +
            "    <a>&name;Jo Smith</a>\n" +
            "    <b>b &name;Jo Smith &name;Jo Smith b</b>\n" +
            "    <c>&name;Jo Smith </c>\n" +
            "    <d>\n" +
            "        <aa>\n" +
            "            <bb>text</bb>\n" +
            "        </aa>\n" +
            "        d\n" +
            "    </d>\n" +
            "    <e>\n" +
            "        <aa>\n" +
            "            <bb>text</bb>\n" +
            "        </aa>\n" +
            "        eee \n" +
            "    </e>\n" +
            "    <f>&lt;att&gt;</f>\n" +
            "    <g>\n" +
            "        <aa>\n" +
            "            <bb>text</bb>\n" +
            "        </aa>\n" +
            "         g\n" +
            "    </g>\n" +
            "    <h>\n" +
            "        <aa>\n" +
            "            <bb>text</bb>\n" +
            "        </aa>\n" +
            "    </h>\n" +
            "</author>\n");

}
 
Example 19
Source File: LSSerializerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testXML11() {

    /**
     * XML 1.1 document to parse.
     */
    final String XML11_DOCUMENT = "<?xml version=\"1.1\" encoding=\"UTF-16\"?>\n" + "<hello>" + "world" + "<child><children/><children/></child>"
            + "</hello>";

    /**JDK-8035467
     * no newline in default output
     */
    final String XML11_DOCUMENT_OUTPUT =
            "<?xml version=\"1.1\" encoding=\"UTF-16\"?>"
            + "<hello>"
            + "world"
            + "<child><children/><children/></child>"
            + "</hello>";

    // it all begins with a Document
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException parserConfigurationException) {
        parserConfigurationException.printStackTrace();
        Assert.fail(parserConfigurationException.toString());
    }
    Document document = null;

    StringReader stringReader = new StringReader(XML11_DOCUMENT);
    InputSource inputSource = new InputSource(stringReader);
    try {
        document = documentBuilder.parse(inputSource);
    } catch (SAXException saxException) {
        saxException.printStackTrace();
        Assert.fail(saxException.toString());
    } catch (IOException ioException) {
        ioException.printStackTrace();
        Assert.fail(ioException.toString());
    }

    // query DOM Interfaces to get to a LSSerializer
    DOMImplementation domImplementation = documentBuilder.getDOMImplementation();
    DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation;
    LSSerializer lsSerializer = domImplementationLS.createLSSerializer();

    System.out.println("Serializer is: " + lsSerializer.getClass().getName() + " " + lsSerializer);

    // get default serialization
    String defaultSerialization = lsSerializer.writeToString(document);

    System.out.println("XML 1.1 serialization = \"" + defaultSerialization + "\"");

    // output should == input
    Assert.assertEquals(XML11_DOCUMENT_OUTPUT, defaultSerialization, "Invalid serialization of XML 1.1 document: ");
}
 
Example 20
Source File: CompoundXmlRequest.java    From aion-germany with GNU General Public License v3.0 4 votes vote down vote up
public String toXml()
{
    Document document;
    DocumentBuilder docBuilder;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try
    {
        docBuilder = factory.newDocumentBuilder();
        document = docBuilder.newDocument();
    }
    catch (ParserConfigurationException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
    DOMImplementationLS implLS = (DOMImplementationLS) docBuilder.getDOMImplementation();
    LSSerializer domWriter = implLS.createLSSerializer();
    LSOutput output = implLS.createLSOutput();
    
    //DOMException: FEATURE_NOT_SUPPORTED: The parameter format-pretty-print is recognized but the requested value cannot be set.
    //domWriter.getDomConfig().setParameter(Constants.DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);
    
    output.setEncoding("UTF-8");
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    output.setByteStream(outStream);
    
    
    Element root = document.createElement("requests");
    for(Request req : _requests)
    {
        Element reqNode = document.createElement("request");
        reqNode.setAttribute("id", Integer.toString(req.getId()));
        reqNode.setAttribute("type", req.getType());
        for(RequestPart part : req.getParts())
        {
            Element partNode = null;
            if(part instanceof RequestForPart)
            {
                partNode = document.createElement("for");
                writeForPart(partNode, (RequestForPart) part, document);
            }
            else
            {
                partNode = document.createElement("part");
                partNode.setAttribute("name", part.getName());
                partNode.setAttribute("value", part.getValue());
            }
            reqNode.appendChild(partNode);
        }
        root.appendChild(reqNode);
    }
    
    document.appendChild(root);
    domWriter.write(document, output);
    
    return outStream.toString();
}