Search in sources :

Example 1 with DsContext

use of com.haulmont.cuba.gui.data.DsContext in project cuba by cuba-platform.

the class WindowManager method loadDsContext.

protected DsContext loadDsContext(Element element) {
    DataSupplier dataSupplier;
    String dataSupplierClass = element.attributeValue("dataSupplier");
    if (StringUtils.isEmpty(dataSupplierClass)) {
        dataSupplier = defaultDataSupplier;
    } else {
        Class<Object> aClass = ReflectionHelper.getClass(dataSupplierClass);
        try {
            dataSupplier = (DataSupplier) aClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("Unable to create data supplier for screen", e);
        }
    }
    // noinspection UnnecessaryLocalVariable
    DsContext dsContext = new DsContextLoader(dataSupplier).loadDatasources(element.element("dsContext"), null);
    return dsContext;
}
Also used : DsContextLoader(com.haulmont.cuba.gui.xml.data.DsContextLoader) DsContext(com.haulmont.cuba.gui.data.DsContext) GenericDataSupplier(com.haulmont.cuba.gui.data.impl.GenericDataSupplier) DataSupplier(com.haulmont.cuba.gui.data.DataSupplier)

Example 2 with DsContext

use of com.haulmont.cuba.gui.data.DsContext in project cuba by cuba-platform.

the class WindowDelegate method getDatasource.

public Datasource getDatasource() {
    Datasource ds = null;
    Element element = ((Component.HasXmlDescriptor) window).getXmlDescriptor();
    String datasourceName = element.attributeValue("datasource");
    if (!StringUtils.isEmpty(datasourceName)) {
        DsContext context = window.getDsContext();
        if (context != null) {
            ds = context.get(datasourceName);
        }
    }
    if (ds == null) {
        throw new GuiDevelopmentException("Can't find main datasource", window.getId());
    }
    return ds;
}
Also used : Datasource(com.haulmont.cuba.gui.data.Datasource) DsContext(com.haulmont.cuba.gui.data.DsContext) Element(org.dom4j.Element) GuiDevelopmentException(com.haulmont.cuba.gui.GuiDevelopmentException)

Example 3 with DsContext

use of com.haulmont.cuba.gui.data.DsContext in project cuba by cuba-platform.

the class EntityRestore method buildLayout.

