Example usage for com.vaadin.server StreamResource StreamResource

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

Introduction

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

Prototype

public StreamResource(StreamSource streamSource, String filename) 

Source Link

Document

Creates a new stream resource for downloading from stream.

Usage

From source file:annis.gui.frequency.FrequencyResultPanel.java

License:Apache License

private void showResult(FrequencyTable table) {
    if (queryPanel != null) {
        queryPanel.notifiyQueryFinished();
    }//from   w  w  w.  j  av  a2  s  .  c om
    recreateTable(table);

    btDownloadCSV.setVisible(true);
    FileDownloader downloader = new FileDownloader(
            new StreamResource(new CSVResource(table, query.getFrequencyDefinition()), "frequency.txt"));
    downloader.extend(btDownloadCSV);

    chart.setVisible(true);
    FrequencyTable clippedTable = table;
    if (clippedTable.getEntries().size() > MAX_NUMBER_OF_CHART_ITEMS) {
        List<FrequencyTable.Entry> entries = new ArrayList<>(clippedTable.getEntries());

        clippedTable = new FrequencyTable();
        clippedTable.setEntries(entries.subList(0, MAX_NUMBER_OF_CHART_ITEMS));
        clippedTable.setSum(table.getSum());
        chart.setCaption("Showing historgram of top " + MAX_NUMBER_OF_CHART_ITEMS
                + " results, see table below for complete dataset.");
    }
    chart.setFrequencyData(clippedTable);

}

From source file:annis.gui.ReportBugWindow.java

License:Apache License

private void addScreenshotPreview(Layout layout, final byte[] rawImage, String mimeType) {
    StreamResource res = new StreamResource(new ScreenDumpStreamSource(rawImage),
            "screendump_" + UUID.randomUUID().toString() + ".png");
    res.setMIMEType(mimeType);//from  w w  w. j a v a 2  s .c  om

    final Image imgScreenshot = new Image("Attached screenshot", res);
    imgScreenshot.setAlternateText(
            "Screenshot of the ANNIS browser window, " + "no other window or part of the desktop is captured.");
    imgScreenshot.setVisible(false);
    imgScreenshot.setWidth("100%");

    Button btShowScreenshot = new Button("Show attached screenshot",
            new ShowScreenshotClickListener(imgScreenshot));
    btShowScreenshot.addStyleName(BaseTheme.BUTTON_LINK);
    btShowScreenshot.setIcon(FontAwesome.PLUS_SQUARE_O);

    layout.addComponent(btShowScreenshot);
    layout.addComponent(imgScreenshot);
}

From source file:annis.visualizers.component.AbstractDotVisualizer.java

License:Apache License

@Override
public ImagePanel createComponent(final VisualizerInput visInput, VisualizationToggle visToggle) {
    try {/*from   ww  w. j  a  v a 2 s.  c  om*/

        final PipedOutputStream out = new PipedOutputStream();
        final PipedInputStream in = new PipedInputStream(out);

        new Thread(new Runnable() {
            @Override
            public void run() {
                writeOutput(visInput, out);
            }
        }).start();

        String fileName = "dotvis_" + new Random().nextInt(Integer.MAX_VALUE) + ".png";
        StreamResource resource = new StreamResource(new StreamResource.StreamSource() {

            @Override
            public InputStream getStream() {
                return in;
            }
        }, fileName);

        Embedded emb = new Embedded("", resource);
        emb.setMimeType("image/png");
        emb.setSizeFull();
        emb.setStandby("loading image");
        emb.setAlternateText("DOT graph visualization");
        return new ImagePanel(emb);

    } catch (IOException ex) {
        log.error(null, ex);
    }
    return new ImagePanel(new Embedded());
}

From source file:annis.visualizers.component.AbstractImageVisualizer.java

License:Apache License

@Override
public ImagePanel createComponent(final VisualizerInput visInput, VisualizationToggle visToggle) {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    writeOutput(visInput, out);//from  www. j  a  v a2 s.  c  o m

    String fileName = "vis_" + UUID.randomUUID().toString() + ".png";
    StreamResource resource = new StreamResource(new StreamResource.StreamSource() {
        @Override
        public InputStream getStream() {
            return new ByteArrayInputStream(out.toByteArray());
        }
    }, fileName);

    Embedded emb = new Embedded("", resource);
    emb.setMimeType(getContentType());
    emb.setSizeUndefined();
    emb.setStandby("loading image");
    emb.setAlternateText("Visualization of the result");

    return new ImagePanel(emb);
}

