Example usage for com.vaadin.server StreamResource setCacheTime

List of usage examples for com.vaadin.server StreamResource setCacheTime

Introduction

In this page you can find the example usage for com.vaadin.server StreamResource setCacheTime.

Prototype

public void setCacheTime(long cacheTime) 

Source Link

Document

Sets the length of cache expiration time.

Usage

From source file:com.hack23.cia.web.impl.ui.application.views.common.pagelinks.impl.ExternalAttachmentDownloadLink.java

License:Apache License

@Override
public void attach() {
    super.attach();

    final StreamResource.StreamSource source = new StreamResource.StreamSource() {

        /**/*ww  w  .java2s  .  c o  m*/
         *
         */
        private static final long serialVersionUID = 1L;

        public InputStream getStream() {

            try {
                return new URL(fileUrl).openStream();
            } catch (final IOException e) {
                LOGGER.warn("Problem opening url:" + fileUrl, e);
                return new ByteArrayInputStream(new byte[0]);
            }
        }
    };

    final StreamResource resource = new StreamResource(source, fileName);

    resource.getStream().setParameter("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
    resource.setMIMEType("application/" + fileType);
    resource.setCacheTime(0);

    setResource(resource);
}

From source file:com.haulmont.cuba.web.gui.components.WebClasspathResource.java

License:Apache License

@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);
}

From source file:com.haulmont.cuba.web.gui.components.WebFileDescriptorResource.java

License:Apache License

