Example usage for org.w3c.dom Document normalizeDocument

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

Introduction

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

Prototype

public void normalizeDocument();

Source Link

Document

This method acts as if the document was going through a save and load cycle, putting the document in a "normal" form.

Usage

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 source file:org.alfresco.web.forms.xforms.Schema2XForms.java

/**
 * Generate the XForm based on a user supplied XML Schema.
 *
 * @param instanceDocument The document source for the XML Schema.
 * @param schemaDocument Schema document
 * @param rootElementName Name of the root element
 * @param resourceBundle Strings to use// w w w.  j  a  v  a  2 s  . co  m
 * @return The Document containing the XForm.
 * @throws org.chiba.tools.schemabuilder.FormBuilderException
 *          If an error occurs building the XForm.
 */
public Pair<Document, XSModel> buildXForm(final Document instanceDocument, final Document schemaDocument,
        String rootElementName, final ResourceBundle resourceBundle) throws FormBuilderException {
    final XSModel schema = SchemaUtil.parseSchema(schemaDocument, true);
    this.typeTree = SchemaUtil.buildTypeTree(schema);

    //refCounter = 0;
    this.counter.clear();

    final Document xformsDocument = this.createFormTemplate(rootElementName);

    //find form element: last element created
    final Element formSection = (Element) xformsDocument.getDocumentElement().getLastChild();
    final Element modelSection = (Element) xformsDocument.getDocumentElement()
            .getElementsByTagNameNS(NamespaceConstants.XFORMS_NS, "model").item(0);

    //add XMLSchema if we use schema types      
    final Element importedSchemaDocumentElement = (Element) xformsDocument
            .importNode(schemaDocument.getDocumentElement(), true);
    importedSchemaDocumentElement.setAttributeNS(null, "id", "schema-1");

    NodeList nl = importedSchemaDocumentElement.getChildNodes();
    boolean hasExternalSchema = false;

    for (int i = 0; i < nl.getLength(); i++) {
        Node current = nl.item(i);
        if (current.getNamespaceURI() != null
                && current.getNamespaceURI().equals(NamespaceConstants.XMLSCHEMA_NS)) {
            String localName = current.getLocalName();
            if (localName.equals("include") || localName.equals("import")) {
                hasExternalSchema = true;
                break;
            }
        }
    }

    // ALF-8105 / ETWOTWO-1384: Only embed the schema if it does not reference externals
    if (!hasExternalSchema) {
        modelSection.appendChild(importedSchemaDocumentElement);
    }

    //check if target namespace
    final StringList schemaNamespaces = schema.getNamespaces();
    final HashMap<String, String> schemaNamespacesMap = new HashMap<String, String>();
    if (schemaNamespaces.getLength() != 0) {
        // will return null if no target namespace was specified
        this.targetNamespace = schemaNamespaces.item(0);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("[buildXForm] using targetNamespace " + this.targetNamespace);

        for (int i = 0; i < schemaNamespaces.getLength(); i++) {
            if (schemaNamespaces.item(i) == null) {
                continue;
            }
            final String prefix = addNamespace(xformsDocument.getDocumentElement(),
                    schemaDocument.lookupPrefix(schemaNamespaces.item(i)), schemaNamespaces.item(i));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[buildXForm] adding namespace " + schemaNamespaces.item(i) + " with prefix "
                        + prefix + " to xform and default instance element");
            }
            schemaNamespacesMap.put(prefix, schemaNamespaces.item(i));
        }
    }

    //if target namespace & we use the schema types: add it to form ns declarations
    //   if (this.targetNamespace != null && this.targetNamespace.length() != 0)
    //       envelopeElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
    //                  "xmlns:schema",
    //                  this.targetNamespace);

    final XSElementDeclaration rootElementDecl = schema.getElementDeclaration(rootElementName,
            this.targetNamespace);
    if (rootElementDecl == null) {
        throw new FormBuilderException("Invalid root element tag name [" + rootElementName
                + ", targetNamespace = " + this.targetNamespace + "]");
    }

    rootElementName = this.getElementName(rootElementDecl, xformsDocument);
    final Element instanceElement = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
            NamespaceConstants.XFORMS_PREFIX + ":instance");
    modelSection.appendChild(instanceElement);
    this.setXFormsId(instanceElement);

    final Element defaultInstanceDocumentElement = xformsDocument.createElement(rootElementName);
    addNamespace(defaultInstanceDocumentElement, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
    if (this.targetNamespace != null) {
        final String targetNamespacePrefix = schemaDocument.lookupPrefix(this.targetNamespace);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[buildXForm] adding target namespace " + this.targetNamespace + " with prefix "
                    + targetNamespacePrefix + " to xform and default instance element");
        }

        addNamespace(defaultInstanceDocumentElement, targetNamespacePrefix, this.targetNamespace);
        addNamespace(xformsDocument.getDocumentElement(), targetNamespacePrefix, this.targetNamespace);
    }

    Element prototypeInstanceElement = null;
    if (instanceDocument == null || instanceDocument.getDocumentElement() == null) {
        instanceElement.appendChild(defaultInstanceDocumentElement);
    } else {
        Element instanceDocumentElement = instanceDocument.getDocumentElement();
        if (!instanceDocumentElement.getNodeName().equals(rootElementName)) {
            throw new IllegalArgumentException("instance document root tag name invalid.  " + "expected "
                    + rootElementName + ", got " + instanceDocumentElement.getNodeName());
        }

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("[buildXForm] importing rootElement from other document");

        prototypeInstanceElement = xformsDocument.createElementNS(NamespaceConstants.XFORMS_NS,
                NamespaceConstants.XFORMS_PREFIX + ":instance");
        modelSection.appendChild(prototypeInstanceElement);
        this.setXFormsId(prototypeInstanceElement, "instance_prototype");
        prototypeInstanceElement.appendChild(defaultInstanceDocumentElement);
    }

    final Element rootGroup = this.addElement(xformsDocument, modelSection, defaultInstanceDocumentElement,
            formSection, schema, rootElementDecl, "/" + this.getElementName(rootElementDecl, xformsDocument),
            new SchemaUtil.Occurrence(1, 1), resourceBundle);
    if (rootGroup.getNodeName() != NamespaceConstants.XFORMS_PREFIX + ":group") {
        throw new FormBuilderException("Expected root form element to be a " + NamespaceConstants.XFORMS_PREFIX
                + ":group, not a " + rootGroup.getNodeName() + ".  Ensure that "
                + this.getElementName(rootElementDecl, xformsDocument)
                + " is a concrete type that has no extensions.  "
                + "Types with extensions are not supported for " + "the root element of a form.");
    }
    this.setXFormsId(rootGroup, "alfresco-xforms-root-group");

    if (prototypeInstanceElement != null) {
        Schema2XForms.rebuildInstance(prototypeInstanceElement, instanceDocument, instanceElement,
                schemaNamespacesMap);
    }

    this.createSubmitElements(xformsDocument, modelSection, rootGroup);
    this.createTriggersForRepeats(xformsDocument, rootGroup);

    final Comment comment = xformsDocument.createComment(
            "This XForm was generated by " + this.getClass().getName() + " on " + (new Date()) + " from the '"
                    + rootElementName + "' element of the '" + this.targetNamespace + "' XML Schema.");
    xformsDocument.getDocumentElement().insertBefore(comment,
            xformsDocument.getDocumentElement().getFirstChild());
    xformsDocument.normalizeDocument();

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("[buildXForm] Returning XForm =\n" + XMLUtil.toString(xformsDocument));

    return new Pair<Document, XSModel>(xformsDocument, schema);
}

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

