Example usage for org.dom4j Element elements

List of usage examples for org.dom4j Element elements

Introduction

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

Prototype

List<Element> elements();

Source Link

Document

Returns the elements contained in this element.

Usage

From source file:com.haulmont.cuba.gui.settings.SettingsImpl.java

License:Apache License

@Override
public Element get(final String componentId) {
    checkLoaded();//from  ww w .  j  ava  2s  . c  o  m
    Element componentsRoot = root.element("components");
    if (componentsRoot == null) {
        componentsRoot = root.addElement("components");
    }
    for (Element e : ((List<Element>) componentsRoot.elements())) {
        if (componentId.equals(e.attributeValue("name"))) {
            return e;
        }
    }
    Element e = componentsRoot.addElement("component");
    e.addAttribute("name", componentId);
    return e;
}

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

License:Apache License

protected void createSubComponents(Component.Container container, Element containerElement) {
    LayoutLoader loader = new LayoutLoader(context, factory, layoutLoaderConfig);
    loader.setLocale(getLocale());//w  w  w .  j  av  a 2s .  c  om
    loader.setMessagesPack(getMessagesPack());

    //noinspection unchecked
    for (Element subElement : (Collection<Element>) containerElement.elements()) {
        if (!isChildElementIgnored(subElement)) {
            ComponentLoader componentLoader = loader.createComponent(subElement);
            pendingLoadComponents.add(componentLoader);

            container.add(componentLoader.getResultComponent());
        }
    }
}

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

License:Apache License

protected void createSubComponents(GridLayout gridLayout, Element element, int row) {
    LayoutLoader loader = new LayoutLoader(context, factory, layoutLoaderConfig);
    loader.setLocale(getLocale());/*from w w  w . jav a2 s . c  o  m*/
    loader.setMessagesPack(getMessagesPack());

    int col = 0;

    //noinspection unchecked
    for (Element subElement : (Collection<Element>) element.elements()) {
        ComponentLoader componentLoader = loader.createComponent(subElement);
        pendingLoadComponents.add(componentLoader);

        Component subComponent = componentLoader.getResultComponent();

        String colspan = subElement.attributeValue("colspan");
        String rowspan = subElement.attributeValue("rowspan");

        if (col >= spanMatrix.length) {
            Map<String, Object> params = new HashMap<>();
            params.put("Grid ID", gridLayout.getId());
            String rowId = element.attributeValue("id");
            if (StringUtils.isNotEmpty(rowId)) {
                params.put("Row ID", rowId);
            } else {
                params.put("Row Index", row);
            }
            throw new GuiDevelopmentException("Grid column count is less than number of components in grid row",
                    context.getFullFrameId(), params);
        }
        while (spanMatrix[col][row]) {
            col++;
        }

        if (StringUtils.isEmpty(colspan) && StringUtils.isEmpty(rowspan)) {
            addSubComponent(gridLayout, subComponent, col, row, col, row);
        } else {
            int cspan = 1;
            int rspan = 1;

            if (StringUtils.isNotEmpty(colspan)) {
                cspan = Integer.parseInt(colspan);
                if (cspan < 1) {
                    throw new GuiDevelopmentException("GridLayout colspan can not be less than 1",
                            context.getFullFrameId(), "colspan", cspan);
                }
                if (cspan == 1) {
                    LoggerFactory.getLogger(GridLayoutLoader.class)
                            .warn("Do not use colspan=\"1\", it will have no effect");
                }
            }

            if (StringUtils.isNotEmpty(rowspan)) {
                rspan = Integer.parseInt(rowspan);
                if (rspan < 1) {
                    throw new GuiDevelopmentException("GridLayout rowspan can not be less than 1",
                            context.getFullFrameId(), "rowspan", rspan);
                }
                if (rspan == 1) {
                    LoggerFactory.getLogger(GridLayoutLoader.class)
                            .warn("Do not use rowspan=\"1\", it will have no effect");
                }
            }

            fillSpanMatrix(col, row, cspan, rspan);

            int endColumn = col + cspan - 1;
            int endRow = row + rspan - 1;

            addSubComponent(gridLayout, subComponent, col, row, endColumn, endRow);
        }

        col++;
    }
}

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

