Java Code Examples for org.w3c.dom.DOMImplementation#getFeature()

The following examples show how to use org.w3c.dom.DOMImplementation#getFeature() . 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: AbstractMethodErrorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.newDocument();

    DOMImplementation impl = document.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer dsi = implLS.createLSSerializer();

    /* We should have here incorrect document without getXmlVersion() method:
     * Such Document is generated by replacing the JDK bootclasses with it's
     * own Node,Document and DocumentImpl classes (see run.sh). According to
     * XERCESJ-1007 the AbstractMethodError should be thrown in such case.
     */
    String result = dsi.writeToString(document);
    System.out.println("Result:" + result);
}
 
Example 2
Source File: Helper.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/***
 * Helper method which converts XML Document into pretty formatted string
 *
 * @param doc to convert
 * @return converted XML as String
 */
public static String documentToString(Document doc) {

    String strMsg = "";
    try {
        DOMImplementation domImpl = doc.getImplementation();
        DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
        LSSerializer lsSerializer = domImplLS.createLSSerializer();
        lsSerializer.getDomConfig().setParameter("format-pretty-print", true);

        Writer stringWriter = new StringWriter();
        LSOutput lsOutput = domImplLS.createLSOutput();
        lsOutput.setEncoding("UTF-8");
        lsOutput.setCharacterStream(stringWriter);
        lsSerializer.write(doc, lsOutput);
        strMsg = stringWriter.toString();
    } catch (Exception e) {
        logger.warn("Error occurred when converting document to string", e);
    }
    return strMsg;
}
 
Example 3
Source File: XmlUtils.java    From Doradus with Apache License 2.0 6 votes vote down vote up
static public String getInnerXmlText(Node xmlNode)
{
    StringBuilder result = new StringBuilder();

    Document xmlDocument = xmlNode.getOwnerDocument();
    DOMImplementation xmlDocumentImpl = xmlDocument.getImplementation();
    DOMImplementationLS lsImpl = (DOMImplementationLS) xmlDocumentImpl.getFeature("LS", "3.0");
    LSSerializer lsSerializer = lsImpl.createLSSerializer();

    NodeList childNodes = xmlNode.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        String childText = lsSerializer.writeToString(childNodes.item(i));
        int pos = childText.indexOf("?>");
        if (pos > -1) {
            childText = childText.substring(pos + 2);
        }
        result.append(childText);
    }

    return result.toString();
}
 
Example 4
Source File: DomHelper.java    From mdw with Apache License 2.0 6 votes vote down vote up
public static String toXml(Document domDoc) throws TransformerException {
    DOMImplementation domImplementation = domDoc.getImplementation();
    if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) {
        DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation.getFeature("LS", "3.0");
        LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
        DOMConfiguration domConfiguration = lsSerializer.getDomConfig();
        if (domConfiguration.canSetParameter("xml-declaration", Boolean.TRUE))
            lsSerializer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE);
        if (domConfiguration.canSetParameter("format-pretty-print", Boolean.TRUE)) {
            lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
            LSOutput lsOutput = domImplementationLS.createLSOutput();
            lsOutput.setEncoding("UTF-8");
            StringWriter stringWriter = new StringWriter();
            lsOutput.setCharacterStream(stringWriter);
            lsSerializer.write(domDoc, lsOutput);
            return stringWriter.toString();
        }
    }
    return toXml((Node) domDoc);
}
 
Example 5
Source File: Formatter.java    From simplexml with Apache License 2.0 6 votes vote down vote up
private void format(Document document, Writer writer) {
   DOMImplementation implementation = document.getImplementation();

   if(implementation.hasFeature(LS_FEATURE_KEY, LS_FEATURE_VERSION) && implementation.hasFeature(CORE_FEATURE_KEY, CORE_FEATURE_VERSION)) {
      DOMImplementationLS implementationLS = (DOMImplementationLS) implementation.getFeature(LS_FEATURE_KEY, LS_FEATURE_VERSION);
      LSSerializer serializer = implementationLS.createLSSerializer();
      DOMConfiguration configuration = serializer.getDomConfig();
      
      configuration.setParameter("format-pretty-print", Boolean.TRUE);
      configuration.setParameter("comments", preserveComments);
      
      LSOutput output = implementationLS.createLSOutput();
      output.setEncoding("UTF-8");
      output.setCharacterStream(writer);
      serializer.write(document, output);
   }
}
 
