Search in sources :

Example 56 with CollectionDatasource

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

the class SearchFieldDsTest method testUnsubscribeSubscribeDsListener.

@Test
public void testUnsubscribeSubscribeDsListener() {
    SearchField searchField = factory.createComponent(SearchField.class);
    CollectionDatasource<Group, UUID> groupsDs = getTestCollectionDatasource();
    searchField.setOptionsDatasource(groupsDs);
    Datasource<User> userDs = getTestUserDatasource();
    Group group = groupsDs.getItems().iterator().next();
    userDs.getItem().setGroup(group);
    searchField.setDatasource(userDs, "group");
    // unbind
    searchField.setDatasource(null, null);
    // setup
    boolean[] valueWasChanged = { false };
    Datasource.ItemPropertyChangeListener<User> listener = e -> valueWasChanged[0] = true;
    userDs.addItemPropertyChangeListener(listener);
    searchField.setDatasource(userDs, "group");
    searchField.setValue(null);
    assertEquals(true, valueWasChanged[0]);
}
Also used : Datasource(com.haulmont.cuba.gui.data.Datasource) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) Datasource(com.haulmont.cuba.gui.data.Datasource) Assert.assertTrue(org.junit.Assert.assertTrue) SearchField(com.haulmont.cuba.gui.components.SearchField) Test(org.junit.Test) UUID(java.util.UUID) User(com.haulmont.cuba.security.entity.User) ArrayList(java.util.ArrayList) Group(com.haulmont.cuba.security.entity.Group) List(java.util.List) Ignore(org.junit.Ignore) Component(com.haulmont.cuba.gui.components.Component) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) Assert.assertEquals(org.junit.Assert.assertEquals) Group(com.haulmont.cuba.security.entity.Group) SearchField(com.haulmont.cuba.gui.components.SearchField) User(com.haulmont.cuba.security.entity.User) UUID(java.util.UUID) Test(org.junit.Test)

Example 57 with CollectionDatasource

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

the class ExcelExporter method exportDataGrid.

public void exportDataGrid(DataGrid<Entity> dataGrid, List<DataGrid.Column> columns, ExportDisplay display, List<String> filterDescription, String fileName, ExportMode exportMode) {
    if (display == null) {
        throw new IllegalArgumentException("ExportDisplay is null");
    }
    createWorkbookWithSheet();
    createFonts();
    createFormats();
    int r = 0;
    if (filterDescription != null) {
        for (r = 0; r < filterDescription.size(); r++) {
            String line = filterDescription.get(r);
            HSSFRow row = sheet.createRow(r);
            if (r == 0) {
                HSSFRichTextString richTextFilterName = new HSSFRichTextString(line);
                richTextFilterName.applyFont(boldFont);
                row.createCell(0).setCellValue(richTextFilterName);
            } else {
                row.createCell(0).setCellValue(line);
            }
        }
        r++;
    }
    HSSFRow row = sheet.createRow(r);
    createAutoColumnSizers(columns.size());
    float maxHeight = sheet.getDefaultRowHeightInPoints();
    CellStyle headerCellStyle = wb.createCellStyle();
    headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
    for (DataGrid.Column column : columns) {
        String caption = column.getCaption();
        int countOfReturnSymbols = StringUtils.countMatches(caption, "\n");
        if (countOfReturnSymbols > 0) {
            maxHeight = Math.max(maxHeight, (countOfReturnSymbols + 1) * sheet.getDefaultRowHeightInPoints());
            headerCellStyle.setWrapText(true);
        }
    }
    row.setHeightInPoints(maxHeight);
    for (int c = 0; c < columns.size(); c++) {
        DataGrid.Column column = columns.get(c);
        String caption = column.getCaption();
        HSSFCell cell = row.createCell(c);
        HSSFRichTextString richTextString = new HSSFRichTextString(caption);
        richTextString.applyFont(boldFont);
        cell.setCellValue(richTextString);
        ExcelAutoColumnSizer sizer = new ExcelAutoColumnSizer();
        sizer.notifyCellValue(caption, boldFont);
        sizers[c] = sizer;
        cell.setCellStyle(headerCellStyle);
    }
    CollectionDatasource datasource = dataGrid.getDatasource();
    if (exportMode == ExportMode.SELECTED_ROWS && dataGrid.getSelected().size() > 0) {
        Set<Entity> selected = dataGrid.getSelected();
        List<Entity> ordered = ((Collection<Entity>) datasource.getItems()).stream().filter(selected::contains).collect(Collectors.toList());
        for (Entity item : ordered) {
            createDataGridRow(dataGrid, columns, 0, ++r, item.getId());
        }
    } else {
        for (Object itemId : datasource.getItemIds()) {
            createDataGridRow(dataGrid, columns, 0, ++r, itemId);
        }
    }
    for (int c = 0; c < columns.size(); c++) {
        sheet.setColumnWidth(c, sizers[c].getWidth() * COL_WIDTH_MAGIC);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        wb.write(out);
    } catch (IOException e) {
        throw new RuntimeException("Unable to write document", e);
    }
    if (fileName == null) {
        fileName = messages.getTools().getEntityCaption(datasource.getMetaClass());
    }
    display.show(new ByteArrayDataProvider(out.toByteArray()), fileName + ".xls", ExportFormat.XLS);
}
Also used : Entity(com.haulmont.cuba.core.entity.Entity) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) CellStyle(org.apache.poi.ss.usermodel.CellStyle)

