Example usage for org.dom4j Element isTextOnly

List of usage examples for org.dom4j Element isTextOnly

Introduction

In this page you can find the example usage for org.dom4j Element isTextOnly.

Prototype

boolean isTextOnly();

Source Link

Document

Returns true if this Element has text only content.

Usage

From source file:nl.architolk.ldt.processors.HttpClientProcessor.java

License:Open Source License

private void populateJSONObject(JSONObject root, Element element) {
    Attribute typeAttr = element.attribute("type");
    String nodeType = (typeAttr != null) ? typeAttr.getValue() : "";
    if (element.isTextOnly()) {
        if (nodeType.equals("node")) {
            //Text only means: no children. If type is explicitly set to "node", the result should be an empty object
            root.put(element.getQName().getName(), new JSONObject());
        } else if (nodeType.equals("number")) {
            //Numeric field
            try {
                root.put(element.getQName().getName(), Float.valueOf(element.getText()));
            } catch (NumberFormatException e) {
                logger.warn("Not a number: " + element.getText());
            }//w  w w .  j a  va 2 s.com
        } else {
            //Default = string
            root.put(element.getQName().getName(), element.getText());
        }
    } else if (nodeType.equals("nodelist")) {
        JSONArray json = new JSONArray();
        Iterator<?> elit = element.elementIterator();
        while (elit.hasNext()) {
            Element child = (Element) elit.next();
            populateJSONArray(json, child);
        }
        root.put(element.getQName().getName(), json);
    } else {
        JSONObject json = new JSONObject();
        Iterator<?> elit = element.elementIterator();
        while (elit.hasNext()) {
            Element child = (Element) elit.next();
            populateJSONObject(json, child);
        }
        root.put(element.getQName().getName(), json);
    }
}

From source file:org.craftercms.core.xml.mergers.impl.cues.impl.MergeParentAndChildMergeCue.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public Element merge(Element parent, Element child, Map<String, String> params) throws XmlMergeException {
    Element merged = DocumentHelper.createElement(child.getQName());
    org.craftercms.core.util.CollectionUtils.move(child.attributes(), merged.attributes());

    if (parent.isTextOnly() && child.isTextOnly()) {
        String parentText = parent.getText();
        String childText = child.getText();

        if (getMergeOrder(params).equalsIgnoreCase("after")) {
            merged.setText(parentText + childText);
        } else {//w  w w  . ja v a2  s. c o m
            merged.setText(childText + parentText);
        }
    } else {
        List<Element> parentElements = parent.elements();
        List<Element> childElements = child.elements();
        List<Element> mergedElements = merged.elements();

        if (CollectionUtils.isNotEmpty(parentElements) && CollectionUtils.isNotEmpty(childElements)) {
            for (Iterator<Element> i = parentElements.iterator(); i.hasNext();) {
                Element parentElement = i.next();
                boolean elementsMerged = false;

                for (Iterator<Element> j = childElements.iterator(); !elementsMerged && j.hasNext();) {
                    Element childElement = j.next();
                    if (elementMergeMatcher.matchForMerge(parentElement, childElement)) {
                        MergeCueContext context = mergeCueResolver.getMergeCue(parentElement, childElement);
                        if (context != null) {
                            i.remove();
                            j.remove();

                            Element mergedElement = context.doMerge();
                            mergedElements.add(mergedElement);

                            elementsMerged = true;
                        } else {
                            throw new XmlMergeException("No merge cue was resolved for matching elements "
                                    + parentElement + " (parent) and " + childElement + " (child)");
                        }
                    }
                }
            }
        }

        if (getMergeOrder(params).equalsIgnoreCase("after")) {
            org.craftercms.core.util.CollectionUtils.move(parentElements, mergedElements);
            org.craftercms.core.util.CollectionUtils.move(childElements, mergedElements);
        } else {
            org.craftercms.core.util.CollectionUtils.move(childElements, mergedElements);
            org.craftercms.core.util.CollectionUtils.move(parentElements, mergedElements);
        }
    }

    return merged;
}

From source file:org.craftercms.search.service.impl.DefaultElementParser.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public boolean parse(Element element, String fieldName, String parentFieldName, SolrInputDocument solrDoc,
        ElementParserService parserService) {
    logger.debug("Parsing element '{}'", fieldName);

    if (element.hasContent()) {
        if (element.isTextOnly()) {
            logger.debug("Adding Solr field '{}'", fieldName);

            Object fieldValue = fieldValueConverter.convert(fieldName, element.getText());

            solrDoc.addField(fieldName, fieldValue);
        } else {//from   w  w w. j  a  v  a2 s.  c o  m
            List<Element> children = element.elements();
            for (Element child : children) {
                parserService.parse(child, fieldName, solrDoc);
            }
        }
    } else {
        logger.debug("Element '{}' has no content. Ignoring it.");
    }

    return true;
}