Example 6
Source File: XmlDocumentBuilder.java    From archistar-core with GNU General Public License v2.0 5 votes vote down vote up
public String stringFromDoc(Document doc) {
    DOMImplementation impl = doc.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer lsSerializer = implLS.createLSSerializer();
    lsSerializer.getDomConfig().setParameter("format-pretty-print", true);

    LSOutput lsOutput = implLS.createLSOutput();
    lsOutput.setEncoding("UTF-8");
    Writer stringWriter = new StringWriter();
    lsOutput.setCharacterStream(stringWriter);
    lsSerializer.write(doc, lsOutput);

    return stringWriter.toString();
}
 
Example 7
Source File: WSDLInlineSchemaValidator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public LSInput resolveResource(String type, 
                               String namespaceURI, 
                               String publicId, 
                               String systemId, 
                               String baseURI) {
    
     LSInput lsi = mDelegate.resolveResource(type, namespaceURI, publicId, systemId, baseURI);

     if (lsi == null) {
         //if we can not get an input from catalog, then it could that
         //there as a schema in types section which refer to schema compoment from other inline schema
         //so we try to check in other inline schema.
         WSDLSchema schema = findSchema(namespaceURI);
         if(schema != null) {
             Reader in = createInlineSchemaSource(mWsdlText, mWsdlPrefixes, mWsdlLinePositions, schema);
             if(in != null) {
                 //create LSInput object
                 DOMImplementation domImpl = null;
                 try {
                     domImpl =  DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
                 } catch (ParserConfigurationException ex) {
                     Logger.getLogger(getClass().getName()).log(Level.SEVERE, "resolveResource", ex); //NOI18N
                     return null;
                 }

                 DOMImplementationLS dols = (DOMImplementationLS) domImpl.getFeature("LS","3.0");
                 lsi = dols.createLSInput();
                 lsi.setCharacterStream(in);

                 if(mWsdlSystemId != null) {
                     lsi.setSystemId(mWsdlSystemId);
                 }
                 return lsi;  
             }
         }
     }
     return lsi;                      
}
 
Example 8
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 9
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 10
Source File: ConvertUserFavoriteSitesSakai11.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private String toXML(Document doc) {
    StringWriter result = new StringWriter();

    DOMImplementation impl = documentBuilder.getDOMImplementation();
    DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = feature.createLSSerializer();
    LSOutput lsoutput = feature.createLSOutput();
    lsoutput.setCharacterStream(result);
    lsoutput.setEncoding("UTF-8");
    serializer.write(doc, lsoutput);

    result.flush();

    return result.toString();
}
 
Example 11
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 12
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 13
Source File: ConvertUserFavoriteSitesSakai11.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private String toXML(Document doc) {
    StringWriter result = new StringWriter();

    DOMImplementation impl = documentBuilder.getDOMImplementation();
    DOMImplementationLS feature = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = feature.createLSSerializer();
    LSOutput lsoutput = feature.createLSOutput();
    lsoutput.setCharacterStream(result);
    lsoutput.setEncoding("UTF-8");
    serializer.write(doc, lsoutput);

    result.flush();

    return result.toString();
}
 
Example 14
Source File: XMLHelper.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Get the DOM Level 3 Load/Save {@link DOMImplementationLS} for the given node.
 *
 * @param node the node to evaluate
 * @return the DOMImplementationLS for the given node
 */
public static DOMImplementationLS getLSDOMImpl(Node node) {
  DOMImplementation domImpl;
  if (node instanceof Document) {
    domImpl = ((Document) node).getImplementation();
  } else {
    domImpl = node.getOwnerDocument().getImplementation();
  }

  DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
  return domImplLS;
}
 
