Search in sources :

Example 1 with Downloader

use of io.jmix.ui.download.Downloader in project jmix by jmix-framework.

the class ExcelExporter method exportDataGrid.

@Override
public void exportDataGrid(Downloader downloader, DataGrid<Object> dataGrid, ExportMode exportMode) {
    if (downloader == null) {
        throw new IllegalArgumentException("Downloader is null");
    }
    createWorkbookWithSheet();
    createFonts();
    createFormats();
    List<DataGrid.Column<Object>> columns = dataGrid.getColumns();
    int r = 0;
    Row 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();
        Cell cell = row.createCell(c);
        RichTextString richTextString = createStringCellValue(caption);
        richTextString.applyFont(boldFont);
        cell.setCellValue(richTextString);
        ExcelAutoColumnSizer sizer = new ExcelAutoColumnSizer();
        sizer.notifyCellValue(caption, boldFont);
        sizers[c] = sizer;
        cell.setCellStyle(headerCellStyle);
    }
    EntityDataGridItems<Object> dataGridSource = (EntityDataGridItems) dataGrid.getItems();
    if (dataGridSource == null) {
        throw new IllegalStateException("DataGrid is not bound to data");
    }
    if (exportMode == ExportMode.SELECTED && dataGrid.getSelected().size() > 0) {
        Set<Object> selected = dataGrid.getSelected();
        List<Object> ordered = dataGridSource.getItems().filter(selected::contains).collect(Collectors.toList());
        for (Object item : ordered) {
            if (checkIsRowNumberExceed(r)) {
                break;
            }
            createDataGridRow(dataGrid, columns, 0, ++r, Id.of(item).getValue());
        }
    } else {
        if (dataGrid instanceof TreeDataGrid) {
            TreeDataGrid treeDataGrid = (TreeDataGrid) dataGrid;
            TreeDataGridItems<Object> treeDataGridItems = (TreeDataGridItems) dataGridSource;
            List<Object> items = treeDataGridItems.getChildren(null).collect(Collectors.toList());
            for (Object item : items) {
                if (checkIsRowNumberExceed(r)) {
                    break;
                }
                r = createDataGridHierarchicalRow(treeDataGrid, treeDataGridItems, columns, 0, r, item);
            }
        } else {
            for (Object itemId : dataGridSource.getItems().map(entity -> Id.of(entity).getValue()).collect(Collectors.toList())) {
                if (checkIsRowNumberExceed(r)) {
                    break;
                }
                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);
    }
    ByteArrayDataProvider dataProvider = new ByteArrayDataProvider(out.toByteArray(), uiProperties.getSaveExportedByteArrayDataThresholdBytes(), coreProperties.getTempDir());
    switch(exportFormat) {
        case XLSX:
            downloader.download(dataProvider, getFileName(dataGrid) + "." + XLSX.getFileExt(), XLSX);
            break;
        case XLS:
            downloader.download(dataProvider, getFileName(dataGrid) + "." + XLS.getFileExt(), XLS);
            break;
    }
}
Also used : Id(io.jmix.core.Id) java.util(java.util) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MetaPropertyPath(io.jmix.core.metamodel.model.MetaPropertyPath) EntityDataGridItems(io.jmix.ui.component.data.meta.EntityDataGridItems) ByteArrayDataProvider(io.jmix.ui.download.ByteArrayDataProvider) BooleanUtils(org.apache.commons.lang3.BooleanUtils) ExportMode(io.jmix.uiexport.exporter.ExportMode) StringUtils(org.apache.commons.lang3.StringUtils) Function(java.util.function.Function) XLS(io.jmix.ui.download.DownloadFormat.XLS) EntityValues(io.jmix.core.entity.EntityValues) Scope(org.springframework.context.annotation.Scope) Notifications(io.jmix.ui.Notifications) org.apache.poi.ss.usermodel(org.apache.poi.ss.usermodel) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) io.jmix.ui.component.data(io.jmix.ui.component.data) InstanceContainer(io.jmix.ui.model.InstanceContainer) XLSX(io.jmix.ui.download.DownloadFormat.XLSX) XSSFRichTextString(org.apache.poi.xssf.usermodel.XSSFRichTextString) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) Range(io.jmix.core.metamodel.model.Range) ParseException(java.text.ParseException) Nullable(javax.annotation.Nullable) AbstractTableExporter(io.jmix.uiexport.exporter.AbstractTableExporter) IOException(java.io.IOException) Datatype(io.jmix.core.metamodel.datatype.Datatype) Collectors(java.util.stream.Collectors) Table(io.jmix.ui.component.Table) ExportAction(io.jmix.uiexport.action.ExportAction) HSSFRichTextString(org.apache.poi.hssf.usermodel.HSSFRichTextString) Component(org.springframework.stereotype.Component) Entity(io.jmix.core.Entity) Downloader(io.jmix.ui.download.Downloader) Element(org.dom4j.Element) MetaProperty(io.jmix.core.metamodel.model.MetaProperty) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook) io.jmix.ui.component(io.jmix.ui.component) EntityDataGridItems(io.jmix.ui.component.data.meta.EntityDataGridItems) XSSFRichTextString(org.apache.poi.xssf.usermodel.XSSFRichTextString) HSSFRichTextString(org.apache.poi.hssf.usermodel.HSSFRichTextString) ByteArrayDataProvider(io.jmix.ui.download.ByteArrayDataProvider) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) XSSFRichTextString(org.apache.poi.xssf.usermodel.XSSFRichTextString) HSSFRichTextString(org.apache.poi.hssf.usermodel.HSSFRichTextString)

