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

项目: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    文件: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    文件: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());
}
项目: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;
}
项目: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);
        }           
    }       
}
项目:hybridbpm    文件:FileField.java   
public OnDemandStreamResource() {
    super(new StreamSource() {

        @Override
        public InputStream getStream() {
            return new ByteArrayInputStream(new byte[1]);
        }
    }, "");
}
项目:minimal-j    文件:VaadinExportDialog.java   
public VaadinExportDialog(String title) {
    super(title);

    try {
        HorizontalLayout horizontalLayout = new HorizontalLayout();
        horizontalLayout.setMargin(false);
        final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);

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

            @Override
               public InputStream getStream() {
                VaadinExportDialog.this.close();
                   return pipedInputStream;
               }
           };
           StreamResource sr = new StreamResource(ss, "export.xml");
        sr.setMIMEType("application/octet-stream");
        sr.setCacheTime(0);
        link = new Link("Link to Download", sr);

        horizontalLayout.addComponent(link);

        setContent(horizontalLayout);

        setModal(true);
        UI.getCurrent().addWindow(this);
    } catch (IOException x) {
        x.printStackTrace();
       }
}
项目:metl    文件:LoggingPanel.java   
private StreamResource getLogFileResource() {
    StreamSource ss = new StreamSource() {
        public InputStream getStream() {
            try {
                return new BufferedInputStream(new FileInputStream(logFile));
            } catch (FileNotFoundException e) {
                Notification note = new Notification("File Not Found", "Could not find "
                        + logFile.getName() + " to download");
                note.show(Page.getCurrent());
                return null;
            }
        }
    };
    return new StreamResource(ss, logFile.getName());
}
项目:sqlexplorer-vaadin    文件:DbExportDialog.java   
private StreamResource createResource() {

        final String format = (String) formatSelect.getValue().toString();
        StreamSource ss = new StreamSource() {
            private static final long serialVersionUID = 1L;

            public InputStream getStream() {

                List<String> list = tableSelectionLayout.getSelectedTables();
                String[] array = new String[list.size()];
                list.toArray(array);

                createDbExport();

                String script;
                try {
                    script = dbExport.exportTables(array);
                    return new ByteArrayInputStream(script.getBytes());
                } catch (IOException e) {
                    String msg = "Failed to export to a file";
                    log.error(msg, e);
                    CommonUiUtils.notify(msg, e);
                }
                return null;
            }
        };
        String datetime = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
        StreamResource sr = new StreamResource(ss, String.format(
                "table-export-%s." + format.toLowerCase(), datetime));
        return sr;
    }
项目:sqlexplorer-vaadin    文件:ReadOnlyTextAreaDialog.java   
private void buildDownloadButton(String title) {
    downloadButton = new Button("Download");
    final byte[] lobData = getLobData(title);
    if (lobData != null) {
    Resource resource = new StreamResource(new StreamSource() {

    private static final long serialVersionUID = 1L;

    public InputStream getStream() {
        return new ByteArrayInputStream(lobData);
    }

}, title);
    FileDownloader fileDownloader = new FileDownloader(resource);
    fileDownloader.extend(downloadButton);
    buttonLayout.addComponent(downloadButton);
    buttonLayout.setComponentAlignment(downloadButton, Alignment.BOTTOM_CENTER);

    long fileSize = lobData.length;
    String sizeText = fileSize + " Bytes";
    if (fileSize / 1024 > 0) {
        sizeText = Math.round(fileSize / 1024.0) + " kB";
        fileSize /= 1024;
    }
    if (fileSize / 1024 > 0) {
        sizeText = Math.round(fileSize / 1024.0) + " MB";
        fileSize /= 1024;
    }
    if (fileSize / 1024 > 0) {
        sizeText = Math.round(fileSize / 1024.0) + " GB";
    }
    Label sizeLabel = new Label(sizeText);
    buttonLayout.addComponent(sizeLabel);
    buttonLayout.setExpandRatio(sizeLabel, 1.0f);
    buttonLayout.setComponentAlignment(sizeLabel, Alignment.BOTTOM_CENTER);
    }
 }
项目:mycollab    文件:StreamDownloadResourceUtil.java   
public static StreamSource getStreamSourceSupportExtDrive(Collection<Resource> lstRes) {
    if (CollectionUtils.isEmpty(lstRes)) {
        throw new UserInvalidInputException(UserUIContext.getMessage(FileI18nEnum.ERROR_NO_SELECTED_FILE_TO_DOWNLOAD));
    } else {
        return new StreamDownloadResourceSupportExtDrive(lstRes);
    }
}
项目:VaadinUtils    文件:JasperReportLayout.java   
private StreamSource getReportStream()
{
    @SuppressWarnings("serial")
    StreamSource source = new StreamSource()
    {

        @Override
        public InputStream getStream()
        {
            try
            {
                InputStream stream = manager.getStream();
                if (stream == null)
                {
                    Notification.show("Couldn't attach to stream, if you cancelled a report this is normal",
                            Type.ERROR_MESSAGE);
                }
                return stream;
            }
            catch (InterruptedException e)
            {
                logger.error(e, e);
            }
            return null;
        }
    };
    return source;
}
项目:RVaadin    文件:RContainer.java   
/**
 * Get a Vaadin Resource object which links to a file in the R working
 * directory. The Resource object can be associated e.g. with Links.
 * 
 * @param filename
 *            The name of the file stored under R current working directory.
 * @return Vaadin Resource object
 */