Example 58 with CollectionDatasource

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

the class ExcelExporter method exportTable.

public void exportTable(Table<Entity> table, List<Table.Column> columns, Boolean exportExpanded, ExportDisplay display, List<String> filterDescription, String fileName, ExportMode exportMode) {
    if (display == null) {
        throw new IllegalArgumentException("ExportDisplay is null");
    }
    createWorkbookWithSheet();
    createFonts();
    createFormats();
    int r = 0;
    if (filterDescription != null) {
        for (r = 0; r < filterDescription.size(); r++) {
            String line = filterDescription.get(r);
            HSSFRow row = sheet.createRow(r);
            if (r == 0) {
                HSSFRichTextString richTextFilterName = new HSSFRichTextString(line);
                richTextFilterName.applyFont(boldFont);
                row.createCell(0).setCellValue(richTextFilterName);
            } else {
                row.createCell(0).setCellValue(line);
            }
        }
        r++;
    }
    HSSFRow row = sheet.createRow(r);
    createAutoColumnSizers(columns.size());
    float maxHeight = sheet.getDefaultRowHeightInPoints();
    CellStyle headerCellStyle = wb.createCellStyle();
    headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
    for (Table.Column column : columns) {
        String caption = column.getCaption();
        int countOfReturnSymbols = StringUtils.countMatches(caption, "\n");
        if (countOfReturnSymbols > 0) {
            maxHeight = Math.max(maxHeight, (countOfReturnSymbols + 1) * sheet.getDefaultRowHeightInPoints());
            headerCellStyle.setWrapText(true);
        }
    }
    row.setHeightInPoints(maxHeight);
    for (int c = 0; c < columns.size(); c++) {
        Table.Column column = columns.get(c);
        String caption = column.getCaption();
        HSSFCell cell = row.createCell(c);
        HSSFRichTextString richTextString = new HSSFRichTextString(caption);
        richTextString.applyFont(boldFont);
        cell.setCellValue(richTextString);
        ExcelAutoColumnSizer sizer = new ExcelAutoColumnSizer();
        sizer.notifyCellValue(caption, boldFont);
        sizers[c] = sizer;
        cell.setCellStyle(headerCellStyle);
    }
    CollectionDatasource datasource = table.getDatasource();
    if (exportMode == ExportMode.SELECTED_ROWS && table.getSelected().size() > 0) {
        Set<Entity> selected = table.getSelected();
        List<Entity> ordered = ((Collection<Entity>) datasource.getItems()).stream().filter(selected::contains).collect(Collectors.toList());
        for (Entity item : ordered) {
            createRow(table, columns, 0, ++r, item.getId());
        }
    } else {
        if (table instanceof TreeTable) {
            TreeTable treeTable = (TreeTable) table;
            HierarchicalDatasource ds = treeTable.getDatasource();
            if (table.isAggregatable()) {
                r = createAggregatableRow(table, columns, ++r, 1, datasource);
            }
            for (Object itemId : ds.getRootItemIds()) {
                r = createHierarhicalRow(treeTable, columns, exportExpanded, r, itemId);
            }
        } else if (table instanceof GroupTable && datasource instanceof GroupDatasource && ((GroupDatasource) datasource).hasGroups()) {
            GroupDatasource ds = (GroupDatasource) datasource;
            if (table.isAggregatable()) {
                r = createAggregatableRow(table, columns, ++r, 1, datasource);
            }
            for (Object item : ds.rootGroups()) {
                r = createGroupRow((GroupTable) table, columns, ++r, (GroupInfo) item, 0);
            }
        } else {
            if (table.isAggregatable()) {
                r = createAggregatableRow(table, columns, ++r, 1, datasource);
            }
            for (Object itemId : datasource.getItemIds()) {
                createRow(table, columns, 0, ++r, itemId);
            }
        }
    }
    for (int c = 0; c < columns.size(); c++) {
        sheet.setColumnWidth(c, sizers[c].getWidth() * COL_WIDTH_MAGIC);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        wb.write(out);
    } catch (IOException e) {
        throw new RuntimeException("Unable to write document", e);
    }
    if (fileName == null) {
        fileName = messages.getTools().getEntityCaption(datasource.getMetaClass());
    }
    display.show(new ByteArrayDataProvider(out.toByteArray()), fileName + ".xls", ExportFormat.XLS);
}
Also used : Entity(com.haulmont.cuba.core.entity.Entity) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) HierarchicalDatasource(com.haulmont.cuba.gui.data.HierarchicalDatasource) GroupDatasource(com.haulmont.cuba.gui.data.GroupDatasource) CellStyle(org.apache.poi.ss.usermodel.CellStyle)

