Example usage for com.vaadin.server StreamResource setMIMEType

List of usage examples for com.vaadin.server StreamResource setMIMEType

Introduction

In this page you can find the example usage for com.vaadin.server StreamResource setMIMEType.

Prototype

public void setMIMEType(String mimeType) 

Source Link

Document

Sets the mime type of the resource.

Usage

From source file:com.jain.addon.component.download.JDownloader.java

License:Apache License

/**
 * Download actual file/*from www  .  j  ava  2  s  .  c o  m*/
 */
public void download() {
    StreamResource resource = new StreamResource(source, fileName);
    resource.getStream().setParameter("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
    resource.setMIMEType("application/octet-stream");
    resource.setCacheTime(0);
    FileDownloader downloader = new FileDownloader(resource);
    downloader.extend(ui);
}

From source file:com.save.reports.maintenance.MaintenanceReportUI.java

void processExportDataToExcel() {
    ExportDataGridToExcel export = new ExportDataGridToExcel(mrDataGrid);
    export.workSheet();/*from w w  w.  ja va2s  .com*/

    StreamResource.StreamSource source = () -> {
        try {
            File f = new File(export.getFilePath());
            FileInputStream fis = new FileInputStream(f);
            return fis;
        } catch (Exception e) {
            ErrorLoggedNotification.showErrorLoggedOnWindow(e.toString(), this.getClass().getName());
            return null;
        }
    };

    Date date = new Date();

    StreamResource resource = new StreamResource(source, "MaintenanceReport" + "-" + date.getTime() + ".xls");
    resource.setMIMEType("application/vnd.ms-office");

    Page.getCurrent().open(resource, null, false);
}

From source file:com.save.reports.PromoDealAcknowledgementReport.java

public PromoDealAcknowledgementReport(int promoId) {
    this.promoId = promoId;

    setCaption("Acknowledgement Report");
    setWidth("800px");
    setHeight("600px");
    center();/*www.j  a  v a2s .co m*/

    Connection conn = DBConnection.connect();

    HashMap hm = new HashMap();
    hm.put("PROMO_ID", getPromoId());

    InputStream template = this.getClass()
            .getResourceAsStream("/reports/PromoDealAcknowledgementFormReport.jasper");

    try {
        JasperPrint print = JasperFillManager.fillReport(template, hm, conn);
        file = File.createTempFile("output", ".pdf");
        JasperExportManager.exportReportToPdfFile(print, file.getPath());
    } catch (JRException | IOException ex) {
        Logger.getLogger(PromoDealAcknowledgementReport.class.getName()).log(Level.SEVERE, null, ex);
    }

    StreamResource.StreamSource source = () -> {
        try {
            FileInputStream fis = new FileInputStream(file);
            return fis;
        } catch (Exception e) {
            e.getMessage();
            return null;
        }
    };

    StreamResource resource = new StreamResource(source, "PromoDealAcknowledgementForm.pdf");
    resource.setMIMEType("application/pdf");

    VerticalLayout v = new VerticalLayout();
    v.setSizeFull();
    Embedded e = new Embedded();
    e.setSource(resource);
    e.setSizeFull();
    e.setType(Embedded.TYPE_BROWSER);
    v.addComponent(e);

    setContent(v);
}

From source file:com.save.reports.promodeals.PromoDealReportUI.java

void processExportDataToExcel() {
    ExportDataGridToExcel export = new ExportDataGridToExcel(promoDealGrid);
    export.workSheet();//  ww  w.  jav a  2s.  c  om

    StreamResource.StreamSource source = () -> {
        try {
            File f = new File(export.getFilePath());
            FileInputStream fis = new FileInputStream(f);
            return fis;
        } catch (Exception e) {
            ErrorLoggedNotification.showErrorLoggedOnWindow(e.toString(), this.getClass().getName());
            return null;
        }
    };

    Date date = new Date();

    StreamResource resource = new StreamResource(source, "PromoDealsReport" + "-" + date.getTime() + ".xls");
    resource.setMIMEType("application/vnd.ms-office");

    Page.getCurrent().open(resource, null, false);
}

From source file:com.save.reports.reimbursement.ReimbursementReportUI.java

void processExportDataToExcel() {
    ExportDataGridToExcel export = new ExportDataGridToExcel(mrDataGrid);
    export.workSheet();//  w  w w  . j a va2 s.  c om

    StreamResource.StreamSource source = () -> {
        try {
            File f = new File(export.getFilePath());
            FileInputStream fis = new FileInputStream(f);
            return fis;
        } catch (Exception e) {
            ErrorLoggedNotification.showErrorLoggedOnWindow(e.toString(), this.getClass().getName());
            return null;
        }
    };

    Date date = new Date();

    StreamResource resource = new StreamResource(source, "ReimbursementReport" + "-" + date.getTime() + ".xls");
    resource.setMIMEType("application/vnd.ms-office");

    Page.getCurrent().open(resource, null, false);
}

From source file:de.symeda.sormas.ui.utils.DownloadUtil.java

License:Open Source License

@SuppressWarnings("serial")
public static StreamResource createDatabaseExportStreamResource(DatabaseExportView databaseExportView,
        String fileName, String mimeType) {
    StreamResource streamResource = new StreamResource(new StreamSource() {
        @Override//from  w  w w.j  a v a2s. com
        public InputStream getStream() {
            try {
                Map<CheckBox, DatabaseTable> databaseToggles = databaseExportView.getDatabaseTableToggles();
                List<DatabaseTable> tablesToExport = new ArrayList<>();
                for (CheckBox checkBox : databaseToggles.keySet()) {
                    if (checkBox.getValue() == true) {
                        tablesToExport.add(databaseToggles.get(checkBox));
                    }
                }

                String zipPath = FacadeProvider.getExportFacade().generateDatabaseExportArchive(tablesToExport);
                return new BufferedInputStream(Files.newInputStream(new File(zipPath).toPath()));
            } catch (IOException | ExportErrorException e) {
                // TODO This currently requires the user to click the "Export" button again or reload the page as the UI
                // is not automatically updated; this should be changed once Vaadin push is enabled (see #516)
                databaseExportView.showExportErrorNotification();
                return null;
            }
        }
    }, fileName);
    streamResource.setMIMEType(mimeType);
    streamResource.setCacheTime(0);
    return streamResource;
}

From source file:de.symeda.sormas.ui.utils.DownloadUtil.java

License:Open Source License

@SuppressWarnings("serial")
public static StreamResource createFileStreamResource(String filePath, String fileName, String mimeType,
        String errorTitle, String errorText) {
    StreamResource streamResource = new StreamResource(new StreamSource() {
        @Override/*from  w ww .ja  v a2 s .c  om*/
        public InputStream getStream() {
            try {
                return new BufferedInputStream(Files.newInputStream(new File(filePath).toPath()));
            } catch (IOException e) {
                // TODO This currently requires the user to click the "Export" button again or reload the page as the UI
                // is not automatically updated; this should be changed once Vaadin push is enabled (see #516)
                new Notification(errorTitle, errorText, Type.ERROR_MESSAGE, false).show(Page.getCurrent());
                return null;
            }
        }
    }, fileName);
    streamResource.setMIMEType(mimeType);
    streamResource.setCacheTime(0);
    return streamResource;
}

From source file:de.symeda.sormas.ui.utils.DownloadUtil.java

License:Open Source License

@SuppressWarnings("serial")
public static StreamResource createStringStreamResource(String content, String fileName, String mimeType) {
    StreamResource streamResource = new StreamResource(new StreamSource() {
        @Override/*from  w  w  w.  j a  v a  2s.  c  o m*/
        public InputStream getStream() {
            return new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
        }
    }, fileName);
    streamResource.setMIMEType(mimeType);
    return streamResource;
}

From source file:de.symeda.sormas.ui.utils.DownloadUtil.java

License:Open Source License

@SuppressWarnings("serial")
public static <T> StreamResource createCsvExportStreamResource(Class<T> exportRowClass,
        BiFunction<Integer, Integer, List<T>> exportRowsSupplier,
        BiFunction<String, Class<?>, String> propertyIdCaptionFunction, String exportFileName) {
    StreamResource extendedStreamResource = new StreamResource(new StreamSource() {
        @Override//from  w w  w  .j a  v a 2s .co  m
        public InputStream getStream() {
            try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {
                try (CSVWriter writer = CSVUtils.createCSVWriter(
                        new OutputStreamWriter(byteStream, StandardCharsets.UTF_8.name()),
                        FacadeProvider.getConfigFacade().getCsvSeparator())) {

                    // 1. fields in order of declaration - not using Introspector here, because it gives properties in alphabetical order
                    List<Method> readMethods = new ArrayList<Method>();
                    readMethods.addAll(Arrays.stream(exportRowClass.getDeclaredMethods())
                            .filter(m -> (m.getName().startsWith("get") || m.getName().startsWith("is"))
                                    && m.isAnnotationPresent(Order.class))
                            .sorted((a, b) -> Integer.compare(a.getAnnotationsByType(Order.class)[0].value(),
                                    b.getAnnotationsByType(Order.class)[0].value()))
                            .collect(Collectors.toList()));

                    // 2. replace entity fields with all the columns of the entity 
                    Map<Method, Function<T, ?>> subEntityProviders = new HashMap<Method, Function<T, ?>>();
                    for (int i = 0; i < readMethods.size(); i++) {
                        Method method = readMethods.get(i);
                        if (EntityDto.class.isAssignableFrom(method.getReturnType())) {

                            // allows us to access the sub entity
                            Function<T, ?> subEntityProvider = (o) -> {
                                try {
                                    return method.invoke(o);
                                } catch (IllegalAccessException | IllegalArgumentException
                                        | InvocationTargetException e) {
                                    throw new RuntimeException(e);
                                }
                            };

                            // remove entity field
                            readMethods.remove(i);

                            // add columns of the entity
                            List<Method> subReadMethods = Arrays
                                    .stream(method.getReturnType().getDeclaredMethods())
                                    .filter(m -> (m.getName().startsWith("get") || m.getName().startsWith("is"))
                                            && m.isAnnotationPresent(Order.class))
                                    .sorted((a, b) -> Integer.compare(
                                            a.getAnnotationsByType(Order.class)[0].value(),
                                            b.getAnnotationsByType(Order.class)[0].value()))
                                    .collect(Collectors.toList());
                            readMethods.addAll(i, subReadMethods);
                            i--;

                            for (Method subReadMethod : subReadMethods) {
                                subEntityProviders.put(subReadMethod, subEntityProvider);
                            }
                        }
                    }

                    String[] fieldValues = new String[readMethods.size()];
                    for (int i = 0; i < readMethods.size(); i++) {
                        Method method = readMethods.get(i);
                        // field caption
                        String propertyId = method.getName().startsWith("get") ? method.getName().substring(3)
                                : method.getName().substring(2);
                        propertyId = Character.toLowerCase(propertyId.charAt(0)) + propertyId.substring(1);
                        fieldValues[i] = propertyIdCaptionFunction.apply(propertyId, method.getReturnType());
                    }
                    writer.writeNext(fieldValues);

                    int startIndex = 0;
                    List<T> exportRows = exportRowsSupplier.apply(startIndex, DETAILED_EXPORT_STEP_SIZE);
                    while (!exportRows.isEmpty()) {
                        try {
                            for (T exportRow : exportRows) {
                                for (int i = 0; i < readMethods.size(); i++) {
                                    Method method = readMethods.get(i);
                                    Function<T, ?> subEntityProvider = subEntityProviders.getOrDefault(method,
                                            null);
                                    Object entity = subEntityProvider != null
                                            ? subEntityProvider.apply(exportRow)
                                            : exportRow;
                                    // Sub entity might be null
                                    Object value = entity != null ? method.invoke(entity) : null;
                                    if (value == null) {
                                        fieldValues[i] = "";
                                    } else if (value instanceof Date) {
                                        fieldValues[i] = DateHelper.formatLocalShortDate((Date) value);
                                    } else if (value.getClass().equals(boolean.class)
                                            || value.getClass().equals(Boolean.class)) {
                                        fieldValues[i] = DataHelper.parseBoolean((Boolean) value);
                                    } else if (value instanceof Set) {
                                        StringBuilder sb = new StringBuilder();
                                        for (Object o : (Set<?>) value) {
                                            if (sb.length() != 0) {
                                                sb.append(", ");
                                            }
                                            sb.append(o);
                                        }
                                        fieldValues[i] = sb.toString();
                                    } else {
                                        fieldValues[i] = value.toString();
                                    }
                                }
                                writer.writeNext(fieldValues);
                            }
                            ;
                        } catch (InvocationTargetException | IllegalAccessException
                                | IllegalArgumentException e) {
                            throw new RuntimeException(e);
                        }

                        writer.flush();
                        startIndex += DETAILED_EXPORT_STEP_SIZE;
                        exportRows = exportRowsSupplier.apply(startIndex, DETAILED_EXPORT_STEP_SIZE);
                    }
                }
                return new BufferedInputStream(new ByteArrayInputStream(byteStream.toByteArray()));
            } catch (IOException e) {
                // TODO This currently requires the user to click the "Export" button again or reload the page as the UI
                // is not automatically updated; this should be changed once Vaadin push is enabled (see #516)
                new Notification(I18nProperties.getString(Strings.headingExportFailed),
                        I18nProperties.getString(Strings.messageExportFailed), Type.ERROR_MESSAGE, false)
                                .show(Page.getCurrent());
                return null;
            }
        }
    }, exportFileName);
    extendedStreamResource.setMIMEType("text/csv");
    extendedStreamResource.setCacheTime(0);
    return extendedStreamResource;
}

From source file:de.unioninvestment.eai.portal.portlet.crud.mvp.views.DefaultRowEditingFormView.java

License:Apache License

private void updateDownloadLink(ContainerRow row, final ContainerBlob containerBlob,
        final FileMetadata metadata, Link link) {

    if (!containerBlob.isEmpty()) {
        StreamSource streamSource = containerBlob.getStreamSource();
        String displayName = metadata.getCurrentDisplayname(row);
        String fileName = metadata.getCurrentFilename(row);
        String mimeType = metadata.getCurrentMimetype(row);
        StreamResource resource = new StreamResource(streamSource, fileName);
        resource.setMIMEType(mimeType);

        link.setVisible(true);//from   www  .  j a va 2  s . c om
        link.setTargetName("_blank");
        link.setCaption(displayName);
        link.setResource(resource);
    }
}