Java 类com.vaadin.server.StreamResource 实例源码

项目:crawling-framework    文件:NamedQueryImportExport.java   
public static StreamResource getNamedQueriesExportStream() {
    StreamResource.StreamSource source = (StreamResource.StreamSource) () -> {
        LOG.info("Exporting http sources data...");
        List<NamedQuery> namedQueries = ElasticSearch.getNamedQueryOperations().all();
        StringWriter writer = new StringWriter();
        CSVWriter csvWriter = CSVUtils.createDefaultWriter(writer);
        csvWriter.writeNext(CSV_COLUMNS);
        for (NamedQuery nq : namedQueries) {
            csvWriter.writeNext(new String[]{
                    nq.getName(),
                    nq.getNotStemmedCaseSensitive(),
                    nq.getNotStemmedCaseInSensitive(),
                    nq.getStemmedCaseSensitive(),
                    nq.getStemmedCaseInSensitive(),
                    nq.getAdvanced()
            });
        }
        String csv = writer.getBuffer().toString();
        return new ByteArrayInputStream(csv.getBytes(Charsets.UTF_8));

    };
    return new StreamResource(source, "named-queries-exported-" +
            new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".csv");
}
项目:crawling-framework    文件:HttpSourceImportExport.java   
public static StreamResource getHttpSourcesExportStream() {
    StreamResource.StreamSource source = (StreamResource.StreamSource) () -> {
        LOG.info("Exporting http sources data...");
        List<HttpSource> sources = ElasticSearch.getHttpSourceOperations().all();
        StringWriter writer = new StringWriter();
        CSVWriter csvWriter = CSVUtils.createDefaultWriter(writer);
        // Header line creation
        csvWriter.writeNext(CSV_COLUMNS);
        for (HttpSource ld : sources) {
            csvWriter.writeNext(mapHttpSourceToCsvRow(ld));
        }
        String csv = writer.getBuffer().toString();
        return new ByteArrayInputStream(csv.getBytes(Charsets.UTF_8));

    };
    return new StreamResource(source, "http-sources-exported-" +
            new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".csv");
}
项目:crawling-framework    文件:HttpSourceTestImportExport.java   
public static StreamResource getHttpSourcesExportStream() {
    StreamResource.StreamSource source = (StreamResource.StreamSource) () -> {
        LOG.info("Exporting http sources data...");
        List<HttpSourceTest> tests = ElasticSearch.getHttpSourceTestOperations().all();
        StringWriter writer = new StringWriter();
        CSVWriter csvWriter = CSVUtils.createDefaultWriter(writer);
        // Header line creation
        csvWriter.writeNext(CSV_COLUMNS);
        for (HttpSourceTest hst : tests) {
            csvWriter.writeNext(mapHttpSourceTestToCsvRow(hst));
        }
        String csv = writer.getBuffer().toString();
        return new ByteArrayInputStream(csv.getBytes(Charsets.UTF_8));

    };
    return new StreamResource(source, "http-source-tests-exported-" +
            new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".csv");
}
项目:osc-core    文件:SummaryLayout.java   
@SuppressWarnings("serial")
private Button createDownloadButton() {
    this.download = new Button(VmidcMessages.getString(VmidcMessages_.SUMMARY_DOWNLOAD_LOG)) {
        @Override
        public void setEnabled(boolean enabled) {
            if (enabled) {
                // because setEnabled(false) calls are ignored and button is disabled
                // on client because of setDisableOnClick(true), by doing this we
                // make sure that the button is actually disabled so that setEnabled(true)
                // has effect
                getUI().getConnectorTracker().getDiffState(this).put("enabled", false);
                super.setEnabled(enabled);
            }
        }
    };
    SummaryLayout.this.download.setDisableOnClick(true);
    if (this.checkbox != null && this.checkbox.getValue()) {
        this.download.setCaption(VmidcMessages.getString(VmidcMessages_.SUMMARY_DOWNLOAD_BUNDLE));
    }
    StreamResource zipStream = getZipStream();
    FileDownloader fileDownloader = new FileDownloader(zipStream);
    fileDownloader.extend(this.download);
    return this.download;
}
项目:live-image-editor    文件:LiveImageEditor.java   
/**
 * Sets the image to be edited.
 */
