Example usage for org.w3c.dom DOMConfiguration setParameter

List of usage examples for org.w3c.dom DOMConfiguration setParameter

Introduction

In this page you can find the example usage for org.w3c.dom DOMConfiguration setParameter.

Prototype

public void setParameter(String name, Object value) throws DOMException;

Source Link

Document

Set the value of a parameter.

Usage

From source file:it.unibas.spicy.persistence.xml.operators.GenerateXSDNodeTree.java

private XSModel initModel(String fileName) throws Exception {
    System.setProperty(DOMImplementationRegistry.PROPERTY,
            "org.apache.xerces.dom.DOMXSImplementationSourceImpl");
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    XSImplementation impl = (XSImplementation) registry.getDOMImplementation("XS-Loader");
    XSLoader schemaLoader = impl.createXSLoader(null);
    DOMConfiguration config = schemaLoader.getConfig();
    config.setParameter("validate", Boolean.TRUE);
    return schemaLoader.loadURI(fileName);
}

From source file:com.haulmont.cuba.restapi.XMLConverter.java

@Override
public CommitRequest parseCommitRequest(String content) {
    try {//from  www. j  a  v  a2s .c om
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS lsImpl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSParser requestConfigParser = lsImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

        // Set options on the parser
        DOMConfiguration config = requestConfigParser.getDomConfig();
        config.setParameter("validate", Boolean.TRUE);
        config.setParameter("element-content-whitespace", Boolean.FALSE);
        config.setParameter("comments", Boolean.FALSE);
        requestConfigParser.setFilter(new LSParserFilter() {
            @Override
            public short startElement(Element elementArg) {
                return LSParserFilter.FILTER_ACCEPT;
            }

            @Override
            public short acceptNode(Node nodeArg) {
                return StringUtils.isBlank(nodeArg.getTextContent()) ? LSParserFilter.FILTER_REJECT
                        : LSParserFilter.FILTER_ACCEPT;
            }

            @Override
            public int getWhatToShow() {
                return NodeFilter.SHOW_TEXT;
            }
        });
        LSInput lsInput = lsImpl.createLSInput();
        lsInput.setStringData(content);
        Document commitRequestDoc = requestConfigParser.parse(lsInput);
        Node rootNode = commitRequestDoc.getFirstChild();
        if (!"CommitRequest".equals(rootNode.getNodeName()))
            throw new IllegalArgumentException("Not a CommitRequest xml passed: " + rootNode.getNodeName());

        CommitRequest result = new CommitRequest();

        NodeList children = rootNode.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            String childNodeName = child.getNodeName();
            if ("commitInstances".equals(childNodeName)) {
                NodeList entitiesNodeList = child.getChildNodes();

                Set<String> commitIds = new HashSet<>(entitiesNodeList.getLength());
                for (int j = 0; j < entitiesNodeList.getLength(); j++) {
                    Node idNode = entitiesNodeList.item(j).getAttributes().getNamedItem("id");
                    if (idNode == null)
                        continue;

                    String id = idNode.getTextContent();
                    if (id.startsWith("NEW-"))
                        id = id.substring(id.indexOf('-') + 1);
                    commitIds.add(id);
                }

                result.setCommitIds(commitIds);
                result.setCommitInstances(parseNodeList(result, entitiesNodeList));
            } else if ("removeInstances".equals(childNodeName)) {
                NodeList entitiesNodeList = child.getChildNodes();

                List removeInstances = parseNodeList(result, entitiesNodeList);
                result.setRemoveInstances(removeInstances);
            } else if ("softDeletion".equals(childNodeName)) {
                result.setSoftDeletion(Boolean.parseBoolean(child.getTextContent()));
            }
        }
        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * Utility method for serializing DOM to a String
 * @param doc Document to serialize/*from w  ww  . j a v  a  2  s.c o m*/
 * @return XML document as a String
 */
private String writeDomToString(Document doc) {
    LSSerializer writer = domLoadSaveImpl.createLSSerializer();
    DOMConfiguration domConfig = writer.getDomConfig();
    domConfig.setParameter("xml-declaration", false);
    String xmlString = writer.writeToString(doc);
    return xmlString;
}

From source file:de.betterform.xml.xforms.model.Model.java

private XSLoader getSchemaLoader()
        throws IllegalAccessException, InstantiationException, ClassNotFoundException {
    // System.setProperty(DOMImplementationRegistry.PROPERTY,
    // "org.apache.xerces.dom.DOMXSImplementationSourceImpl");
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    XSImplementation implementation = (XSImplementation) registry.getDOMImplementation("XS-Loader");
    XSLoader loader = implementation.createXSLoader(null);

    DOMConfiguration cfg = loader.getConfig();

    cfg.setParameter("resource-resolver", new LSResourceResolver() {
        public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
                String baseURI) {
            LSInput input = new LSInput() {
                String systemId;/*  ww  w . j  av a  2s.  c  o  m*/

                public void setSystemId(String systemId) {
                    this.systemId = systemId;
                }

                public void setStringData(String s) {
                }

                String publicId;

                public void setPublicId(String publicId) {
                    this.publicId = publicId;
                }

                public void setEncoding(String s) {
                }

                public void setCharacterStream(Reader reader) {
                }

                public void setCertifiedText(boolean flag) {
                }

                public void setByteStream(InputStream inputstream) {
                }

                String baseURI;

                public void setBaseURI(String baseURI) {
                    if (baseURI == null || "".equals(baseURI)) {
                        baseURI = getContainer().getProcessor().getBaseURI();
                    }
                    this.baseURI = baseURI;
                }

                public String getSystemId() {
                    return this.systemId;
                }

                public String getStringData() {
                    return null;
                }

                public String getPublicId() {
                    return this.publicId;
                }

                public String getEncoding() {
                    return null;
                }

                public Reader getCharacterStream() {
                    return null;
                }

                public boolean getCertifiedText() {
                    return false;
                }

                public InputStream getByteStream() {
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("Schema resource\n\t\t publicId '" + publicId + "'\n\t\t systemId '"
                                + systemId + "' requested");
                    }
                    try {
                        String pathToSchema = null;
                        if ("http://www.w3.org/MarkUp/SCHEMA/xml-events-attribs-1.xsd".equals(systemId)) {
                            pathToSchema = "schema/xml-events-attribs-1.xsd";
                        } else if ("http://www.w3.org/2001/XMLSchema.xsd".equals(systemId)) {
                            pathToSchema = "schema/XMLSchema.xsd";
                        } else if ("-//W3C//DTD XMLSCHEMA 200102//EN".equals(publicId)) {
                            pathToSchema = "schema/XMLSchema.dtd";
                        } else if ("datatypes".equals(publicId)) {
                            pathToSchema = "schema/datatypes.dtd";
                        } else if ("http://www.w3.org/2001/xml.xsd".equals(systemId)) {
                            pathToSchema = "schema/xml.xsd";
                        }

                        // LOAD WELL KNOWN SCHEMA
                        if (pathToSchema != null) {
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("loading Schema '" + pathToSchema + "'\n\n");
                            }
                            return Thread.currentThread().getContextClassLoader()
                                    .getResourceAsStream(pathToSchema);
                        }
                        // LOAD SCHEMA THAT IS NOT(!) YET KNWON TO THE XFORMS PROCESSOR
                        else if (systemId != null && !"".equals(systemId)) {
                            URI schemaURI = new URI(baseURI);
                            schemaURI = schemaURI.resolve(systemId);

                            // ConnectorFactory.getFactory()
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("loading schema resource '" + schemaURI.toString() + "'\n\n");
                            }
                            return ConnectorFactory.getFactory().getHTTPResourceAsStream(schemaURI);

                        } else {
                            LOGGER.error("resource not known '" + systemId + "'\n\n");
                            return null;
                        }

                    } catch (XFormsException e) {
                        e.printStackTrace();
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                public String getBaseURI() {
                    return this.baseURI;
                }
            };
            input.setSystemId(systemId);
            input.setBaseURI(baseURI);
            input.setPublicId(publicId);
            return input;
        }
    });
    // END: Patch
    return loader;
}

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

