Example usage for org.w3c.dom Element normalize

List of usage examples for org.w3c.dom Element normalize

Introduction

In this page you can find the example usage for org.w3c.dom Element normalize.

Prototype

public void normalize();

Source Link

Document

Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

Usage

From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java

protected GroupShadow processXmlGroupRecursive(Element groupElem) {
    GroupShadow shadow = new GroupShadow();
    shadow.key = groupElem.getAttribute("key");
    shadow.name = groupElem.getAttribute("name");
    //System.out.println("Loading configuration for group "+shadow.name);
    ArrayList subgroups = new ArrayList();
    NodeList nl = groupElem.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        if (nl.item(i).getNodeType() == ELEMENT_NODE) {
            Element e = (Element) nl.item(i);
            if (e.getNodeName().equals("group")) {
                GroupShadow sub = processXmlGroupRecursive(e);
                subgroups.add(sub);//from   w  w  w .j  a  v a 2  s. c  o m
                groups.put(sub.key, sub);
            } else if (e.getNodeName().equals("entity-set")) {
                shadow.entities = new EntitySet(e);
            } else if (e.getNodeName().equals("description")) {
                e.normalize();
                Text t = (Text) e.getFirstChild();
                if (t != null) {
                    shadow.description = t.getData();
                }
            }
        }
    }
    shadow.subgroups = (GroupShadow[]) subgroups.toArray(new GroupShadow[0]);
    return shadow;
}

From source file:org.b3log.latke.util.StaticResources.java

/**
 * Initializes the static resource path patterns.
 *///  ww w. java  2 s  .  c o m
private static synchronized void init() {
    LOGGER.trace("Reads static resources definition from [static-resources.xml]");

    final File staticResources = Latkes.getWebFile("/WEB-INF/static-resources.xml");
    if (null == staticResources || !staticResources.exists()) {
        throw new IllegalStateException("Not found static resources definition from [static-resources.xml]");
    }

    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

    try {
        final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        final Document document = documentBuilder.parse(staticResources);
        final Element root = document.getDocumentElement();

        root.normalize();

        final StringBuilder logBuilder = new StringBuilder("Reading static files: [")
                .append(Strings.LINE_SEPARATOR);
        final NodeList includes = root.getElementsByTagName("include");
        for (int i = 0; i < includes.getLength(); i++) {
            final Element include = (Element) includes.item(i);
            String path = include.getAttribute("path");
            final URI uri = new URI("http", "b3log.org", path, null);
            final String s = uri.toASCIIString();
            path = StringUtils.substringAfter(s, "b3log.org");

            STATIC_RESOURCE_PATHS.add(path);

            logBuilder.append("    ").append("path pattern [").append(path).append("]");
            if (i < includes.getLength() - 1) {
                logBuilder.append(",");
            }
            logBuilder.append(Strings.LINE_SEPARATOR);
        }

        logBuilder.append("]");

        if (LOGGER.isTraceEnabled()) {
            LOGGER.debug(logBuilder.toString());
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Reads [" + staticResources.getName() + "] failed", e);
        throw new RuntimeException(e);
    }

    final StringBuilder logBuilder = new StringBuilder("Static files: [").append(Strings.LINE_SEPARATOR);
    final Iterator<String> iterator = STATIC_RESOURCE_PATHS.iterator();
    while (iterator.hasNext()) {
        final String pattern = iterator.next();

        logBuilder.append("    ").append(pattern);
        if (iterator.hasNext()) {
            logBuilder.append(',');
        }
        logBuilder.append(Strings.LINE_SEPARATOR);
    }
    logBuilder.append("], ").append('[').append(STATIC_RESOURCE_PATHS.size()).append("] path patterns");

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(logBuilder.toString());
    }

    inited = true;
}

From source file:org.eclipse.buildship.docs.formatting.LinkRenderer.java

Node link(TypeMetaData type, final GenerationListener listener) {
    final Element linkElement = document.createElement(TAG_NAME);
    //        final Element linkElement = document.createElement("a");

    type.visitSignature(new TypeMetaData.SignatureVisitor() {
        public void visitText(String text) {
            linkElement.appendChild(document.createTextNode(text));
        }/*from w  w  w .  ja  v  a2  s.c o  m*/

        public void visitType(String name) {
            linkElement.appendChild(addType(name, listener));
        }
    });

    linkElement.normalize();
    if (linkElement.getChildNodes().getLength() == 1 && linkElement.getFirstChild() instanceof Element) {
        return linkElement.getFirstChild();
    }
    return linkElement;
}

From source file:org.getobjects.eoaccess.EOModelLoader.java

