下面列出了怎么用com.vaadin.server.StreamResource的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected void createResource() {
StringBuilder name = new StringBuilder();
String fullName = StringUtils.isNotEmpty(fileName) ? fileName : path;
String baseName = FilenameUtils.getBaseName(fullName);
if (StringUtils.isNotEmpty(baseName)) {
name.append(baseName)
.append('-')
.append(UUID.randomUUID().toString())
.append('.')
.append(FilenameUtils.getExtension(fullName));
} else {
name.append(UUID.randomUUID().toString());
}
resource = new StreamResource(() ->
AppBeans.get(Resources.class).getResourceAsStream(path), name.toString());
StreamResource streamResource = (StreamResource) this.resource;
streamResource.setMIMEType(mimeType);
streamResource.setCacheTime(cacheTime);
streamResource.setBufferSize(bufferSize);
}
private StreamResource createStreamResource(final Long id) {
Optional<Artifact> artifact = this.artifactManagement.get(id);
if (artifact.isPresent()) {
Optional<AbstractDbArtifact> file = artifactManagement.loadArtifactBinary(artifact.get().getSha1Hash());
return new StreamResource(new StreamResource.StreamSource() {
private static final long serialVersionUID = 1L;
@Override
public InputStream getStream() {
if (file.isPresent()) {
return file.get().getFileInputStream();
}
return null;
}
}, artifact.get().getFilename());
}
return null;
}
/**
* Display document attachements.
*
* @param panelContent the panel content
* @param documentAttachmentList the document attachment list
*/
private static void displayDocumentAttachements(final VerticalLayout panelContent,
final List<DocumentAttachment> documentAttachmentList) {
for (final DocumentAttachment documentAttachment : documentAttachmentList) {
if (PDF.equalsIgnoreCase(documentAttachment.getFileType())) {
final WTPdfViewer wtPdfViewer = new WTPdfViewer();
wtPdfViewer.setSizeFull();
wtPdfViewer.setResource(new StreamResource(new StreamSourceImplementation(documentAttachment.getFileUrl()), documentAttachment.getFileName()));
panelContent.addComponent(wtPdfViewer);
panelContent.setExpandRatio(wtPdfViewer, ContentRatio.LARGE);
} else {
final VerticalLayout verticalLayout = new VerticalLayout();
panelContent.addComponent(verticalLayout);
panelContent.setExpandRatio(verticalLayout, ContentRatio.SMALL);
final ExternalAttachmentDownloadLink link = new ExternalAttachmentDownloadLink(
documentAttachment.getFileName(), documentAttachment.getFileType(),
documentAttachment.getFileUrl());
verticalLayout.addComponent(link);
}
}
}
@Override
public StreamResource buildStreamResource(ReportExportType exportType) {
IPagedTable pagedBeanTable = ((IListView) presenter.getView()).getPagedBeanGrid();
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());
}
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);
}
@Override
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
if (resource != null) {
((StreamResource) resource).setMIMEType(mimeType);
}
}
@Override
public void setCacheTime(long cacheTime) {
this.cacheTime = cacheTime;
if (resource != null) {
((StreamResource) resource).setCacheTime(cacheTime);
}
}
@Override
public void setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
if (resource != null) {
((StreamResource) resource).setBufferSize(bufferSize);
}
}
@Override
public void setFileName(String fileName) {
this.fileName = fileName;
if (resource != null) {
((StreamResource) resource).setFilename(fileName);
}
}
@Override
protected void createResource() {
resource = new StreamResource(() -> {
try {
return AppBeans.get(FileLoader.class).openStream(fileDescriptor);
} catch (FileStorageException e) {
throw new RuntimeException(FILE_STORAGE_EXCEPTION_MESSAGE, e);
}
}, getResourceName());
StreamResource streamResource = (StreamResource) this.resource;
streamResource.setCacheTime(cacheTime);
streamResource.setBufferSize(bufferSize);
}
@Override
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
if (resource != null) {
((StreamResource) resource).setMIMEType(mimeType);
}
}
@Override
public void attach() {
super.attach();
final StreamResource.StreamSource source = new StreamSourceImplementation(fileUrl);
final StreamResource resource = new StreamResource(source, fileName);
resource.getStream().setParameter("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
resource.setMIMEType("application/" + fileType);
resource.setCacheTime(0);
setResource(resource);
}
@Override
protected HorizontalLayout createButtonControls() {
ProjectPreviewFormControlsGenerator<Page> pagesPreviewForm = new ProjectPreviewFormControlsGenerator<>(previewForm);
HorizontalLayout buttonControls = pagesPreviewForm.createButtonControls(
ProjectPreviewFormControlsGenerator.ADD_BTN_PRESENTED
| ProjectPreviewFormControlsGenerator.EDIT_BTN_PRESENTED
| ProjectPreviewFormControlsGenerator.DELETE_BTN_PRESENTED,
ProjectRolePermissionCollections.PAGES);
MButton exportPdfBtn = new MButton("").withIcon(VaadinIcons.FILE_O).withStyleName(WebThemes
.BUTTON_OPTION).withDescription(UserUIContext.getMessage(GenericI18Enum.BUTTON_EXPORT_PDF));
OnDemandFileDownloader fileDownloader = new OnDemandFileDownloader(new LazyStreamSource() {
@Override
protected StreamResource.StreamSource buildStreamSource() {
return new PageReportStreamSource(beanItem);
}
@Override
public String getFilename() {
return "Document.pdf";
}
});
fileDownloader.extend(exportPdfBtn);
pagesPreviewForm.insertToControlBlock(exportPdfBtn);
pageVersionsSelection = new PageVersionSelectionBox();
pagesPreviewForm.insertToControlBlock(pageVersionsSelection);
return buttonControls;
}
public PrintButton(String caption) {
setCaption(caption);
setIcon(VaadinIcons.PRINT);
formReportStreamSource = new FormReportStreamSource<>(new FormReportTemplateExecutor<>("", UserUIContext.getUserTimeZone(), UserUIContext.getUserLocale()));
BrowserWindowOpener printWindowOpener = new BrowserWindowOpener(new StreamResource(formReportStreamSource, UUID.randomUUID().toString() + ".pdf"));
printWindowOpener.extend(this);
}
public ByteArrayImageResource(final byte[] imageData, String mimeType) {
super(new StreamResource.StreamSource() {
private static final long serialVersionUID = 1L;
public InputStream getStream() {
return new ByteArrayInputStream(imageData);
}
}, "avatar");
this.setMIMEType(mimeType);
}
public OnDemandFileDownloader(OnDemandStreamResource resource) {
super(new StreamResource(resource, ""));
this.resource = resource;
if (this.resource == null) {
throw new NullPointerException("Can't send null resource");
}
}
protected void initializeButtons() {
//
// The Save button
//
this.buttonSave.addClickListener(new ClickListener() {
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
self.savePolicy();
}
});
//
// Attach a window opener to the View XML button
//
BrowserWindowOpener opener = new BrowserWindowOpener(new StreamResource(new StreamResource.StreamSource() {
private static final long serialVersionUID = 1L;
@Override
public InputStream getStream() {
try {
if (logger.isDebugEnabled()) {
logger.debug("Setting view xml button to: " + self.file.getAbsolutePath());
}
return new FileInputStream(self.file);
} catch (Exception e) {
logger.error("Failed to open input stream " + self.file);
}
return null;
}
}, self.file.getName()));
opener.setWindowName("_new");
opener.extend(this.buttonViewXML);
}
/**
* Show/Download resource at client side
*
* @param dataProvider ExportDataProvider
* @param resourceName ResourceName for client side
* @param exportFormat ExportFormat
* @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();
fileDownloader.setFileNotFoundExceptionListener(this::handleFileNotFoundException);
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 && isBrowserSupportsPopups()) || isIOS()) {
fileDownloader.viewDocument(resource);
} else {
fileDownloader.downloadFile(resource);
}
}
public static StreamResource getStreamResourceSupportExtDrive(List<Resource> lstRes) {
String filename = getDownloadFileName(lstRes);
StreamSource streamSource = getStreamSourceSupportExtDrive(lstRes);
return new StreamResource(streamSource, filename);
}
private void constructBody() {
final MVerticalLayout layout = new MVerticalLayout().withFullWidth();
CssLayout iconWrapper = new CssLayout();
final ELabel iconEmbed = ELabel.fontIcon(FileAssetsUtil.getFileIconResource(content.getName()));
iconEmbed.addStyleName("icon-48px");
iconWrapper.addComponent(iconEmbed);
layout.with(iconWrapper).withAlign(iconWrapper, Alignment.MIDDLE_CENTER);
final GridFormLayoutHelper infoLayout = GridFormLayoutHelper.defaultFormLayoutHelper(LayoutType.ONE_COLUMN);
if (content.getDescription() != null) {
final Label descLbl = new Label();
if (!content.getDescription().equals("")) {
descLbl.setData(content.getDescription());
} else {
descLbl.setValue(" ");
descLbl.setContentMode(ContentMode.HTML);
}
infoLayout.addComponent(descLbl, UserUIContext.getMessage(GenericI18Enum.FORM_DESCRIPTION), 0, 0);
}
UserService userService = AppContextUtil.getSpringBean(UserService.class);
SimpleUser user = userService.findUserByUserNameInAccount(content.getCreatedUser(), AppUI.getAccountId());
if (user == null) {
infoLayout.addComponent(new UserLink(UserUIContext.getUsername(), UserUIContext.getUserAvatarId(),
UserUIContext.getUserDisplayName()), UserUIContext.getMessage(GenericI18Enum.OPT_CREATED_BY), 0, 1);
} else {
infoLayout.addComponent(new UserLink(user.getUsername(), user.getAvatarid(), user.getDisplayName()),
UserUIContext.getMessage(GenericI18Enum.OPT_CREATED_BY), 0, 1);
}
final Label size = new Label(FileUtils.getVolumeDisplay(content.getSize()));
infoLayout.addComponent(size, UserUIContext.getMessage(FileI18nEnum.OPT_SIZE), 0, 2);
ELabel dateCreate = new ELabel().prettyDateTime(DateTimeUtils.toLocalDateTime(content.getCreated()));
infoLayout.addComponent(dateCreate, UserUIContext.getMessage(GenericI18Enum.FORM_CREATED_TIME), 0, 3);
layout.addComponent(infoLayout.getLayout());
MButton downloadBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_DOWNLOAD))
.withIcon(VaadinIcons.DOWNLOAD).withStyleName(WebThemes.BUTTON_ACTION);
List<Resource> resources = new ArrayList<>();
resources.add(content);
StreamResource downloadResource = StreamDownloadResourceUtil.getStreamResourceSupportExtDrive(resources);
FileDownloader fileDownloader = new FileDownloader(downloadResource);
fileDownloader.extend(downloadBtn);
MButton cancelBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_CANCEL), clickEvent -> close())
.withStyleName(WebThemes.BUTTON_OPTION);
MHorizontalLayout buttonControls = new MHorizontalLayout(cancelBtn, downloadBtn);
layout.with(buttonControls).withAlign(buttonControls, Alignment.MIDDLE_RIGHT);
this.setContent(layout);
}