public Resource getDownloadResource(String filename) {

    StreamSource filesource = new RDownloadSource(filename, this);
    StreamResource fileresource = new StreamResource(filesource, filename);

    fileresource.setCacheTime(0);
    return fileresource;
}
项目:root    文件:ShowWoundPhotoView.java   
@SuppressWarnings("serial")
public ShowWoundPhotoView() {
    this.woundDescription = getEnvironment().getCurrentWoundDescription();
    if (woundDescription.getImage() != null) {

        DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
        setCaption(MessageResources.getString("photo") + " "
                + dateFormat.format(woundDescription.getDate()));

        // using stream-resource class to avoid creation/deletion of unnecessary files to show the image
        final class MyImageSource implements StreamSource {
            ByteArrayInputStream imagebuffer = null;

            public InputStream getStream() {

                try {

                    imagebuffer = new ByteArrayInputStream(
                            woundDescription.getImage());

                    return imagebuffer;
                } catch (Exception e) {
                    return null;
                }
            }
        }

        // by using StreamResources, the image is now shown without creating a file
        StreamSource imagesource = new MyImageSource();
        StreamResource resource = new StreamResource(imagesource,
                "bufferedimage.png");

        Image myImage = new Image(null, resource);
        myImage.setSizeFull();

        Panel panel = new Panel();
        Layout panelContent = new VerticalLayout();

        panelContent.addComponent(myImage);
        panel.setContent(panelContent);

        setContent(panel);

        setLeftComponent(new BackButton(MessageResources.getString("showWoundDescView"), "showWoundDescription"));
    }
}
项目:dhconvalidator    文件:PaperSelectionPanel.java   
/**
 * Setup UI.
 */