public void setImage(final byte[] imageData) {
    this.imageData = imageData;
    String imageFileName = "image-file-name-" + getConnectorId();
    StreamResource resource = new StreamResource(new StreamResource.StreamSource() {
        @Override
        public InputStream getStream() {
            return new ByteArrayInputStream(imageData);
        }
    }, imageFileName);

    setResource(IMAGE_KEY, resource);
    String imageUrl = getResourceUrl(IMAGE_KEY);
    callFunction("setImageUrl", imageUrl);
    callFunction("setBackgroundColor", red, green, blue);
}
项目:kumoreg    文件:PrintBadgeWindow.java   
public void showBadgesInBrowser(List<Attendee> attendeeList) {
    if (attendeeList.size() > 0) {
        StreamResource.StreamSource source = handler.getBadgeFormatter(this, attendeeList);
        String filename = "testbadge" + System.currentTimeMillis() + ".pdf";
        StreamResource resource = new StreamResource(source, filename);

        resource.setMIMEType("application/pdf");
        resource.getStream().setParameter("Content-Disposition", "attachment; filename="+filename);

        Window window = new Window();
        window.setWidth(800, Sizeable.Unit.PIXELS);
        window.setHeight(600, Sizeable.Unit.PIXELS);
        window.setModal(true);
        window.center();
        BrowserFrame pdf = new BrowserFrame("test", resource);
        pdf.setSizeFull();

        window.setContent(pdf);
        getUI().addWindow(window);
    } else {
        Notification.show("No attendees selected");
    }
}
项目:cuba    文件:WebEmbedded.java   
@Override
public void setSource(String fileName, final InputStream src) {
    if (src != null) {
        resource = new StreamResource((StreamResource.StreamSource) () -> {
            try {
                src.reset();
            } catch (IOException e) {
                Logger log = LoggerFactory.getLogger(WebEmbedded.this.getClass());
                log.debug("Ignored IOException on stream reset", e);
            }
            return src;
        }, fileName);
        component.setSource(resource);
    } else {
        resetSource();
    }
}
项目:cuba    文件:WebEmbedded.java   
protected void provideType() {
    switch (type) {
        case OBJECT:
            component.setType(com.vaadin.ui.Embedded.TYPE_OBJECT);
            break;
        case IMAGE:
            component.setType(com.vaadin.ui.Embedded.TYPE_IMAGE);
            break;
        case BROWSER:
            component.setType(com.vaadin.ui.Embedded.TYPE_BROWSER);
            if (resource == null) {
                component.setSource(new StreamResource((StreamResource.StreamSource) () -> {
                    return new ByteArrayInputStream("<html></html>".getBytes());
                }, UUID.randomUUID() + ".html"));
            }
            break;
    }
}
项目:cuba    文件:WebFileDescriptorResource.java   
@Override
protected void createResource() {
    String name = StringUtils.isNotEmpty(fileName) ? fileName : fileDescriptor.getName();

    resource = new StreamResource(() -> {
        try {
            return new ByteArrayDataProvider(AppBeans.get(FileStorageService.class).loadFile(fileDescriptor))
                    .provide();
        } catch (FileStorageException e) {
            throw new RuntimeException(FILE_STORAGE_EXCEPTION_MESSAGE, e);
        }
    }, name);

    StreamResource streamResource = (StreamResource) this.resource;

    streamResource.setCacheTime(cacheTime);
    streamResource.setBufferSize(bufferSize);
}
项目:bookery    文件:BookDetailLayout.java   
public void loadData(BookEntry bookEntry) {
    this.bookEntry = bookEntry;
    titleLabel.setValue(bookEntry.getTitle() + "-" + bookEntry.getAuthor());
    descriptionLabel.setValue(bookEntry.getDescription());
    StreamResource.StreamSource source = new ByteStreamResource(bookEntry.getCover());
    image.setSource(new StreamResource(source, bookEntry.getId() + ".png"));
    likeButton.setCaption(bookEntry.getLikes() + " likes");
    downloadCount.setValue(bookEntry.getDownloads() + " downloads");
    try {
        byte[] data = presenter.getEbookFile(bookEntry.getId());
        fileDownloader.setFileDownloadResource(new StreamResource(new BookStreamSource(data), bookEntry.getTitle() + "-" + bookEntry.getAuthor()+".epub"));
    } catch(SolrServerException ex) {
        logger.error(ex, ex);
    }

    if (presenter.isOnWatchList(bookEntry, SecurityUtils.getSubject().getPrincipal().toString())) {
        watchListButton.setCaption("vergessen");
        watchListButton.setIcon(FontAwesome.STAR);
    }
    else {
        watchListButton.setCaption("merken");
        watchListButton.setIcon(FontAwesome.STAR_O);
    }

}
项目:incubator-openaz    文件:PolicyEditor.java   
protected void initializeDownload() {
    //
    // Create a stream resource pointing to the file
    //
    StreamResource r = new StreamResource(new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                return new FileInputStream(self.file);
            } catch (Exception e) {
                logger.error("Failed to open input stream " + self.file);
            }
            return null;
        }
    }, self.file.getName());
    r.setCacheTime(-1);
    r.setMIMEType("application/xml");
    //
    // Extend a downloader to attach to the Export Button
    //
    FileDownloader downloader = new FileDownloader(r);
    downloader.extend(this.buttonExport);
}
项目:kumoreg    文件:PrintBadgeWindow.java   
public void showBadgesInBrowser(List<Attendee> attendeeList) {
    if (attendeeList.size() > 0) {
        StreamResource.StreamSource source = handler.getBadgeFormatter(this, attendeeList);
        String filename = "testbadge" + System.currentTimeMillis() + ".pdf";
        StreamResource resource = new StreamResource(source, filename);

        resource.setMIMEType("application/pdf");
        resource.getStream().setParameter("Content-Disposition", "attachment; filename="+filename);

        Window window = new Window();
        window.setWidth(800, Sizeable.Unit.PIXELS);
        window.setHeight(600, Sizeable.Unit.PIXELS);
        window.setModal(true);
        window.center();
        BrowserFrame pdf = new BrowserFrame("test", resource);
        pdf.setSizeFull();

        window.setContent(pdf);
        getUI().addWindow(window);
    } else {
        Notification.show("No attendees selected");
    }
}
项目:jain-I18n    文件:JImage.java   
protected Component initContent() {
    layout = new HorizontalLayout();
    layout.setSpacing(true);
    layout.setWidth("100%");

    if (super.getInternalValue() != null) {
        createImage();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = "myfilename-" + df.format(new Date()) + ".png";
        JStreamSource source = new JStreamSource(new ByteArrayInputStream(super.getInternalValue()));
        image.setSource(new StreamResource(source, fileName));
        image.markAsDirty();
    } 

    if (!isReadOnly()) {
        layout.addComponent(uploader);
        layout.setComponentAlignment(uploader, Alignment.MIDDLE_CENTER);
    }
    return layout;
}
项目:metl    文件:ReleasesView.java   
protected void downloadExport(final String export, String filename) {

        StreamSource ss = new StreamSource() {
            private static final long serialVersionUID = 1L;

            public InputStream getStream() {
                try {
                    return new ByteArrayInputStream(export.getBytes(Charset.forName("utf-8")));
                } catch (Exception e) {
                    log.error("Failed to export configuration", e);
                    CommonUiUtils.notify("Failed to export configuration.", Type.ERROR_MESSAGE);
                    return null;
                }
            }
        };
        String datetime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        StreamResource resource = new StreamResource(ss,
                String.format("%s-config-%s.json", filename, datetime));
        final String KEY = "export";
        setResource(KEY, resource);
        Page.getCurrent().open(ResourceReference.create(resource, this, KEY).getURL(), null);
    }