protected void buildLayout() {
    Object value = entities.getValue();
    if (value != null) {
        MetaClass metaClass = (MetaClass) value;
        MetaProperty deleteTsMetaProperty = metaClass.getProperty("deleteTs");
        if (deleteTsMetaProperty != null) {
            if (entitiesTable != null) {
                tablePanel.remove(entitiesTable);
            }
            if (filter != null) {
                tablePanel.remove(filter);
            }
            entitiesTable = uiComponents.create(Table.NAME);
            entitiesTable.setFrame(frame);
            restoreButton = uiComponents.create(Button.class);
            restoreButton.setId("restore");
            restoreButton.setCaption(getMessage("entityRestore.restore"));
            ButtonsPanel buttonsPanel = uiComponents.create(ButtonsPanel.class);
            buttonsPanel.add(restoreButton);
            entitiesTable.setButtonsPanel(buttonsPanel);
            RowsCount rowsCount = uiComponents.create(RowsCount.class);
            entitiesTable.setRowsCount(rowsCount);
            SimpleDateFormat dateTimeFormat = new SimpleDateFormat(getMessage("dateTimeFormat"));
            Function<Object, String> dateTimeFormatter = propertyValue -> {
                if (propertyValue == null) {
                    return StringUtils.EMPTY;
                }
                return dateTimeFormat.format(propertyValue);
            };
            // collect properties in order to add non-system columns first
            LinkedList<Table.Column<Entity>> nonSystemPropertyColumns = new LinkedList<>();
            LinkedList<Table.Column<Entity>> systemPropertyColumns = new LinkedList<>();
            List<MetaProperty> metaProperties = new ArrayList<>();
            for (MetaProperty metaProperty : metaClass.getProperties()) {
                // don't show embedded, transient & multiple referred entities
                Range range = metaProperty.getRange();
                if (isEmbedded(metaProperty) || metadataTools.isNotPersistent(metaProperty) || range.getCardinality().isMany() || metadataTools.isSystemLevel(metaProperty) || (range.isClass() && metadataTools.isSystemLevel(range.asClass()))) {
                    continue;
                }
                metaProperties.add(metaProperty);
                Table.Column<Entity> column = new Table.Column<>(metaClass.getPropertyPath(metaProperty.getName()));
                if (!metadataTools.isSystem(metaProperty)) {
                    column.setCaption(getPropertyCaption(metaClass, metaProperty));
                    nonSystemPropertyColumns.add(column);
                } else {
                    column.setCaption(metaProperty.getName());
                    column.setDescription(getSystemAttributeDescription(metaClass, metaProperty));
                    systemPropertyColumns.add(column);
                }
                if (range.isDatatype() && range.asDatatype().getJavaClass().equals(Date.class)) {
                    column.setFormatter(dateTimeFormatter);
                }
            }
            for (Table.Column<Entity> column : nonSystemPropertyColumns) {
                entitiesTable.addColumn(column);
            }
            for (Table.Column<Entity> column : systemPropertyColumns) {
                entitiesTable.addColumn(column);
            }
            DsContext dsContext = getDsContext();
            if (entitiesDs != null) {
                ((DsContextImplementation) dsContext).unregister(entitiesDs);
            }
            entitiesDs = DsBuilder.create(dsContext).setId("entitiesDs").setMetaClass(metaClass).setView(buildView(metaClass, metaProperties)).buildGroupDatasource();
            entitiesDs.setQuery("select e from " + metaClass.getName() + " e " + "where e.deleteTs is not null order by e.deleteTs");
            entitiesDs.setSoftDeletion(false);
            entitiesDs.refresh();
            entitiesTable.setDatasource(entitiesDs);
            String filterId = metaClass.getName().replace("$", "") + "GenericFilter";
            filter = uiComponents.create(Filter.class);
            filter.setId(filterId);
            filter.setFrame(getFrame());
            StringBuilder sb = new StringBuilder();
            for (MetaProperty property : metaClass.getProperties()) {
                AnnotatedElement annotatedElement = property.getAnnotatedElement();
                if (annotatedElement.getAnnotation(com.haulmont.chile.core.annotations.MetaProperty.class) != null) {
                    sb.append(property.getName()).append("|");
                }
            }
            Element filterElement = dom4JTools.readDocument(String.format("<filter id=\"%s\">\n" + "    <properties include=\".*\" exclude=\"\"/>\n" + "</filter>", filterId)).getRootElement();
            String excludedProperties = sb.toString();
            if (StringUtils.isNotEmpty(excludedProperties)) {
                Element properties = filterElement.element("properties");
                properties.attribute("exclude").setValue(excludedProperties.substring(0, excludedProperties.lastIndexOf("|")));
            }
            ((HasXmlDescriptor) filter).setXmlDescriptor(filterElement);
            filter.setUseMaxResults(true);
            filter.setDatasource(entitiesDs);
            entitiesTable.setSizeFull();
            entitiesTable.setMultiSelect(true);
            Action restoreAction = new ItemTrackingAction("restore").withCaption(getMessage("entityRestore.restore")).withPrimary(true).withHandler(event -> showRestoreDialog());
            entitiesTable.addAction(restoreAction);
            restoreButton.setAction(restoreAction);
            tablePanel.add(filter);
            tablePanel.add(entitiesTable);
            tablePanel.expand(entitiesTable, "100%", "100%");
            entitiesTable.refresh();
            ((FilterImplementation) filter).loadFiltersAndApplyDefault();
        }
    }
}
Also used : SoftDelete(com.haulmont.cuba.core.entity.SoftDelete) java.util(java.util) Dom4jTools(com.haulmont.cuba.core.sys.xmlparsing.Dom4jTools) DsBuilder(com.haulmont.cuba.gui.data.DsBuilder) EntityRestoreService(com.haulmont.cuba.core.app.EntityRestoreService) SimpleDateFormat(java.text.SimpleDateFormat) EnableRestore(com.haulmont.cuba.core.entity.annotation.EnableRestore) StringUtils(org.apache.commons.lang3.StringUtils) Function(java.util.function.Function) MetaClass(com.haulmont.chile.core.model.MetaClass) com.haulmont.cuba.core.global(com.haulmont.cuba.core.global) Inject(javax.inject.Inject) DsContextImplementation(com.haulmont.cuba.gui.data.impl.DsContextImplementation) GroupDatasource(com.haulmont.cuba.gui.data.GroupDatasource) com.haulmont.cuba.gui.components(com.haulmont.cuba.gui.components) ItemTrackingAction(com.haulmont.cuba.gui.components.actions.ItemTrackingAction) DsContext(com.haulmont.cuba.gui.data.DsContext) Range(com.haulmont.chile.core.model.Range) MetaProperty(com.haulmont.chile.core.model.MetaProperty) Status(com.haulmont.cuba.gui.components.Action.Status) Type(com.haulmont.cuba.gui.components.DialogAction.Type) Element(org.dom4j.Element) UiComponents(com.haulmont.cuba.gui.UiComponents) Entity(com.haulmont.cuba.core.entity.Entity) AnnotatedElement(java.lang.reflect.AnnotatedElement) Entity(com.haulmont.cuba.core.entity.Entity) ItemTrackingAction(com.haulmont.cuba.gui.components.actions.ItemTrackingAction) DsContext(com.haulmont.cuba.gui.data.DsContext) ItemTrackingAction(com.haulmont.cuba.gui.components.actions.ItemTrackingAction) Element(org.dom4j.Element) AnnotatedElement(java.lang.reflect.AnnotatedElement) AnnotatedElement(java.lang.reflect.AnnotatedElement) MetaProperty(com.haulmont.chile.core.model.MetaProperty) DsContextImplementation(com.haulmont.cuba.gui.data.impl.DsContextImplementation) Range(com.haulmont.chile.core.model.Range) MetaClass(com.haulmont.chile.core.model.MetaClass) SimpleDateFormat(java.text.SimpleDateFormat)

