Example usage for org.w3c.dom Document getDomConfig

List of usage examples for org.w3c.dom Document getDomConfig

Introduction

In this page you can find the example usage for org.w3c.dom Document getDomConfig.

Prototype

public DOMConfiguration getDomConfig();

Source Link

Document

The configuration used when Document.normalizeDocument() is invoked.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true); // Set namespace aware
    builderFactory.setValidating(true); // and validating parser feaures
    builderFactory.setIgnoringElementContentWhitespace(true);

    DocumentBuilder builder = builderFactory.newDocumentBuilder(); // Create the parser
    Document xmlDoc = builder.parse(new InputSource(new StringReader(xmlString)));

    DOMConfiguration config = xmlDoc.getDomConfig();
}

From source file:DOM3.java

public static void main(String[] argv) {

    if (argv.length == 0) {
        printUsage();//from  w  ww. j  a va  2  s  .  c o  m
        System.exit(1);
    }

    try {

        // get DOM Implementation using DOM Registry
        System.setProperty(DOMImplementationRegistry.PROPERTY,
                "org.apache.xerces.dom.DOMXSImplementationSourceImpl");
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");

        // create DOMBuilder
        builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

        DOMConfiguration config = builder.getDomConfig();

        // create Error Handler
        DOMErrorHandler errorHandler = new DOM3();

        // create filter
        LSParserFilter filter = new DOM3();

        builder.setFilter(filter);

        // set error handler
        config.setParameter("error-handler", errorHandler);

        // set validation feature
        // config.setParameter("validate", Boolean.FALSE);
        config.setParameter("validate", Boolean.TRUE);

        // set schema language
        config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema");
        // config.setParameter("psvi",Boolean.TRUE);
        // config.setParameter("schema-type","http://www.w3.org/TR/REC-xml");

        // set schema location
        config.setParameter("schema-location", "personal.xsd");

        // parse document
        System.out.println("Parsing " + argv[0] + "...");
        Document doc = builder.parseURI(argv[0]);

        // set error handler on the Document
        config = doc.getDomConfig();

        config.setParameter("error-handler", errorHandler);

        // set validation feature
        config.setParameter("validate", Boolean.TRUE);
        config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema");
        // config.setParameter("schema-type","http://www.w3.org/TR/REC-xml");
        config.setParameter("schema-location", "data/personal.xsd");

        // remove comments from the document
        config.setParameter("comments", Boolean.FALSE);

        System.out.println("Normalizing document... ");
        doc.normalizeDocument();

        // create DOMWriter
        LSSerializer domWriter = impl.createLSSerializer();

        System.out.println("Serializing document... ");
        config = domWriter.getDomConfig();
        config.setParameter("xml-declaration", Boolean.FALSE);
        // config.setParameter("validate",errorHandler);

        // serialize document to standard output
        // domWriter.writeNode(System.out, doc);
        LSOutput dOut = impl.createLSOutput();
        dOut.setByteStream(System.out);
        domWriter.write(doc, dOut);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

/**
 * Coalesce adjacent text nodes in the given document. CDATA sections are preserved. This method
 * is useful to compare output from two non coalescing parsers.
 * /*from   ww  w. j  a v  a  2  s .  c  o m*/
 * @param document
 *            the document to process
 */
public static void coalesceTextNodes(Document document) {
    document.getDomConfig().setParameter("cdata-sections", true);
    document.normalize();
}

From source file:Main.java

/**
 * Set standard DOM configuration.//ww  w . j av  a2  s . c  o  m
 *
 * @param document The document to set the configuration for.
 */
public static void setConfigParams(Document document) {
    DOMConfiguration config = document.getDomConfig();
    config.setParameter(DOM_CONFIG_COMMENTS, true);
    config.setParameter(DOM_CONFIG_ELEMENT_CONTENT_WHITESPACE, true);
    if (config.canSetParameter(DOM_CONFIG_CANONICAL_FORM, true)) {
        config.setParameter(DOM_CONFIG_CANONICAL_FORM, true);
    }
}

From source file:net.svcret.core.util.XMLUtils.java

public static void validate(Document d, String schema, DOMErrorHandler handler) {
    DOMConfiguration config = d.getDomConfig();
    config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema");
    config.setParameter("validate", true);
    config.setParameter("schema-location", schema);
    config.setParameter("resource-resolver", new ClasspathResourceResolver());
    config.setParameter("error-handler", handler);
    d.normalizeDocument();/*from  w ww.  j ava 2  s  .  c  om*/
}

From source file:org.apache.rahas.test.util.TestUtil.java

/**
 * TODO we need to move these common code to a new module. Otherwise code will be duplicated.
 * We cannot use following method from rampart-core as it creates a cyclic dependency. Therefore we have
 * to live with following.//from ww w  .ja v a2s  .  c  o  m
* Creates a DOM Document using the SOAP Envelope.
* @param env An org.apache.axiom.soap.SOAPEnvelope instance
* @return Returns the DOM Document of the given SOAP Envelope.
* @throws Exception If an error occurred during conversion.
*/
public static Document getDocumentFromSOAPEnvelope(SOAPEnvelope env, boolean useDoom)
        throws WSSecurityException {
    try {
        if (env instanceof Element) {
            Element element = (Element) env;
            Document document = element.getOwnerDocument();
            // For outgoing messages, Axis2 only creates the SOAPEnvelope, but no document. If
            // the Axiom implementation also supports DOM, then the envelope (seen as a DOM
            // element) will have an owner document, but the document and the envelope have no
            // parent-child relationship. On the other hand, the input expected by WSS4J is
            // a document with the envelope as document element. Therefore we need to set the
            // envelope as document element on the owner document.
            if (element.getParentNode() != document) {
                document.appendChild(element);
            }
            // If the Axiom implementation supports DOM, then it is possible/likely that the
            // DOM API was used to create the object model (or parts of it). In this case, the
            // object model is not necessarily well formed with respect to namespaces because
            // DOM doesn't generate namespace declarations automatically. This is an issue
            // because WSS4J/Santuario expects that all namespace declarations are present.
            // If this is not the case, then signature values or encryptions will be incorrect.
            // To avoid this, we normalize the document. Note that if we disable the other
            // normalizations supported by DOM, this is generally not a heavy operation.
            // In particular, the Axiom implementation is not required to expand the object
            // model (including OMSourcedElements) because the Axiom builder is required to
            // perform namespace repairing, so that no modifications to unexpanded parts of
            // the message are required.
            DOMConfiguration domConfig = document.getDomConfig();
            domConfig.setParameter("split-cdata-sections", Boolean.FALSE);
            domConfig.setParameter("well-formed", Boolean.FALSE);
            domConfig.setParameter("namespaces", Boolean.TRUE);
            document.normalizeDocument();
            return document;
        }

        if (useDoom) {
            env.build();

            // Workaround to prevent a bug in AXIOM where
            // there can be an incomplete OMElement as the first child body
            OMElement firstElement = env.getBody().getFirstElement();
            if (firstElement != null) {
                firstElement.build();
            }

            //Get processed headers
            SOAPHeader soapHeader = env.getHeader();
            ArrayList processedHeaderQNames = new ArrayList();
            if (soapHeader != null) {
                Iterator headerBlocs = soapHeader.getChildElements();
                while (headerBlocs.hasNext()) {
                    SOAPHeaderBlock element = (SOAPHeaderBlock) headerBlocs.next();
                    if (element.isProcessed()) {
                        processedHeaderQNames.add(element.getQName());
                    }
                }
            }

            SOAPModelBuilder stAXSOAPModelBuilder = OMXMLBuilderFactory.createStAXSOAPModelBuilder(
                    OMAbstractFactory.getMetaFactory(OMAbstractFactory.FEATURE_DOM), env.getXMLStreamReader());
            SOAPEnvelope envelope = (stAXSOAPModelBuilder).getSOAPEnvelope();
            envelope.getParent().build();

            //Set the processed flag of the processed headers
            SOAPHeader header = envelope.getHeader();
            for (Iterator iter = processedHeaderQNames.iterator(); iter.hasNext();) {
                QName name = (QName) iter.next();
                Iterator omKids = header.getChildrenWithName(name);
                if (omKids.hasNext()) {
                    ((SOAPHeaderBlock) omKids.next()).setProcessed();
                }
            }

            Element envElem = (Element) envelope;
            return envElem.getOwnerDocument();
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            env.build();
            env.serialize(baos);
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            return factory.newDocumentBuilder().parse(bais);
        }
    } catch (Exception e) {
        throw new WSSecurityException("Error in converting SOAP Envelope to Document", e);
    }
}