项目:metl    文件:ExploreDirectoryView.java   
protected Component fileLinkComponent(Table source, Object itemId, Object propertyId) {
    if (itemId instanceof FileInfo) {
        final FileInfo file = (FileInfo) itemId;
        if (!file.isDirectory()) {
            final Button button = new Button(file.getName());
            button.addStyleName(ValoTheme.BUTTON_LINK);
            button.addStyleName(ValoTheme.BUTTON_SMALL);
            button.setIcon(FontAwesome.FILE);
            StreamResource resource = new StreamResource(() -> stream(file), file.getName());
            FileDownloader fileDownloader = new FileDownloader(resource);
            fileDownloader.extend(button);
            return button;
        } else {
            return new Label(file.getName());
        }
    } else {
        return new Label(((DirectoryResource) itemId).getName());

    }
}
项目:metl    文件:EditAgentPanel.java   
protected void exportConfiguration() {
    final String export = context.getImportExportService().exportAgent(agent.getId(), AppConstants.SYSTEM_USER);
    StreamSource ss = new StreamSource() {
        private static final long serialVersionUID = 1L;

        public InputStream getStream() {
            try {
                return new ByteArrayInputStream(export.getBytes());
            } catch (Exception e) {
                log.error("Failed to export configuration", e);
                CommonUiUtils.notify("Failed to export configuration.", Type.ERROR_MESSAGE);
                return null;
            }

        }
    };
    String datetime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    StreamResource resource = new StreamResource(ss,
            String.format("%s-config-%s.json", agent.getName().toLowerCase().replaceAll(" ", "-"), datetime));
    final String KEY = "export";
    setResource(KEY, resource);
    Page.getCurrent().open(ResourceReference.create(resource, this, KEY).getURL(), null);
}
项目:metl    文件:ExecutionRunPanel.java   
protected void download() {
    String stepId = (String) stepTable.getSelectedRow();
    if (stepId != null) {
        final File file = executionService.getExecutionStepLog(stepId);
        StreamSource ss = new StreamSource() {
            private static final long serialVersionUID = 1L;

            public InputStream getStream() {
                try {
                    return new FileInputStream(file);
                } catch (Exception e) {
                    log.error("Failed to download log file", e);
                    CommonUiUtils.notify("Failed to download log file", Type.ERROR_MESSAGE);
                    return null;
                }
            }
        };
        StreamResource resource = new StreamResource(ss, file.getName());
        final String KEY = "export";
        setResource(KEY, resource);
        Page.getCurrent().open(ResourceReference.create(resource, this, KEY).getURL(), null);
    }
}
项目:metl    文件:EditFlowPalette.java   
protected void addItemToFlowPanelSection(String labelName, String componentType, VerticalLayout componentLayout, StreamResource icon,
        String componentId) {

    FlowPaletteItem paletteItem = new FlowPaletteItem(labelName);
    if (componentId != null) {
        paletteItem.setShared(true);
        paletteItem.setComponentId(componentId);
    } else {
        paletteItem.setComponentType(componentType);
        paletteItem.setShared(false);
    }
    paletteItem.setIcon(icon);
    paletteItem.addStyleName(ValoTheme.BUTTON_ICON_ALIGN_TOP);
    paletteItem.addStyleName(ValoTheme.BUTTON_BORDERLESS_COLORED);
    paletteItem.addStyleName("leftAligned");
    paletteItem.setWidth(100, Unit.PERCENTAGE);
    DragAndDropWrapper wrapper = new DragAndDropWrapper(paletteItem);
    wrapper.setSizeUndefined();
    wrapper.setDragStartMode(DragStartMode.WRAPPER);
    componentLayout.addComponent(wrapper);
    componentLayout.setComponentAlignment(wrapper, Alignment.TOP_CENTER);

}
项目:metl    文件:ExportDialog.java   
protected void downloadExport(final String export, String filename) {

        StreamSource ss = new StreamSource() {
            private static final long serialVersionUID = 1L;

            public InputStream getStream() {
                try {
                    return new ByteArrayInputStream(export.getBytes(Charset.forName("utf-8")));
                } catch (Exception e) {
                    log.error("Failed to export configuration", e);
                    CommonUiUtils.notify("Failed to export configuration.", Type.ERROR_MESSAGE);
                    return null;
                }
            }
        };
        String datetime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        StreamResource resource = new StreamResource(ss, String.format("%s-config-%s.json", filename, datetime));
        final String KEY = "export";
        setResource(KEY, resource);
        Page.getCurrent().open(ResourceReference.create(resource, this, KEY).getURL(), null);
    }
