Java Code Examples for org.w3c.dom.DOMConfiguration#setParameter()

The following examples show how to use org.w3c.dom.DOMConfiguration#setParameter() . 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: DOMConfigurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 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 two Comment nodes, <br>
 * <b>name</b>: comments <br>
 * <b>value</b>: true. <br>
 * <b>Expected results</b>: the Comment nodes belong to the root element
 */
@Test
public void testComments001() {
    DOMImplementation domImpl = null;
    try {
        domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException pce) {
        Assert.fail(pce.toString());
    } catch (FactoryConfigurationError fce) {
        Assert.fail(fce.toString());
    }

    Document doc = domImpl.createDocument("namespaceURI", "ns:root", null);

    Comment comment1 = doc.createComment("comment1");
    Comment comment2 = doc.createComment("comment2");

    DOMConfiguration config = doc.getDomConfig();
    config.setParameter("comments", Boolean.TRUE);

    Element root = doc.getDocumentElement();
    root.appendChild(comment1);
    root.appendChild(comment2);

    setHandler(doc);
    doc.normalizeDocument();

    if (comment1.getParentNode() != root) {
        Assert.fail("comment1 is attached to " + comment1.getParentNode() + ", but expected to be a child of root");
    }

    if (comment2.getParentNode() != root) {
        Assert.fail("comment1 is attached to " + comment2.getParentNode() + ", but expected to be a child of root");
    }

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

}
 
Example 2
Source File: XMLHelper.java    From saml-client with MIT License 5 votes vote down vote up
/**
 * Obtain a the DOM, level 3, Load/Save serializer {@link LSSerializer} instance from the
 * given {@link DOMImplementationLS} instance.
 *
 * <p>
 * The serializer instance will be configured with the parameters passed as the <code>serializerParams</code>
 * argument. It will also be configured with an {@link LSSerializerFilter} that shows all nodes to the filter,
 * and accepts all nodes shown.
 * </p>
 *
 * @param domImplLS the DOM Level 3 Load/Save implementation to use
 * @param serializerParams parameters to pass to the {@link DOMConfiguration} of the serializer
 *         instance, obtained via {@link LSSerializer#getDomConfig()}. May be null.
 *
 * @return a new LSSerializer instance
 */
public static LSSerializer getLSSerializer(
    DOMImplementationLS domImplLS, Map<String, Object> serializerParams) {
  LSSerializer serializer = domImplLS.createLSSerializer();

  serializer.setFilter(
      new LSSerializerFilter() {

        @Override
        public short acceptNode(Node arg0) {
          return FILTER_ACCEPT;
        }

        @Override
        public int getWhatToShow() {
          return SHOW_ALL;
        }
      });

  if (serializerParams != null) {
    DOMConfiguration serializerDOMConfig = serializer.getDomConfig();
    for (String key : serializerParams.keySet()) {
      serializerDOMConfig.setParameter(key, serializerParams.get(key));
    }
  }

  return serializer;
}
 
Example 3
Source File: Bug4915748.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testMain() throws Exception {

    final boolean[] hadError = new boolean[1];

    DocumentBuilderFactory docBF = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBF.newDocumentBuilder();

    Document doc = docBuilder.getDOMImplementation().createDocument("namespaceURI", "ns:root", null);

    CDATASection cdata = doc.createCDATASection("text1]]>text2");
    doc.getDocumentElement().appendChild(cdata);

    DOMConfiguration config = doc.getDomConfig();
    DOMErrorHandler erroHandler = new DOMErrorHandler() {
        public boolean handleError(DOMError error) {
            System.out.println(error.getMessage());
            Assert.assertEquals(error.getType(), "cdata-sections-splitted");
            Assert.assertFalse(hadError[0], "two errors were reported");
            hadError[0] = true;
            return false;
        }
    };
    config.setParameter("error-handler", erroHandler);
    doc.normalizeDocument();
    Assert.assertTrue(hadError[0]);
}
 
Example 4
Source File: DOMConfigurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 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 two Comment nodes, <br>
 * <b>name</b>: comments <br>
 * <b>value</b>: false. <br>
 * <b>Expected results</b>: the root element has no children
 */