From source file:com.adonis.ui.menu.Menu.java

private void showUploadedImage(UploadField upload, Image image, String fileName, String newNameFile)
        throws IOException {
    File value = (File) upload.getValue();
    //copy to resources
    FileReader.copyFile(value.getAbsolutePath().toString(), VaadinUtils.getResourcePath(newNameFile));
    //copy to server directory
    FileReader.createDirectoriesFromCurrent(getInitialPath());
    FileReader.copyFile(value.getAbsolutePath().toString(),
            VaadinUtils.getInitialPath() + File.separator + newNameFile);
    FileInputStream fileInputStream = new FileInputStream(value);
    long byteLength = value.length(); //bytecount of the file-content

    byte[] filecontent = new byte[(int) byteLength];
    fileInputStream.read(filecontent, 0, (int) byteLength);
    final byte[] data = filecontent;

    StreamResource resource = new StreamResource(new StreamResource.StreamSource() {
        @Override/*  w w w .ja v  a2 s.  co  m*/
        public InputStream getStream() {
            return new ByteArrayInputStream(data);
        }
    }, fileName);

    image.setSource(resource);
    image.setVisible(true);
}

From source file:com.esofthead.mycollab.community.ui.chart.JFreeChartWrapper.java

License:Open Source License

@Override
public Resource getSource() {
    if (res == null) {
        StreamSource streamSource = new StreamResource.StreamSource() {
            private ByteArrayInputStream bytestream = null;

            ByteArrayInputStream getByteStream() {
                if (chart != null && bytestream == null) {
                    int width = getGraphWidth();
                    int height = getGraphHeight();

                    if (mode == RenderingMode.SVG) {

                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = null;
                        try {
                            docBuilder = docBuilderFactory.newDocumentBuilder();
                        } catch (ParserConfigurationException e1) {
                            throw new RuntimeException(e1);
                        }/*from   w  w  w. j a  v  a2s. c  o m*/
                        Document document = docBuilder.newDocument();
                        Element svgelem = document.createElement("svg");
                        document.appendChild(svgelem);

                        // Create an instance of the SVG Generator
                        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

                        // draw the chart in the SVG generator
                        chart.draw(svgGenerator, new Rectangle(width, height));
                        Element el = svgGenerator.getRoot();
                        el.setAttributeNS(null, "viewBox", "0 0 " + width + " " + height + "");
                        el.setAttributeNS(null, "style", "width:100%;height:100%;");
                        el.setAttributeNS(null, "preserveAspectRatio", getSvgAspectRatio());

                        // Write svg to buffer
                        ByteArrayOutputStream baoutputStream = new ByteArrayOutputStream();
                        Writer out;
                        try {
                            OutputStream outputStream = gzipEnabled ? new GZIPOutputStream(baoutputStream)
                                    : baoutputStream;
                            out = new OutputStreamWriter(outputStream, "UTF-8");
                            /*
                            * don't use css, FF3 can'd deal with the result
                            * perfectly: wrong font sizes
                            */
                            boolean useCSS = false;
                            svgGenerator.stream(el, out, useCSS, false);
                            outputStream.flush();
                            outputStream.close();
                            bytestream = new ByteArrayInputStream(baoutputStream.toByteArray());
                        } catch (Exception e) {
                            log.error("Error while generating SVG chart", e);
                        }
                    } else {
                        // Draw png to bytestream
                        try {
                            byte[] bytes = ChartUtilities.encodeAsPNG(chart.createBufferedImage(width, height));
                            bytestream = new ByteArrayInputStream(bytes);
                        } catch (Exception e) {
                            log.error("Error while generating PNG chart", e);
                        }

                    }

                } else {
                    bytestream.reset();
                }
                return bytestream;
            }

            @Override
            public InputStream getStream() {
                return getByteStream();
            }
        };

        res = new StreamResource(streamSource, String.format("graph%d", System.currentTimeMillis())) {

            @Override
            public int getBufferSize() {
                if (getStreamSource().getStream() != null) {
                    try {
                        return getStreamSource().getStream().available();
                    } catch (IOException e) {
                        log.warn("Error while get stream info", e);
                        return 0;
                    }
                } else {
                    return 0;
                }
            }

            @Override
            public long getCacheTime() {
                return 0;
            }

            @Override
            public String getFilename() {
                if (mode == RenderingMode.PNG) {
                    return super.getFilename() + ".png";
                } else {
                    return super.getFilename() + (gzipEnabled ? ".svgz" : ".svg");
                }
            }

            @Override
            public DownloadStream getStream() {
                DownloadStream downloadStream = new DownloadStream(getStreamSource().getStream(), getMIMEType(),
                        getFilename());
                if (gzipEnabled && mode == RenderingMode.SVG) {
                    downloadStream.setParameter("Content-Encoding", "gzip");
                }
                return downloadStream;
            }

            @Override
            public String getMIMEType() {
                if (mode == RenderingMode.PNG) {
                    return "image/png";
                } else {
                    return "image/svg+xml";
                }
            }
        };
    }
    return res;
}