项目:mycollab    文件:FollowingTicketViewImpl.java   
private StreamResource constructStreamResource(final ReportExportType exportType) {
    LazyStreamSource streamSource = new LazyStreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        protected StreamSource buildStreamSource() {
            SimpleReportTemplateExecutor reportTemplateExecutor = new SimpleReportTemplateExecutor.AllItems<>(
                    UserUIContext.getUserTimeZone(), UserUIContext.getUserLocale(), "Following Tickets",
                    new RpFieldsBuilder(ticketTable.getDisplayColumns()), exportType, FollowingTicket.class,
                    AppContextUtil.getSpringBean(ProjectFollowingTicketService.class));
            //TODO: correct the report of following tickets
            return null;
        }
    };

    return new StreamResource(streamSource, exportType.getDefaultFileName());
}
项目:mycollab    文件:DefaultMassEditActionHandler.java   
@Override
public StreamResource buildStreamResource(ReportExportType exportType) {
    IPagedBeanTable pagedBeanTable = ((IListView) presenter.getView()).getPagedBeanTable();
    final Map<String, Object> additionalParameters = new HashMap<>();
    additionalParameters.put("siteUrl", AppUI.getSiteUrl());
    additionalParameters.put(SimpleReportTemplateExecutor.CRITERIA, presenter.searchCriteria);
    ReportTemplateExecutor reportTemplateExecutor;
    if (presenter.isSelectAll) {
        reportTemplateExecutor = new SimpleReportTemplateExecutor.AllItems(UserUIContext.getUserTimeZone(),
                UserUIContext.getUserLocale(), getReportTitle(),
                new RpFieldsBuilder(pagedBeanTable.getDisplayColumns()), exportType, getReportModelClassType(),
                presenter.getSearchService());
    } else {
        reportTemplateExecutor = new SimpleReportTemplateExecutor.ListData(UserUIContext.getUserTimeZone(),
                UserUIContext.getUserLocale(), getReportTitle(),
                new RpFieldsBuilder(pagedBeanTable.getDisplayColumns()), exportType, presenter.getSelectedItems(),
                getReportModelClassType());
    }
    return new StreamResource(new ReportStreamSource(reportTemplateExecutor) {
        @Override
        protected void initReportParameters(Map<String, Object> parameters) {
            parameters.putAll(additionalParameters);
        }
    }, exportType.getDefaultFileName());
}
项目:XACML    文件:PolicyEditor.java   
protected void initializeDownload() {
    //
    // Create a stream resource pointing to the file
    //
    StreamResource r = new StreamResource(new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                return new FileInputStream(self.file);
            } catch (Exception e) {
                logger.error("Failed to open input stream " + self.file);
            }
            return null;
        }
    }, self.file.getName());
    r.setCacheTime(-1);
    r.setMIMEType("application/xml");
    //
    // Extend a downloader to attach to the Export Button
    //
    FileDownloader downloader = new FileDownloader(r);
    downloader.extend(this.buttonExport);
}
项目:RVaadin    文件:RContainer.java   
/**
 * This function is the actual workhorse for
 * {@link RContainer#getEmbeddedGraph}. It gets a Vaadin StreamResource
 * object that contains the corresponding R plot generated by submitting and
 * evaluating the RPlotCall String. The imageName corresponds to the
 * downloadable image name, and device is the format supported by the Cairo
 * graphics engine. The full name of the images shown in the browser are
 * imageName_ISODate_runningId_[sessionId].[device], e.g.
 * 'Image_2012-08-29_001_[bmgolmfgvk].png' to keep them chronologically
 * ordered.
 * 
 * @param RPlotCall
 *            the String to be evaluated by R
 * @param width
 *            plot width in pixels
 * @param height
 *            plot height in pixels
 * @param device
 *            A plot device supported by Cairo ('png','pdf',...)
 * @return The image as Embedded Vaadin object
 */
