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.foc.web.modules.business.PrnLayout_BrowserWindowOpenerStreamResource.java

License:Apache License

@Override
public DownloadStream getStream() {
    beforeGetStream();//  w  w  w .j  ava 2  s  .  c o m
    DownloadStream downloadStream = null;
    if (getPrintingAction() != null && getPrintingAction().getLauncher() != null) {
        if (prnLayout != null) {

            //            if(this.prnLayout_Table.getPrintLogoCheckBox() != null){
            //              boolean withLogo = this.prnLayout_Table.getPrintLogoCheckBox().getValue();
            //              this.prnLayout_Table.getPrintingAction().getLauncher().setWithLogo(withLogo);
            //            }

            getPrintingAction().getLauncher().setWithLogo(isWithLogo());
            getPrintingAction().setLaunchedAutomatically(false);

            byte[] bytes = null;
            if (outputFormat == DOC) {
                if (outputFileNameWithoutExtension != null)
                    setFilename(outputFileNameWithoutExtension + ".docx");
                bytes = getPrintingAction().getLauncher().printWordDocument(prnLayout);
                if (bytes != null)
                    setMIMEType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            } else if (outputFormat == RTF) {
                if (outputFileNameWithoutExtension != null)
                    setFilename(outputFileNameWithoutExtension + ".rtf");
                bytes = getPrintingAction().getLauncher().printRTFDocument(prnLayout);
                if (bytes != null)
                    setMIMEType("application/rtf");
            } else {
                if (outputFileNameWithoutExtension != null)
                    setFilename(outputFileNameWithoutExtension + ".pdf");
                bytes = getPrintingAction().getLauncher().web_FillReport(prnLayout, prnLayout.getFileName());
                if (bytes != null)
                    setMIMEType("application/pdf");
            }
            if (bytes != null) {
                setStreamSource(new FStreamSource(bytes));
            }
            downloadStream = super.getStream();
        }
    } else {
        StreamSource source = new StreamSource() {
            @Override
            public InputStream getStream() {
                try {
                    return new ByteArrayInputStream(getErrorMessageAsHTML().getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }
        };
        // second, create a StreamResource and pass the previous StreamResource:
        StreamResource resource = new StreamResource(source, "file.html");
        resource.setMIMEType("text/html; charset=utf-8");
        downloadStream = ((ConnectorResource) resource).getStream();
    }
    return downloadStream;
}

From source file:com.hack23.cia.web.impl.ui.application.views.common.pagelinks.impl.ExternalAttachmentDownloadLink.java

License:Apache License

@Override
public void attach() {
    super.attach();

    final StreamResource.StreamSource source = new StreamResource.StreamSource() {

        /**// www. j av  a 2  s.  c  om
         *
         */
        private static final long serialVersionUID = 1L;

        public InputStream getStream() {

            try {
                return new URL(fileUrl).openStream();
            } catch (final IOException e) {
                LOGGER.warn("Problem opening url:" + fileUrl, e);
                return new ByteArrayInputStream(new byte[0]);
            }
        }
    };

    final StreamResource resource = new StreamResource(source, fileName);

    resource.getStream().setParameter("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
    resource.setMIMEType("application/" + fileType);
    resource.setCacheTime(0);

    setResource(resource);
}

From source file:com.haulmont.cuba.web.filestorage.WebExportDisplay.java

License:Apache License

/**
 * Show/Download resource at client side
 *
 * @param dataProvider ExportDataProvider
 * @param resourceName ResourceName for client side
 * @param exportFormat ExportFormat/*from  w w  w .ja v a 2 s .  c  om*/
 * @see com.haulmont.cuba.gui.export.FileDataProvider
 * @see com.haulmont.cuba.gui.export.ByteArrayDataProvider
 */
@Override
public void show(ExportDataProvider dataProvider, String resourceName, final ExportFormat exportFormat) {
    backgroundWorker.checkUIAccess();

    boolean showNewWindow = this.newWindow;

    if (useViewList) {
        String fileExt;

        if (exportFormat != null) {
            fileExt = exportFormat.getFileExt();
        } else {
            fileExt = FilenameUtils.getExtension(resourceName);
        }

        WebConfig webConfig = configuration.getConfig(WebConfig.class);
        showNewWindow = webConfig.getViewFileExtensions().contains(StringUtils.lowerCase(fileExt));
    }

    if (exportFormat != null) {
        if (StringUtils.isEmpty(FilenameUtils.getExtension(resourceName))) {
            resourceName += "." + exportFormat.getFileExt();
        }
    }

    CubaFileDownloader fileDownloader = AppUI.getCurrent().getFileDownloader();

    StreamResource resource = new StreamResource(dataProvider::provide, resourceName);

    if (exportFormat != null && StringUtils.isNotEmpty(exportFormat.getContentType())) {
        resource.setMIMEType(exportFormat.getContentType());
    } else {
        resource.setMIMEType(FileTypesHelper.getMIMEType(resourceName));
    }

    if (showNewWindow) {
        fileDownloader.viewDocument(resource);
    } else {
        fileDownloader.downloadFile(resource);
    }
}

From source file:com.haulmont.cuba.web.gui.components.WebClasspathResource.java

License:Apache License

@Override
protected void createResource() {
    String name = StringUtils.isNotEmpty(fileName) ? fileName : FilenameUtils.getName(path);

    resource = new StreamResource(() -> AppBeans.get(Resources.class).getResourceAsStream(path), name);

    StreamResource streamResource = (StreamResource) this.resource;

    streamResource.setMIMEType(mimeType);
    streamResource.setCacheTime(cacheTime);
    streamResource.setBufferSize(bufferSize);
}

From source file:com.hris.payroll.alphalist.AlphaListMainUI.java

private Button exportToExcelButton() {
    ExportDataGridToExcel exportGrid = new ExportDataGridToExcel(grid);

    exportToExcelButton.setEnabled(false);
    exportToExcelButton.setWidth("200px");
    exportToExcelButton.setIcon(FontAwesome.EXCLAMATION_CIRCLE);
    exportToExcelButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
    exportToExcelButton.addStyleName(ValoTheme.BUTTON_SMALL);
    exportToExcelButton.addClickListener((Button.ClickEvent e) -> {
        exportGrid.workSheet();// www .  j  a v a 2 s .  c  o m

        StreamResource.StreamSource source = () -> {
            try {
                File f = new File(exportGrid.getFilePath());
                FileInputStream fis = new FileInputStream(f);
                return fis;
            } catch (Exception e1) {
                e1.getMessage();
                return null;
            }
        };

        Date date = new Date();
        String branchName = cs.getBranchById(getBranchId());
        int tradeId = cs.getTradeIdByBranchId(getBranchId());
        String tradeName = cs.getTradeById(tradeId);
        int corporateId = cs.getCorporateIdByTradeId(tradeId);
        String corporateName = cs.getCorporateById(corporateId);

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

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

    return exportToExcelButton;
}

From source file:com.hris.payroll.reports.ReportViewer.java

public ReportViewer(String reportType, int branchId, Date payrollDate) {
    this.reportType = reportType;
    this.branchId = branchId;
    this.payrollDate = payrollDate;

    setWidth("900px");
    setHeight("600px");
    center();/*  ww w . ja v a 2s. c  o  m*/

    StreamResource resource = null;

    switch (reportType) {
    case "Payslip": {
        String filename = "Payslip-" + new Date().getTime() + ".pdf";
        resource = new StreamResource(new PayslipReportPDF(getBranchId(), getPayrollDate()), filename);
        break;
    }

    case "Advances Summary": {
        String filename = "Advances-" + new Date().getTime() + ".pdf";
        resource = new StreamResource(new AdvancesSummaryReportPdf(getBranchId(), getPayrollDate()), filename);
        break;
    }

    default: {
        String filename = "Advances-" + new Date().getTime() + ".pdf";
        resource = new StreamResource(new AdvancesReportPdf(getBranchId(), getPayrollDate(), reportType),
                filename);
        break;
    }
    }

    resource.setMIMEType("application/pdf");

    VerticalLayout v = new VerticalLayout();
    v.setSizeFull();
    v.setSpacing(true);
    v.setMargin(new MarginInfo(false, false, true, false));

    Embedded em = new Embedded();
    em.setSource(resource);
    em.setSizeFull();
    em.setType(Embedded.TYPE_BROWSER);
    v.addComponent(em);
    v.setExpandRatio(em, 1);

    setContent(v);
}

From source file:com.hris.payroll.thirteenthmonth.ExportDataGridToExcel.java

public void workSheet() {
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Sample sheet");

    int rownum = 1;
    for (Object itemId : getDataGrid().getContainerDataSource().getItemIds()) {
        System.out.println("itemId: " + itemId);
    }//ww  w .ja  v  a 2 s  .  com
    for (Object itemId : getDataGrid().getContainerDataSource().getItemIds()) {
        Row row = sheet.createRow(rownum);
        int cellcount = 0;
        if ((rownum - 1) == 0) {
            Row rowHeader = sheet.createRow(rownum - 1);
            for (Object propertyId : getDataGrid().getContainerDataSource().getContainerPropertyIds()) {
                Cell cell = rowHeader.createCell(cellcount);
                if (propertyId.toString().contains("salary")) {
                    if (!propertyId.toString().equals("salary grand total")) {
                        cell.setCellValue(propertyId.toString().replace("salary", "").toUpperCase());
                    } else {
                        cell.setCellValue(propertyId.toString().toUpperCase());
                    }
                } else if (propertyId.toString().contains("tax")) {
                    if (!propertyId.toString().equals("tax grand total")) {
                        cell.setCellValue(propertyId.toString().replace("tax", "").toUpperCase());
                    } else {
                        cell.setCellValue(propertyId.toString().toUpperCase());
                    }
                } else if (propertyId.toString().contains("sss")) {
                    if (!propertyId.toString().equals("sss grand total")) {
                        cell.setCellValue(propertyId.toString().replace("sss", "").toUpperCase());
                    } else {
                        cell.setCellValue(propertyId.toString().toUpperCase());
                    }
                } else if (propertyId.toString().contains("phic")) {
                    if (!propertyId.toString().equals("phic grand total")) {
                        cell.setCellValue(propertyId.toString().replace("phic", "").toUpperCase());
                    } else {
                        cell.setCellValue(propertyId.toString().toUpperCase());
                    }
                } else if (propertyId.toString().contains("hdmf")) {
                    if (!propertyId.toString().equals("hdmf grand total")) {
                        cell.setCellValue(propertyId.toString().replace("hdmf", "").toUpperCase());
                    } else {
                        cell.setCellValue(propertyId.toString().toUpperCase());
                    }
                }

                else {
                    cell.setCellValue(propertyId.toString().toUpperCase());
                }

                sheet.autoSizeColumn(cellcount);
                cellcount++;
            }
        }

        Item item = getDataGrid().getContainerDataSource().getItem(itemId);
        int cellnum = 0;
        for (Object propertyId : item.getItemPropertyIds()) {
            Cell cell = row.createCell(cellnum);
            if (propertyId.equals("employee")) {
                cell.setCellValue(item.getItemProperty(propertyId).getValue().toString().toUpperCase());
            } else {
                cell.setCellValue((item.getItemProperty(propertyId).getValue() == null) ? " "
                        : item.getItemProperty(propertyId).getValue().toString());
            }

            sheet.autoSizeColumn(cellnum);
            cellnum++;
        }
        rownum++;
    }

    FileOutputStream fos;
    try {
        Date date = new Date();
        path = "C:/payroll-files/format-" + date.getTime() + ".xls";
        file = new File(path);
        fos = new FileOutputStream(path);
        workbook.write(fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException ex) {
        ErrorLoggedNotification.showErrorLoggedOnWindow(ex.toString(), this.getClass().getName());
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        ErrorLoggedNotification.showErrorLoggedOnWindow(ex.toString(), this.getClass().getName());
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    }

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

    StreamResource resource = new StreamResource(source, "ThirteenthMonth.xls");
    resource.setMIMEType("application/vnd.ms-office");

}

From source file:com.hris.payroll.thirteenthmonth.ExportDataGridToExcel.java

public StreamResource getExcelStream(ByteArrayOutputStream bos) {
    StreamResource resource = new StreamResource(() -> {
        return new ByteArrayInputStream(bos.toByteArray());
    }, "ThirteenthMonth.xls");
    resource.setMIMEType("application/vnd.ms-office");
    return resource;
}

From source file:com.hris.payroll.thirteenthmonth.ThirteenthMonth.java

private Button exportToExcelButton() {
    exportToExcelButton.setWidth("200px");
    exportToExcelButton.setIcon(FontAwesome.EXCLAMATION_CIRCLE);
    exportToExcelButton.addStyleName(ValoTheme.BUTTON_PRIMARY);
    exportToExcelButton.addStyleName(ValoTheme.BUTTON_SMALL);
    exportToExcelButton.addClickListener((Button.ClickEvent e) -> {
        ExportDataGridToExcel exportGrid = new ExportDataGridToExcel(grid);
        exportGrid.workSheet();//  w w w .j  ava  2 s  . com

        StreamResource.StreamSource source = () -> {
            try {
                File f = new File(exportGrid.getFilePath());
                FileInputStream fis = new FileInputStream(f);
                return fis;
            } catch (Exception e1) {
                e1.getMessage();
                return null;
            }
        };

        Date date = new Date();
        String branchName = cs.getBranchById(getBranchId());
        int tradeId = cs.getTradeIdByBranchId(getBranchId());
        String tradeName = cs.getTradeById(tradeId);
        int corporateId = cs.getCorporateIdByTradeId(tradeId);
        String corporateName = cs.getCorporateById(corporateId);

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

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

    return exportToExcelButton;
}

From source file:com.hris.payroll.thirteenthmonth.ThirteenthMonth.java

StreamResource streamResource(String path) {
    StreamResource.StreamSource source = () -> {
        try {/*from   w  w  w.  j a va  2  s  .  c om*/
            File f = new File(path);
            FileInputStream fis = new FileInputStream(f);
            return fis;
        } catch (Exception e1) {
            e1.getMessage();
            return null;
        }
    };

    StreamResource resource = new StreamResource(source, path);
    resource.setMIMEType("application/vnd.ms-excel");

    return resource;
}