@Test
public void testComments002() {
    DOMImplementation domImpl = null;
    try {
        domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException pce) {
        Assert.fail(pce.toString());
    } catch (FactoryConfigurationError fce) {
        Assert.fail(fce.toString());
    }

    Document doc = domImpl.createDocument("namespaceURI", "ns:root", null);

    Comment comment1 = doc.createComment("comment1");
    Comment comment2 = doc.createComment("comment2");

    DOMConfiguration config = doc.getDomConfig();
    config.setParameter("comments", Boolean.FALSE);

    Element root = doc.getDocumentElement();
    root.appendChild(comment1);
    root.appendChild(comment2);

    doc.normalizeDocument();

    if (root.getFirstChild() != null) {
        Assert.fail("root has a child " + root.getFirstChild() + ", but expected to has none");
    }

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

}
 
Example 5
Source File: DOMConfigurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 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 document root element has a text node with
 * four white space characters, <br>
 * <b>name</b>: element-content-whitespace <br>
 * <b>value</b>: true. <br>
 * <b>Expected results</b>: the text node is preserved
 */
@Test
public void testECWhitespace001() {
    Document doc = null;
    try {
        doc = loadDocument(null, test3_xml);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }

    Element root = doc.getDocumentElement();
    Text text = doc.createTextNode("\t\n\r ");
    root.appendChild(text);

    DOMConfiguration config = doc.getDomConfig();
    if (!config.canSetParameter("element-content-whitespace", Boolean.TRUE)) {
        Assert.fail("setting 'element-content-whitespace' to true is not supported");
    }
    config.setParameter("element-content-whitespace", Boolean.TRUE);

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

    setHandler(doc);
    doc.normalizeDocument();

    Node firstChild = root.getFirstChild();
    if (firstChild == null || firstChild.getNodeType() != Node.TEXT_NODE || !((Text) firstChild).isElementContentWhitespace()) {
        Assert.fail("the first child is " + firstChild + ", expected a text node with the four whitespace characters");
    }

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

}
 
Example 6
Source File: DOMConfigurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 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 document root element has a text node with
 * four white space characters, <br>
 * <b>name</b>: element-content-whitespace <br>
 * <b>value</b>: false. <br>
 * <b>Expected results</b>: the text node is discarded
 */
@Test
public void testECWhitespace002() {
    Document doc = null;
    try {
        doc = loadDocument(null, test3_xml);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }

    Element root = doc.getDocumentElement();
    Text text = doc.createTextNode("\t\n\r ");
    root.appendChild(text);

    DOMConfiguration config = doc.getDomConfig();
    if (!config.canSetParameter("element-content-whitespace", Boolean.FALSE)) {
        System.out.println("OK, setting 'element-content-whitespace' to false is not supported");
        return;
    }
    config.setParameter("element-content-whitespace", Boolean.FALSE);

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

    setHandler(doc);
    doc.normalizeDocument();

    Node firstChild = root.getFirstChild();
    if (firstChild != null) {
        Assert.fail("the first child is " + firstChild + ", but no child is expected");
    }

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

}
 
Example 7
Source File: DOMConfigurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 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 CDATASection followed by
 * one Text node, <br>
 * <b>name</b>: cdata-sections <br>
 * <b>value</b>: true. <br>
 * <b>Expected results</b>: the CDATASection is left intact
 */
@Test
public void testCdataSections001() {
    DOMImplementation domImpl = null;
    try {
        domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException pce) {
        Assert.fail(pce.toString());
    } catch (FactoryConfigurationError fce) {
        Assert.fail(fce.toString());
    }

    Document doc = domImpl.createDocument("namespaceURI", "ns:root", null);

    String cdataText = "CDATA CDATA CDATA";
    String textText = "text text text";

    CDATASection cdata = doc.createCDATASection(cdataText);
    Text text = doc.createTextNode(textText);

    DOMConfiguration config = doc.getDomConfig();
    config.setParameter("cdata-sections", Boolean.TRUE);

    Element root = doc.getDocumentElement();
    root.appendChild(cdata);
    root.appendChild(text);

    setHandler(doc);
    doc.normalizeDocument();

    Node returned = root.getFirstChild();

    if (returned.getNodeType() != Node.CDATA_SECTION_NODE) {
        Assert.fail("reurned: " + returned + ", expected: CDATASection");
    }

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

}
 