Example 59 with CollectionDatasource

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

the class AbstractTableLoader method loadComponent.

@Override
public void loadComponent() {
    assignXmlDescriptor(resultComponent, element);
    assignFrame(resultComponent);
    loadEnable(resultComponent, element);
    loadVisible(resultComponent, element);
    loadEditable(resultComponent, element);
    loadValidators(resultComponent, element);
    loadSettingsEnabled(resultComponent, element);
    loadAlign(resultComponent, element);
    loadStyleName(resultComponent, element);
    loadHeight(resultComponent, element);
    loadWidth(resultComponent, element);
    loadIcon(resultComponent, element);
    loadCaption(resultComponent, element);
    loadDescription(resultComponent, element);
    loadTabIndex(resultComponent, element);
    loadSortable(resultComponent, element);
    loadReorderingAllowed(resultComponent, element);
    loadColumnControlVisible(resultComponent, element);
    loadAggregatable(resultComponent, element);
    loadAggregationStyle(resultComponent, element);
    loadPresentations(resultComponent, element);
    loadActions(resultComponent, element);
    loadContextMenuEnabled(resultComponent, element);
    loadMultiLineCells(resultComponent, element);
    loadColumnHeaderVisible(resultComponent, element);
    loadShowSelection(resultComponent, element);
    loadTextSelectionEnabled(resultComponent, element);
    loadResponsive(resultComponent, element);
    Element columnsElement = element.element("columns");
    Element rowsElement = element.element("rows");
    if (rowsElement == null) {
        throw new GuiDevelopmentException("Table doesn't have 'rows' element", context.getCurrentFrameId(), "Table ID", element.attributeValue("id"));
    }
    String rowHeaderMode = rowsElement.attributeValue("rowHeaderMode");
    if (StringUtils.isBlank(rowHeaderMode)) {
        rowHeaderMode = rowsElement.attributeValue("headerMode");
        if (StringUtils.isNotBlank(rowHeaderMode)) {
            Logger log = LoggerFactory.getLogger(AbstractTableLoader.class);
            log.warn("Attribute headerMode is deprecated. Use rowHeaderMode.");
        }
    }
    if (!StringUtils.isEmpty(rowHeaderMode)) {
        resultComponent.setRowHeaderMode(Table.RowHeaderMode.valueOf(rowHeaderMode));
    }
    loadButtonsPanel(resultComponent);
    // must be before datasource setting
    loadRowsCount(resultComponent, element);
    String datasource = rowsElement.attributeValue("datasource");
    if (StringUtils.isBlank(datasource)) {
        throw new GuiDevelopmentException("Table 'rows' element doesn't have 'datasource' attribute", context.getCurrentFrameId(), "Table ID", element.attributeValue("id"));
    }
    Datasource ds = context.getDsContext().get(datasource);
    if (ds == null) {
        throw new GuiDevelopmentException("Can't find datasource by name: " + datasource, context.getCurrentFrameId());
    }
    if (!(ds instanceof CollectionDatasource)) {
        throw new GuiDevelopmentException("Not a CollectionDatasource: " + datasource, context.getCurrentFrameId());
    }
    CollectionDatasource cds = (CollectionDatasource) ds;
    List<Table.Column> availableColumns;
    if (columnsElement != null) {
        availableColumns = loadColumns(resultComponent, columnsElement, cds);
    } else {
        availableColumns = new ArrayList<>();
    }
    for (Table.Column column : availableColumns) {
        resultComponent.addColumn(column);
        loadValidators(resultComponent, column);
        loadRequired(resultComponent, column);
    }
    addDynamicAttributes(resultComponent, ds, availableColumns);
    resultComponent.setDatasource(cds);
    for (Table.Column column : availableColumns) {
        if (column.getXmlDescriptor() != null) {
            String generatorMethod = column.getXmlDescriptor().attributeValue("generator");
            if (StringUtils.isNotEmpty(generatorMethod)) {
                // noinspection unchecked
                resultComponent.addGeneratedColumn(String.valueOf(column), new DeclarativeColumnGenerator(resultComponent, generatorMethod));
            }
        }
    }
    String multiselect = element.attributeValue("multiselect");
    if (StringUtils.isNotEmpty(multiselect)) {
        resultComponent.setMultiSelect(Boolean.parseBoolean(multiselect));
    }
}
Also used : Datasource(com.haulmont.cuba.gui.data.Datasource) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) DeclarativeColumnGenerator(com.haulmont.cuba.gui.xml.DeclarativeColumnGenerator) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) Element(org.dom4j.Element) GuiDevelopmentException(com.haulmont.cuba.gui.GuiDevelopmentException) Logger(org.slf4j.Logger)