protected String joinTrimmedTextsOfElements(NodeList _nodes, String _sep) {
    if (_nodes == null || _nodes.getLength() == 0)
        return null;

    StringBuilder sb = new StringBuilder(256);
    boolean isFirst = true;
    for (int i = 0; i < _nodes.getLength(); i++) {
        Element node = (Element) _nodes.item(i);
        node.normalize();

        String txt = node.getTextContent();
        if (txt == null)
            continue;

        /* we replace newlines, so you can't use them inside <sql> elements */
        txt = txt.replace("\n", " ").trim();
        if (txt.length() == 0)
            continue;

        if (isFirst)
            isFirst = false;/*from w w  w. j a  v  a 2s .co  m*/
        else if (_sep != null)
            sb.append(_sep);

        sb.append(txt);
    }
    return sb.length() > 0 ? sb.toString() : null;
}

From source file:org.getobjects.rules.RuleModelLoader.java

protected String joinTrimmedTextsOfElements(NodeList _nodes, String _sep) {
    if (_nodes == null || _nodes.getLength() == 0)
        return null;

    StringBuilder sb = new StringBuilder(256);
    boolean isFirst = true;
    for (int i = 0; i < _nodes.getLength(); i++) {
        Element node = (Element) _nodes.item(i);
        node.normalize();

        String txt = node.getTextContent();
        if (txt == null)
            continue;
        txt = txt.trim();//from   www . j  av  a 2s .  com
        if (txt.length() == 0)
            continue;

        if (isFirst)
            isFirst = false;
        else if (_sep != null)
            sb.append(_sep);

        sb.append(txt);
    }
    return sb.length() > 0 ? sb.toString() : null;
}

From source file:org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.PomReader.java

private Map<String, String> getPomProperties(Element parentElement) {
    Map<String, String> pomProperties = new HashMap<String, String>();
    Element propsEl = getFirstChildElement(parentElement, PROPERTIES);
    if (propsEl != null) {
        propsEl.normalize();
    }//from   w  ww.j ava 2s.com
    for (Element prop : getAllChilds(propsEl)) {
        pomProperties.put(prop.getNodeName(), getTextContent(prop));
    }
    return pomProperties;
}

From source file:org.gradle.build.docs.dsl.docbook.LinkRenderer.java

Node link(TypeMetaData type, final GenerationListener listener) {
    final Element linkElement = document.createElement("classname");

    type.visitSignature(new TypeMetaData.SignatureVisitor() {
        public void visitText(String text) {
            linkElement.appendChild(document.createTextNode(text));
        }// w  ww . jav a2 s.co m

        public void visitType(String name) {
            linkElement.appendChild(addType(name, listener));
        }
    });

    linkElement.normalize();
    if (linkElement.getChildNodes().getLength() == 1 && linkElement.getFirstChild() instanceof Element) {
        return linkElement.getFirstChild();
    }
    return linkElement;
}

From source file:org.kuali.rice.kns.workflow.attribute.KualiXmlAttributeHelper.java

/**
 * This method overrides the super class and modifies the XML that it operates on to put the name and the title in the place
 * where the super class expects to see them, overwriting the original title in the XML.
 *
 * @see org.kuali.rice.kew.rule.xmlrouting.StandardGenericXMLRuleAttribute#getConfigXML()
 *//*from   w  w  w  .j a v a 2  s  .  c  o  m*/