Example 8
Source File: DOMConfigurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 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 doc's root element contains superfluous
 * namespace declarations, <br>
 * <b>name</b>: canonical-form <br>
 * <b>value</b>: true. <br>
 * <b>Expected results</b>: the superfluous namespace declarations are
 * removed
 */
@Test
public void testCanonicalForm003() {
    DOMImplementation domImpl = null;
    try {
        domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException pce) {
        Assert.fail(pce.toString());
    } catch (FactoryConfigurationError fce) {
        Assert.fail(fce.toString());
    }

    Document doc = domImpl.createDocument("namespaceURI", "ns:root", null);

    DOMConfiguration config = doc.getDomConfig();

    Element root = doc.getDocumentElement();
    String XMLNS = "http://www.w3.org/2000/xmlns/";
    root.setAttributeNS(XMLNS, "xmlns:extra1", "ExtraNS1");
    root.setAttributeNS(XMLNS, "xmlns:extra2", "ExtraNS2");

    if (!config.canSetParameter("canonical-form", Boolean.TRUE)) {
        System.out.println("OK, setting 'canonical-form' to true is not supported");
        return;
    }
    config.setParameter("canonical-form", Boolean.TRUE);
    setHandler(doc);
    doc.normalizeDocument();

    String xmlns2 = root.getAttributeNS(XMLNS, "extra1");
    if (xmlns2 == null || xmlns2.length() != 0) {
        Assert.fail("superfluous namespace declarations is not removed: xmlns:extra2 = " + xmlns2);
    }

    return; // Status.passed("OK");
}
 
Example 9
Source File: DOMConfigurationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 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 attribute has EntityReference to '&lt;', <br>
 * <b>name</b>: well-formed <br>
 * <b>value</b>: false. <br>
 * <b>Expected results</b>: No error is reported
 */
@Test
public void testWellFormed002() {
    Document doc = null;
    try {
        doc = loadDocument(null, test2_xml);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }

    DOMConfiguration config = doc.getDomConfig();
    if (!config.canSetParameter("well-formed", Boolean.FALSE)) {
        System.out.println("OK, setting 'well-formed' to false is not supported");
        return;
    }
    config.setParameter("well-formed", Boolean.FALSE);

    Element root = doc.getDocumentElement();

    Attr attr = doc.createAttributeNS(null, "attr");
    attr.appendChild(doc.createEntityReference("x"));

    root.setAttributeNode(attr);

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

    doc.normalizeDocument();

    if (testHandler.getError() != null || null != testHandler.getFatalError()) {
        Assert.fail("unexpected error: " + testHandler.getFatalError() + "; " + testHandler.getError());
    }

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

}
 
Example 10
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 CDATASection followed by
 * one Text node, <br>
 * <b>name</b>: cdata-sections <br>
 * <b>value</b>: false. <br>
 * <b>Expected results</b>: the root element has one Text node with text of
 * the CDATASection and the Text node
 */
@Test
public void testCdataSections002() {
    DOMImplementation domImpl = null;
    try {
        domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException pce) {
        Assert.fail(pce.toString());
    } catch (FactoryConfigurationError fce) {
        Assert.fail(fce.toString());
    }

    Document doc = domImpl.createDocument("namespaceURI", "ns:root", null);

    String cdataText = "CDATA CDATA CDATA";
    String textText = "text text text";

    CDATASection cdata = doc.createCDATASection(cdataText);
    Text text = doc.createTextNode(textText);

    DOMConfiguration config = doc.getDomConfig();
    config.setParameter("cdata-sections", Boolean.FALSE);

    Element root = doc.getDocumentElement();
    root.appendChild(cdata);
    root.appendChild(text);

    setHandler(doc);
    doc.normalizeDocument();

    Node returned = root.getFirstChild();

    if (returned.getNodeType() != Node.TEXT_NODE) {
        Assert.fail("reurned: " + returned + ", expected: TEXT_NODE");
    }

    String returnedText = returned.getNodeValue();
    if (!(cdataText + textText).equals(returnedText)) {
        Assert.fail("reurned: " + returnedText + ", expected: \"" + cdataText + textText + "\"");
    }

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

}
 
