Example usage for org.dom4j DocumentHelper createElement

List of usage examples for org.dom4j DocumentHelper createElement

Introduction

In this page you can find the example usage for org.dom4j DocumentHelper createElement.

Prototype

public static Element createElement(String name) 

Source Link

Usage

From source file:com.easyjf.web.config.BeanConfigReader.java

License:Apache License

public static Collection parseCollectionValue(Element e) {
    java.util.Collection values = null;
    Element node = XmlElementUtil.findElement("list", e);
    if (node != null) {
        List ps = XmlElementUtil.findElements("value", node);
        if (ps != null && ps.size() > 0) {
            values = new ArrayList();
            for (int i = 0; i < ps.size(); i++) {
                Element parent = DocumentHelper.createElement("property");
                parent.add((Element) ((org.dom4j.Node) ps.get(i)).clone());
                values.add(parsePropertyValue(parent));
            }//from  w w  w  .  j  a  va  2 s .  co  m
        } else {

        }
    }
    return values;
}

From source file:com.flaptor.hounder.indexer.HtmlParser.java

License:Apache License

/**
 * Parses a tag to produce a field./*from w w  w  . j  a  va  2 s. c o  m*/
 * @param doc the doc to modify
 * @throw exception on error, signaling the main method to return no document.
 */
private void processTag(Document doc, final String tagName, final String fieldName) throws Exception {
    Node bodyElement = doc.selectSingleNode("/*/" + tagName);
    if (null == bodyElement) {
        logger.warn("Content element missing from document. I was expecting a '" + tagName + "'. Will not add '"
                + fieldName + "' field.");
        return;
    }

    Node destElement = doc.selectSingleNode("//field[@name='" + fieldName + "']");
    if (null != destElement) {
        logger.warn("Parsed element '" + fieldName + "' already present in document. Will not overwrite.");
        return;
    }

    ParseOutput out = parser.parse("", bodyElement.getText().getBytes("UTF-8"), "UTF-8");

    for (String field : extraFields) {
        String content = out.getField(field);
        if (null == content) {
            logger.debug("had document without " + field + " field. Continuing with other fields.");
            continue;
        }
        Element docField = DocumentHelper.createElement("field");
        docField.addText(content);
        docField.addAttribute("name", field);
        docField.addAttribute("indexed", Boolean.toString(INDEXED));
        docField.addAttribute("stored", Boolean.toString(STORED));
        docField.addAttribute("tokenized", "true");
        bodyElement.getParent().add(docField);
    }

    String text = out.getText();
    Element field = DocumentHelper.createElement("field");
    field.addText(text);
    field.addAttribute("name", fieldName);
    field.addAttribute("indexed", Boolean.toString(INDEXED));
    field.addAttribute("stored", Boolean.toString(STORED));
    field.addAttribute("tokenized", "true");
    bodyElement.getParent().add(field);
}

From source file:com.globalsight.cxe.adapter.msoffice.WordRepairer.java

License:Apache License

private static void forTextInWp(Element element) {
    @SuppressWarnings("unchecked")
    List<Node> ts = element.selectNodes("//w:p/text()");

    for (Node t : ts) {
        String c = t.getText();// w w  w.j a va  2 s .com
        if (c.matches("[\n\r]*")) {
            continue;
        }

        Element wp = t.getParent();
        Element wr = DocumentHelper.createElement("w:r");
        wp.content().add(wp.indexOf(t), wr);
        Element wt = wr.addElement("w:t");
        wt.setText(t.getText());
        wp.remove(t);
    }
}

From source file:com.hand.hemp.push.server.xmpp.handler.IQAuthHandler.java

License:Open Source License

/**
 * Constructor./*  w w w.  j a va 2  s  .  c om*/
 */
public IQAuthHandler() {
    clientService = ServiceLocator.getClientService();
    probeResponse = DocumentHelper.createElement(QName.get("query", NAMESPACE));
    probeResponse.addElement("username");
    if (AuthManager.isPlainSupported()) {
        probeResponse.addElement("password");
    }
    if (AuthManager.isDigestSupported()) {
        probeResponse.addElement("digest");
    }
    probeResponse.addElement("resource");
}

