Example usage for org.dom4j Element getText

List of usage examples for org.dom4j Element getText

Introduction

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

Prototype

String getText();

Source Link

Document

Returns the text value of this element without recursing through child elements.

Usage

From source file:com.haulmont.cuba.gui.xml.layout.loaders.AbstractComponentLoader.java

License:Apache License

@SuppressWarnings("unchecked")
protected Field.Validator loadValidator(Element validatorElement) {
    final String className = validatorElement.attributeValue("class");
    final String scriptPath = validatorElement.attributeValue("script");
    final String script = validatorElement.getText();

    Field.Validator validator = null;

    if (StringUtils.isNotBlank(scriptPath) || StringUtils.isNotBlank(script)) {
        validator = new ScriptValidator(validatorElement, getMessagesPack());
    } else {//from w  ww  .j  a  v  a2s. c om
        Class aClass = scripting.loadClass(className);
        if (aClass == null)
            throw new GuiDevelopmentException("Class " + className + " is not found", context.getFullFrameId());
        if (!StringUtils.isBlank(getMessagesPack()))
            try {
                validator = (Field.Validator) ReflectionHelper.newInstance(aClass, validatorElement,
                        getMessagesPack());
            } catch (NoSuchMethodException e) {
                //
            }
        if (validator == null) {
            try {
                validator = (Field.Validator) ReflectionHelper.newInstance(aClass, validatorElement);
            } catch (NoSuchMethodException e) {
                try {
                    validator = (Field.Validator) ReflectionHelper.newInstance(aClass);
                } catch (NoSuchMethodException e1) {
                    //
                }
            }
        }
        if (validator == null) {
            throw new GuiDevelopmentException("Validator class " + aClass + " has no supported constructors",
                    context.getFullFrameId());
        }
    }
    return validator;
}

From source file:com.haulmont.cuba.gui.xml.layout.loaders.HtmlBoxLayoutLoader.java

License:Apache License

protected void loadTemplateContents(HtmlBoxLayout htmlBox, Element element) {
    Element templateContentsElement = element.element(TEMPLATE_CONTENTS_ELEMENT_NAME);
    if (templateContentsElement != null) {
        String templateContents = templateContentsElement.getText();
        if (StringUtils.isNotBlank(templateContents)) {
            htmlBox.setTemplateContents(templateContents);
        }/*www  .  j  a  v  a  2  s .c o m*/
    }
}

From source file:com.haulmont.cuba.gui.xml.XmlInheritanceProcessor.java

License:Apache License

private void process(Element resultElem, Element extElem) {
    // set text//from  w  w w. j  a va  2s.  com
    if (!StringUtils.isBlank(extElem.getText()))
        resultElem.setText(extElem.getText());

    // add all attributes from extension
    for (Attribute attribute : Dom4j.attributes(extElem)) {
        if (resultElem == document.getRootElement() && attribute.getName().equals("extends")) {
            // ignore "extends" in root element
            continue;
        }
        resultElem.addAttribute(attribute.getName(), attribute.getValue());
    }

    String idx = extElem.attributeValue(new QName("index", extNs));
    if (resultElem != document.getRootElement() && StringUtils.isNotBlank(idx)) {
        int index = Integer.parseInt(idx);

        Element parent = resultElem.getParent();
        if (index < 0 || index > parent.elements().size()) {
            String message = String.format(
                    "Incorrect extension XML for screen. Could not move existing element %s to position %s",
                    resultElem.getName(), index);

            throw new DevelopmentException(message,
                    ParamsMap.of("element", resultElem.getName(), "index", index));
        }

        parent.remove(resultElem);
        //noinspection unchecked
        parent.elements().add(index, resultElem);
    }

    // add and process elements
    Set<Element> justAdded = new HashSet<>();
    for (Element element : Dom4j.elements(extElem)) {
        // look for suitable locator
        ElementTargetLocator locator = null;
        for (ElementTargetLocator l : targetLocators) {
            if (l.suitableFor(element)) {
                locator = l;
                break;
            }
        }
        if (locator != null) {
            Element target = locator.locate(resultElem, element);
            // process target or a new element if target not found
            if (target != null) {
                process(target, element);
            } else {
                addNewElement(resultElem, element, justAdded);
            }
        } else {
            // if no suitable locator found, look for a single element with the same name
            List<Element> list = Dom4j.elements(resultElem, element.getName());
            if (list.size() == 1 && !justAdded.contains(list.get(0))) {
                process(list.get(0), element);
            } else {
                addNewElement(resultElem, element, justAdded);
            }
        }
    }
}

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