Example 4 with DsContext

use of com.haulmont.cuba.gui.data.DsContext in project cuba by cuba-platform.

the class WebTabSheet method initComponentTabChangeListener.

private void initComponentTabChangeListener() {
    // after all lazy tabs listeners
    if (!componentTabChangeListenerInitialized) {
        component.addSelectedTabChangeListener(event -> {
            if (context instanceof ComponentLoader.ComponentContext) {
                ((ComponentLoader.ComponentContext) context).executeInjectTasks();
                ((ComponentLoader.ComponentContext) context).executeInitTasks();
            }
            // Fire GUI listener
            fireTabChanged(new SelectedTabChangeEvent(WebTabSheet.this, getSelectedTab(), event.isUserOriginated()));
            // We suppose that context.executePostInitTasks() executes a task once and then remove it from task list.
            if (context instanceof ComponentLoader.ComponentContext) {
                ((ComponentLoader.ComponentContext) context).executePostInitTasks();
            }
            Window window = ComponentsHelper.getWindow(WebTabSheet.this);
            if (window != null) {
                if (window.getFrameOwner() instanceof LegacyFrame) {
                    DsContext dsContext = ((LegacyFrame) window.getFrameOwner()).getDsContext();
                    if (dsContext != null) {
                        ((DsContextImplementation) dsContext).resumeSuspended();
                    }
                }
            } else {
                LoggerFactory.getLogger(WebTabSheet.class).warn("Please specify Frame for TabSheet");
            }
        });
        componentTabChangeListenerInitialized = true;
    }
}
Also used : DsContextImplementation(com.haulmont.cuba.gui.data.impl.DsContextImplementation) DsContext(com.haulmont.cuba.gui.data.DsContext) LegacyFrame(com.haulmont.cuba.gui.screen.compatibility.LegacyFrame)

Example 5 with DsContext

use of com.haulmont.cuba.gui.data.DsContext in project cuba by cuba-platform.

the class FieldGroupLoader method loadField.

