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

下面列出了怎么用com.vaadin.server.StreamResource的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: cuba   文件: WebClasspathResource.java
@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);
}
 
源代码2 项目: hawkbit   文件: ArtifactDetailsLayout.java
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);
		}
	}
}
 
源代码4 项目: mycollab   文件: DefaultMassEditActionHandler.java
@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());
}
 
源代码5 项目: 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);
}
 
源代码6 项目: cuba   文件: WebClasspathResource.java
@Override
public void setMimeType(String mimeType) {
    this.mimeType = mimeType;

    if (resource != null) {
        ((StreamResource) resource).setMIMEType(mimeType);
    }
}
 
源代码7 项目: cuba   文件: WebAbstractStreamSettingsResource.java
@Override
public void setCacheTime(long cacheTime) {
    this.cacheTime = cacheTime;

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

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

    if (resource != null) {
        ((StreamResource) resource).setFilename(fileName);
    }
}
 
源代码10 项目: cuba   文件: WebFileDescriptorResource.java
@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);
}
 
源代码11 项目: cuba   文件: WebFileDescriptorResource.java
@Override
public void setMimeType(String mimeType) {
    this.mimeType = mimeType;

    if (resource != null) {
        ((StreamResource) resource).setMIMEType(mimeType);
    }
}
 
源代码12 项目: cia   文件: ExternalAttachmentDownloadLink.java
@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);
}
 
源代码13 项目: mycollab   文件: PageReadViewImpl.java
@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;
}
 
源代码14 项目: mycollab   文件: PrintButton.java
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);
}
 
源代码15 项目: mycollab   文件: ByteArrayImageResource.java
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);
}
 
源代码16 项目: XACML   文件: 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");
	}
}
 
源代码17 项目: XACML   文件: PolicyEditor.java
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);
}
 
源代码18 项目: cuba   文件: WebExportDisplay.java
/**
 * 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);
    }
}
 
源代码19 项目: mycollab   文件: StreamDownloadResourceUtil.java
public static StreamResource getStreamResourceSupportExtDrive(List<Resource> lstRes) {
    String filename = getDownloadFileName(lstRes);
    StreamSource streamSource = getStreamSourceSupportExtDrive(lstRes);
    return new StreamResource(streamSource, filename);
}
 
源代码20 项目: mycollab   文件: FileDownloadWindow.java
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("&nbsp;");
            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);
}