@Override
protected void createResource() {
    String name = StringUtils.isNotEmpty(fileName) ? fileName : fileDescriptor.getName();

    resource = new StreamResource(() -> {
        try {/* w  ww . ja  v a  2s  .  c o m*/
            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);
}

From source file:com.jain.addon.component.download.JDownloader.java

License:Apache License

/**
 * Download actual file//from w ww .j a va  2  s. c o m
 */
public void download() {
    StreamResource resource = new StreamResource(source, fileName);
    resource.getStream().setParameter("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
    resource.setMIMEType("application/octet-stream");
    resource.setCacheTime(0);
    FileDownloader downloader = new FileDownloader(resource);
    downloader.extend(ui);
}

From source file:com.klwork.explorer.ui.user.ProfilePanel.java

License:Apache License

protected void initPicture() {
    StreamResource imageresource = new StreamResource(new StreamSource() {
        private static final long serialVersionUID = 1L;

        public InputStream getStream() {
            return picture.getInputStream();
        }//from  www .  ja  v a 2s .  co  m
    }, user.getId());
    imageresource.setCacheTime(0);

    Embedded picture = new Embedded(null, imageresource);
    picture.setType(Embedded.TYPE_IMAGE);
    picture.setHeight(200, UNITS_PIXELS);
    picture.setWidth(200, UNITS_PIXELS);
    picture.addStyleName(ExplorerLayout.STYLE_PROFILE_PICTURE);

    imageLayout.addComponent(picture);
    imageLayout.setWidth(picture.getWidth() + 5, picture.getWidthUnits());

    // Change picture button
    if (isCurrentLoggedInUser) {
        Upload changePictureButton = initChangePictureButton();
        imageLayout.addComponent(changePictureButton);
        imageLayout.setComponentAlignment(changePictureButton, Alignment.MIDDLE_CENTER);
    }
}

From source file:de.symeda.sormas.ui.utils.DownloadUtil.java

License:Open Source License

@SuppressWarnings("serial")
public static StreamResource createDatabaseExportStreamResource(DatabaseExportView databaseExportView,
        String fileName, String mimeType) {
    StreamResource streamResource = new StreamResource(new StreamSource() {
        @Override/*  w  w  w  .j av a2  s.  c om*/
        public InputStream getStream() {
            try {
                Map<CheckBox, DatabaseTable> databaseToggles = databaseExportView.getDatabaseTableToggles();
                List<DatabaseTable> tablesToExport = new ArrayList<>();
                for (CheckBox checkBox : databaseToggles.keySet()) {
                    if (checkBox.getValue() == true) {
                        tablesToExport.add(databaseToggles.get(checkBox));
                    }
                }

                String zipPath = FacadeProvider.getExportFacade().generateDatabaseExportArchive(tablesToExport);
                return new BufferedInputStream(Files.newInputStream(new File(zipPath).toPath()));
            } catch (IOException | ExportErrorException e) {
                // TODO This currently requires the user to click the "Export" button again or reload the page as the UI
                // is not automatically updated; this should be changed once Vaadin push is enabled (see #516)
                databaseExportView.showExportErrorNotification();
                return null;
            }
        }
    }, fileName);
    streamResource.setMIMEType(mimeType);
    streamResource.setCacheTime(0);
    return streamResource;
}

From source file:de.symeda.sormas.ui.utils.DownloadUtil.java

License:Open Source License

@SuppressWarnings("serial")
public static StreamResource createFileStreamResource(String filePath, String fileName, String mimeType,
        String errorTitle, String errorText) {
    StreamResource streamResource = new StreamResource(new StreamSource() {
        @Override/*  ww  w .  j  av a  2 s . c o m*/
        public InputStream getStream() {
            try {
                return new BufferedInputStream(Files.newInputStream(new File(filePath).toPath()));
            } catch (IOException e) {
                // TODO This currently requires the user to click the "Export" button again or reload the page as the UI
                // is not automatically updated; this should be changed once Vaadin push is enabled (see #516)
                new Notification(errorTitle, errorText, Type.ERROR_MESSAGE, false).show(Page.getCurrent());
                return null;
            }
        }
    }, fileName);
    streamResource.setMIMEType(mimeType);
    streamResource.setCacheTime(0);
    return streamResource;
}

From source file:de.symeda.sormas.ui.utils.DownloadUtil.java

License:Open Source License

@SuppressWarnings("serial")
public static <T> StreamResource createCsvExportStreamResource(Class<T> exportRowClass,
        BiFunction<Integer, Integer, List<T>> exportRowsSupplier,
        BiFunction<String, Class<?>, String> propertyIdCaptionFunction, String exportFileName) {
    StreamResource extendedStreamResource = new StreamResource(new StreamSource() {
        @Override//w w w.  j ava2s  . c  om
        public InputStream getStream() {
            try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {
                try (CSVWriter writer = CSVUtils.createCSVWriter(
                        new OutputStreamWriter(byteStream, StandardCharsets.UTF_8.name()),
                        FacadeProvider.getConfigFacade().getCsvSeparator())) {

                    // 1. fields in order of declaration - not using Introspector here, because it gives properties in alphabetical order
                    List<Method> readMethods = new ArrayList<Method>();
                    readMethods.addAll(Arrays.stream(exportRowClass.getDeclaredMethods())
                            .filter(m -> (m.getName().startsWith("get") || m.getName().startsWith("is"))
                                    && m.isAnnotationPresent(Order.class))
                            .sorted((a, b) -> Integer.compare(a.getAnnotationsByType(Order.class)[0].value(),
                                    b.getAnnotationsByType(Order.class)[0].value()))
                            .collect(Collectors.toList()));

                    // 2. replace entity fields with all the columns of the entity 
                    Map<Method, Function<T, ?>> subEntityProviders = new HashMap<Method, Function<T, ?>>();
                    for (int i = 0; i < readMethods.size(); i++) {
                        Method method = readMethods.get(i);
                        if (EntityDto.class.isAssignableFrom(method.getReturnType())) {

                            // allows us to access the sub entity
                            Function<T, ?> subEntityProvider = (o) -> {
                                try {
                                    return method.invoke(o);
                                } catch (IllegalAccessException | IllegalArgumentException
                                        | InvocationTargetException e) {
                                    throw new RuntimeException(e);
                                }
                            };

                            // remove entity field
                            readMethods.remove(i);

                            // add columns of the entity
                            List<Method> subReadMethods = Arrays
                                    .stream(method.getReturnType().getDeclaredMethods())
                                    .filter(m -> (m.getName().startsWith("get") || m.getName().startsWith("is"))
                                            && m.isAnnotationPresent(Order.class))
                                    .sorted((a, b) -> Integer.compare(
                                            a.getAnnotationsByType(Order.class)[0].value(),
                                            b.getAnnotationsByType(Order.class)[0].value()))
                                    .collect(Collectors.toList());
                            readMethods.addAll(i, subReadMethods);
                            i--;

                            for (Method subReadMethod : subReadMethods) {
                                subEntityProviders.put(subReadMethod, subEntityProvider);
                            }
                        }
                    }

                    String[] fieldValues = new String[readMethods.size()];
                    for (int i = 0; i < readMethods.size(); i++) {
                        Method method = readMethods.get(i);
                        // field caption
                        String propertyId = method.getName().startsWith("get") ? method.getName().substring(3)
                                : method.getName().substring(2);
                        propertyId = Character.toLowerCase(propertyId.charAt(0)) + propertyId.substring(1);
                        fieldValues[i] = propertyIdCaptionFunction.apply(propertyId, method.getReturnType());
                    }
                    writer.writeNext(fieldValues);

                    int startIndex = 0;
                    List<T> exportRows = exportRowsSupplier.apply(startIndex, DETAILED_EXPORT_STEP_SIZE);
                    while (!exportRows.isEmpty()) {
                        try {
                            for (T exportRow : exportRows) {
                                for (int i = 0; i < readMethods.size(); i++) {
                                    Method method = readMethods.get(i);
                                    Function<T, ?> subEntityProvider = subEntityProviders.getOrDefault(method,
                                            null);
                                    Object entity = subEntityProvider != null
                                            ? subEntityProvider.apply(exportRow)
                                            : exportRow;
                                    // Sub entity might be null
                                    Object value = entity != null ? method.invoke(entity) : null;
                                    if (value == null) {
                                        fieldValues[i] = "";
                                    } else if (value instanceof Date) {
                                        fieldValues[i] = DateHelper.formatLocalShortDate((Date) value);
                                    } else if (value.getClass().equals(boolean.class)
                                            || value.getClass().equals(Boolean.class)) {
                                        fieldValues[i] = DataHelper.parseBoolean((Boolean) value);
                                    } else if (value instanceof Set) {
                                        StringBuilder sb = new StringBuilder();
                                        for (Object o : (Set<?>) value) {
                                            if (sb.length() != 0) {
                                                sb.append(", ");
                                            }
                                            sb.append(o);
                                        }
                                        fieldValues[i] = sb.toString();
                                    } else {
                                        fieldValues[i] = value.toString();
                                    }
                                }
                                writer.writeNext(fieldValues);
                            }
                            ;
                        } catch (InvocationTargetException | IllegalAccessException
                                | IllegalArgumentException e) {
                            throw new RuntimeException(e);
                        }

                        writer.flush();
                        startIndex += DETAILED_EXPORT_STEP_SIZE;
                        exportRows = exportRowsSupplier.apply(startIndex, DETAILED_EXPORT_STEP_SIZE);
                    }
                }
                return new BufferedInputStream(new ByteArrayInputStream(byteStream.toByteArray()));
            } catch (IOException e) {
                // TODO This currently requires the user to click the "Export" button again or reload the page as the UI
                // is not automatically updated; this should be changed once Vaadin push is enabled (see #516)
                new Notification(I18nProperties.getString(Strings.headingExportFailed),
                        I18nProperties.getString(Strings.messageExportFailed), Type.ERROR_MESSAGE, false)
                                .show(Page.getCurrent());
                return null;
            }
        }
    }, exportFileName);
    extendedStreamResource.setMIMEType("text/csv");
    extendedStreamResource.setCacheTime(0);
    return extendedStreamResource;
}

From source file:eu.maxschuster.vaadin.signaturefield.demo.DemoUI.java

License:Apache License

@Override
protected void init(VaadinRequest request) {

    getPage().setTitle(pageTitle);/*from   w  w w .j ava 2 s. com*/

    final VerticalLayout margin = new VerticalLayout();
    setContent(margin);

    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    layout.setSpacing(true);
    layout.setWidth("658px");
    margin.addComponent(layout);
    margin.setComponentAlignment(layout, Alignment.TOP_CENTER);

    final Label header1 = new Label(pageTitle);
    header1.addStyleName("h1");
    header1.setSizeUndefined();
    layout.addComponent(header1);
    layout.setComponentAlignment(header1, Alignment.TOP_CENTER);

    final TabSheet tabSheet = new TabSheet();
    tabSheet.setWidth("100%");
    layout.addComponent(tabSheet);
    layout.setComponentAlignment(tabSheet, Alignment.TOP_CENTER);

    final Panel signaturePanel = new Panel();
    signaturePanel.addStyleName("signature-panel");
    signaturePanel.setWidth("100%");
    tabSheet.addTab(signaturePanel, "Demo");

    final VerticalLayout signatureLayout = new VerticalLayout();
    signatureLayout.setMargin(true);
    signatureLayout.setSpacing(true);
    signatureLayout.setSizeFull();
    signaturePanel.setContent(signatureLayout);

    final SignatureField signatureField = new SignatureField();
    signatureField.setWidth("100%");
    signatureField.setHeight("318px");
    signatureField.setPenColor(Color.ULTRAMARINE);
    signatureField.setBackgroundColor("white");
    signatureField.setConverter(new StringToDataUrlConverter());
    signatureField.setPropertyDataSource(dataUrlProperty);
    signatureField.setVelocityFilterWeight(0.7);
    signatureLayout.addComponent(signatureField);
    signatureLayout.setComponentAlignment(signatureField, Alignment.MIDDLE_CENTER);

    final HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    buttonLayout.setWidth("100%");
    signatureLayout.addComponent(buttonLayout);

    final Button clearButton = new Button("Clear", new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            signatureField.clear();
        }
    });
    buttonLayout.addComponent(clearButton);
    buttonLayout.setComponentAlignment(clearButton, Alignment.MIDDLE_LEFT);

    final Label message = new Label("Sign above");
    message.setSizeUndefined();
    buttonLayout.addComponent(message);
    buttonLayout.setComponentAlignment(message, Alignment.MIDDLE_CENTER);

    final ButtonLink saveButtonLink = new ButtonLink("Save", null);
    saveButtonLink.setTargetName("_blank");
    buttonLayout.addComponent(saveButtonLink);
    buttonLayout.setComponentAlignment(saveButtonLink, Alignment.MIDDLE_RIGHT);

    final Panel optionsPanel = new Panel();
    optionsPanel.setSizeFull();
    tabSheet.addTab(optionsPanel, "Options");

    final FormLayout optionsLayout = new FormLayout();
    optionsLayout.setMargin(true);
    optionsLayout.setSpacing(true);
    optionsPanel.setContent(optionsLayout);

    final ComboBox mimeTypeComboBox = new ComboBox(null, mimeTypeContainer);
    optionsLayout.addComponent(mimeTypeComboBox);
    mimeTypeComboBox.setItemCaptionPropertyId("mimeType");
    mimeTypeComboBox.setNullSelectionAllowed(false);
    mimeTypeComboBox.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            MimeType mimeType = (MimeType) event.getProperty().getValue();
            signatureField.setMimeType(mimeType);
        }
    });
    mimeTypeComboBox.setValue(MimeType.PNG);
    mimeTypeComboBox.setCaption("Result MIME-Type");

    final CheckBox immediateCheckBox = new CheckBox("immediate", false);
    optionsLayout.addComponent(immediateCheckBox);
    immediateCheckBox.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            boolean immediate = (Boolean) event.getProperty().getValue();
            signatureField.setImmediate(immediate);
        }
    });

    final CheckBox readOnlyCheckBox = new CheckBox("readOnly", false);
    optionsLayout.addComponent(readOnlyCheckBox);
    readOnlyCheckBox.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            boolean readOnly = (Boolean) event.getProperty().getValue();
            signatureField.setReadOnly(readOnly);
            mimeTypeComboBox.setReadOnly(readOnly);
            clearButton.setEnabled(!readOnly);
        }
    });

    final CheckBox requiredCheckBox = new CheckBox("required (causes bug that clears field)", false);
    optionsLayout.addComponent(requiredCheckBox);
    requiredCheckBox.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            boolean required = (Boolean) event.getProperty().getValue();
            signatureField.setRequired(required);
        }
    });

    final CheckBox clearButtonEnabledButton = new CheckBox("clearButtonEnabled", false);
    optionsLayout.addComponent(clearButtonEnabledButton);
    clearButtonEnabledButton.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            boolean clearButtonEnabled = (Boolean) event.getProperty().getValue();
            signatureField.setClearButtonEnabled(clearButtonEnabled);
        }
    });

    final Panel resultPanel = new Panel("Results:");
    resultPanel.setWidth("100%");
    layout.addComponent(resultPanel);

    final VerticalLayout resultLayout = new VerticalLayout();
    resultLayout.setMargin(true);
    resultPanel.setContent(resultLayout);

    final Image stringPreviewImage = new Image("String preview image:");
    stringPreviewImage.setWidth("500px");
    resultLayout.addComponent(stringPreviewImage);

    final Image dataUrlPreviewImage = new Image("DataURL preview image:");
    dataUrlPreviewImage.setWidth("500px");
    resultLayout.addComponent(dataUrlPreviewImage);

    final TextArea textArea = new TextArea("DataURL:");
    textArea.setWidth("100%");
    textArea.setHeight("300px");
    resultLayout.addComponent(textArea);

    final Label emptyLabel = new Label();
    emptyLabel.setCaption("Is Empty:");
    emptyLabel.setValue(String.valueOf(signatureField.isEmpty()));
    resultLayout.addComponent(emptyLabel);

    signatureField.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            String signature = (String) event.getProperty().getValue();
            stringPreviewImage.setSource(signature != null ? new ExternalResource(signature) : null);
            textArea.setValue(signature);
            emptyLabel.setValue(String.valueOf(signatureField.isEmpty()));
        }
    });
    dataUrlProperty.addValueChangeListener(new ValueChangeListener() {

        @Override
        public void valueChange(ValueChangeEvent event) {
            try {
                final DataUrl signature = (DataUrl) event.getProperty().getValue();
                dataUrlPreviewImage.setSource(
                        signature != null ? new ExternalResource(serializer.serialize(signature)) : null);
                StreamResource streamResource = null;
                if (signature != null) {
                    StreamSource streamSource = new StreamSource() {

                        @Override
                        public InputStream getStream() {
                            return new ByteArrayInputStream(signature.getData());
                        }
                    };
                    MimeType mimeType = MimeType.valueOfMimeType(signature.getMimeType());
                    String extension = null;

                    switch (mimeType) {
                    case JPEG:
                        extension = "jpg";
                        break;
                    case PNG:
                        extension = "png";
                        break;
                    }

                    streamResource = new StreamResource(streamSource, "signature." + extension);
                    streamResource.setMIMEType(signature.getMimeType());
                    streamResource.setCacheTime(0);
                }
                saveButtonLink.setResource(streamResource);
            } catch (MalformedURLException e) {
                logger.error(e.getMessage(), e);
            }
        }
    });
}

From source file:fi.vtt.RVaadin.RContainer.java

License:Apache License

/**
 * 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./*from w w  w  .  j a  v a  2s.c o  m*/
 * 
 * @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;
}