Example 11
Source File: XercesSchemaValidationUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
void tryToParseSchemas(XmlSchemaCollection collection, DOMErrorHandler handler)
    throws Exception {

    final List<DOMLSInput> inputs = new ArrayList<>();
    final Map<String, LSInput> resolverMap = new HashMap<>();

    for (XmlSchema schema : collection.getXmlSchemas()) {
        if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(schema.getTargetNamespace())) {
            continue;
        }
        Document document = new XmlSchemaSerializer().serializeSchema(schema, false)[0];
        DOMLSInput input = new DOMLSInput(document, schema.getTargetNamespace());
        resolverMap.put(schema.getTargetNamespace(), input);
        inputs.add(input);
    }

    try {

        Object schemaLoader = findMethod(impl, "createXSLoader").invoke(impl, new Object[1]);
        DOMConfiguration config = (DOMConfiguration)findMethod(schemaLoader, "getConfig").invoke(schemaLoader);

        config.setParameter("validate", Boolean.TRUE);
        config.setParameter("error-handler", handler);
        config.setParameter("resource-resolver", new LSResourceResolver() {
            public LSInput resolveResource(String type, String namespaceURI, String publicId,
                                           String systemId, String baseURI) {
                return resolverMap.get(namespaceURI);
            }
        });


        Method m = findMethod(schemaLoader, "loadInputList");
        String name = m.getParameterTypes()[0].getName() + "Impl";
        name = name.replace("xs.LS", "impl.xs.util.LS");
        Class<?> c = Class.forName(name);
        Object inputList = c.getConstructor(LSInput[].class, Integer.TYPE)
            .newInstance(inputs.toArray(new LSInput[0]), inputs.size());
        m.invoke(schemaLoader, inputList);
    } catch (InvocationTargetException e) {
        throw (Exception)e.getTargetException();
    }
}
 
Example 12
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 parameters "namespaces",
 * "namespace-declarations", "well-formed", "element-content-whitespace" are
 * set to false if possible; the parameters "entities",
 * "normalize-characters", "cdata-sections" are set to true if possible, <br>
 * <b>name</b>: canonical-form <br>
 * <b>value</b>: true. <br>
 * <b>Expected results</b>: the parameters "namespaces",
 * "namespace-declarations", "well-formed", "element-content-whitespace" are
 * set to true; the parameters "entities", "normalize-characters",
 * "cdata-sections" are set to false
 */
@Test
public void testCanonicalForm002() {
    Object[][] params = { { "namespaces", Boolean.TRUE }, { "namespace-declarations", Boolean.TRUE }, { "well-formed", Boolean.TRUE },
            { "element-content-whitespace", Boolean.TRUE },

            { "entities", Boolean.FALSE }, { "normalize-characters", Boolean.FALSE }, { "cdata-sections", Boolean.FALSE }, };

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

    Document doc = domImpl.createDocument("namespaceURI", "ns:root", null);

    DOMConfiguration config = doc.getDomConfig();

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

    for (int i = params.length; --i >= 0;) {
        Boolean reset = params[i][1].equals(Boolean.TRUE) ? Boolean.FALSE : Boolean.TRUE;
        if (config.canSetParameter(params[i][0].toString(), reset)) {
            config.setParameter(params[i][0].toString(), reset);
        }
    }

    config.setParameter("canonical-form", Boolean.TRUE);

    StringBuffer result = new StringBuffer();

    for (int i = params.length; --i >= 0;) {
        Object param = config.getParameter(params[i][0].toString());
        if (!params[i][1].equals(param)) {
            result.append("; the parameter \'" + params[i][0] + "\' is set to " + param + ", expected: " + params[i][1]);
        }
    }

    if (result.length() > 0) {
        Assert.fail(result.toString().substring(2));
    }

    return; // Status.passed("OK");
}
 