public StreamResource getImageResource(String RPlotCall, int width,
        int height, String imageName, String device) {

    StreamSource imagesource = new RImageSource(rc, RPlotCall, width,
            height, rSemaphore, device);

    /* Get a systematic name for the image */
    imageCount++;
    String fileName = imageName + "_" + getDateAndCount(imageCount) + "_["
            + sessionID + "]." + device;

    /*
     * Create a resource that uses the stream source and give it a name. The
     * constructor will automatically register the resource with the
     * application.
     */
    StreamResource imageresource = new StreamResource(imagesource, fileName);

    /*
     * Instruct browser not to cache the image. See the Book of Vaadin 6
     * page 131.
     */
    imageresource.setCacheTime(0);
    return imageresource;
}
项目:obog-manager    文件:RequestListView.java   
private StreamResource createCSV2(String subject, List<Attendance> attendances) {
    return new StreamResource(() -> {
        String csv = "名前,コメント\r\n" + attendances.stream().filter(Attendance::isAttend)
                .map(a -> a.getMembership().getName() + "," +
                        a.getComment().replaceAll("\r", "").replaceAll("\n", ""))
                .collect(Collectors.joining("\r\n"));
        try {
            return new ByteArrayInputStream(csv.getBytes("Shift_JIS"));
        } catch (UnsupportedEncodingException e) {
            return new ByteArrayInputStream(csv.getBytes(StandardCharsets.UTF_8));
        }
    }, subject + ".csv");
}
项目:obog-manager    文件:RequestListView.java   
private StreamResource createCSV4(String subject, List<Membership> memberships) {
    return new StreamResource(() -> {
        String csv = "名前,Java 研修,Java 8 研修,Go 研修\r\n" + memberships.stream()
                .map(m -> m.getName() + "," + MemberInfo.safeTerm2Text(m.getJavaTerm()) + "," +
                        MemberInfo.safeTerm2Text(m.getJava8Term()) + "," + MemberInfo.safeTerm2Text(m.getGoTerm()))
                .collect(Collectors.joining("\r\n"));
        try {
            return new ByteArrayInputStream(csv.getBytes("Shift_JIS"));
        } catch (UnsupportedEncodingException e) {
            return new ByteArrayInputStream(csv.getBytes(StandardCharsets.UTF_8));
        }
    }, subject + ".csv");
}
项目:obog-manager    文件:RequestListView.java   
private StreamResource createTXT(String subject, List<Membership> memberships) {
    return new StreamResource(() -> {
        String list = memberships.stream()
                .map(Membership::getName)
                .collect(Collectors.joining("\r\n"));
        try {
            return new ByteArrayInputStream(list.getBytes("Shift_JIS"));
        } catch (UnsupportedEncodingException e) {
            return new ByteArrayInputStream(list.getBytes(StandardCharsets.UTF_8));
        }
    }, subject + ".txt");
}
项目:esup-ecandidat    文件:CommissionParametreView.java   
/** Met a jour le container
 * @param ctrCand
 */