private void initComponents() {
    Label info = new Label(
        Messages.getString("PaperSelectionPanel.hintMsg"), //$NON-NLS-1$
        ContentMode.HTML); 

    languages = 
            new ComboBox(Messages.getString("PaperSelectionPanel.language"), //$NON-NLS-1$
                    Arrays.asList(SubmissionLanguage.values()));
    languages.setNullSelectionAllowed(false);
    languages.setValue(SubmissionLanguage.valueOf(PropertyKey.defaultSubmissionLanguage.getValue(SubmissionLanguage.ENGLISH.name())));

    paperTable = new Table(Messages.getString("PaperSelectionPanel.tableTitle")); //$NON-NLS-1$
    paperTable.setSelectable(true);
    paperTable.setMultiSelect(true);
    paperTable.setPageLength(4);
    paperTable.addContainerProperty("title", String.class, null); //$NON-NLS-1$
    paperTable.setColumnHeader(
        "title", 
        Messages.getString("PaperSelectionPanel.titleColumnTitle")); //$NON-NLS-1$ //$NON-NLS-2$
    paperTable.setWidth("100%"); //$NON-NLS-1$
    paperTable.setImmediate(true);

    btGenerate = new Button(
        Messages.getString(
            "PaperSelectionPanel.generateButtonCaption")); //$NON-NLS-1$
    StreamResource templateStreamResource = 
            new StreamResource(
                    new StreamSource() {
                        @Override
                        public InputStream getStream() {
                            return createTemplates();
                        }
                    }, "your_personal_dh_templates.zip" ); //$NON-NLS-1$

    templateStreamResource.setCacheTime(0);
    new FileDownloader(templateStreamResource).extend(btGenerate);

    addCenteredComponent(info);
    addCenteredComponent(languages);
    addCenteredComponent(paperTable);
    addCenteredComponent(btGenerate);

    postDownloadLabel = 
            new Label(
                Messages.getString("PaperSelectionPanel.postDownloadInfo",
                    inputConverter.getTextEditorDescription(),
                    PropertyKey.base_url.getValue()+"popup/DHConvalidatorServices#!converter"),
                ContentMode.HTML);
    postDownloadLabel.addStyleName("postDownloadInfoRedAndBold");
    postDownloadLabel.setVisible(false);

    addCenteredComponent(postDownloadLabel);

}
项目:dhconvalidator    文件:DHConvalidatorExample.java   
@Override
protected void init(VaadinRequest request) {
    try {
        Messages.setLocaleProvider(VaadinSessionLocaleProvider.INSTANCE);

        VerticalLayout content = new VerticalLayout();
        content.setMargin(true);
        content.setSpacing(true);

        setContent(content);

        HeaderPanel headerPanel  = new HeaderPanel(null);
        headerPanel.getBackLink().setVisible(false);

        content.addComponent(headerPanel);

        // prepare downloader for input file
        Button btGetInputfile = 
            new Button(
                Messages.getString("DHConvalidatorExample.btInputCaption")); //$NON-NLS-1$
        content.addComponent(btGetInputfile);

        FileDownloader inputFileDownloader = new FileDownloader(new StreamResource(
            new StreamSource() {

                @Override
                public InputStream getStream() {
                    return Thread.currentThread().getContextClassLoader().getResourceAsStream(
                        "/org/adho/dhconvalidator/conversion/example/1_Digital_Humanities.odt"); //$NON-NLS-1$
                }
            }, "1_Digital_Humanities.odt")); //$NON-NLS-1$
        inputFileDownloader.extend(btGetInputfile);

        // prepare downloader for output file
        Button btGetOutputfile = 
                new Button(
                    Messages.getString(
                        "DHConvalidatorExample.btConversionResultCaption")); //$NON-NLS-1$
        content.addComponent(btGetOutputfile);

        FileDownloader outputFileDownloader = new FileDownloader(new StreamResource(
            new StreamSource() {

                @Override
                public InputStream getStream() {
                    return Thread.currentThread().getContextClassLoader().getResourceAsStream(
                        "/org/adho/dhconvalidator/conversion/example/1_Digital_Humanities.dhc"); //$NON-NLS-1$
                }
            }, "1_Digital_Humanities.dhc")); //$NON-NLS-1$
        outputFileDownloader.extend(btGetOutputfile);

        // setup visual feedback
        Label preview = new Label("", ContentMode.HTML); //$NON-NLS-1$
        preview.addStyleName("tei-preview"); //$NON-NLS-1$
        preview.setWidth("800px"); //$NON-NLS-1$

        content.addComponent(preview);
        content.setComponentAlignment(preview, Alignment.MIDDLE_CENTER);

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        IOUtils.copy(
            Thread.currentThread().getContextClassLoader().getResourceAsStream(
                    "/org/adho/dhconvalidator/conversion/example/1_Digital_Humanities.html"),  //$NON-NLS-1$
            buffer);

        preview.setValue(buffer.toString("UTF-8")); //$NON-NLS-1$

        Page.getCurrent().setTitle(Messages.getString("DHConvalidatorExample.title")); //$NON-NLS-1$
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}
项目:mycollab    文件:ContactReadFormFieldFactory.java   
@Override
protected StreamSource buildStreamSource() {
    return null;
}
项目:mycollab    文件:ResourcesDisplayComponent.java   
private void displaySelectedResourceControls() {
    if (selectedResource != null) {
        selectedResourceControlLayout.removeAllComponents();
        ELabel resourceHeaderLbl = ELabel.h3(selectedResource.getName()).withStyleName(UIConstants.TEXT_ELLIPSIS);
        MHorizontalLayout headerLayout = new MHorizontalLayout(resourceHeaderLbl).withMargin(new MarginInfo
                (false, true, false, true)).withStyleName(WebThemes.PANEL_HEADER).withFullWidth().alignAll(Alignment.MIDDLE_LEFT);
        selectedResourceControlLayout.with(headerLayout);

        MButton renameBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.ACTION_RENAME), clickEvent -> UI.getCurrent()
                .addWindow(new RenameResourceWindow(selectedResource)))
                .withIcon(FontAwesome.EDIT).withStyleName(WebThemes.BUTTON_LINK);

        MButton downloadBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_DOWNLOAD))
                .withStyleName(WebThemes.BUTTON_LINK).withIcon(FontAwesome.DOWNLOAD);

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

            @Override
            protected StreamSource buildStreamSource() {
                List<Resource> lstRes = new ArrayList<>();
                lstRes.add(selectedResource);
                return StreamDownloadResourceUtil.getStreamSourceSupportExtDrive(lstRes);
            }

            @Override
            public String getFilename() {
                return (selectedResource instanceof Folder) ? "out.zip" : selectedResource.getName();
            }
        };

        OnDemandFileDownloader downloaderExt = new OnDemandFileDownloader(streamSource);
        downloaderExt.extend(downloadBtn);

        MButton moveBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.ACTION_MOVE) + "...", clickEvent ->
                UI.getCurrent().addWindow(new MoveResourceWindow(selectedResource)))
                .withIcon(FontAwesome.ARROWS).withStyleName(WebThemes.BUTTON_LINK);

        MButton deleteBtn = new MButton(UserUIContext.getMessage(GenericI18Enum.BUTTON_DELETE),
                clickEvent -> deleteResourceAction(Collections.singletonList(selectedResource)))
                .withStyleName(WebThemes.BUTTON_LINK).withIcon(FontAwesome.TRASH_O);

        selectedResourceControlLayout.with(new MVerticalLayout(renameBtn, downloadBtn, moveBtn, deleteBtn)
                .withStyleName("panel-body"));
    } else {
        selectedResourceControlLayout.removeAllComponents();
        selectedResourceControlLayout.removeStyleName(WebThemes.BOX);
    }
}
项目:mycollab    文件:StreamDownloadResourceUtil.java   
public static StreamResource getStreamResourceSupportExtDrive(List<Resource> lstRes) {
    String filename = getDownloadFileName(lstRes);
    StreamSource streamSource = getStreamSourceSupportExtDrive(lstRes);
    return new StreamResource(streamSource, filename);
}