From source file:org.craftercms.search.service.impl.SolrDocumentBuilder.java

License:Open Source License

protected void build(SolrInputDocument solrDoc, String branchName, Element element) {
    branchName = (StringUtils.isNotEmpty(branchName) ? branchName + '.' : "") + element.getName();

    // All fields are indexable unless excluded using the indexable attribute, e.g. <name indexable="false"/>.
    // If the element is a branch, skip the children too.
    if (BooleanUtils.toBoolean(element.attributeValue("indexable"), true)) {
        if (element.hasContent()) {
            if (element.isTextOnly()) {
                // If a field name is not specified as attribute, use the branch name.
                String fieldName = element.attributeValue("fieldName");
                if (StringUtils.isEmpty(fieldName)) {
                    fieldName = branchName;
                }/* w w  w. j a  va 2s. c  om*/

                String fieldValue = element.getText();
                // If fieldName ends with HTML prefix, strip all HTML markup from the field value.
                if (fieldName.endsWith(htmlFieldSuffix)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Stripping HTML from field '" + fieldName + "'");
                    }

                    fieldValue = stripHtml(fieldName, fieldValue);
                }
                // If fieldName ends with datetime prefix, convert the field value to an ISO datetime string.
                if (fieldName.endsWith(dateTimeFieldSuffix)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Converting '" + fieldValue + "' to ISO datetime");
                    }

                    fieldValue = convertToISODateTimeString(fieldValue);
                }

                if (logger.isDebugEnabled()) {
                    logger.debug("Adding field '" + fieldName + "' to the Solr doc");
                }

                solrDoc.addField(fieldName, fieldValue);
            } else {
                List<Element> children = element.elements();
                for (Element child : children) {
                    build(solrDoc, branchName, child);
                }
            }
        }
    } else if (logger.isDebugEnabled()) {
        logger.debug("Element '" + branchName + "' is not indexable: it won't be added to the Solr doc");
    }
}

From source file:org.craftercms.studio.impl.v1.service.site.SiteServiceImpl.java

License:Open Source License

private Map<String, Object> createMap(Element element) {
    Map<String, Object> map = new HashMap<String, Object>();
    for (int i = 0, size = element.nodeCount(); i < size; i++) {
        Node currentNode = element.node(i);
        if (currentNode instanceof Element) {
            Element currentElement = (Element) currentNode;
            String key = currentElement.getName();
            Object toAdd = null;/*from  w w  w . j a  v  a  2  s .  co  m*/
            if (currentElement.isTextOnly()) {
                toAdd = currentElement.getStringValue();
            } else {
                toAdd = createMap(currentElement);
            }
            if (map.containsKey(key)) {
                Object value = map.get(key);
                List listOfValues = new ArrayList<Object>();
                if (value instanceof List) {
                    listOfValues = (List<Object>) value;
                } else {
                    listOfValues.add(value);
                }
                listOfValues.add(toAdd);
                map.put(key, listOfValues);
            } else {
                map.put(key, toAdd);
            }
        }
    }
    return map;
}

From source file:org.dcm4chex.archive.hl7.HL7SendService.java

License:LGPL

/** Parse the PID entries into a list of maps */
public static final List<Map<String, String>> parsePDQ(Document msg) {
    List<Map<String, String>> ret = new ArrayList<Map<String, String>>();
    Element root = msg.getRootElement();
    List<?> content = root.content();
    for (Object c : content) {
        if (!(c instanceof Element))
            continue;
        Element e = (Element) c;
        if (e.getName().equals("PID")) {
            Map<String, String> pid = new HashMap<String, String>();
            pid.put("Type", "Patient");
            List<?> fields = e.elements(HL7XMLLiterate.TAG_FIELD);

            int pidNo = 0;
            for (Object f : fields) {
                pidNo++;/* w  ww  .  ja v  a 2s  .  c  o  m*/
                if (pidNo >= FIELD_NAMES.length)
                    continue;
                String fieldName = FIELD_NAMES[pidNo];
                if (fieldName == null)
                    continue;
                Element field = (Element) f;
                if (field.isTextOnly()) {
                    String txt = field.getText();
                    if (txt == null || txt.length() == 0)
                        continue;
                    pid.put(fieldName, txt);
                    continue;
                }
                if (pidNo == 3) {
                    List<?> comps = field.elements(HL7XMLLiterate.TAG_COMPONENT);
                    if (comps.size() < 3) {
                        throw new IllegalArgumentException("Missing Authority in PID-3");
                    }
                    Element authority = (Element) comps.get(2);
                    List<?> authorityUID = authority.elements(HL7XMLLiterate.TAG_SUBCOMPONENT);
                    pid.put("PatientID", field.getText());
                    StringBuffer issuer = new StringBuffer(authority.getText());
                    for (int i = 0; i < authorityUID.size(); i++) {
                        issuer.append("&").append(((Element) authorityUID.get(i)).getText());
                    }
                    pid.put("IssuerOfPatientID", issuer.toString());
                    continue;
                }
                if (pidNo == 5) {
                    String name = field.getText() + "^" + field.elementText(HL7XMLLiterate.TAG_COMPONENT);
                    pid.put(fieldName, name);
                    continue;
                }
                pid.put(fieldName, field.asXML());
            }
            ret.add(pid);
        }
    }
    return ret;
}