Example 13
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 is declared as int and its value
 * has subsequent characters #x9 (tab), #xA (line feed) and #xD (carriage
 * return) , #x20 (space), '1', #x20 (space), <br>
 * <b>name</b>: datatype-normalization <br>
 * <b>value</b>: true. <br>
 * <b>Expected results</b>: after Document.normalizeDocument() is called the
 * content of the root is '1'
 */
@Test
public void testDatatypeNormalization001() {
    Document doc = null;
    try {
        doc = loadDocument(test1_xsd_url, test_xml);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }

    DOMConfiguration config = doc.getDomConfig();

    if (!config.canSetParameter("schema-location", test1_xsd_url) || !config.canSetParameter("schema-type", XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
        System.out.println("cannot set the parameters 'schema-location' and 'schema-type'" + " to '" + test1_xsd_url + "' and '"
                + XMLConstants.W3C_XML_SCHEMA_NS_URI + "' respectively");
        return;
    }
    config.setParameter("schema-type", XMLConstants.W3C_XML_SCHEMA_NS_URI);
    config.setParameter("schema-location", test1_xsd_url);

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

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

    Element root = doc.getDocumentElement();
    while (root.getFirstChild() != null) {
        root.removeChild(root.getFirstChild());
    }
    root.appendChild(doc.createTextNode("\t\r\n 1 "));

    setHandler(doc);
    doc.normalizeDocument();

    Node child = root.getFirstChild();
    if (child == null || child.getNodeType() != Node.TEXT_NODE || !"1".equals(child.getNodeValue())) {
        Assert.fail("child: " + child + ", expected: text node '1'");
    }

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

}
 
Example 14
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 is declared as int and its value
 * has subsequent characters #x9 (tab), #xA (line feed) and #xD (carriage
 * return) , #x20 (space), '1', #x20 (space), <br>
 * <b>name</b>: datatype-normalization <br>
 * <b>value</b>: false. <br>
 * <b>Expected results</b>: after Document.normalizeDocument() is called the
 * value is left unchanged
 */
@Test
public void testDatatypeNormalization002() {
    Document doc = null;
    try {
        doc = loadDocument(test1_xsd_url, test_xml);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }

    DOMConfiguration config = doc.getDomConfig();

    if (!config.canSetParameter("schema-location", test1_xsd_url) || !config.canSetParameter("schema-type", XMLConstants.W3C_XML_SCHEMA_NS_URI)) {
        System.out.println("cannot set the parameters 'schema-location' and 'schema-type'" + " to '" + test1_xsd_url + "' and '"
                + XMLConstants.W3C_XML_SCHEMA_NS_URI + "' respectively");
        return;
    }
    config.setParameter("schema-type", XMLConstants.W3C_XML_SCHEMA_NS_URI);
    config.setParameter("schema-location", test1_xsd_url);

    if (config.canSetParameter("validate", Boolean.TRUE)) {
        config.setParameter("validate", Boolean.TRUE);
    }

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

    Element root = doc.getDocumentElement();
    while (root.getFirstChild() != null) {
        root.removeChild(root.getFirstChild());
    }
    String value = "\t\r\n 1 ";
    root.appendChild(doc.createTextNode(value));

    setHandler(doc);
    doc.normalizeDocument();

    Node child = root.getFirstChild();
    if (child == null || child.getNodeType() != Node.TEXT_NODE || !value.equals(child.getNodeValue())) {
        Assert.fail("child: " + child + ", expected: '\\t\\r\\n 1 '");
    }

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

}
 
Example 15
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 doc contains one entity and one entity
 * reference, <br>
 * <b>name</b>: entities <br>
 * <b>value</b>: true. <br>
 * <b>Expected results</b>: the entity and the entity reference are left
 * unchanged
 */