private void miseAJourContainer(Commission commission){
    containerReadOnly.removeAllItems();     
    containerGeneral.removeAllItems();
    containerLettre.removeAllItems();
    labelSignataire.setValue("");
    if (commission != null){
        containerReadOnly.addAll(commissionController.getListPresentation(commission,ConstanteUtils.COMM_TYP_AFF_READONLY));
        containerGeneral.addAll(commissionController.getListPresentation(commission,ConstanteUtils.COMM_TYP_AFF_GEN));
        containerLettre.addAll(commissionController.getListPresentation(commission,ConstanteUtils.COMM_TYP_AFF_LETTRE));
        labelSignataire.setValue(commission.getSignataireComm());
        Fichier file = commission.getFichier();
        if (file!=null){
            StreamResource imageResource =  new StreamResource(new StreamSource() {
                /**serialVersionUID**/
                private static final long serialVersionUID = -4583630655596056637L;

                @Override
                public InputStream getStream() {
                    InputStream is = fileController.getInputStreamFromFichier(file);
                    if (is != null){
                        return is;
                    }
                    return null;
                }
            }, file.getNomFichier());
            imgSignataire.setSource(imageResource);
            btnAddImage.setVisible(false);
            btnDeleteImage.setVisible(true);
        }else{
            imgSignataire.setSource(null);
            btnAddImage.setVisible(true);
            btnDeleteImage.setVisible(false);
        }           
    }       
}
项目:Persephone    文件:LogsPage.java   
private Button getDownloadButton(Application app) {
    // Download logs button : download file
    StreamResource resource = getLogsStream(app);

    // Download logs button
    Button downloadButton = new Button("Download full logfile");

    FileDownloader fileDownloader = new FileDownloader(resource);
    fileDownloader.setOverrideContentType(false);
    fileDownloader.extend(downloadButton);

    // Download logs button : on click
    downloadButton.addClickListener(e -> fileDownloader.setFileDownloadResource(getLogsStream(app)));
    return downloadButton;
}
项目:Persephone    文件:LogsPage.java   
private StreamResource getLogsStream(Application app) {
    return new StreamResource(() -> {
        try (InputStream logsStream = logsService.downloadLogs(app).getInputStream()) {
            return logsStream;
        } catch (IOException ex) {
            throw new ApplicationRuntimeException(app, String.format("Unable to get logs file: %s", ex.getMessage()));
        }
    }, String.format("logs-%s-%s-%s.txt", app.getName(), app.getEnvironment(), (new Date()).getTime()));
}
项目:kumoreg    文件:ReportWindow.java   
private StreamResource getDownloadStream() {
    return new StreamResource((StreamResource.StreamSource) () -> {
        String output = lblReport.getValue();
        if (output == null) { output = "Empty report"; }
        return new ByteArrayInputStream(output.getBytes(Charset.forName("UTF-8")));
    }, generateFilename(title));
}
项目:s3browser    文件:BrowseUI.java   
private void updateDetails(ListEntry item) {
    LOG.info("Display details for {}", item);

    ObjectMetadata objectMetadata = s3Client.getObjectMetadata(item.getBucket(), item.getKey());

    VerticalLayout detailsContent = new VerticalLayout();
    detailsContent.setSpacing(true);
    detailsContent.setMargin(true);
    Label caption = new Label(item.getKey());
    caption.addStyleName(ValoTheme.LABEL_H3);
    detailsContent.addComponent(caption);

    if (objectMetadata.getLastModified() != null) {
        detailsContent.addComponent(buildDetailsTextField("LastModified", objectMetadata.getLastModified().toString()));
    }
    detailsContent.addComponent(buildDetailsTextField("ContentLength", Long.toString(objectMetadata.getContentLength())));
    if (objectMetadata.getContentType() != null) {
        detailsContent.addComponent(buildDetailsTextField("ContentType", objectMetadata.getContentType()));
    }
    if (objectMetadata.getETag() != null) {
        detailsContent.addComponent(buildDetailsTextField("ETag", objectMetadata.getETag()));
    }

    Button downloadButton = new Button("Download");

    FileDownloader fileDownloader = new FileDownloader(new StreamResource(() -> {
        LOG.info("Download {}/{}", item.getBucket(), item.getKey());
        return s3Client.getObject(item.getBucket(), item.getKey()).getObjectContent();
    }, item.getKey()));
    fileDownloader.extend(downloadButton);
    detailsContent.addComponent(downloadButton);

    details.setContent(detailsContent);
}
项目:cuba    文件:WebClasspathResource.java   
@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);
}
项目:cuba    文件:WebClasspathResource.java   
@Override
public void setMimeType(String mimeType) {
    this.mimeType = mimeType;

    if (resource != null) {
        ((StreamResource) resource).setMIMEType(mimeType);
    }
}
项目:cuba    文件:WebEmbedded.java   
@Override
public void setSource(String fileName, final ExportDataProvider dataProvider) {
    if (dataProvider != null) {
        resource = new StreamResource(
                dataProvider::provide,
                fileName
        );
        component.setSource(resource);
    } else {
        resetSource();
    }
}
项目:cuba    文件:WebEmbedded.java   
@Override
public void resetSource() {
    resource = null;
    component.markAsDirty();
    component.setMimeType("image/png");
    component.setType(com.vaadin.ui.Embedded.TYPE_IMAGE);
    component.setSource(new StreamResource(new EmptyStreamSource(), UUID.randomUUID() + ".png"));
}
项目:cuba    文件:WebAbstractStreamSettingsResource.java   
@Override
public void setCacheTime(long cacheTime) {
    this.cacheTime = cacheTime;

    if (resource != null) {
        ((StreamResource) resource).setCacheTime(cacheTime);
    }
}
项目:cuba    文件:WebAbstractStreamSettingsResource.java   
@Override
public void setBufferSize(int bufferSize) {
    this.bufferSize = bufferSize;

    if (resource != null) {
        ((StreamResource) resource).setBufferSize(bufferSize);
    }
}
项目:cuba    文件:WebAbstractStreamSettingsResource.java   
@Override
public void setFileName(String fileName) {
    this.fileName = fileName;

    if (resource != null) {
        ((StreamResource) resource).setFilename(fileName);
    }
}
项目:cuba    文件:WebFileDescriptorResource.java   
@Override
public void setMimeType(String mimeType) {
    this.mimeType = mimeType;

    if (resource != null) {
        ((StreamResource) resource).setMIMEType(mimeType);
    }
}
项目:incubator-openaz    文件:OnDemandFileDownloader.java   
public OnDemandFileDownloader(OnDemandStreamResource resource) {
    super(new StreamResource(resource, ""));
    this.resource = resource;
    if (this.resource == null) {
        throw new NullPointerException("Can't send null resource");
    }
}