protected FieldGroup.FieldConfig loadField(Element element, Datasource ds, String columnWidth) {
    String id = element.attributeValue("id");
    String property = element.attributeValue("property");
    if (Strings.isNullOrEmpty(id) && Strings.isNullOrEmpty(property)) {
        throw new GuiDevelopmentException(String.format("id/property is not defined for field of FieldGroup '%s'. " + "Set id or property attribute.", resultComponent.getId()), context);
    }
    if (Strings.isNullOrEmpty(property)) {
        property = id;
    } else if (Strings.isNullOrEmpty(id)) {
        id = property;
    }
    Datasource targetDs = ds;
    Datasource datasource = loadDatasource(element);
    if (datasource != null) {
        targetDs = datasource;
    }
    CollectionDatasource optionsDs = null;
    String optDsName = element.attributeValue("optionsDatasource");
    if (StringUtils.isNotBlank(optDsName)) {
        LegacyFrame frame = (LegacyFrame) getComponentContext().getFrame().getFrameOwner();
        DsContext dsContext = frame.getDsContext();
        optionsDs = findDatasourceRecursively(dsContext, optDsName);
        if (optionsDs == null) {
            throw new GuiDevelopmentException(String.format("Options datasource %s not found for field %s", optDsName, id), context);
        }
    }
    boolean customField = false;
    String custom = element.attributeValue("custom");
    if (StringUtils.isNotEmpty(custom)) {
        customField = Boolean.parseBoolean(custom);
    }
    if (StringUtils.isNotEmpty(element.attributeValue("generator"))) {
        customField = true;
    }
    List<Element> elements = element.elements();
    List<Element> customElements = elements.stream().filter(e -> !("formatter".equals(e.getName()) || "validator".equals(e.getName()))).collect(Collectors.toList());
    if (!customElements.isEmpty()) {
        if (customElements.size() > 1) {
            throw new GuiDevelopmentException(String.format("FieldGroup field %s element cannot contains two or more custom field definitions", id), context);
        }
        if (customField) {
            throw new GuiDevelopmentException(String.format("FieldGroup field %s cannot use both custom/generator attribute and inline component definition", id), context);
        }
        customField = true;
    }
    if (!customField && targetDs == null) {
        throw new GuiDevelopmentException(String.format("Datasource is not defined for FieldGroup field '%s'. " + "Only custom fields can have no datasource.", property), context);
    }
    FieldGroup.FieldConfig field = resultComponent.createField(id);
    if (property != null) {
        field.setProperty(property);
    }
    if (datasource != null) {
        field.setDatasource(datasource);
    }
    if (optionsDs != null) {
        field.setOptionsDatasource(optionsDs);
    }
    String stylename = element.attributeValue("stylename");
    if (StringUtils.isNotEmpty(stylename)) {
        field.setStyleName(stylename);
    }
    MetaPropertyPath metaPropertyPath = null;
    if (targetDs != null && property != null) {
        MetaClass metaClass = targetDs.getMetaClass();
        metaPropertyPath = getMetadataTools().resolveMetaPropertyPath(targetDs.getMetaClass(), property);
        if (metaPropertyPath == null) {
            if (!customField) {
                throw new GuiDevelopmentException(String.format("Property '%s' is not found in entity '%s'", property, metaClass.getName()), context);
            }
        }
    }
    String propertyName = metaPropertyPath != null ? metaPropertyPath.getMetaProperty().getName() : null;
    if (metaPropertyPath != null && DynamicAttributesUtils.isDynamicAttribute(metaPropertyPath.getMetaProperty())) {
        CategoryAttribute categoryAttribute = DynamicAttributesUtils.getCategoryAttribute(metaPropertyPath.getMetaProperty());
        field.setCaption(categoryAttribute != null ? categoryAttribute.getLocaleName() : propertyName);
        field.setDescription(categoryAttribute != null ? categoryAttribute.getLocaleDescription() : null);
    } else {
        loadCaption(field, element);
        if (field.getCaption() == null) {
            field.setCaption(getDefaultCaption(field, targetDs));
        }
    }
    loadDescription(field, element);
    loadContextHelp(field, element);
    field.setXmlDescriptor(element);
    Function formatter = loadFormatter(element);
    if (formatter != null) {
        field.setFormatter(formatter);
    }
    String defaultWidth = element.attributeValue("width");
    if (StringUtils.isEmpty(defaultWidth)) {
        defaultWidth = columnWidth;
    }
    loadWidth(field, defaultWidth);
    if (customField) {
        field.setCustom(true);
    }
    String required = element.attributeValue("required");
    if (StringUtils.isNotEmpty(required)) {
        field.setRequired(Boolean.parseBoolean(required));
    }
    String requiredMsg = element.attributeValue("requiredMessage");
    if (requiredMsg != null) {
        requiredMsg = loadResourceString(requiredMsg);
        field.setRequiredMessage(requiredMsg);
    }
    String tabIndex = element.attributeValue("tabIndex");
    if (StringUtils.isNotEmpty(tabIndex)) {
        field.setTabIndex(Integer.parseInt(tabIndex));
    }
    loadInputPrompt(field, element);
    if (customElements.size() == 1) {
        // load nested component defined as inline
        Element customFieldElement = customElements.get(0);
        LayoutLoader loader = getLayoutLoader();
        ComponentLoader childComponentLoader = loader.createComponent(customFieldElement);
        childComponentLoader.loadComponent();
        Component customComponent = childComponentLoader.getResultComponent();
        String inlineAttachMode = element.attributeValue("inlineAttachMode");
        if (StringUtils.isNotEmpty(inlineAttachMode)) {
            field.setComponent(customComponent, FieldGroup.FieldAttachMode.valueOf(inlineAttachMode));
        } else {
            field.setComponent(customComponent);
        }
    }
    return field;
}
Also used : Datasource(com.haulmont.cuba.gui.data.Datasource) EmbeddedDatasource(com.haulmont.cuba.gui.data.EmbeddedDatasource) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) Iterables(com.google.common.collect.Iterables) java.util(java.util) FieldGroupFieldFactory(com.haulmont.cuba.gui.components.FieldGroupFieldFactory) Datasource(com.haulmont.cuba.gui.data.Datasource) DynamicAttributesGuiTools(com.haulmont.cuba.gui.dynamicattributes.DynamicAttributesGuiTools) MetaPropertyPath(com.haulmont.chile.core.model.MetaPropertyPath) DynamicAttributesUtils(com.haulmont.cuba.core.app.dynamicattributes.DynamicAttributesUtils) BooleanUtils(org.apache.commons.lang3.BooleanUtils) StringUtils(org.apache.commons.lang3.StringUtils) Function(java.util.function.Function) MetaClass(com.haulmont.chile.core.model.MetaClass) Strings(com.google.common.base.Strings) MetadataTools(com.haulmont.cuba.core.global.MetadataTools) CategoryAttribute(com.haulmont.cuba.core.entity.CategoryAttribute) EmbeddedDatasource(com.haulmont.cuba.gui.data.EmbeddedDatasource) Preconditions.checkNotNullArgument(com.haulmont.bali.util.Preconditions.checkNotNullArgument) Component(com.haulmont.cuba.gui.components.Component) FieldGroup(com.haulmont.cuba.gui.components.FieldGroup) DsContext(com.haulmont.cuba.gui.data.DsContext) Nullable(javax.annotation.Nullable) LegacyFrame(com.haulmont.cuba.gui.screen.compatibility.LegacyFrame) LayoutLoader(com.haulmont.cuba.gui.xml.layout.LayoutLoader) MetaProperty(com.haulmont.chile.core.model.MetaProperty) DeclarativeFieldGenerator(com.haulmont.cuba.gui.xml.DeclarativeFieldGenerator) Collectors(java.util.stream.Collectors) ComponentLoader(com.haulmont.cuba.gui.xml.layout.ComponentLoader) Consumer(java.util.function.Consumer) EntityOp(com.haulmont.cuba.security.entity.EntityOp) EntityAttrAccess(com.haulmont.cuba.security.entity.EntityAttrAccess) GuiDevelopmentException(com.haulmont.cuba.gui.GuiDevelopmentException) FieldCaptionAlignment(com.haulmont.cuba.gui.components.FieldGroup.FieldCaptionAlignment) Element(org.dom4j.Element) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) MessageTools(com.haulmont.cuba.core.global.MessageTools) LayoutLoader(com.haulmont.cuba.gui.xml.layout.LayoutLoader) DsContext(com.haulmont.cuba.gui.data.DsContext) FieldGroup(com.haulmont.cuba.gui.components.FieldGroup) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) Element(org.dom4j.Element) LegacyFrame(com.haulmont.cuba.gui.screen.compatibility.LegacyFrame) MetaPropertyPath(com.haulmont.chile.core.model.MetaPropertyPath) ComponentLoader(com.haulmont.cuba.gui.xml.layout.ComponentLoader) Function(java.util.function.Function) CategoryAttribute(com.haulmont.cuba.core.entity.CategoryAttribute) MetaClass(com.haulmont.chile.core.model.MetaClass) GuiDevelopmentException(com.haulmont.cuba.gui.GuiDevelopmentException) Component(com.haulmont.cuba.gui.components.Component)