public void handleSubmit(Node result) {
    final Document instanceData = this.getXformsSession().getFormInstanceData();
    Element documentElement = instanceData.getDocumentElement();
    if (documentElement != null) {
        instanceData.removeChild(documentElement);
    }//from ww  w . j ava 2s.c o  m
    if (result instanceof Document) {
        result = ((Document) result).getDocumentElement();
    }
    documentElement = (Element) instanceData.importNode(result.cloneNode(true), true);
    Schema2XForms.removePrototypeNodes(documentElement);
    instanceData.appendChild(documentElement);
    instanceData.normalizeDocument();
}

From source file:org.apache.rahas.impl.util.SAMLUtilsTest.java

private static boolean equals(String element1, String element2)
        throws ParserConfigurationException, IOException, SAXException {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from  w w w. j a v a 2  s . c  o m*/
    dbf.setCoalescing(true);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setIgnoringComments(true);
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc1 = db.parse(new ByteArrayInputStream(element1.getBytes("UTF-8")));
    doc1.normalizeDocument();

    Document doc2 = db.parse(new ByteArrayInputStream(element1.getBytes("UTF-8")));
    doc2.normalizeDocument();

    return doc1.isEqualNode(doc2);
}

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  a v a 2  s  .  com
* 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);
    }
}