public Element processConfigXML(Element root, String[] xpathExpressionElements) {

    NodeList fields = root.getElementsByTagName("fieldDef");
    Element theTag = null;
    String docContent = "";

    /**
     * This section will check to see if document content has been defined in the configXML for the document type, by running an
     * XPath. If this is an empty list the xpath expression in the fieldDef is used to define the xml document content that is
     * added to the configXML. The xmldocument content is of this form, when in the document configXML. <xmlDocumentContent>
     * <org.kuali.rice.krad.bo.SourceAccountingLine> <amount> <value>%totaldollarAmount%</value> </amount>
     * </org.kuali.rice.krad.bo.SourceAccountingLine> </xmlDocumentContent> This class generates this on the fly, by creating an XML
     * element for each term in the XPath expression. When this doesn't apply XML can be coded in the configXML for the
     * ruleAttribute.
     *
     * @see org.kuali.rice.kew.plugin.attributes.WorkflowAttribute#getDocContent()
     */

    org.w3c.dom.Document xmlDoc = null;
    if (!xmlDocumentContentExists(root)) { // XML Document content is given because the xpath is non standard
        fields = root.getElementsByTagName("fieldDef");
        xmlDoc = root.getOwnerDocument();
    }
    for (int i = 0; i < fields.getLength(); i++) { // loop over each fieldDef
        String name = null;
        if (!xmlDocumentContentExists(root)) {
            theTag = (Element) fields.item(i);

            /*
             * Even though there may be multiple xpath test, for example one for source lines and one for target lines, the
             * xmlDocumentContent only needs one, since it is used for formatting. The first one is arbitrarily selected, since
             * they are virtually equivalent in structure, most of the time.
             */

            List<String> xPathTerms = getXPathTerms(theTag);
            if (xPathTerms.size() != 0) {
                Node iterNode = xmlDoc.createElement("xmlDocumentContent");

                xmlDoc.normalize();

                iterNode.normalize();

                /*
                 * Since this method is run once per attribute and there may be multiple fieldDefs, the first fieldDef is used
                 * to create the configXML.
                 */
                for (int j = 0; j < xPathTerms.size(); j++) {// build the configXML based on the Xpath
                    // TODO - Fix the document content element generation
                    iterNode.appendChild(xmlDoc.createElement(xPathTerms.get(j)));
                    xmlDoc.normalize();

                    iterNode = iterNode.getFirstChild();
                    iterNode.normalize();

                }
                iterNode.setTextContent("%" + xPathTerms.get(xPathTerms.size() - 1) + "%");
                root.appendChild(iterNode);
            }
        }
        theTag = (Element) fields.item(i);
        // check to see if a values finder is being used to set valid values for a field
        NodeList displayTagElements = theTag.getElementsByTagName("display");
        if (displayTagElements.getLength() == 1) {
            Element displayTag = (Element) displayTagElements.item(0);
            List valuesElementsToAdd = new ArrayList();
            for (int w = 0; w < displayTag.getChildNodes().getLength(); w++) {
                Node displayTagChildNode = (Node) displayTag.getChildNodes().item(w);
                if ((displayTagChildNode != null) && ("values".equals(displayTagChildNode.getNodeName()))) {
                    if (displayTagChildNode.getChildNodes().getLength() > 0) {
                        String valuesNodeText = displayTagChildNode.getFirstChild().getNodeValue();
                        String potentialClassName = getPotentialKualiClassName(valuesNodeText,
                                KUALI_VALUES_FINDER_REFERENCE_PREFIX, KUALI_VALUES_FINDER_REFERENCE_SUFFIX);
                        if (StringUtils.isNotBlank(potentialClassName)) {
                            try {
                                Class finderClass = Class.forName((String) potentialClassName);
                                KeyValuesFinder finder = (KeyValuesFinder) finderClass.newInstance();
                                NamedNodeMap valuesNodeAttributes = displayTagChildNode.getAttributes();
                                Node potentialSelectedAttribute = (valuesNodeAttributes != null)
                                        ? valuesNodeAttributes.getNamedItem("selected")
                                        : null;
                                for (Iterator iter = finder.getKeyValues().iterator(); iter.hasNext();) {
                                    KeyValue keyValue = (KeyValue) iter.next();
                                    Element newValuesElement = root.getOwnerDocument().createElement("values");
                                    newValuesElement.appendChild(
                                            root.getOwnerDocument().createTextNode(keyValue.getKey()));
                                    // newValuesElement.setNodeValue(KeyValue.getKey().toString());
                                    newValuesElement.setAttribute("title", keyValue.getValue());
                                    if (potentialSelectedAttribute != null) {
                                        newValuesElement.setAttribute("selected",
                                                potentialSelectedAttribute.getNodeValue());
                                    }
                                    valuesElementsToAdd.add(newValuesElement);
                                }
                            } catch (ClassNotFoundException cnfe) {
                                String errorMessage = "Caught an exception trying to find class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, cnfe);
                                throw new RuntimeException(errorMessage, cnfe);
                            } catch (InstantiationException ie) {
                                String errorMessage = "Caught an exception trying to instantiate class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, ie);
                                throw new RuntimeException(errorMessage, ie);
                            } catch (IllegalAccessException iae) {
                                String errorMessage = "Caught an access exception trying to instantiate class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, iae);
                                throw new RuntimeException(errorMessage, iae);
                            }
                        } else {
                            valuesElementsToAdd.add(displayTagChildNode.cloneNode(true));
                        }
                        displayTag.removeChild(displayTagChildNode);
                    }
                }
            }
            for (Iterator iter = valuesElementsToAdd.iterator(); iter.hasNext();) {
                Element valuesElementToAdd = (Element) iter.next();
                displayTag.appendChild(valuesElementToAdd);
            }
        }
        if ((xpathExpressionElements != null) && (xpathExpressionElements.length > 0)) {
            NodeList fieldEvaluationElements = theTag.getElementsByTagName("fieldEvaluation");
            if (fieldEvaluationElements.getLength() == 1) {
                Element fieldEvaluationTag = (Element) fieldEvaluationElements.item(0);
                List tagsToAdd = new ArrayList();
                for (int w = 0; w < fieldEvaluationTag.getChildNodes().getLength(); w++) {
                    Node fieldEvaluationChildNode = (Node) fieldEvaluationTag.getChildNodes().item(w);
                    Element newTagToAdd = null;
                    if ((fieldEvaluationChildNode != null)
                            && ("xpathexpression".equals(fieldEvaluationChildNode.getNodeName()))) {
                        newTagToAdd = root.getOwnerDocument().createElement("xpathexpression");
                        newTagToAdd.appendChild(root.getOwnerDocument()
                                .createTextNode(generateNewXpathExpression(
                                        fieldEvaluationChildNode.getFirstChild().getNodeValue(),
                                        xpathExpressionElements)));
                        tagsToAdd.add(newTagToAdd);
                        fieldEvaluationTag.removeChild(fieldEvaluationChildNode);
                    }
                }
                for (Iterator iter = tagsToAdd.iterator(); iter.hasNext();) {
                    Element elementToAdd = (Element) iter.next();
                    fieldEvaluationTag.appendChild(elementToAdd);
                }
            }
        }
        theTag.setAttribute("title", getBusinessObjectTitle(theTag));

    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(XmlJotter.jotNode(root));
        StringWriter xmlBuffer = new StringWriter();
        try {

            root.normalize();
            Source source = new DOMSource(root);
            Result result = new StreamResult(xmlBuffer);
            TransformerFactory.newInstance().newTransformer().transform(source, result);
        } catch (Exception e) {
            LOG.debug(" Exception when printing debug XML output " + e);
        }
        LOG.debug(xmlBuffer.getBuffer());
    }

    return root;
}