Example 2 with Downloader

use of io.jmix.ui.download.Downloader in project jmix by jmix-framework.

the class ExcelExporter method exportTable.

@Override
public void exportTable(Downloader downloader, Table<Object> table, ExportMode exportMode) {
    if (downloader == null) {
        throw new IllegalArgumentException("Downloader is null");
    }
    if (table.getItems() == null) {
        throw new IllegalStateException("Table items should not be null");
    }
    @SuppressWarnings("unchecked") List<Table.Column<Object>> columns = Collections.unmodifiableList(table.getNotCollapsedColumns()).stream().map(c -> (Table.Column<Object>) c).collect(Collectors.toList());
    createWorkbookWithSheet();
    createFonts();
    createFormats();
    int r = 0;
    Row row = sheet.createRow(r);
    createAutoColumnSizers(columns.size());
    float maxHeight = sheet.getDefaultRowHeightInPoints();
    CellStyle headerCellStyle = wb.createCellStyle();
    headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
    for (Table.Column<Object> 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<Object> column = columns.get(c);
        String caption = column.getCaption();
        Cell cell = row.createCell(c);
        RichTextString richTextString = createStringCellValue(caption);
        richTextString.applyFont(boldFont);
        cell.setCellValue(richTextString);
        ExcelAutoColumnSizer sizer = new ExcelAutoColumnSizer();
        sizer.notifyCellValue(caption, boldFont);
        sizers[c] = sizer;
        cell.setCellStyle(headerCellStyle);
    }
    TableItems<Object> tableItems = table.getItems();
    if (exportMode == ExportMode.SELECTED && table.getSelected().size() > 0) {
        Set<Object> selected = table.getSelected();
        List<Object> ordered = tableItems.getItemIds().stream().map(tableItems::getItem).filter(selected::contains).collect(Collectors.toList());
        for (Object item : ordered) {
            if (checkIsRowNumberExceed(r)) {
                break;
            }
            createRow(table, columns, 0, ++r, Id.of(item).getValue());
        }
    } else {
        if (table.isAggregatable() && exportAggregation && hasAggregatableColumn(table)) {
            if (table.getAggregationStyle() == Table.AggregationStyle.TOP) {
                r = createAggregatableRow(table, columns, ++r, 1);
            }
        }
        if (table instanceof TreeTable) {
            TreeTable<Object> treeTable = (TreeTable<Object>) table;
            TreeTableItems<Object> treeTableSource = (TreeTableItems<Object>) treeTable.getItems();
            if (treeTableSource != null) {
                for (Object itemId : treeTableSource.getRootItemIds()) {
                    if (checkIsRowNumberExceed(r)) {
                        break;
                    }
                    r = createHierarchicalRow(treeTable, columns, exportExpanded, r, itemId);
                }
            }
        } else if (table instanceof GroupTable && tableItems instanceof GroupTableItems && ((GroupTableItems<Object>) tableItems).hasGroups()) {
            GroupTableItems<Object> groupTableSource = (GroupTableItems<Object>) tableItems;
            for (Object item : groupTableSource.rootGroups()) {
                if (checkIsRowNumberExceed(r)) {
                    break;
                }
                r = createGroupRow((GroupTable<Object>) table, columns, ++r, (GroupInfo<?>) item, 0);
            }
        } else {
            if (tableItems != null) {
                for (Object itemId : tableItems.getItemIds()) {
                    if (checkIsRowNumberExceed(r)) {
                        break;
                    }
                    createRow(table, columns, 0, ++r, itemId);
                }
            }
        }
        if (table.isAggregatable() && exportAggregation && hasAggregatableColumn(table)) {
            if (table.getAggregationStyle() == Table.AggregationStyle.BOTTOM) {
                r = createAggregatableRow(table, columns, ++r, 1);
            }
        }
    }
    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 (isXlsMaxRowNumberExceeded()) {
        Notifications notifications = ComponentsHelper.getScreenContext(table).getNotifications();
        notifications.create(Notifications.NotificationType.WARNING).withCaption(messages.getMessage("actions.warningExport.title")).withDescription(messages.getMessage("actions.warningExport.message")).show();
    }
    ByteArrayDataProvider dataProvider = new ByteArrayDataProvider(out.toByteArray(), uiProperties.getSaveExportedByteArrayDataThresholdBytes(), coreProperties.getTempDir());
    switch(exportFormat) {
        case XLSX:
            downloader.download(dataProvider, getFileName(table) + ".xlsx", XLSX);
            break;
        case XLS:
            downloader.download(dataProvider, getFileName(table) + ".xls", XLS);
            break;
    }
}
Also used : Id(io.jmix.core.Id) java.util(java.util) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MetaPropertyPath(io.jmix.core.metamodel.model.MetaPropertyPath) EntityDataGridItems(io.jmix.ui.component.data.meta.EntityDataGridItems) ByteArrayDataProvider(io.jmix.ui.download.ByteArrayDataProvider) BooleanUtils(org.apache.commons.lang3.BooleanUtils) ExportMode(io.jmix.uiexport.exporter.ExportMode) StringUtils(org.apache.commons.lang3.StringUtils) Function(java.util.function.Function) XLS(io.jmix.ui.download.DownloadFormat.XLS) EntityValues(io.jmix.core.entity.EntityValues) Scope(org.springframework.context.annotation.Scope) Notifications(io.jmix.ui.Notifications) org.apache.poi.ss.usermodel(org.apache.poi.ss.usermodel) XSSFWorkbook(org.apache.poi.xssf.usermodel.XSSFWorkbook) io.jmix.ui.component.data(io.jmix.ui.component.data) InstanceContainer(io.jmix.ui.model.InstanceContainer) XLSX(io.jmix.ui.download.DownloadFormat.XLSX) XSSFRichTextString(org.apache.poi.xssf.usermodel.XSSFRichTextString) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) Range(io.jmix.core.metamodel.model.Range) ParseException(java.text.ParseException) Nullable(javax.annotation.Nullable) AbstractTableExporter(io.jmix.uiexport.exporter.AbstractTableExporter) IOException(java.io.IOException) Datatype(io.jmix.core.metamodel.datatype.Datatype) Collectors(java.util.stream.Collectors) Table(io.jmix.ui.component.Table) ExportAction(io.jmix.uiexport.action.ExportAction) HSSFRichTextString(org.apache.poi.hssf.usermodel.HSSFRichTextString) Component(org.springframework.stereotype.Component) Entity(io.jmix.core.Entity) Downloader(io.jmix.ui.download.Downloader) Element(org.dom4j.Element) MetaProperty(io.jmix.core.metamodel.model.MetaProperty) HSSFWorkbook(org.apache.poi.hssf.usermodel.HSSFWorkbook) io.jmix.ui.component(io.jmix.ui.component) XSSFRichTextString(org.apache.poi.xssf.usermodel.XSSFRichTextString) HSSFRichTextString(org.apache.poi.hssf.usermodel.HSSFRichTextString) ByteArrayDataProvider(io.jmix.ui.download.ByteArrayDataProvider) Table(io.jmix.ui.component.Table) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) XSSFRichTextString(org.apache.poi.xssf.usermodel.XSSFRichTextString) HSSFRichTextString(org.apache.poi.hssf.usermodel.HSSFRichTextString) Notifications(io.jmix.ui.Notifications)