From source file:com.esofthead.mycollab.module.project.view.bug.BugListViewImpl.java

License:Open Source License

private ComponentContainer constructTableActionControls() {
    final MHorizontalLayout layout = new MHorizontalLayout().withWidth("100%");

    final Label lbEmpty = new Label("");
    layout.with(lbEmpty).expand(lbEmpty);

    MHorizontalLayout buttonControls = new MHorizontalLayout();
    layout.addComponent(buttonControls);

    Button customizeViewBtn = new Button("", new Button.ClickListener() {
        private static final long serialVersionUID = 1L;

        @Override//from   w w  w.j a v a 2 s.  co  m
        public void buttonClick(ClickEvent event) {
            UI.getCurrent().addWindow(new BugListCustomizeWindow(BugListView.VIEW_DEF_ID, tableItem));

        }
    });
    customizeViewBtn.setIcon(FontAwesome.COG);
    customizeViewBtn.setDescription("Layout Options");
    customizeViewBtn.setStyleName(UIConstants.THEME_GRAY_LINK);
    buttonControls.addComponent(customizeViewBtn);

    PopupButton exportButtonControl = new PopupButton();
    exportButtonControl.addStyleName(UIConstants.THEME_GRAY_LINK);
    exportButtonControl.setIcon(FontAwesome.EXTERNAL_LINK);
    exportButtonControl.setDescription(AppContext.getMessage(FileI18nEnum.EXPORT_FILE));

    VerticalLayout popupButtonsControl = new VerticalLayout();
    exportButtonControl.setContent(popupButtonsControl);

    Button exportPdfBtn = new Button(AppContext.getMessage(FileI18nEnum.PDF));

    StreamWrapperFileDownloader fileDownloader = new StreamWrapperFileDownloader(new StreamResourceFactory() {

        @Override
        public StreamResource getStreamResource() {
            String title = "Bugs of Project " + ((CurrentProjectVariables.getProject() != null
                    && CurrentProjectVariables.getProject().getName() != null)
                            ? CurrentProjectVariables.getProject().getName()
                            : "");
            BugSearchCriteria searchCriteria = new BugSearchCriteria();
            searchCriteria.setProjectId(
                    new NumberSearchField(SearchField.AND, CurrentProjectVariables.getProject().getId()));

            return new StreamResource(new SimpleGridExportItemsStreamResource.AllItems<>(title,
                    new RpParameterBuilder(tableItem.getDisplayColumns()), ReportExportType.PDF,
                    ApplicationContextUtil.getSpringBean(BugService.class), searchCriteria, SimpleBug.class),
                    "export.pdf");
        }

    });
    fileDownloader.extend(exportPdfBtn);
    exportPdfBtn.setIcon(FontAwesome.FILE_PDF_O);
    exportPdfBtn.setStyleName("link");
    popupButtonsControl.addComponent(exportPdfBtn);

    Button exportExcelBtn = new Button(AppContext.getMessage(FileI18nEnum.EXCEL));
    StreamWrapperFileDownloader excelDownloader = new StreamWrapperFileDownloader(new StreamResourceFactory() {

        @Override
        public StreamResource getStreamResource() {
            String title = "Bugs of Project " + ((CurrentProjectVariables.getProject() != null
                    && CurrentProjectVariables.getProject().getName() != null)
                            ? CurrentProjectVariables.getProject().getName()
                            : "");
            BugSearchCriteria searchCriteria = new BugSearchCriteria();
            searchCriteria.setProjectId(
                    new NumberSearchField(SearchField.AND, CurrentProjectVariables.getProject().getId()));

            return new StreamResource(new SimpleGridExportItemsStreamResource.AllItems<>(title,
                    new RpParameterBuilder(tableItem.getDisplayColumns()), ReportExportType.EXCEL,
                    ApplicationContextUtil.getSpringBean(BugService.class), searchCriteria, SimpleBug.class),
                    "export.xlsx");
        }
    });
    excelDownloader.extend(exportExcelBtn);
    exportExcelBtn.setIcon(FontAwesome.FILE_EXCEL_O);
    exportExcelBtn.setStyleName("link");
    popupButtonsControl.addComponent(exportExcelBtn);

    Button exportCsvBtn = new Button(AppContext.getMessage(FileI18nEnum.CSV));

    StreamWrapperFileDownloader csvFileDownloader = new StreamWrapperFileDownloader(
            new StreamResourceFactory() {

                @Override
                public StreamResource getStreamResource() {
                    String title = "Bugs of Project " + ((CurrentProjectVariables.getProject() != null
                            && CurrentProjectVariables.getProject().getName() != null)
                                    ? CurrentProjectVariables.getProject().getName()
                                    : "");
                    BugSearchCriteria searchCriteria = new BugSearchCriteria();
                    searchCriteria.setProjectId(new NumberSearchField(SearchField.AND,
                            CurrentProjectVariables.getProject().getId()));

                    return new StreamResource(new SimpleGridExportItemsStreamResource.AllItems<>(title,
                            new RpParameterBuilder(tableItem.getDisplayColumns()), ReportExportType.CSV,
                            ApplicationContextUtil.getSpringBean(BugService.class), searchCriteria,
                            SimpleBug.class), "export.csv");
                }
            });
    csvFileDownloader.extend(exportCsvBtn);

    exportCsvBtn.setIcon(FontAwesome.FILE_TEXT_O);
    exportCsvBtn.setStyleName("link");
    popupButtonsControl.addComponent(exportCsvBtn);

    buttonControls.addComponent(exportButtonControl);
    return layout;
}