From source file:com.hand.hemp.push.server.xmpp.handler.IQRegisterHandler.java

License:Open Source License

/**
 * Constructor.//from   w ww. ja  v  a2 s. co  m
 */
public IQRegisterHandler() {
    clientService = ServiceLocator.getClientService();
    probeResponse = DocumentHelper.createElement(QName.get("query", NAMESPACE));
    probeResponse.addElement("username");
    probeResponse.addElement("password");
    probeResponse.addElement("email");
    probeResponse.addElement("name");
}

From source file:com.hand.hemp.push.server.xmpp.push.NotificationManager.java

License:Open Source License

/**
 * Creates a new notification IQ and returns it.
 *
 * @param apiKey/*  w  ww .jav  a 2  s .  c o m*/
 * @param title
 * @param message
 * @param uri
 * @return
 */
private IQ createNotificationIQ(String apiKey, String title, String message, String uri) {
    Random random = new Random();
    String id = Integer.toHexString(random.nextInt());
    // String id = String.valueOf(System.currentTimeMillis());

    Element notification = DocumentHelper.createElement(QName.get("notification", NOTIFICATION_NAMESPACE));
    notification.addElement("id").setText(id);
    notification.addElement("apiKey").setText(apiKey);
    if (title == null) {
        title = " ";
    }
    notification.addElement("title").setText(title);
    notification.addElement("message").setText(message);

    if (uri == null) {
        uri = " ";
    }
    notification.addElement("uri").setText(uri);

    IQ iq = new IQ();
    iq.setType(IQ.Type.set);
    iq.setChildElement(notification);

    return iq;
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopAbstractTable.java

License:Apache License

@Override
public void setDatasource(final CollectionDatasource datasource) {
    Preconditions.checkNotNullArgument(datasource, "datasource is null");

    final Collection<Object> properties;
    if (this.columns.isEmpty()) {
        MetadataTools metadataTools = AppBeans.get(MetadataTools.NAME);
        MessageTools messageTools = AppBeans.get(MessageTools.NAME);

        Collection<MetaPropertyPath> paths = datasource.getView() != null ?
        // if a view is specified - use view properties
                metadataTools.getViewPropertyPaths(datasource.getView(), datasource.getMetaClass()) :
                // otherwise use only string properties from meta-class - the temporary solution for KeyValue datasources
                metadataTools.getPropertyPaths(datasource.getMetaClass()).stream()
                        .filter(mpp -> mpp.getRangeJavaClass().equals(String.class))
                        .collect(Collectors.toList());

        for (MetaPropertyPath metaPropertyPath : paths) {
            MetaProperty property = metaPropertyPath.getMetaProperty();
            if (!property.getRange().getCardinality().isMany() && !metadataTools.isSystem(property)) {
                Table.Column column = new Table.Column(metaPropertyPath);

                String propertyName = property.getName();
                MetaClass propertyMetaClass = metadataTools.getPropertyEnclosingMetaClass(metaPropertyPath);

                column.setCaption(messageTools.getPropertyCaption(propertyMetaClass, propertyName));
                column.setType(metaPropertyPath.getRangeJavaClass());

                Element element = DocumentHelper.createElement("column");
                column.setXmlDescriptor(element);

                addColumn(column);//from  w  w w . j  av  a2 s  .  c o m
            }
        }
    }
    properties = this.columns.keySet();

    this.datasource = datasource;

    collectionChangeListener = e -> {
        switch (e.getOperation()) {
        case CLEAR:
        case REFRESH:
            fieldDatasources.clear();
            break;

        case UPDATE:
        case REMOVE:
            for (Object entity : e.getItems()) {
                fieldDatasources.remove(entity);
            }
            break;
        }
    };
    //noinspection unchecked
    datasource.addCollectionChangeListener(
            new WeakCollectionChangeListener(datasource, collectionChangeListener));

    initTableModel(datasource);

    initChangeListener();

    setColumnIdentifiers();

    // Major change in table columns behavior #PL-4853
    // We need not to recreate all columns on each table change after initTableModel
    //        impl.setAutoCreateColumnsFromModel(false);

    if (isSortable()) {
        impl.setRowSorter(new RowSorterImpl(tableModel));
    }

    initSelectionListener(datasource);

    List<MetaPropertyPath> editableColumns = null;
    if (isEditable()) {
        editableColumns = new LinkedList<>();
    }

    MetaClass metaClass = datasource.getMetaClass();
    for (final Object property : properties) {
        final Table.Column column = this.columns.get(property);

        //            todo implement setColumnHeader
        //            final String caption;
        //            if (column != null) {
        //                caption = StringUtils.capitalize(column.getCaption() != null ? column.getCaption() : getColumnCaption(property));
        //            } else {
        //                caption = StringUtils.capitalize(getColumnCaption(property));
        //            }
        //
        //            setColumnHeader(property, caption);

        if (column != null) {
            if (column.isCollapsed() && getColumnControlVisible()) {
                TableColumn tableColumn = getColumn(column);
                if (tableColumn instanceof TableColumnExt) {
                    ((TableColumnExt) tableColumn).setVisible(false);
                }
            }

            if (editableColumns != null && column.isEditable() && (property instanceof MetaPropertyPath)) {
                MetaPropertyPath propertyPath = (MetaPropertyPath) property;
                if (security.isEntityAttrUpdatePermitted(metaClass, property.toString())) {
                    editableColumns.add(propertyPath);
                }
            }
        }
    }

    if (editableColumns != null && !editableColumns.isEmpty()) {
        setEditableColumns(editableColumns);
    }

    List<Object> columnsOrder = new ArrayList<>();
    for (Table.Column column : this.columnsOrder) {
        if (column.getId() instanceof MetaPropertyPath) {
            MetaPropertyPath metaPropertyPath = (MetaPropertyPath) column.getId();
            if (security.isEntityAttrReadPermitted(metaClass, metaPropertyPath.toString())) {
                columnsOrder.add(column.getId());
            }
        } else {
            columnsOrder.add(column.getId());
        }
    }

    setVisibleColumns(columnsOrder);

    if (security.isSpecificPermitted(ShowInfoAction.ACTION_PERMISSION)) {
        ShowInfoAction action = (ShowInfoAction) getAction(ShowInfoAction.ACTION_ID);
        if (action == null) {
            action = new ShowInfoAction();
            addAction(action);
        }
        action.setDatasource(datasource);
    }

    securityCollectionChangeListener = e -> {
        onDataChange();
        packRows();

        // #PL-2035, reload selection from ds
        Set<E> selectedItems1 = getSelected();
        if (selectedItems1 == null) {
            selectedItems1 = Collections.emptySet();
        }

        Set<E> newSelection = new HashSet<>();
        for (E entity : selectedItems1) {
            if (e.getDs().containsItem(entity.getId())) {
                newSelection.add(entity);
            }
        }

        if (e.getDs().getState() == Datasource.State.VALID && e.getDs().getItem() != null) {
            if (e.getDs().containsItem(e.getDs().getItem().getId())) {
                newSelection.add((E) e.getDs().getItem());
            }
        }

        if (newSelection.isEmpty()) {
            setSelected((E) null);
        } else {
            setSelected(newSelection);
        }
    };
    // noinspection unchecked
    datasource.addCollectionChangeListener(
            new WeakCollectionChangeListener(datasource, securityCollectionChangeListener));

    itemPropertyChangeListener = e -> {
        List<Column> columns1 = getColumns();
        boolean find = false;
        int i = 0;
        while ((i < columns1.size()) & !find) {
            Object columnId = columns1.get(i).getId();
            if (columnId instanceof MetaPropertyPath) {
                String propertyName = ((MetaPropertyPath) columnId).getMetaProperty().getName();
                if (propertyName.equals(e.getProperty())) {
                    find = true;
                }
            }
            i++;
        }
        if (find) {
            onDataChange();
        }
        packRows();
    };
    // noinspection unchecked
    datasource.addItemPropertyChangeListener(
            new WeakItemPropertyChangeListener(datasource, itemPropertyChangeListener));

    if (rowsCount != null) {
        rowsCount.setDatasource(datasource);
    }

    collectionDsActionsNotifier = new CollectionDsActionsNotifier(this);
    collectionDsActionsNotifier.bind(datasource);

    for (Action action : getActions()) {
        action.refreshState();
    }

    if (!canBeSorted(datasource))
        setSortable(false);
}

From source file:com.haulmont.cuba.gui.app.core.entityinspector.EntityInspectorEditor.java

License:Apache License

/**
 * Adds field to the specified field group.
 * If the field should be custom, adds it to the specified customFields collection
 * which can be used later to create fieldGenerators
 *
 * @param metaProperty meta property of the item's property which field is creating
 * @param item         entity instance containing given property
 * @param fieldGroup   field group to which created field will be added
 * @param customFields if the field is custom it will be added to this collection
 * @param required     true if the field is required
 * @param custom       true if the field is custom
 *///w  w w.  ja  v a 2  s  .  co  m
protected void addField(MetaClass metaClass, MetaProperty metaProperty, Entity item, FieldGroup fieldGroup,
        boolean required, boolean custom, boolean readOnly, Collection<FieldGroup.FieldConfig> customFields) {
    if (!attrViewPermitted(metaClass, metaProperty))
        return;

    if ((metaProperty.getType() == MetaProperty.Type.COMPOSITION
            || metaProperty.getType() == MetaProperty.Type.ASSOCIATION)
            && !entityOpPermitted(metaProperty.getRange().asClass(), EntityOp.READ))
        return;

    FieldGroup.FieldConfig field = fieldGroup.createField(metaProperty.getName());
    field.setProperty(metaProperty.getName());
    field.setCaption(getPropertyCaption(metaClass, metaProperty));
    field.setCustom(custom);
    field.setRequired(required);
    field.setEditable(!readOnly);
    field.setWidth("100%");

    if (requireTextArea(metaProperty, item)) {
        Element root = DocumentHelper.createElement("textArea");
        root.addAttribute("rows", "3");
        field.setXmlDescriptor(root);
    }

    if (focusFieldId == null && !readOnly) {
        focusFieldId = field.getId();
        focusFieldGroup = fieldGroup;
    }

    if (required) {
        field.setRequiredMessage(messageTools.getDefaultRequiredMessage(metaClass, metaProperty.getName()));
    }
    fieldGroup.addField(field);
    if (custom)
        customFields.add(field);
}

From source file:com.haulmont.cuba.gui.components.filter.UserSetHelper.java

License:Apache License

public static String generateSetFilter(Set ids, String entityClass, String componentId, String entityAlias) {
    Document document = DocumentHelper.createDocument();
    Element root = DocumentHelper.createElement("filter");
    Element or = root.addElement("and");

    Element condition = or.addElement("c");
    condition.addAttribute("name", "set");
    condition.addAttribute("inExpr", "true");
    condition.addAttribute("hidden", "true");
    condition.addAttribute("locCaption", "Set filter");
    condition.addAttribute("entityAlias", entityAlias);
    condition.addAttribute("class", entityClass);
    condition.addAttribute("type", ConditionType.CUSTOM.name());

    String listOfId = createIdsString(ids);
    String randomName = RandomStringUtils.randomAlphabetic(10);
    condition.addText(entityAlias + ".id in :component$" + componentId + "." + randomName);

    Element param = condition.addElement("param");
    param.addAttribute("name", "component$" + componentId + "." + randomName);
    param.addText(listOfId);/*from w w w .j  av a 2 s .  c  o m*/

    document.add(root);
    return Dom4j.writeDocument(document, true);
}

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;/* w ww .  j  a  v a 2  s . c  o  m*/
    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);
}