From source file:org.excalibur.core.util.JAXBContextFactory.java

public Document loadFromXmlFile(File xmlFile) throws IOException, ParserConfigurationException, SAXException {
    Document document = this.documentFactory.newDocumentBuilder().parse(xmlFile);
    document.normalizeDocument();
    return document;
}

From source file:org.excalibur.core.util.JAXBContextFactory.java

public Document getXmlDocumentFromText(final String xmlText)
        throws IOException, ParserConfigurationException, SAXException {
    Document document = this.getDocumentFactory().newDocumentBuilder()
            .parse(new ByteArrayInputStream(xmlText.getBytes(DEFAULT_XML_ENCODING)));
    document.normalizeDocument();
    return document;
}

From source file:org.mule.modules.sugarcrm.automation.unit.TransformerXmlToCxfTest.java

@Test
public void validTransformationXmlFromSugar() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//  w w  w  . j  ava 2s .  com
    dbf.setCoalescing(true);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setIgnoringComments(true);
    DocumentBuilder db = dbf.newDocumentBuilder();

    String xml = IOUtils.getResourceAsString("response-searchByModule.xml", getClass());
    String xmlTransform = new XmlToCxfTransformer().transform(xml);

    Document doc1 = db.parse(org.apache.commons.io.IOUtils.toInputStream(xmlTransform));
    doc1.normalizeDocument();

    Document doc2 = db.parse(IOUtils.getResourceAsStream("response-searchByModule-ok.xml", getClass()));
    doc2.normalizeDocument();

    Assert.assertTrue(doc1.isEqualNode(doc2));
}

From source file:org.ojbc.processor.firearm.search.FirearmSearchRequestProcessor.java