License:Apache License

private void process(Element resultElem, Element extElem) {
    // set text/*from www.  j ava2s  .  c o  m*/
    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.gui.xml.XmlInheritanceProcessor.java

License:Apache License

private void addNewElement(Element resultElem, Element element, Set<Element> justAdded) {
    String idx = element.attributeValue(new QName("index", extNs));
    Element newElement;//  ww w  .j a  v a2 s  . c om
    if (StringUtils.isBlank(idx)) {
        newElement = resultElem.addElement(element.getName());
    } else {
        newElement = DocumentHelper.createElement(element.getName());

        @SuppressWarnings("unchecked")
        List<Element> elements = resultElem.elements();
        int index = Integer.parseInt(idx);
        if (index < 0 || index > elements.size()) {
            String message = String.format(
                    "Incorrect extension XML for screen. Could not paste new element %s to position %s",
                    newElement.getName(), index);

            throw new DevelopmentException(message,
                    ParamsMap.of("element", newElement.getName(), "index", index));
        }
        elements.add(index, newElement);
    }
    justAdded.add(newElement);
    process(newElement, element);
}

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./*from   www  .j  a  v  a  2 s .  c om*/
 */
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.command.AbstractCommand.java

License:Open Source License

@Override
public void startAll(String args) throws Exception {
    Document document = DocumentHelper.parseText(args);
    Element root = document.getRootElement();
    List elements = root.elements();
    List<Map<String, String>> eachElement = XmlUtils.getEachElement(elements);
    for (Map<String, String> map : eachElement) {
        String eleName = map.get("eleName");
        String name = map.get("name");
        String ip = map.get("ip");
        String port = map.get("port");
        String nameSuffix = map.get("nameSuffix");
        String status = map.get("status");
        String needToFilter = map.get("needToFilter");
        String method = map.get("method");
        String methodType = map.get("methodType");
        Class<?> aClass = Class.forName(name);
        if (Boolean.valueOf(status) && eleName.equals("Soap")) {
            Command command = new SoapCommand(aClass, Boolean.valueOf(needToFilter), Integer.parseInt(port), ip,
                    nameSuffix);/*w w  w  .  j a va  2  s  .co m*/
            command.start();
        } else if (Boolean.valueOf(status) && eleName.equals("Rest")) {
            Command command = new RestCommand(aClass, Boolean.valueOf(needToFilter), Integer.parseInt(port), ip,
                    nameSuffix);
            command.start();
        } else if (Boolean.valueOf(status) && eleName.equals("Netty")) {
            Command command = new NettyCommand(aClass, Boolean.valueOf(needToFilter), Integer.parseInt(port),
                    method, methodType);
            command.start();
        }
    }
}

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

License:Open Source License

/**
 * @param elements/*from ww w .j  a  v a2s . co  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.gear.meta.AbstractService.java

License:Open Source License

protected Map<String, Object> getMessage(String message) throws DocumentException {
    Document document = DocumentHelper.parseText(message);
    Element rootElement = document.getRootElement();
    List elements = rootElement.elements();
    Map<String, Object> result = new HashMap<String, Object>();
    for (Iterator it = elements.iterator(); it.hasNext();) {
        Element subElement = (Element) it.next();
        if (subElement.isTextOnly()) {
            result.put(subElement.getName(), subElement.getTextTrim());
        } else {//from  w ww.  j  a v  a 2s. c o  m
            List<String> subList = new ArrayList<String>();
            List subEle = subElement.elements();
            for (Iterator iterator = subEle.iterator(); iterator.hasNext();) {
                Element itemElements = (Element) iterator.next();
                subList.add(itemElements.getTextTrim());
            }
            result.put(subElement.getName(), subList);
        }
    }
    return result;
}

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

License:Open Source License

/**
 * @param elements/*from   www .  ja  v a 2s .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 (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;
}