com.vaadin.server.StreamResource Java Examples

The following examples show how to use com.vaadin.server.StreamResource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebClasspathResource.java    From cuba with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #2
Source File: PolicyEditor.java    From XACML with MIT License 6 votes vote down vote up
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);
}
 
Example #3
Source File: DefaultMassEditActionHandler.java    From mycollab with GNU Affero General Public License v3.0 6 votes vote down vote up
@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());
}
 
Example #4
Source File: DocumentAttachementsPageModContentFactoryImpl.java    From cia with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
		}
	}
}
 
Example #5
Source File: ArtifactDetailsLayout.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
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;
    }
 
Example #6
Source File: WebAbstractStreamSettingsResource.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void setFileName(String fileName) {
    this.fileName = fileName;

    if (resource != null) {
        ((StreamResource) resource).setFilename(fileName);
    }
}
 
Example #7
Source File: WebFileDescriptorResource.java    From cuba with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #8
Source File: WebFileDescriptorResource.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void setMimeType(String mimeType) {
    this.mimeType = mimeType;

    if (resource != null) {
        ((StreamResource) resource).setMIMEType(mimeType);
    }
}
 
Example #9
Source File: WebAbstractStreamSettingsResource.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void setBufferSize(int bufferSize) {
    this.bufferSize = bufferSize;

    if (resource != null) {
        ((StreamResource) resource).setBufferSize(bufferSize);
    }
}
 
Example #10
Source File: WebAbstractStreamSettingsResource.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void setCacheTime(long cacheTime) {
    this.cacheTime = cacheTime;

    if (resource != null) {
        ((StreamResource) resource).setCacheTime(cacheTime);
    }
}
 
Example #11
Source File: ExternalAttachmentDownloadLink.java    From cia with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #12
Source File: PageReadViewImpl.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example #13
Source File: PrintButton.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
}
 
Example #14
Source File: WebClasspathResource.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void setMimeType(String mimeType) {
    this.mimeType = mimeType;

    if (resource != null) {
        ((StreamResource) resource).setMIMEType(mimeType);
    }
}
 
Example #15
Source File: ByteArrayImageResource.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
}
 
Example #16
Source File: OnDemandFileDownloader.java    From XACML with MIT License 5 votes vote down vote up
public OnDemandFileDownloader(OnDemandStreamResource resource) {
	super(new StreamResource(resource, ""));
	this.resource = resource;
	if (this.resource == null) {
		throw new NullPointerException("Can't send null resource");
	}
}
 
Example #17
Source File: PolicyEditor.java    From XACML with MIT License 5 votes vote down vote up
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);
}
 
Example #18
Source File: StreamDownloadResourceUtil.java    From mycollab with GNU Affero General Public License v3.0 4 votes vote down vote up
public static StreamResource getStreamResourceSupportExtDrive(List<Resource> lstRes) {
    String filename = getDownloadFileName(lstRes);
    StreamSource streamSource = getStreamSourceSupportExtDrive(lstRes);
    return new StreamResource(streamSource, filename);
}
 
Example #19
Source File: FileDownloadWindow.java    From mycollab with GNU Affero General Public License v3.0 4 votes vote down vote up
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);
}
 
Example #20
Source File: WebExportDisplay.java    From cuba with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
    }
}