Example 3 with Downloader

use of io.jmix.ui.download.Downloader in project jmix by jmix-framework.

the class UiControllerDependencyInjector method getInjectedInstance.

@Nullable
protected Object getInjectedInstance(Class<?> type, String name, InjectElement injectElement, FrameOwner frameOwner, ScreenOptions options) {
    AnnotatedElement element = injectElement.getElement();
    Class annotationClass = injectElement.getAnnotationClass();
    Frame frame = UiControllerUtils.getFrame(frameOwner);
    if (annotationClass == WindowParam.class) {
        if (options instanceof MapScreenOptions) {
            return ((MapScreenOptions) options).getParams().get(name);
        }
        // Injecting a parameter
        return null;
    } else if (ScreenFragment.class.isAssignableFrom(type)) {
        // Injecting inner fragment controller
        Component fragment = frame.getComponent(name);
        if (fragment == null) {
            return null;
        }
        return ((Fragment) fragment).getFrameOwner();
    } else if (Component.class.isAssignableFrom(type)) {
        // / if legacy frame - inject controller
        Component component = frame.getComponent(name);
        if (component instanceof Fragment) {
            ScreenFragment fragmentFrameOwner = ((Fragment) component).getFrameOwner();
            if (type.isAssignableFrom(fragmentFrameOwner.getClass())) {
                return fragmentFrameOwner;
            }
        }
        // Injecting a UI component
        return component;
    } else if (InstanceContainer.class.isAssignableFrom(type)) {
        // Injecting a container
        ScreenData data = getScreenData(frameOwner);
        return data.getContainer(name);
    } else if (DataLoader.class.isAssignableFrom(type)) {
        // Injecting a loader
        ScreenData data = getScreenData(frameOwner);
        return data.getLoader(name);
    } else if (DataContext.class.isAssignableFrom(type)) {
        // Injecting the data context
        ScreenData data = getScreenData(frameOwner);
        return data.getDataContext();
    } else if (FrameContext.class.isAssignableFrom(type)) {
        // Injecting the FrameContext
        return frame.getContext();
    } else if (Action.class.isAssignableFrom(type)) {
        // Injecting an action
        return ComponentsHelper.findAction(name, frame);
    } else if (Facet.class.isAssignableFrom(type)) {
        // Injecting non-visual component
        String[] elements = ValuePathHelper.parse(name);
        if (elements.length == 1) {
            return frame.getFacet(name);
        }
        String prefix = pathPrefix(elements);
        Component component = frame.getComponent(prefix);
        if (component == null) {
            return null;
        }
        if (!(component instanceof Fragment)) {
            throw new UnsupportedOperationException(String.format("Unable to inject facet with id %s and type %s. Component %s is not a fragment", name, type, prefix));
        }
        String facetId = elements[elements.length - 1];
        return ((Fragment) component).getFacet(facetId);
    } else if (Downloader.class.isAssignableFrom(type)) {
        // Injecting a Downloader
        return applicationContext.getBean(Downloader.class);
    } else if (MessageBundle.class == type) {
        return createMessageBundle(element, frameOwner, frame);
    } else if (ThemeConstants.class == type) {
        // Injecting a Theme
        ThemeConstantsManager themeManager = applicationContext.getBean(ThemeConstantsManager.class);
        return themeManager.getConstants();
    } else if (BeanFactory.class.isAssignableFrom(type)) {
        return applicationContext;
    } else if (ObjectProvider.class.isAssignableFrom(type)) {
        if (!(element instanceof Field && ((Field) element).getGenericType() instanceof ParameterizedType) && !(element instanceof Method && ((Method) element).getGenericParameterTypes().length > 0 && ((Method) element).getGenericParameterTypes()[0] instanceof ParameterizedType)) {
            throw new UnsupportedOperationException("Unable to inject ObjectProvider without generic parameter");
        }
        Type genericType;
        if (element instanceof Field) {
            genericType = ((ParameterizedType) ((Field) element).getGenericType()).getActualTypeArguments()[0];
        } else {
            genericType = ((ParameterizedType) ((Method) element).getGenericParameterTypes()[0]).getActualTypeArguments()[0];
        }
        if (genericType instanceof ParameterizedType) {
            genericType = ((ParameterizedType) genericType).getRawType();
        }
        return applicationContext.getBeanProvider((Class<?>) genericType);
    } else if (ActionsAwareDialogFacet.DialogAction.class.isAssignableFrom(type)) {
        // facet's action
        Facet facet;
        String actionId;
        String[] path = ValuePathHelper.parse(name);
        if (path.length == 2) {
            facet = frame.getFacet(path[0]);
            actionId = path[1];
        } else {
            String prefix = ValuePathHelper.pathPrefix(path, 2);
            Component component = frame.getComponent(prefix);
            if (component == null) {
                return null;
            }
            if (!(component instanceof Fragment)) {
                throw new UnsupportedOperationException(String.format("Unable to inject dialog action with id '%s'. Component '%s' is not a fragment", name, prefix));
            }
            actionId = path[path.length - 1];
            facet = ((Fragment) component).getFacet(path[path.length - 2]);
        }
        if (!(facet instanceof ActionsAwareDialogFacet)) {
            return null;
        }
        // noinspection unchecked
        Collection<ActionsAwareDialogFacet.DialogAction<Facet>> actions = ((ActionsAwareDialogFacet<Facet>) facet).getActions();
        if (CollectionUtils.isNotEmpty(actions)) {
            return actions.stream().filter(action -> action.getId().equals(actionId)).findFirst().orElse(null);
        }
    } else {
        Object instance;
        // Try to find a Spring bean
        Map<String, ?> beans = applicationContext.getBeansOfType(type);
        if (!beans.isEmpty()) {
            instance = beans.get(name);
            // If a bean with required name found, return it
            if (instance != null) {
                return instance;
            } else {
                // Otherwise get a bean from the context again to respect @Primary annotation
                return applicationContext.getBean(type);
            }
        }
    }
    return null;
}
Also used : Action(io.jmix.ui.action.Action) ThemeConstantsManager(io.jmix.ui.theme.ThemeConstantsManager) Downloader(io.jmix.ui.download.Downloader) InstanceContainer(io.jmix.ui.model.InstanceContainer) ThemeConstants(io.jmix.ui.theme.ThemeConstants) Field(java.lang.reflect.Field) DataContext(io.jmix.ui.model.DataContext) AnnotatedMethod(io.jmix.ui.sys.UiControllerReflectionInspector.AnnotatedMethod) ObjectProvider(org.springframework.beans.factory.ObjectProvider) UiControllerUtils.getScreenData(io.jmix.ui.screen.UiControllerUtils.getScreenData) ScreenData(io.jmix.ui.model.ScreenData) Nullable(javax.annotation.Nullable)