License:Apache License

@Override
public CommitRequest parseCommitRequest(String content) {
    try {/*from  www  .j  av  a2 s  .  c  o  m*/
        CommitRequest commitRequest = new CommitRequest();

        Document document = Dom4j.readDocument(content);
        Element rootElement = document.getRootElement();

        //commit instances
        Element commitInstancesEl = rootElement.element("commitInstances");
        if (commitInstancesEl != null) {
            //first find and register ids of all entities to be commited
            Set<String> commitIds = new HashSet<>();
            for (Object instance : commitInstancesEl.elements("instance")) {
                Element instanceEl = (Element) instance;
                String id = instanceEl.attributeValue("id");
                if (id.startsWith("NEW-"))
                    id = id.substring(id.indexOf('-') + 1);
                commitIds.add(id);
            }
            commitRequest.setCommitIds(commitIds);

            List commitInstanceElements = commitInstancesEl.elements("instance");
            List<Entity> commitInstances = new ArrayList<>();
            for (Object el : commitInstanceElements) {
                Element commitInstanceEl = (Element) el;
                String id = commitInstanceEl.attributeValue("id");
                InstanceRef ref = commitRequest.parseInstanceRefAndRegister(id);
                Entity instance = ref.getInstance();
                parseEntity(commitInstanceEl, instance, commitRequest);
                commitInstances.add(instance);
            }
            commitRequest.setCommitInstances(commitInstances);
        }

        //remove instances
        Element removeInstancesEl = rootElement.element("removeInstances");
        if (removeInstancesEl != null) {
            List removeInstanceElements = removeInstancesEl.elements("instance");
            List<Entity> removeInstances = new ArrayList<>();
            for (Object el : removeInstanceElements) {
                Element removeInstance = (Element) el;
                String id = removeInstance.attributeValue("id");
                InstanceRef ref = commitRequest.parseInstanceRefAndRegister(id);
                Entity instance = ref.getInstance();
                removeInstances.add(instance);
            }
            commitRequest.setRemoveInstances(removeInstances);
        }

        //soft deletion
        Element softDeletionEl = rootElement.element("softDeletion");
        if (softDeletionEl != null) {
            commitRequest.setSoftDeletion(Boolean.parseBoolean(softDeletionEl.getText()));
        }

        return commitRequest;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

License:Apache License

@Override
public ServiceRequest parseServiceRequest(String content) throws Exception {
    Document document = Dom4j.readDocument(content);
    Element rootElement = document.getRootElement();
    Element serviceEl = rootElement.element("service");
    if (serviceEl == null) {
        throw new IllegalArgumentException("Service name not specified in request");
    }// w ww.  jav a 2s .  c  o  m
    String serviceName = serviceEl.getTextTrim();
    Element methodEl = rootElement.element("method");
    if (methodEl == null) {
        throw new IllegalArgumentException("Method name not specified in request");
    }
    String methodName = methodEl.getTextTrim();
    String viewName = null;
    Element viewEl = rootElement.element("view");
    if (viewEl != null)
        viewName = viewEl.getTextTrim();

    ServiceRequest serviceRequest = new ServiceRequest(serviceName, methodName, this);

    Element paramsEl = rootElement.element("params");
    if (paramsEl != null) {
        int idx = 0;
        while (true) {
            String paramName = "param" + idx;
            Element paramEl = findParamByName(paramsEl, paramName);
            if (paramEl == null)
                break;
            serviceRequest.getParamValuesString().add(paramElementContentAsString(paramEl));

            Element paramTypeEl = findParamByName(paramsEl, paramName + "_type");
            if (paramTypeEl != null) {
                String type = paramTypeEl.getText();
                serviceRequest.getParamTypes().add(ClassUtils.forName(type, null));
            } else {
                if (!serviceRequest.getParamTypes().isEmpty()) {
                    //types should be defined for all parameters or for none of them
                    throw new RestServiceException("Parameter type for param" + idx + " is not defined");
                }
            }
            idx++;
        }
    }

    return serviceRequest;
}

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

License:Apache License

protected String paramElementContentAsString(Element paramEl) {
    Element nestedEl = paramEl.element("instance");
    if (nestedEl == null) {
        nestedEl = paramEl.element("instances");
    }//from   w  w w. ja  v a  2  s.c  o m

    if (nestedEl == null) {
        return paramEl.getText();
    } else {
        Document doc = DocumentHelper.createDocument(nestedEl.createCopy());
        return doc.asXML();
    }
}

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

License:Apache License

/**
 * Converts a content of XML element to an entity.
 *
 * @param instanceEl    element that contains entity description
 * @param entity        if this parameter is not null then its fields will be filled,
 *                      if it is null then new entity will be created.
 * @param commitRequest must not be null if method is called when parsing a {@code CommitRequest}.
 *                      Security permissions checks are performed based on existing/absence of this
 *                      parameter.// w ww  . j av a 2s.c o m
 */
protected Entity parseEntity(Element instanceEl, @Nullable Entity entity,
        @Nullable CommitRequest commitRequest) {
    try {
        if (entity == null) {
            String id = instanceEl.attributeValue("id");
            EntityLoadInfo loadInfo = EntityLoadInfo.parse(id);

            if (loadInfo == null)
                throw new IllegalArgumentException(
                        "XML description of entity doesn't contain valid 'id' attribute");

            entity = createEmptyInstance(loadInfo);
            entity.setValue("id", loadInfo.getId());
        }

        MetaClass metaClass = entity.getMetaClass();
        List propertyEls = instanceEl.elements();
        for (Object el : propertyEls) {
            Element propertyEl = (Element) el;

            if (entity instanceof BaseGenericIdEntity && "__securityToken".equals(propertyEl.getName())) {
                byte[] securityToken = Base64.getDecoder().decode(propertyEl.getText());
                SecurityState securityState = BaseEntityInternalAccess
                        .getOrCreateSecurityState((BaseGenericIdEntity) entity);
                BaseEntityInternalAccess.setSecurityToken(securityState, securityToken);
                continue;
            }

            String propertyName = propertyEl.attributeValue("name");

            MetaPropertyPath metaPropertyPath = metadata.getTools().resolveMetaPropertyPath(metaClass,
                    propertyName);
            Preconditions.checkNotNullArgument(metaPropertyPath, "Could not resolve property '%s' in '%s'",
                    propertyName, metaClass);
            MetaProperty property = metaPropertyPath.getMetaProperty();

            if (commitRequest != null && !attrModifyPermitted(metaClass, propertyName))
                continue;

            if (commitRequest != null && metadataTools.isNotPersistent(property)
                    && !DynamicAttributesUtils.isDynamicAttribute(propertyName))
                continue;

            if (Boolean.parseBoolean(propertyEl.attributeValue("null"))) {
                entity.setValue(propertyName, null);
                continue;
            }

            if (entity instanceof BaseGenericIdEntity && DynamicAttributesUtils.isDynamicAttribute(propertyName)
                    && ((BaseGenericIdEntity) entity).getDynamicAttributes() == null) {
                ConverterHelper.fetchDynamicAttributes(entity);
            }

            String stringValue = propertyEl.getText();
            Object value;
            switch (property.getType()) {
            case DATATYPE:
                value = property.getRange().asDatatype().parse(stringValue);
                entity.setValue(propertyName, value);
                break;
            case ENUM:
                value = property.getRange().asEnumeration().parse(stringValue);
                entity.setValue(propertyName, value);
                break;
            case COMPOSITION:
            case ASSOCIATION:
                MetaClass propertyMetaClass = propertyMetaClass(property);
                //checks if the user permitted to read and update a property
                if (commitRequest != null && !updatePermitted(propertyMetaClass)
                        && !readPermitted(propertyMetaClass))
                    break;

                if (!property.getRange().getCardinality().isMany()) {
                    Element refInstanceEl = propertyEl.element("instance");
                    if (metadataTools.isEmbedded(property)) {
                        MetaClass embeddedMetaClass = property.getRange().asClass();
                        Entity embeddedEntity = metadata.create(embeddedMetaClass);
                        value = parseEntity(refInstanceEl, embeddedEntity, commitRequest);
                    } else {
                        String id = refInstanceEl.attributeValue("id");

                        //reference to an entity that also a commit instance
                        //will be registered later
                        if (commitRequest != null && commitRequest.getCommitIds().contains(id)) {
                            EntityLoadInfo loadInfo = EntityLoadInfo.parse(id);
                            Entity ref = metadata.create(loadInfo.getMetaClass());
                            ref.setValue("id", loadInfo.getId());
                            entity.setValue(propertyName, ref);
                            break;
                        }

                        value = parseEntity(refInstanceEl, null, commitRequest);
                    }
                    entity.setValue(propertyName, value);

                } else {
                    Class<?> propertyJavaType = property.getJavaType();
                    Collection<Object> coll;
                    if (List.class.isAssignableFrom(propertyJavaType))
                        coll = new ArrayList<>();
                    else if (Set.class.isAssignableFrom(propertyJavaType))
                        coll = new HashSet<>();
                    else
                        throw new RuntimeException("Datatype " + propertyJavaType.getName() + " of "
                                + metaClass.getName() + "#" + property.getName() + " is not supported");
                    entity.setValue(propertyName, coll);

                    for (Object childInstenceEl : propertyEl.elements("instance")) {
                        Entity childEntity = parseEntity((Element) childInstenceEl, null, commitRequest);
                        coll.add(childEntity);
                    }
                }
                break;
            default:
                throw new IllegalStateException("Unknown property type");
            }
        }

        return entity;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.heren.turtle.entry.util.XmlUtils.java

License:Open Source License

/**
 * @param elements/*from   ww  w . ja va2  s .c  o m*/
 * @return
 * @throws DocumentException
 */
public static List<Map<String, String>> getEachElement(List elements) throws DocumentException {
    List<Map<String, String>> resultList = new ArrayList<>();
    if (elements.size() > 0) {
        for (Iterator it = elements.iterator(); it.hasNext();) {
            Map<String, String> resultMap = new HashMap<>();
            Element subElement = (Element) it.next();
            resultMap.put("eleName", subElement.getName());
            List subElements = subElement.elements();
            for (Iterator subIt = subElements.iterator(); subIt.hasNext();) {
                Element son = (Element) subIt.next();
                String name = son.getName();
                String text = son.getText();
                resultMap.put(name, text);
            }
            resultList.add(resultMap);
        }
    } else {
        throw new DocumentException("this element is disappeared");
    }
    return resultList;
}

From source file:com.heren.turtle.server.utils.XmlUtils.java

License:Open Source License

/**
 * @param elements/*from   w ww  . j  a v a 2 s.c  om*/
 * @return
 * @throws DocumentException
 */
public static List<Map<String, String>> getEachElement(List elements) throws DocumentException {
    List<Map<String, String>> resultList = new ArrayList<>();
    if (elements.size() > 0) {
        for (Object element : elements) {
            Map<String, String> resultMap = new HashMap<>();
            Element subElement = (Element) element;
            resultMap.put("eleName", subElement.getName());
            List subElements = subElement.elements();
            for (Object subElement1 : subElements) {
                Element son = (Element) subElement1;
                String name = son.getName();
                String text = son.getText();
                resultMap.put(name, text);
            }
            resultList.add(resultMap);
        }
    } else {
        throw new DocumentException("this element is disappeared");
    }
    return resultList;
}

From source file:com.hihframework.osplugins.dom4j.XmlParseUtil.java

License:Apache License

/**
 * ??/*  w  ww .j ava 2 s. co  m*/
 *
 * @param element
 *            
 * @return 
 */
public String getElementText(Element element) {
    String elementText = element.getText();
    return elementText;
}