Example 60 with CollectionDatasource

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

the class WebDataGrid method setDatasource.

@Override
public void setDatasource(CollectionDatasource datasource) {
    checkNotNullArgument(datasource, "datasource is null");
    if (!(datasource instanceof CollectionDatasource.Indexed)) {
        throw new IllegalArgumentException("Datasource must implement " + "com.haulmont.cuba.gui.data.CollectionDatasource.Indexed");
    }
    if (this.datasource != null) {
        if (!this.datasource.getMetaClass().equals(datasource.getMetaClass())) {
            throw new IllegalArgumentException("The new datasource must correspond to the same MetaClass");
        }
        if (collectionDsListenersWrapper != null) {
            collectionDsListenersWrapper.unbind(this.datasource);
            if (containerDatasource != null) {
                containerDatasource.unsubscribe();
                containerDatasource = null;
            }
        }
    }
    addInitialColumns(datasource);
    this.datasource = datasource;
    List<Column> visibleColumnsOrder = getInitialVisibleColumns();
    if (collectionDsListenersWrapper == null) {
        collectionDsListenersWrapper = new CollectionDsListenersWrapper();
    }
    component.removeAllColumns();
    containerDatasource = createContainerDatasource((CollectionDatasource.Indexed) datasource, getPropertyColumns(), collectionDsListenersWrapper);
    containerWrapper = new GeneratedPropertyContainer(containerDatasource);
    component.setContainerDataSource(containerWrapper);
    createStubsForGeneratedColumns();
    // mark columns hidden by security permissions as visible = false
    // and remove Grid.Column to prevent its property changing
    columnsOrder.stream().filter(column -> !visibleColumnsOrder.contains(column)).forEach(column -> {
        ColumnImpl columnImpl = (ColumnImpl) column;
        columnImpl.setVisible(false);
        columnImpl.setGridColumn(null);
    });
    for (Column column : visibleColumnsOrder) {
        Grid.Column gridColumn = component.getColumn(((ColumnImpl) column).getColumnPropertyId());
        setupGridColumnProperties(gridColumn, column);
    }
    component.setColumnOrder(getColumnPropertyIds());
    initShowInfoAction(datasource);
    if (rowsCount != null) {
        rowsCount.setDatasource(datasource);
    }
    collectionDsListenersWrapper.bind(datasource);
    refreshActionsState();
    if (!canBeSorted(datasource)) {
        setSortable(false);
    }
    assignAutoDebugId();
    component.setCollectionDatasource(datasource);
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) Datasource(com.haulmont.cuba.gui.data.Datasource) Dom4j(com.haulmont.bali.util.Dom4j) DsBuilder(com.haulmont.cuba.gui.data.DsBuilder) IconResolver(com.haulmont.cuba.web.gui.icons.IconResolver) Window(com.haulmont.cuba.gui.components.Window) AppUI(com.haulmont.cuba.web.AppUI) MenuItem(com.vaadin.addon.contextmenu.MenuItem) EventRouter(com.haulmont.bali.events.EventRouter) SecuredActionsHolder(com.haulmont.cuba.gui.components.Component.SecuredActionsHolder) FormatterBasedConverter(com.haulmont.cuba.web.toolkit.ui.converters.FormatterBasedConverter) Preconditions.checkNotNullArgument(com.haulmont.bali.util.Preconditions.checkNotNullArgument) com.haulmont.cuba.gui.components(com.haulmont.cuba.gui.components) PropertyDatasource(com.haulmont.cuba.gui.data.PropertyDatasource) ImmutableMap(com.google.common.collect.ImmutableMap) PropertyValueGenerator(com.vaadin.data.util.PropertyValueGenerator) App(com.haulmont.cuba.web.App) Collectors(java.util.stream.Collectors) ObjectToObjectConverter(com.haulmont.cuba.web.toolkit.ui.converters.ObjectToObjectConverter) PropertyChangeListener(java.beans.PropertyChangeListener) ComponentsHelper.findActionById(com.haulmont.cuba.gui.ComponentsHelper.findActionById) GeneratedPropertyContainer(com.vaadin.data.util.GeneratedPropertyContainer) ThemeConstants(com.haulmont.cuba.gui.theme.ThemeConstants) ClientConfig(com.haulmont.cuba.client.ClientConfig) ComponentsHelper(com.haulmont.cuba.gui.ComponentsHelper) com.haulmont.cuba.web.gui.components.renderers(com.haulmont.cuba.web.gui.components.renderers) java.util(java.util) CollectionFormatter(com.haulmont.cuba.gui.components.formatters.CollectionFormatter) GridContextMenuOpenListener(com.vaadin.addon.contextmenu.GridContextMenu.GridContextMenuOpenListener) MetaPropertyPath(com.haulmont.chile.core.model.MetaPropertyPath) CssLayout(com.vaadin.ui.CssLayout) MetaClass(com.haulmont.chile.core.model.MetaClass) CollectionUtils(org.apache.commons.collections4.CollectionUtils) com.haulmont.cuba.core.global(com.haulmont.cuba.core.global) Validator(com.vaadin.data.Validator) Field(com.haulmont.cuba.gui.components.Field) SortableDataGridIndexedCollectionDsWrapper(com.haulmont.cuba.web.gui.data.SortableDataGridIndexedCollectionDsWrapper) com.haulmont.cuba.gui.data.impl(com.haulmont.cuba.gui.data.impl) DataGridIndexedCollectionDsWrapper(com.haulmont.cuba.web.gui.data.DataGridIndexedCollectionDsWrapper) com.haulmont.cuba.web.toolkit.ui(com.haulmont.cuba.web.toolkit.ui) KeyCode(com.vaadin.event.ShortcutAction.KeyCode) Nullable(javax.annotation.Nullable) Item(com.vaadin.data.Item) Formatter(com.haulmont.cuba.gui.components.Formatter) DataGridContainer(com.haulmont.cuba.web.toolkit.data.DataGridContainer) MetaProperty(com.haulmont.chile.core.model.MetaProperty) StringToObjectConverter(com.haulmont.cuba.web.toolkit.ui.converters.StringToObjectConverter) ErrorMessage(com.vaadin.server.ErrorMessage) Preconditions(com.haulmont.bali.util.Preconditions) HeightMode(com.vaadin.shared.ui.grid.HeightMode) ShortcutListener(com.vaadin.event.ShortcutListener) Menu(com.vaadin.addon.contextmenu.Menu) Element(org.dom4j.Element) CollectionDatasource(com.haulmont.cuba.gui.data.CollectionDatasource) YesNoIconConverter(com.haulmont.cuba.web.toolkit.ui.converters.YesNoIconConverter) Entity(com.haulmont.cuba.core.entity.Entity) com.vaadin.ui(com.vaadin.ui) Component(com.vaadin.ui.Component) GeneratedPropertyContainer(com.vaadin.data.util.GeneratedPropertyContainer)

Aggregations

CollectionDatasource (com.haulmont.cuba.gui.data.CollectionDatasource)67 Datasource (com.haulmont.cuba.gui.data.Datasource)39 UUID (java.util.UUID)24 Group (com.haulmont.cuba.security.entity.Group)23 User (com.haulmont.cuba.security.entity.User)23 ArrayList (java.util.ArrayList)23 Ignore (org.junit.Ignore)23 Test (org.junit.Test)23 Component (com.haulmont.cuba.gui.components.Component)20 List (java.util.List)19 Assert.assertEquals (org.junit.Assert.assertEquals)19 Assert.assertTrue (org.junit.Assert.assertTrue)19 Entity (com.haulmont.cuba.core.entity.Entity)15 MetaClass (com.haulmont.chile.core.model.MetaClass)10 MetaProperty (com.haulmont.chile.core.model.MetaProperty)10 LookupField (com.haulmont.cuba.gui.components.LookupField)8 GuiDevelopmentException (com.haulmont.cuba.gui.GuiDevelopmentException)7 LookupPickerField (com.haulmont.cuba.gui.components.LookupPickerField)7 Element (org.dom4j.Element)7 Assert.assertNotNull (org.junit.Assert.assertNotNull)7