From source file:org.openmrs.module.muzima.handler.XmlEncounterQueueDataHandler.java

@Override
public boolean validate(QueueData queueData) {

    log.info("Processing encounter form data: " + queueData.getUuid());
    queueProcessorException = new QueueProcessorException();

    String payload = queueData.getPayload();

    try {/*from   w w  w . ja va2  s  .  c  o  m*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(new InputSource(new ByteArrayInputStream(payload.getBytes("utf-8"))));

        Element element = document.getDocumentElement();
        element.normalize();

        // we need to get the form id to get the encounter type associated with this form from the form record.
        encounter.setEncounterType(Context.getEncounterService().getEncounterType(1));

        processPatient(encounter, document.getElementsByTagName("patient"));
        processEncounter(encounter, document.getElementsByTagName("encounter"));
        processObs(encounter, document.getElementsByTagName("obs"));
        return true;

    } catch (Exception e) {
        queueProcessorException.addException(e);
        return false;
    } finally {
        if (queueProcessorException.anyExceptions()) {
            throw queueProcessorException;
        }
    }
}

From source file:org.openmrs.module.muzima.handler.XmlRegistrationQueueDataHandler.java

private Patient createPatientFromPayload(final String payload) {
    Patient unsavedPatient = new Patient();
    try {/*  w  ww . jav a2s .  co  m*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(new InputSource(new ByteArrayInputStream(payload.getBytes("utf-8"))));

        Element element = document.getDocumentElement();
        element.normalize();

        Node patientNode = document.getElementsByTagName("patient").item(0);
        NodeList patientElementNodes = patientNode.getChildNodes();

        PersonName personName = new PersonName();
        PatientIdentifier patientIdentifier = new PatientIdentifier();
        for (int i = 0; i < patientElementNodes.getLength(); i++) {
            Node patientElementNode = patientElementNodes.item(i);
            if (patientElementNode.getNodeType() == Node.ELEMENT_NODE) {
                Element patientElement = (Element) patientElementNode;
                String tagName = patientElement.getTagName();
                if (tagName.equals("patient.middle_name")) {
                    personName.setMiddleName(patientElement.getTextContent());
                } else if (tagName.equals("patient.given_name")) {
                    personName.setGivenName(patientElement.getTextContent());
                } else if (tagName.equals("patient.family_name")) {
                    personName.setFamilyName(patientElement.getTextContent());
                } else if (tagName.equals("patient_identifier.identifier_type_id")) {
                    int identifierTypeId = Integer.parseInt(patientElement.getTextContent());
                    PatientIdentifierType identifierType = Context.getPatientService()
                            .getPatientIdentifierType(identifierTypeId);
                    if (identifierType == null) {
                        queueProcessorException.addException(new Exception(
                                "Unable to find patient identifier type with id: " + identifierTypeId));
                    } else {
                        patientIdentifier.setIdentifierType(identifierType);
                    }
                } else if (tagName.equals("patient.medical_record_number")) {
                    patientIdentifier.setIdentifier(patientElement.getTextContent());
                } else if (tagName.equals("patient.sex")) {
                    unsavedPatient.setGender(patientElement.getTextContent());
                } else if (tagName.equals("patient.birthdate")) {
                    Date dob = parseDate(patientElement.getTextContent());
                    unsavedPatient.setBirthdate(dob);
                } else if (tagName.equals("patient.uuid")) {
                    unsavedPatient.setUuid(patientElement.getTextContent());
                    setTemporaryPatientUuid(patientElement.getTextContent());
                } else if (tagName.equals("patient.finger")) {
                    savePatientsFinger(unsavedPatient, patientElement.getTextContent());
                } else if (tagName.equals("patient.fingerprint")) {
                    savePatientsFingerprint(unsavedPatient, patientElement.getTextContent());
                } else if (tagName.equals("amrs_medical_record_number_identifier_type")) {
                    extractIdentifier(unsavedPatient, patientElement, "AMRS Medical Record Number");
                } else if (tagName.equals("ccc_identifier_type")) {
                    extractIdentifier(unsavedPatient, patientElement, "CCC Number ");
                } else if (tagName.equals("hct_identifier_type")) {
                    extractIdentifier(unsavedPatient, patientElement, "HCT ID");
                } else if (tagName.equals("kni_identifier_type")) {
                    extractIdentifier(unsavedPatient, patientElement, "KENYAN NATIONAL ID NUMBER");
                } else if (tagName.equals("mtct_identifier_type")) {
                    extractIdentifier(unsavedPatient, patientElement, "MTCT Plus ID");
                } else if (tagName.equals("mtrh_hospital_number_identifier_type")) {
                    extractIdentifier(unsavedPatient, patientElement, "MTRH Hospital Number");
                } else if (tagName.equals("old_amrs_number_identifier_type")) {
                    extractIdentifier(unsavedPatient, patientElement, "Old AMPATH Medical Record Number");
                } else if (tagName.equals("pmtc_identifier_type")) {
                    extractIdentifier(unsavedPatient, patientElement, "pMTCT ID");
                } else if (tagName.startsWith("person_attribute")) {
                    PersonService personService = Context.getPersonService();

                    int personAttributeTypeId = NumberUtils.toInt(tagName.replace("person_attribute", ""));
                    PersonAttributeType personAttributeType = personService
                            .getPersonAttributeType(personAttributeTypeId);
                    if (personAttributeType == null) {
                        queueProcessorException.addException(new Exception(
                                "Unable to find attribute type with id: " + personAttributeTypeId));
                    } else {
                        PersonAttribute personAttribute = new PersonAttribute();
                        personAttribute.setAttributeType(personAttributeType);
                        personAttribute.setValue(patientElement.getTextContent());
                        unsavedPatient.addAttribute(personAttribute);
                    }
                }
            }
        }

        Node encounterNode = document.getElementsByTagName("encounter").item(0);
        NodeList encounterElementNodes = encounterNode.getChildNodes();

        for (int i = 0; i < encounterElementNodes.getLength(); i++) {
            Node encounterElementNode = encounterElementNodes.item(i);
            if (encounterElementNode.getNodeType() == Node.ELEMENT_NODE) {
                Element encounterElement = (Element) encounterElementNode;
                if (encounterElement.getTagName().equals("encounter.location_id")) {
                    int locationId = Integer.parseInt(encounterElement.getTextContent());
                    Location location = Context.getLocationService().getLocation(locationId);
                    if (location == null) {
                        queueProcessorException
                                .addException(new Exception("Unable to find location with id: " + locationId));
                    } else {
                        patientIdentifier.setLocation(location);
                    }
                    for (PatientIdentifier identifier : unsavedPatient.getIdentifiers()) {
                        identifier.setLocation(location);
                    }
                }
            }
        }

        unsavedPatient.addName(personName);
        unsavedPatient.addIdentifier(patientIdentifier);
    } catch (ParserConfigurationException e) {
        queueProcessorException.addException(new Exception(e.getMessage()));
    } catch (SAXException e) {
        queueProcessorException.addException(new Exception(e.getMessage()));
    } catch (IOException e) {
        queueProcessorException.addException(new Exception(e.getMessage()));
    }
    return unsavedPatient;
}