Example 15
Source File: XMLHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the DOM Level 3 Load/Save {@link DOMImplementationLS} for the given node.
 * 
 * @param node the node to evaluate
 * @return the DOMImplementationLS for the given node
 */
public static DOMImplementationLS getLSDOMImpl(Node node) {
    DOMImplementation domImpl;
    if (node instanceof Document) {
        domImpl = ((Document) node).getImplementation();
    } else {
        domImpl = node.getOwnerDocument().getImplementation();
    }

    DOMImplementationLS domImplLS = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
    return domImplLS;
}
 
Example 16
Source File: DOMConfigurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Equivalence class partitioning with state and input values orientation
 * for public void setParameter(String name, Object value) throws
 * DOMException, <br>
 * <b>pre-conditions</b>: the root element contains a fully-normalized text, <br>
 * <b>name</b>: check-character-normalization <br>
 * <b>value</b>: false. <br>
 * <b>Expected results</b>: LSParser reports no errors
 */
@Test
public void testCheckCharNorm002() {
    DOMImplementation domImpl = null;
    try {
        domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException pce) {
        Assert.fail(pce.toString());
    } catch (FactoryConfigurationError fce) {
        Assert.fail(fce.toString());
    }

    DOMImplementationLS lsImpl = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");

    if (lsImpl == null) {
        System.out.println("OK, the DOM implementation does not support the LS 3.0");
        return;
    }

    LSParser lsParser = lsImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

    DOMConfiguration config = lsParser.getDomConfig();

    if (!config.canSetParameter("check-character-normalization", Boolean.FALSE)) {
        Assert.fail("setting 'check-character-normalization' to false is not supported");
    }

    config.setParameter("check-character-normalization", Boolean.FALSE);

    TestHandler testHandler = new TestHandler();
    config.setParameter("error-handler", testHandler);

    LSInput lsInput = lsImpl.createLSInput();
    lsInput.setStringData("<root>fully-normalized</root>");
    Document doc = lsParser.parse(lsInput);

    if (null != testHandler.getError()) {
        Assert.fail("no error is expected, but reported: " + testHandler.getError());

    }

    return; // Status.passed("OK");

}
 
Example 17
Source File: DOMConfigurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Equivalence class partitioning with state and input values orientation
 * for public void setParameter(String name, Object value) throws
 * DOMException, <br>
 * <b>pre-conditions</b>: the root element has one Text node with not fully
 * normalized characters, the 'check-character-normalization' parameter set
 * to true, <br>
 * <b>name</b>: error-handler <br>
 * <b>value</b>: DOMErrorHandler. <br>
 * <b>Expected results</b>: LSParser calls the specified error handler
 */