From source file:com.esofthead.mycollab.module.project.view.FollowingTicketViewImpl.java

License:Open Source License

private StreamResource constructStreamResource(final ReportExportType exportType) {

    LazyStreamSource streamSource = new LazyStreamSource() {
        private static final long serialVersionUID = 1L;

        @Override/*from   www.j av a 2s  . c  o m*/
        protected StreamSource buildStreamSource() {
            return new SimpleGridExportItemsStreamResource.AllItems<>("Following Tickets Report",
                    new RpParameterBuilder(ticketTable.getDisplayColumns()), exportType,
                    ApplicationContextUtil.getSpringBean(ProjectFollowingTicketService.class),
                    new FollowingTicketSearchCriteria(), FollowingTicket.class);
        }
    };

    return new StreamResource(streamSource, ExportItemsStreamResource.getDefaultExportFileName(exportType));
}

From source file:com.esofthead.mycollab.module.project.view.page.PageReadViewImpl.java

License:Open Source License

private StreamResource getPDFStream() {
    return new StreamResource(new StreamSource() {
        private static final long serialVersionUID = 1L;

        public InputStream getStream() {
            try {
                return new FileInputStream(writePdf());
            } catch (Exception e) {
                LOG.error("Error while export PDF", e);
                return null;
            }/*w  w  w  .j a v  a2  s. com*/
        }
    }, "Document.pdf");
}

From source file:com.esofthead.mycollab.module.project.view.task.TaskGroupDisplayViewImpl.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
private StreamResource constructStreamResource(ReportExportType exportType) {
    final String title = "Tasks report of project " + ((CurrentProjectVariables.getProject() != null
            && CurrentProjectVariables.getProject().getName() != null)
                    ? CurrentProjectVariables.getProject().getName()
                    : "");

    final TaskListSearchCriteria tasklistSearchCriteria = new TaskListSearchCriteria();
    tasklistSearchCriteria/*from  ww  w  . ja  v a 2s .  c om*/
            .setProjectId(new NumberSearchField(SearchField.AND, CurrentProjectVariables.getProject().getId()));

    StreamResource res;
    if (exportType.equals(ReportExportType.PDF)) {
        res = new StreamResource(new ExportTaskListStreamResource(title, exportType,
                ApplicationContextUtil.getSpringBean(ProjectTaskListService.class), tasklistSearchCriteria,
                null), "task_list.pdf");
    } else if (exportType.equals(ReportExportType.CSV)) {
        res = new StreamResource(new ExportTaskListStreamResource(title, exportType,
                ApplicationContextUtil.getSpringBean(ProjectTaskListService.class), tasklistSearchCriteria,
                null), "task_list.csv");
    } else {
        res = new StreamResource(new ExportTaskListStreamResource(title, exportType,
                ApplicationContextUtil.getSpringBean(ProjectTaskListService.class), tasklistSearchCriteria,
                null), "task_list.xls");
    }

    return res;
}