Aggregations

DsContext (com.haulmont.cuba.gui.data.DsContext)15 LegacyFrame (com.haulmont.cuba.gui.screen.compatibility.LegacyFrame)5 Element (org.dom4j.Element)5 Datasource (com.haulmont.cuba.gui.data.Datasource)4 DsContextImplementation (com.haulmont.cuba.gui.data.impl.DsContextImplementation)4 DsContextLoader (com.haulmont.cuba.gui.xml.data.DsContextLoader)3 MetaClass (com.haulmont.chile.core.model.MetaClass)2 MetaProperty (com.haulmont.chile.core.model.MetaProperty)2 GuiDevelopmentException (com.haulmont.cuba.gui.GuiDevelopmentException)2 CollectionDatasource (com.haulmont.cuba.gui.data.CollectionDatasource)2 DataSupplier (com.haulmont.cuba.gui.data.DataSupplier)2 DatasourceImplementation (com.haulmont.cuba.gui.data.impl.DatasourceImplementation)2 GenericDataSupplier (com.haulmont.cuba.gui.data.impl.GenericDataSupplier)2 java.util (java.util)2 Function (java.util.function.Function)2 StringUtils (org.apache.commons.lang3.StringUtils)2 Strings (com.google.common.base.Strings)1 Iterables (com.google.common.collect.Iterables)1 Preconditions.checkNotNullArgument (com.haulmont.bali.util.Preconditions.checkNotNullArgument)1 MetaPropertyPath (com.haulmont.chile.core.model.MetaPropertyPath)1