@Test
public void testEntities001() {
    Document doc = null;
    try {
        doc = loadDocument(null, test1_xml);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }

    DOMConfiguration config = doc.getDomConfig();
    if (!config.canSetParameter("entities", Boolean.TRUE)) {
        Assert.fail("setting 'entities' to true is not supported");
    }

    Element root = doc.getDocumentElement();
    root.appendChild(doc.createEntityReference("x"));

    config.setParameter("entities", Boolean.TRUE);

    setHandler(doc);
    doc.normalizeDocument();
    Node child = root.getFirstChild();
    if (child == null) {
        Assert.fail("root has no child");
    }
    if (child.getNodeType() != Node.ENTITY_REFERENCE_NODE) {
        Assert.fail("root's child is " + child + ", expected entity reference &x;");
    }

    if (doc.getDoctype() == null) {
        Assert.fail("no doctype found");
    }

    if (doc.getDoctype().getEntities() == null) {
        Assert.fail("no entitiy found");
    }

    if (doc.getDoctype().getEntities().getNamedItem("x") == null) {
        Assert.fail("no entitiy with name 'x' found");
    }

    return; // Status.passed("OK");
}
 
Example 16
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 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 'infoset' parameter is set to true, <br>
 * <b>name</b>: infoset <br>
 * <b>value</b>: false. <br>
 * <b>Expected results</b>: the parameters "validate-if-schema", "entities",
 * "datatype-normalization", "cdata-sections", "namespace-declarations",
 * "well-formed", "element-content-whitespace", "comments", "namespaces" are
 * left unchanged
 */
@Test
public void testInfoset001() {
    Object[][] params = { { "validate-if-schema", Boolean.FALSE }, { "entities", Boolean.FALSE }, { "datatype-normalization", Boolean.FALSE },
            { "cdata-sections", Boolean.FALSE },

            { "namespace-declarations", Boolean.TRUE }, { "well-formed", Boolean.TRUE }, { "element-content-whitespace", Boolean.TRUE },
            { "comments", Boolean.TRUE }, { "namespaces", Boolean.TRUE }, };

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

    Document doc = domImpl.createDocument("namespaceURI", "ns:root", null);

    DOMConfiguration config = doc.getDomConfig();

    if (!config.canSetParameter("infoset", Boolean.TRUE)) {
        Assert.fail("setting 'infoset' to true is not supported");
    }

    for (int i = params.length; --i >= 0;) {
        Boolean reset = params[i][1].equals(Boolean.TRUE) ? Boolean.FALSE : Boolean.TRUE;
        if (config.canSetParameter(params[i][0].toString(), reset)) {
            config.setParameter(params[i][0].toString(), reset);
        }
    }

    config.setParameter("infoset", Boolean.TRUE);
    config.setParameter("infoset", Boolean.FALSE); // has no effect

    StringBuffer result = new StringBuffer();

    for (int i = params.length; --i >= 0;) {
        Object param = config.getParameter(params[i][0].toString());
        if (!params[i][1].equals(param)) {
            result.append("; the parameter \'" + params[i][0] + "\' is set to " + param + ", expected: " + params[i][1]);
        }
    }

    if (result.length() > 0) {
        Assert.fail(result.toString().substring(2));
    }

    return; // Status.passed("OK");
}
 
Example 18
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 doc contains two subsequent processing
 * instrictions, <br>
 * <b>name</b>: canonical-form <br>
 * <b>value</b>: true. <br>
 * <b>Expected results</b>: the subsequent processing instrictions are
 * separated with a single line break
 */
@Test
public void testCanonicalForm001() {
    DOMImplementation domImpl = null;
    try {
        domImpl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
    } catch (ParserConfigurationException pce) {
        Assert.fail(pce.toString());
    } catch (FactoryConfigurationError fce) {
        Assert.fail(fce.toString());
    }

    Document doc = domImpl.createDocument("namespaceURI", "ns:root", null);

    DOMConfiguration config = doc.getDomConfig();

    Element root = doc.getDocumentElement();
    ProcessingInstruction pi1 = doc.createProcessingInstruction("target1", "data1");
    ProcessingInstruction pi2 = doc.createProcessingInstruction("target2", "data2");

    root.appendChild(pi1);
    root.appendChild(pi2);

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

    config.setParameter("canonical-form", Boolean.TRUE);
    setHandler(doc);
    doc.normalizeDocument();

    Node child1 = root.getFirstChild();
    Node child2 = child1.getNextSibling();

    if (child2.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
        Assert.fail("the second child is expected to be a" + "single line break, returned: " + child2);
    }

    // return Status.passed("OK");
}
 