public static void serialize(Document document, boolean prettyPrint, Writer theWriter) {
    DOMImplementationLS impl = getDOMImpl();
    LSSerializer serializer = impl.createLSSerializer();
    // document.normalizeDocument();
    DOMConfiguration config = serializer.getDomConfig();
    if (prettyPrint && config.canSetParameter("format-pretty-print", Boolean.TRUE)) {
        config.setParameter("format-pretty-print", true);
    }//from  ww w  .  j  a v a2  s.  c o  m
    config.setParameter("xml-declaration", true);
    LSOutput output = impl.createLSOutput();
    output.setEncoding("UTF-8");
    output.setCharacterStream(theWriter);
    serializer.write(document, output);
}

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();//  w w  w  .j av a  2 s.c  om
}

From source file:org.alfresco.web.forms.xforms.SchemaUtil.java

public static XSModel parseSchema(final Document schemaDocument, final boolean failOnError)
        throws FormBuilderException {
    try {//from w  w  w.  j  a v  a2  s . c om
        // Get DOM Implementation using DOM Registry
        System.setProperty(DOMImplementationRegistry.PROPERTY,
                "org.apache.xerces.dom.DOMXSImplementationSourceImpl");

        final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

        final DOMImplementationLS lsImpl = (DOMImplementationLS) registry
                .getDOMImplementation("XML 1.0 LS 3.0");
        if (lsImpl == null) {
            throw new FormBuilderException("unable to create DOMImplementationLS using " + registry);
        }
        final LSInput in = lsImpl.createLSInput();
        in.setStringData(XMLUtil.toString(schemaDocument));

        final XSImplementation xsImpl = (XSImplementation) registry.getDOMImplementation("XS-Loader");
        final XSLoader schemaLoader = xsImpl.createXSLoader(null);
        final DOMConfiguration config = (DOMConfiguration) schemaLoader.getConfig();
        final LinkedList<DOMError> errors = new LinkedList<DOMError>();
        config.setParameter("error-handler", new DOMErrorHandler() {
            public boolean handleError(final DOMError domError) {
                errors.add(domError);
                return true;
            }
        });

        final XSModel result = schemaLoader.load(in);
        if (failOnError && errors.size() != 0) {
            final HashSet<String> messages = new HashSet<String>();
            StringBuilder message = null;
            for (DOMError e : errors) {
                message = new StringBuilder();
                final DOMLocator dl = e.getLocation();
                if (dl != null) {
                    message.append("at line ").append(dl.getLineNumber()).append(" column ")
                            .append(dl.getColumnNumber());
                    if (dl.getRelatedNode() != null) {
                        message.append(" node ").append(dl.getRelatedNode().getNodeName());
                    }
                    message.append(": ").append(e.getMessage());
                }
                messages.add(message.toString());
            }

            message = new StringBuilder();
            message.append(messages.size() > 1 ? "errors" : "error").append(" parsing schema: \n");
            for (final String s : messages) {
                message.append(s).append("\n");
            }

            throw new FormBuilderException(message.toString());
        }

        if (result == null) {
            throw new FormBuilderException("invalid schema");
        }
        return result;
    } catch (ClassNotFoundException x) {
        throw new FormBuilderException(x);
    } catch (InstantiationException x) {
        throw new FormBuilderException(x);
    } catch (IllegalAccessException x) {
        throw new FormBuilderException(x);
    }
}

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  w  ww . j av a2  s  . 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);
    }
}