@Test
public void testCheckCharNorm001() {
    DOMImplementation domImpl = null;
    try {
        domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException pce) {
        Assert.fail(pce.toString());
    } catch (FactoryConfigurationError fce) {
        Assert.fail(fce.toString());
    }

    DOMImplementationLS lsImpl = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");

    if (lsImpl == null) {
        System.out.println("OK, the DOM implementation does not support the LS 3.0");
        return;
    }

    LSParser lsParser = lsImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

    DOMConfiguration config = lsParser.getDomConfig();

    if (!config.canSetParameter("check-character-normalization", Boolean.TRUE)) {
        System.out.println("OK, setting 'check-character-normalization' to true is not supported");
        return;
    }

    config.setParameter("check-character-normalization", Boolean.TRUE);

    TestHandler testHandler = new TestHandler();
    config.setParameter("error-handler", testHandler);

    LSInput lsInput = lsImpl.createLSInput();
    lsInput.setStringData("<root>\u0073\u0075\u0063\u0327\u006F\u006E</root>");
    Document doc = lsParser.parse(lsInput);

    if (null == testHandler.getError()) {
        Assert.fail("no error is reported, expected 'check-character-normalization-failure'");

    }

    return; // Status.passed("OK");

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

    final DOMErrorHandler handler = new DOMErrorHandler() {
        public boolean handleError(final DOMError error) {
            return false;
        }
    };

    final LSResourceResolver resolver = new LSResourceResolver() {
        public LSInput resolveResource(final String type, final String namespaceURI, final String publicId, final String systemId, final String baseURI) {
            return null;
        }
    };

    final Object[][] values = {
            // parameter, value
            { "canonical-form", Boolean.FALSE }, { "cdata-sections", Boolean.FALSE }, { "cdata-sections", Boolean.TRUE },
            { "check-character-normalization", Boolean.FALSE }, { "comments", Boolean.FALSE }, { "comments", Boolean.TRUE },
            { "datatype-normalization", Boolean.FALSE }, { "entities", Boolean.FALSE }, { "entities", Boolean.TRUE }, { "error-handler", handler },
            { "infoset", Boolean.TRUE }, { "namespaces", Boolean.TRUE }, { "namespace-declarations", Boolean.TRUE },
            { "namespace-declarations", Boolean.FALSE }, { "normalize-characters", Boolean.FALSE }, { "split-cdata-sections", Boolean.TRUE },
            { "split-cdata-sections", Boolean.FALSE }, { "validate", Boolean.FALSE }, { "validate-if-schema", Boolean.FALSE },
            { "well-formed", Boolean.TRUE }, { "element-content-whitespace", Boolean.TRUE },

            { "charset-overrides-xml-encoding", Boolean.TRUE }, { "charset-overrides-xml-encoding", Boolean.FALSE }, { "disallow-doctype", Boolean.FALSE },
            { "ignore-unknown-character-denormalizations", Boolean.TRUE }, { "resource-resolver", resolver }, { "resource-resolver", null },
            { "supported-media-types-only", Boolean.FALSE }, };

    DOMImplementation domImpl = null;
    try {
        domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException parserConfigurationException) {
        parserConfigurationException.printStackTrace();
        Assert.fail(parserConfigurationException.toString());
    }

    DOMImplementationLS lsImpl = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");

    LSParser lsParser = lsImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

    DOMConfiguration config = lsParser.getDomConfig();

    for (int i = values.length; --i >= 0;) {
        Object val = values[i][1];
        String param = (String) values[i][0];
        try {
            config.setParameter(param, val);
            Object returned = config.getParameter(param);
            Assert.assertEquals(val, returned, "'" + param + "' is set to " + returned + ", but expected " + val);
            System.out.println("set '" + param + "'" + " to '" + val + "'" + " and returned '" + returned + "'");
        } catch (DOMException e) {
            String settings = "setting '" + param + "' to " + val;
            System.err.println(settings);
            e.printStackTrace();
            Assert.fail(settings + ", " + e.toString());
        }
    }
}
 
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 testDOMErrorHandler() {

    final String XML_DOCUMENT = "<?xml version=\"1.0\"?>" + "<hello>" + "world" + "</hello>";

    StringReader stringReader = new StringReader(XML_DOCUMENT);
    InputSource inputSource = new InputSource(stringReader);
    Document doc = null;
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        // LSSerializer defaults to Namespace processing
        // so parsing must also
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder parser = documentBuilderFactory.newDocumentBuilder();
        doc = parser.parse(inputSource);

    } catch (Throwable e) {
        e.printStackTrace();
        Assert.fail(e.toString());
    }

    DOMImplementation impl = doc.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer writer = implLS.createLSSerializer();

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

    DOMErrorHandlerImpl eh = new DOMErrorHandlerImpl();
    writer.getDomConfig().setParameter("error-handler", eh);

    boolean serialized = false;
    try {
        serialized = writer.write(doc, new Output());

        // unexpected success
        Assert.fail("Serialized without raising an LSException due to " + "'no-output-specified'.");
    } catch (LSException lsException) {
        // expected exception
        System.out.println("Expected LSException: " + lsException.toString());
        // continue processing
    }

    Assert.assertFalse(serialized, "Expected writer.write(doc, new Output()) == false");

    Assert.assertTrue(eh.NoOutputSpecifiedErrorReceived, "'no-output-specified' error was expected");
}