From source file:org.jbpm.graph.action.Script.java

License:Open Source License

public void read(Element scriptElement, JpdlXmlReader jpdlReader) {
    if (scriptElement.isTextOnly()) {
        expression = scriptElement.getText();
    } else {/*from ww w  .j ava  2 s  . com*/
        this.variableAccesses = new HashSet(jpdlReader.readVariableAccesses(scriptElement));
        expression = scriptElement.element("expression").getText();
    }
}

From source file:org.jbpm.instantiation.FieldInstantiator.java

License:Open Source License

public static Object getValue(Class type, Element propertyElement) {
    // parse the value
    Object value = null;/*w  w  w . j av  a  2  s. com*/
    try {

        if (type == String.class) {
            value = propertyElement.getText();
        } else if ((type == Integer.class) || (type == int.class)) {
            value = new Integer(propertyElement.getTextTrim());
        } else if ((type == Long.class) || (type == long.class)) {
            value = new Long(propertyElement.getTextTrim());
        } else if ((type == Float.class) || (type == float.class)) {
            value = new Float(propertyElement.getTextTrim());
        } else if ((type == Double.class) || (type == double.class)) {
            value = new Double(propertyElement.getTextTrim());
        } else if ((type == Boolean.class) || (type == boolean.class)) {
            value = Boolean.valueOf(propertyElement.getTextTrim());
        } else if ((type == Character.class) || (type == char.class)) {
            value = new Character(propertyElement.getTextTrim().charAt(0));
        } else if ((type == Short.class) || (type == short.class)) {
            value = new Short(propertyElement.getTextTrim());
        } else if ((type == Byte.class) || (type == byte.class)) {
            value = new Byte(propertyElement.getTextTrim());
        } else if (List.class.isAssignableFrom(type)) {
            value = getCollection(propertyElement, new ArrayList());
        } else if (Set.class.isAssignableFrom(type)) {
            value = getCollection(propertyElement, new HashSet());
        } else if (Collection.class.isAssignableFrom(type)) {
            value = getCollection(propertyElement, new ArrayList());
        } else if (Map.class.isAssignableFrom(type)) {
            value = getMap(propertyElement, new HashMap());
        } else if (Element.class.isAssignableFrom(type)) {
            value = propertyElement;
        } else {
            Constructor constructor = type.getConstructor(new Class[] { String.class });
            if ((propertyElement.isTextOnly()) && (constructor != null)) {
                value = constructor.newInstance(new Object[] { propertyElement.getTextTrim() });
            }
        }
    } catch (Exception e) {
        log.error("couldn't parse the bean property value '" + propertyElement.asXML() + "' to a '"
                + type.getName() + "'");
        throw new JbpmException(e);
    }
    return value;
}

From source file:org.jbpm.jpdl.internal.convert.action.Script.java

License:Open Source License

public void read(Element actionElement, Jpdl3Converter jpdlReader) {
    String expression = null;//from  w w  w.java2 s. c  o  m
    if (actionElement.isTextOnly()) {
        expression = actionElement.getText();
    } else {
        //TODO:Unsupported variable conversion
        //List<VariableAccess> vias = jpdlReader.readVariableAccesses(actionElement);
        expression = actionElement.element("expression").getText();
    }
    convertedElement.addAttribute("expr", expression);
    convertedElement.addAttribute("lang", "juel");
}

From source file:org.onosproject.yang.serializers.xml.DefaultXmlWalker.java

License:Apache License

@Override
public void walk(XmlListener listener, Element element, Element rootElement) {
    try {//from  w w  w.ja  v a 2  s. c  o  m

        listener.enterXmlElement(element, getElementType(element), rootElement);

        if (element.hasContent() && !element.isTextOnly()) {
            Iterator i = element.elementIterator();
            while (i.hasNext()) {
                Element childElement = (Element) i.next();
                walk(listener, childElement, rootElement);
            }
        }

        listener.exitXmlElement(element, getElementType(element), rootElement);
    } catch (Exception e) {
        throw new XmlSerializerException(e.getMessage());
    }
}