Aggregations

Downloader (io.jmix.ui.download.Downloader)3 InstanceContainer (io.jmix.ui.model.InstanceContainer)3 Nullable (javax.annotation.Nullable)3 Entity (io.jmix.core.Entity)2 Id (io.jmix.core.Id)2 EntityValues (io.jmix.core.entity.EntityValues)2 Datatype (io.jmix.core.metamodel.datatype.Datatype)2 MetaProperty (io.jmix.core.metamodel.model.MetaProperty)2 MetaPropertyPath (io.jmix.core.metamodel.model.MetaPropertyPath)2 Range (io.jmix.core.metamodel.model.Range)2 Notifications (io.jmix.ui.Notifications)2 io.jmix.ui.component (io.jmix.ui.component)2 Table (io.jmix.ui.component.Table)2 io.jmix.ui.component.data (io.jmix.ui.component.data)2 EntityDataGridItems (io.jmix.ui.component.data.meta.EntityDataGridItems)2 ByteArrayDataProvider (io.jmix.ui.download.ByteArrayDataProvider)2 XLS (io.jmix.ui.download.DownloadFormat.XLS)2 XLSX (io.jmix.ui.download.DownloadFormat.XLSX)2 ExportAction (io.jmix.uiexport.action.ExportAction)2 AbstractTableExporter (io.jmix.uiexport.exporter.AbstractTableExporter)2