@Override
public String invokeFirearmSearchRequest(FirearmSearchRequest firearmSearchRequest, String federatedQueryID,
        Element samlToken) throws Exception {
    String response = "";
    try {/*from  ww  w  . j a  v  a 2 s .co m*/
        if (allowQueriesWithoutSAMLToken) {
            if (samlToken == null) {
                //Add SAML token to request call
                samlToken = SAMLTokenUtils.createStaticAssertionAsElement(
                        "https://idp.ojbc-local.org:9443/idp/shibboleth",
                        SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS,
                        SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1, true, true, null);

            }
        }

        if (samlToken == null) {
            throw new Exception("No SAML token provided. Unable to perform query.");
        }

        //POJO to XML Request
        Document firearmSearchRequestPayload = RequestMessageBuilderUtilities
                .createFirearmSearchRequest(firearmSearchRequest);
        firearmSearchRequestPayload.normalizeDocument();

        //Create exchange
        Exchange senderExchange = new DefaultExchange(camelContext, ExchangePattern.InOnly);

        //Set exchange body to XML Request message
        senderExchange.getIn().setBody(firearmSearchRequestPayload);

        //Set reply to and WS-Addressing message ID
        senderExchange.getIn().setHeader("federatedQueryRequestGUID", federatedQueryID);
        senderExchange.getIn().setHeader("WSAddressingReplyTo", this.getReplyToAddress());

        //Set the token header so that CXF can retrieve this on the outbound call
        String tokenID = senderExchange.getExchangeId();
        senderExchange.getIn().setHeader("tokenID", tokenID);

        OJBSamlMap.putToken(tokenID, samlToken);

        firearmSearchMessageProcessor.sendResponseMessage(camelContext, senderExchange);

        //Put message ID and "noResponse" place holder.  
        putRequestInMap(federatedQueryID);

        response = pollMap(federatedQueryID);

        if (response.equals(NO_RESPONSE)) {
            log.debug("Endpoints timed out and no response recieved at web app, create error response");
            response = MergeNotificationErrorProcessor.returnMergeNotificationErrorMessage();
        }

        if (response.length() > 500) {
            log.debug("Here is the response (truncated): " + response.substring(0, 500));
        } else {
            log.debug("Here is the response: " + response);
        }

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

    //return response here
    return response;

}

From source file:org.ojbc.processor.incident.search.IncidentSearchRequestProcessor.java

@Override
public String invokeIncidentSearchRequest(IncidentSearchRequest incidentSearchRequest, String federatedQueryID,
        Element samlToken) throws Exception {

    if (allowQueriesWithoutSAMLToken) {
        if (samlToken == null) {
            //Add SAML token to request call
            samlToken = SAMLTokenUtils.createStaticAssertionAsElement(
                    "https://idp.ojbc-local.org:9443/idp/shibboleth",
                    SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS,
                    SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1, true, true, null);

        }/*from www.  j  a  va  2 s.c om*/
    }

    if (samlToken == null) {
        throw new Exception("No SAML token provided. Unable to perform query.");
    }

    //POJO to XML Request
    //When multiple operations are supported, we will call the appropriate POJO to XML Method
    Document incidentRequestPayload = RequestMessageBuilderUtilities.createIncidentSearchRequest(
            incidentSearchRequest, cityTownCodelistNamespace, cityTownCodelistElementName);

    incidentRequestPayload.normalizeDocument();

    log.debug(OJBUtils.getStringFromDocument(incidentRequestPayload));

    //Create exchange
    Exchange senderExchange = new DefaultExchange(camelContext, ExchangePattern.InOnly);

    //Set exchange body to XML Request message
    senderExchange.getIn().setBody(incidentRequestPayload);

    //Set reply to and WS-Addressing message ID
    senderExchange.getIn().setHeader("federatedQueryRequestGUID", federatedQueryID);
    senderExchange.getIn().setHeader("WSAddressingReplyTo", this.getReplyToAddress());

    //Set the token header so that CXF can retrieve this on the outbound call
    String tokenID = senderExchange.getExchangeId();
    senderExchange.getIn().setHeader("tokenID", tokenID);
    OJBSamlMap.putToken(tokenID, samlToken);

    incidentSearchMessageProcessor.sendResponseMessage(camelContext, senderExchange);

    //Put message ID and "noResponse" place holder.  
    putRequestInMap(federatedQueryID);

    String response = pollMap(federatedQueryID);

    if (response.length() > 500) {
        log.debug("Here is the response (truncated): " + response.substring(0, 500));
    } else {
        log.debug("Here is the response: " + response);
    }

    //This is a defensive check in case the polling completes and the service has not yet returned a response
    //In this case we send back an empty search result
    if (response.equals(NO_RESPONSE)) {
        log.debug("Endpoints timed out and no response recieved at web app, create error response");
        response = MergeNotificationErrorProcessor.returnMergeNotificationErrorMessage();
    }

    //return response here
    return response;
}