Example 19
Source File: ImportRepairTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void tryToParseSchemas() throws Exception {
    // Get DOM Implementation using DOM Registry
    final List<DOMLSInput> inputs = new ArrayList<>();
    final Map<String, LSInput> resolverMap = new HashMap<>();

    for (XmlSchema schema : collection.getXmlSchemas()) {
        if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(schema.getTargetNamespace())) {
            continue;
        }
        Document document = new XmlSchemaSerializer().serializeSchema(schema, false)[0];
        DOMLSInput input = new DOMLSInput(document, schema.getTargetNamespace());
        dumpSchema(document);
        resolverMap.put(schema.getTargetNamespace(), input);
        inputs.add(input);
    }

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XS-Loader");


    try {
        Object schemaLoader = findMethod(impl, "createXSLoader").invoke(impl, new Object[1]);
        DOMConfiguration config = (DOMConfiguration)findMethod(schemaLoader, "getConfig").invoke(schemaLoader);

        config.setParameter("validate", Boolean.TRUE);
        try {
            //bug in the JDK doesn't set this, but accesses it
            config.setParameter("http://www.oracle.com/xml/jaxp/properties/xmlSecurityPropertyManager",
                                Class.forName("com.sun.org.apache.xerces.internal.utils.XMLSecurityPropertyManager")
                                    .newInstance());

            config.setParameter("http://apache.org/xml/properties/security-manager",
                                Class.forName("com.sun.org.apache.xerces.internal.utils.XMLSecurityManager")
                                    .newInstance());
        } catch (Throwable t) {
            //ignore
        }
        config.setParameter("error-handler", new DOMErrorHandler() {

            public boolean handleError(DOMError error) {
                LOG.info("Schema parsing error: " + error.getMessage()
                         + " " + error.getType()
                         + " " + error.getLocation().getUri()
                         + " " + error.getLocation().getLineNumber()
                         + ":" + error.getLocation().getColumnNumber());
                throw new DOMErrorException(error);
            }
        });
        config.setParameter("resource-resolver", new LSResourceResolver() {

            public LSInput resolveResource(String type, String namespaceURI, String publicId,
                                           String systemId, String baseURI) {
                return resolverMap.get(namespaceURI);
            }
        });

        Method m = findMethod(schemaLoader, "loadInputList");
        String name = m.getParameterTypes()[0].getName() + "Impl";
        name = name.replace("xs.LS", "impl.xs.util.LS");
        Class<?> c = Class.forName(name);
        Object inputList = c.getConstructor(LSInput[].class, Integer.TYPE)
        .newInstance(inputs.toArray(new LSInput[0]), inputs.size());

        findMethod(schemaLoader, "loadInputList").invoke(schemaLoader, inputList);
    } catch (InvocationTargetException ite) {
        throw (Exception)ite.getTargetException();
    }
}
 
Example 20
Source File: UtilXml.java    From scipio-erp with Apache License 2.0 3 votes vote down vote up
/** Returns a <code>LSSerializer</code> instance.
 * @param impl A <code>DOMImplementationLS</code> instance
 * @param includeXmlDeclaration If set to <code>true</code>,
 * the xml declaration will be included in the output
 * @param enablePrettyPrint If set to <code>true</code>, the
 * output will be formatted in human-readable form. If set to
 * <code>false</code>, the entire document will consist of a single line.
 * @return A <code>LSSerializer</code> instance
 * @see <a href="http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407/">DOM Level 3 Load and Save Specification</a>
 */
public static LSSerializer createLSSerializer(DOMImplementationLS impl, boolean includeXmlDeclaration, boolean enablePrettyPrint) {
    LSSerializer writer = impl.createLSSerializer();
    DOMConfiguration domConfig = writer.getDomConfig();
    domConfig.setParameter("xml-declaration", includeXmlDeclaration);
    domConfig.setParameter("format-pretty-print", enablePrettyPrint);
    return writer;
}