Example usage for com.vaadin.ui Upload Upload

List of usage examples for com.vaadin.ui Upload Upload

Introduction

In this page you can find the example usage for com.vaadin.ui Upload Upload.

Prototype

public Upload(String caption, Receiver uploadReceiver) 

Source Link

Usage

From source file:de.catma.ui.dialog.UploadDialog.java

License:Open Source License

private void initComponents() {
    setSizeFull();/*from  w  ww.j av a 2 s  . c o  m*/
    setSpacing(true);

    dialogWindow = new Window(caption);
    dialogWindow.setModal(true);

    upload = new Upload("Please select a file to upload", new DataReceiver(data));
    upload.setButtonCaption("Select file");
    upload.setImmediate(true);

    addComponent(upload);
    pi = new ProgressIndicator();
    pi.setVisible(false);
    addComponent(pi);

    HorizontalLayout buttonPanel = new HorizontalLayout();
    buttonPanel.setSpacing(true);

    btCancel = new Button("Cancel");
    buttonPanel.addComponent(btCancel);

    addComponent(buttonPanel);
    this.setComponentAlignment(buttonPanel, Alignment.BOTTOM_RIGHT);

    dialogWindow.addComponent(this);

    upload.focus();

}

From source file:de.unioninvestment.portal.explorer.view.vfs.TableView.java

License:Apache License

public void attach() {

    selectedDir = cb.getVfsUrl();//from   ww  w.  ja  v  a 2  s .c  o m
    try {

        final VFSFileExplorerPortlet app = instance;
        final User user = (User) app.getUser();
        final FileSystemManager fFileSystemManager = fileSystemManager;
        final FileSystemOptions fOpts = opts;

        final Table table = new Table() {

            private static final long serialVersionUID = 1L;

            protected String formatPropertyValue(Object rowId, Object colId, Property property) {

                if (TABLE_PROP_FILE_NAME.equals(colId)) {
                    if (property != null && property.getValue() != null) {
                        return getDisplayPath(property.getValue().toString());
                    }
                }
                if (TABLE_PROP_FILE_DATE.equals(colId)) {
                    if (property != null && property.getValue() != null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("dd.MMM yyyy HH:mm:ss");
                        return sdf.format((Date) property.getValue());
                    }
                }
                return super.formatPropertyValue(rowId, colId, property);
            }

        };
        table.setSizeFull();
        table.setMultiSelect(true);
        table.setSelectable(true);
        table.setImmediate(true);
        table.addContainerProperty(TABLE_PROP_FILE_NAME, String.class, null);
        table.addContainerProperty(TABLE_PROP_FILE_SIZE, Long.class, null);
        table.addContainerProperty(TABLE_PROP_FILE_DATE, Date.class, null);
        if (app != null) {
            app.getEventBus().addHandler(TableChangedEvent.class, new TableChangedEventHandler() {
                private static final long serialVersionUID = 1L;

                @Override
                public void onValueChanged(TableChangedEvent event) {
                    try {
                        selectedDir = event.getNewDirectory();
                        fillTableData(event.getNewDirectory(), table, fFileSystemManager, fOpts, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        table.addListener(new Table.ValueChangeListener() {
            private static final long serialVersionUID = 1L;

            public void valueChange(ValueChangeEvent event) {

                Set<?> value = (Set<?>) event.getProperty().getValue();
                if (null == value || value.size() == 0) {
                    markedRows = null;
                } else {
                    markedRows = value;
                }
            }
        });

        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);

        Button btDownload = new Button("Download File(s)");
        btDownload.addListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {
                if (markedRows == null || markedRows.size() == 0)
                    getWindow().showNotification("No Files selected !",
                            Window.Notification.TYPE_WARNING_MESSAGE);
                else {
                    String[] files = new String[markedRows.size()];
                    int fileCount = 0;

                    for (Object item : markedRows) {
                        Item it = table.getItem(item);
                        files[fileCount] = it.getItemProperty(TABLE_PROP_FILE_NAME).toString();
                        fileCount++;
                    }

                    File dlFile = null;
                    if (fileCount == 1) {
                        try {
                            String fileName = files[0];
                            dlFile = getFileFromVFSObject(fFileSystemManager, fOpts, fileName);
                            logger.log(Level.INFO,
                                    "vfs2portlet: download file " + fileName + " by " + user.getScreenName());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        byte[] buf = new byte[1024];

                        try {
                            dlFile = File.createTempFile("Files", ".zip");
                            ZipOutputStream out = new ZipOutputStream(
                                    new FileOutputStream(dlFile.getAbsolutePath()));
                            for (int i = 0; i < files.length; i++) {
                                String fileName = files[i];
                                logger.log(Level.INFO, "vfs2portlet: download file " + fileName + " by "
                                        + user.getScreenName());
                                File f = getFileFromVFSObject(fFileSystemManager, fOpts, fileName);
                                FileInputStream in = new FileInputStream(f);
                                out.putNextEntry(new ZipEntry(f.getName()));
                                int len;
                                while ((len = in.read(buf)) > 0) {
                                    out.write(buf, 0, len);
                                }
                                out.closeEntry();
                                in.close();
                            }
                            out.close();
                        } catch (IOException e) {
                        }

                    }

                    if (dlFile != null) {
                        try {
                            DownloadResource downloadResource = new DownloadResource(dlFile, getApplication());
                            getApplication().getMainWindow().open(downloadResource, "_new");
                        } catch (FileNotFoundException e) {
                            getWindow().showNotification("File not found !",
                                    Window.Notification.TYPE_ERROR_MESSAGE);
                            e.printStackTrace();
                        }

                    }

                    if (dlFile != null) {
                        dlFile.delete();
                    }
                }

            }
        });

        Button btDelete = new Button("Delete File(s)");
        btDelete.addListener(new Button.ClickListener() {
            private static final long serialVersionUID = 1L;

            public void buttonClick(ClickEvent event) {

                if (markedRows == null || markedRows.size() == 0)
                    getWindow().showNotification("No Files selected !",
                            Window.Notification.TYPE_WARNING_MESSAGE);
                else {
                    for (Object item : markedRows) {
                        Item it = table.getItem(item);
                        String fileToDelete = it.getItemProperty(TABLE_PROP_FILE_NAME).toString();
                        logger.log(Level.INFO, "Delete File " + fileToDelete);
                        try {
                            FileObject delFile = fFileSystemManager.resolveFile(fileToDelete, fOpts);
                            logger.log(Level.INFO, "vfs2portlet: delete file " + delFile.getName() + " by "
                                    + user.getScreenName());
                            boolean b = delFile.delete();
                            if (b)
                                logger.log(Level.INFO, "delete ok");
                            else
                                logger.log(Level.INFO, "delete failed");
                        } catch (FileSystemException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

        Button selAll = new Button("Select All", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                table.setValue(table.getItemIds());
            }
        });

        Button selNone = new Button("Select None", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                table.setValue(null);
            }
        });

        final UploadReceiver receiver = new UploadReceiver();
        upload = new Upload(null, receiver);
        upload.setImmediate(true);
        upload.setButtonCaption("File Upload");

        upload.addListener((new Upload.SucceededListener() {

            private static final long serialVersionUID = 1L;

            public void uploadSucceeded(SucceededEvent event) {

                try {
                    String fileName = receiver.getFileName();
                    ByteArrayOutputStream bos = receiver.getUploadedFile();
                    byte[] buf = bos.toByteArray();
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    String fileToAdd = selectedDir + "/" + fileName;
                    logger.log(Level.INFO,
                            "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName());
                    FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts);
                    localFile.createFile();
                    OutputStream localOutputStream = localFile.getContent().getOutputStream();
                    IOUtils.copy(bis, localOutputStream);
                    localOutputStream.flush();
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    app.getMainWindow().showNotification("Upload " + fileName + " successful ! ",
                            Notification.TYPE_TRAY_NOTIFICATION);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }));

        upload.addListener(new Upload.FailedListener() {
            private static final long serialVersionUID = 1L;

            public void uploadFailed(FailedEvent event) {
                System.out.println("Upload failed ! ");
            }
        });

        multiFileUpload = new MultiFileUpload() {

            private static final long serialVersionUID = 1L;

            protected void handleFile(File file, String fileName, String mimeType, long length) {
                try {
                    byte[] buf = FileUtils.readFileToByteArray(file);
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    String fileToAdd = selectedDir + "/" + fileName;
                    logger.log(Level.INFO,
                            "vfs2portlet: add file " + fileToAdd + " by " + user.getScreenName());
                    FileObject localFile = fFileSystemManager.resolveFile(fileToAdd, fOpts);
                    localFile.createFile();
                    OutputStream localOutputStream = localFile.getContent().getOutputStream();
                    IOUtils.copy(bis, localOutputStream);
                    localOutputStream.flush();
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                } catch (FileSystemException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            protected FileBuffer createReceiver() {
                FileBuffer receiver = super.createReceiver();
                /*
                 * Make receiver not to delete files after they have been
                 * handled by #handleFile().
                 */
                receiver.setDeleteFiles(false);
                return receiver;
            }
        };
        multiFileUpload.setUploadButtonCaption("Upload File(s)");

        HorizontalLayout filterGrp = new HorizontalLayout();
        filterGrp.setSpacing(true);
        final TextField tfFilter = new TextField();
        Button btFileFilter = new Button("Filter", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                String filterVal = (String) tfFilter.getValue();
                try {
                    if (filterVal == null || filterVal.length() == 0) {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                    } else {
                        fillTableData(selectedDir, table, fFileSystemManager, fOpts, filterVal);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        Button btResetFileFilter = new Button("Reset", new Button.ClickListener() {

            private static final long serialVersionUID = 1L;

            public void buttonClick(Button.ClickEvent event) {
                try {
                    tfFilter.setValue("");
                    fillTableData(selectedDir, table, fFileSystemManager, fOpts, null);
                } catch (ReadOnlyException e) {
                    e.printStackTrace();
                } catch (ConversionException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        filterGrp.addComponent(tfFilter);
        filterGrp.addComponent(btFileFilter);
        filterGrp.addComponent(btResetFileFilter);

        addComponent(filterGrp);

        addComponent(table);

        HorizontalLayout btGrp = new HorizontalLayout();

        btGrp.setSpacing(true);
        btGrp.addComponent(selAll);
        btGrp.setComponentAlignment(selAll, Alignment.MIDDLE_CENTER);
        btGrp.addComponent(selNone);
        btGrp.setComponentAlignment(selNone, Alignment.MIDDLE_CENTER);
        btGrp.addComponent(btDownload);
        btGrp.setComponentAlignment(btDownload, Alignment.MIDDLE_CENTER);

        List<Role> roles = null;
        boolean matchUserRole = false;
        try {

            if (user != null) {
                roles = user.getRoles();

            }
        } catch (SystemException e) {
            e.printStackTrace();
        }

        if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() == 0) {
            btGrp.addComponent(btDelete);
            btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER);
        } else if (cb.isDeleteEnabled() && cb.getDeleteRoles().length() > 0) {
            matchUserRole = isUserInRole(roles, cb.getDeleteRoles());
            if (matchUserRole) {
                btGrp.addComponent(btDelete);
                btGrp.setComponentAlignment(btDelete, Alignment.MIDDLE_CENTER);
            }

        }
        if (cb.isUploadEnabled() && cb.getUploadRoles().length() == 0) {
            btGrp.addComponent(upload);
            btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER);
            btGrp.addComponent(multiFileUpload);
            btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER);
        } else if (cb.isUploadEnabled() && cb.getUploadRoles().length() > 0) {

            matchUserRole = isUserInRole(roles, cb.getUploadRoles());
            if (matchUserRole) {
                btGrp.addComponent(upload);
                btGrp.setComponentAlignment(upload, Alignment.MIDDLE_CENTER);
                btGrp.addComponent(multiFileUpload);
                btGrp.setComponentAlignment(multiFileUpload, Alignment.MIDDLE_CENTER);
            }
        }
        addComponent(btGrp);

    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:dhbw.ka.mwi.businesshorizon2.ui.initialscreen.InitialScreenViewImpl.java

License:Open Source License

public void createImportButton() {
    importButton = new VerticalLayout();
    importButton.setWidth(150, com.vaadin.terminal.Sizeable.UNITS_PIXELS);
    importButton.setHeight(80, com.vaadin.terminal.Sizeable.UNITS_PIXELS);
    importButton.setStyleName("topBarButtonContainer");
    UploadReceiver receiver = new UploadReceiver(eventBus);
    Upload upload = new Upload(null, receiver);
    upload.setButtonCaption("");
    upload.setImmediate(true);/*from   ww w. j a v  a  2 s. c  o m*/
    upload.addListener(receiver);
    upload.setStyleName("importButton");
    upload.setWidth(30, com.vaadin.terminal.Sizeable.UNITS_PIXELS);
    upload.setHeight(30, com.vaadin.terminal.Sizeable.UNITS_PIXELS);
    Label gap = new Label();
    gap.setHeight("5px");
    Label label = new Label("Projekte");
    label.setStyleName("topBarButtonLabel");
    label.setSizeUndefined();
    Label label2 = new Label("importieren");
    label2.setStyleName("topBarButtonLabel");
    label2.setSizeUndefined();
    VerticalLayout labelLayout = new VerticalLayout();
    labelLayout.setHeight(45, com.vaadin.terminal.Sizeable.UNITS_PIXELS);
    labelLayout.setWidth(100, UNITS_PERCENTAGE);
    importButton.addComponent(upload);
    labelLayout.addComponent(label);
    labelLayout.addComponent(label2);
    importButton.addComponent(gap);
    importButton.addComponent(labelLayout);
    importButton.setComponentAlignment(upload, Alignment.TOP_CENTER);
    labelLayout.setComponentAlignment(label, Alignment.MIDDLE_CENTER);
    labelLayout.setComponentAlignment(label2, Alignment.MIDDLE_CENTER);
}

From source file:fi.aalto.drumbeat.drumbeatUI.DrumbeatinterfaceUI.java

License:Open Source License

@SuppressWarnings("deprecation")
private void createTab_Datasets() {
    VerticalLayout tab_datasets = new VerticalLayout();
    tab_datasets.setCaption("Data sets");
    tabsheet.addTab(tab_datasets);//from  w  ww .  j a  va 2 s  . co  m
    tab_datasets.addComponent(datasets_tree);
    Link void_link = new Link("Void description of the data sets",
            new ExternalResource("http://drumbeat.cs.hut.fi/void.ttl"));
    tab_datasets.addComponent(void_link);
    Panel p_model = new Panel("Upload and convert an IFC file");
    p_model.setWidth("900");
    tab_datasets.addComponent(p_model);

    HorizontalLayout hor1 = new HorizontalLayout();
    hor1.setSizeFull(); // Use all available space
    hor1.setMargin(true);
    p_model.setContent(hor1);

    VerticalLayout upload_selections = new VerticalLayout();
    hor1.addComponent(upload_selections);

    upload_selections.addComponent(sites_tree_4upload);
    VerticalLayout upload_panels = new VerticalLayout();
    hor1.addComponent(upload_panels);

    Panel p_model_file = new Panel("Upload a file");
    p_model_file.setWidth("400");
    upload_panels.addComponent(p_model_file);

    Panel p_model_url = new Panel("Upload from a URL");
    p_model_url.setWidth("400");
    upload_panels.addComponent(p_model_url);

    // Create the upload with a caption and set receiver later
    Upload upload = new Upload("Select a file and press Upload", drumbeat_fileReceiver);
    upload.addSucceededListener(drumbeat_fileReceiver);
    upload.addFailedListener(drumbeat_fileReceiver);
    p_model_file.setContent(upload);

    url_textField.setImmediate(true);
    Button button = new Button("Upload from the URL", new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            drumbeat_fileReceiver.receiveFileFromURL(url_textField.getValue());
        }
    });

    HorizontalLayout url_upload = new HorizontalLayout();
    url_upload.setSizeUndefined();
    url_upload.addComponent(url_textField);
    url_upload.addComponent(button);
    url_upload.setSpacing(true);
    p_model_url.setContent(url_upload);

    bim_projects_selection.setInvalidAllowed(false);
    bim_projects_selection.setNullSelectionAllowed(false);
    bim_projects_selection.setNewItemsAllowed(false);
    bim_projects_selection.setWidth("400");
    final VerticalLayout project_browser = new VerticalLayout();
    bim_projects_selection.addListener(new Property.ValueChangeListener() {
        private static final long serialVersionUID = -5188369735622627751L;

        public void valueChange(ValueChangeEvent event) {
            if (bim_projects_selection.getValue() != null) {
                htmlView_BIMProject(project_browser, bim_projects.get(bim_projects_selection.getValue()));
            }
        }
    });

    tab_datasets.addComponent(bim_projects_selection);
    tab_datasets.addComponent(project_browser);
}

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

License:Apache License

/**
 * Contruct an upload element for R (implemented as Vaadin CustomComponent).
 * /* w w w  .ja  v  a 2  s .  c  o m*/
 * @param caption
 *            String caption or null
 * @param R
 *            the corresponding RSession to upload the files to
 */
public RUpload(String caption, RContainer R) {

    /* Create the RUpload custom component */
    super.setSizeUndefined();
    root = new Panel(caption);
    root.setWidth("90ex");

    setCompositionRoot(root);

    HorizontalLayout hbox = new HorizontalLayout();
    hbox.setWidth("100%");

    /* Create the Upload component */
    final Upload upload = new Upload("Choose file", this);
    upload.setButtonCaption("Submit");

    /* Listen for events regarding the success of upload. */
    upload.addSucceededListener(this);
    upload.addFailedListener(this);
    hbox.addComponent(upload);

    Label hfill = new Label();
    hbox.addComponent(hfill);
    hbox.setExpandRatio(hfill, 1.0f);

    remove = new Button("Remove", new Button.ClickListener() {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {
            String current = getSelection();

            if (current != null) {
                /* Delete the file */
                delete(current);

                /* Update the lists and the notification area */
                int i = fileNames.indexOf(current);
                fileNames.remove(i);
                mimeTypes.remove(i);
                uploadedFiles.removeItem(current);

                /* Gray out the button, if this was the last item */
                if (fileNames.isEmpty()) {
                    remove.setEnabled(false);
                }
            }
        }
    });

    hbox.addComponent(remove);
    remove.setEnabled(false);
    hbox.setComponentAlignment(remove, Alignment.BOTTOM_RIGHT);

    /* Notification area for already uploaded files */
    uploadedFiles = new ListSelect("Already submitted files");
    uploadedFiles.setMultiSelect(false);
    uploadedFiles.setNullSelectionAllowed(false);
    uploadedFiles.setHeight("4em");
    uploadedFiles.setWidth("100%");

    // Changed for Vaadin 7, not tested!!
    VerticalLayout vbox = new VerticalLayout();
    vbox.addComponent(hbox);
    vbox.addComponent(uploadedFiles);
    root.setContent(vbox);

    /* Bind the component to the given R session */
    this.R = R;
}

From source file:fr.amapj.view.views.importdonnees.ImportDonneesView.java

License:Open Source License

private Component getUtilisateurPanel() {
    VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);// www.  j  av a2  s.c om

    addEmptyLine(layout);
    addLabel(layout,
            "Pour importer les utilisateurs en masse, vous devez remplir un fichier Excel  un certain format.");
    addLabel(layout, "Pour avoir un exemple du fichier  remplir, merci de cliquer sur ce lien :");
    layout.addComponent(LinkCreator.createLink(new EGListeAdherent(Type.EXAMPLE)));
    addEmptyLine(layout);

    addLabel(layout, "Une fois que votre fichier Excel est prt, vous pouvez le charger dans l'application."
            + " Pour cela, cliquez sur le bouton \"Charger les utilisateurs\", slectionnez votre fichier, cliquez sur OK. Les utilisateurs seront alors automatiquement crs, sans mot de passe ");
    addEmptyLine(layout);
    //
    UtilisateurImporter utilisateurImporter = new UtilisateurImporter();
    Upload upload = new Upload(null, utilisateurImporter);
    upload.addSucceededListener(utilisateurImporter);
    upload.setImmediate(true);
    upload.setButtonCaption("Charger les utilisateurs");

    layout.addComponent(upload);

    addEmptyLine(layout);

    return layout;
}

From source file:fr.amapj.view.views.importdonnees.ImportDonneesView.java

License:Open Source License

private Component getProduitPanel() {
    VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);// ww w  .j av a  2s  .  c  o  m

    addEmptyLine(layout);
    addLabel(layout,
            "Pour importer les produits et les producteurs en masse, vous devez remplir un fichier Excel  un certain format.");
    addLabel(layout, "Pour avoir un exemple du fichier  remplir, merci de cliquer sur ce lien :");
    layout.addComponent(LinkCreator.createLink(new EGListeProduitProducteur(
            fr.amapj.service.services.edgenerator.excel.EGListeProduitProducteur.Type.EXAMPLE)));
    addEmptyLine(layout);

    addLabel(layout, "Une fois que votre fichier Excel est prt, vous pouvez le charger dans l'application."
            + " Pour cela, cliquez sur le bouton \"Charger les produits et les producteurs\", slectionnez votre fichier, cliquez sur OK. Les produits et les producteurs seront alors automatiquement crs.");

    //

    ProduitImporter produitImporter = new ProduitImporter();
    Upload upload = new Upload(null, produitImporter);
    upload.addSucceededListener(produitImporter);
    upload.setImmediate(true);
    upload.setButtonCaption("Charger les produits et les producteurs");

    addEmptyLine(layout);
    layout.addComponent(upload);
    addEmptyLine(layout);

    return layout;
}

From source file:info.magnolia.dam.app.assets.field.PermissionedUploadAssetActionRenderer.java

License:Open Source License

@Override
public View start(final ActionDefinition action, final ActionListener listener) {
    this.upload = new Upload(action.getLabel(), receiver) {
        @Override//  w ww.  ja  va  2 s  .  c  o m
        public void setCaption(String caption) {
            setButtonCaption(caption);
        }
    };

    this.upload.addStartedListener(new StartedListener() {
        @Override
        public void uploadStarted(StartedEvent event) {
            UI.getCurrent().setPollInterval(1000);
            progressIndicator = new ProgressPopup(upload, i18n);
            progressIndicatorCloseHandle = layer.openOverlay(new ViewAdapter(progressIndicator),
                    ModalityLevel.NON_MODAL);
            progressIndicator.progressIndicator.setProgress(0);
            progressIndicator.progressIndicator.setVisible(true);
        }
    });

    this.upload.addFinishedListener(new FinishedListener() {
        @Override
        public void uploadFinished(FinishedEvent event) {
            UI.getCurrent().setPollInterval(-1);
            progressIndicatorCloseHandle.close();
        }
    });

    this.upload.addProgressListener(new ProgressListener() {
        @Override
        public void updateProgress(long readBytes, long contentLength) {
            progressIndicator.progressIndicator.refreshLayout(readBytes, contentLength, receiver.getFileName());
        }
    });

    this.upload.addFailedListener(new FailedListener() {
        @Override
        public void uploadFailed(FailedEvent event) {
            progressIndicatorCloseHandle.close();
        }
    });

    this.upload.addSucceededListener(new SucceededListener() {
        @Override
        public void uploadSucceeded(SucceededEvent event) {
            listener.onActionFired(action.getName(), upload.getReceiver());
        }
    });

    this.upload.setImmediate(true);
    return new ViewAdapter(upload);
}

From source file:info.magnolia.ui.form.field.upload.AbstractUploadField.java

License:Open Source License

/**
 * Create the Upload component./*from www.ja  va  2  s . co m*/
 */
private void createUpload() {
    this.upload = new Upload(null, getValue());
    this.upload.addStartedListener(this);
    this.upload.addFinishedListener(this);
    this.upload.addProgressListener(this);
    this.upload.setImmediate(true);
}

From source file:io.mateu.ui.vaadin.framework.MyUI.java

License:Apache License

/**
 * abre el dilogo para cambiar la foto/* w ww  .j a  v a  2 s . com*/
 *
 *
 */
private void uploadFoto() {
    // Create a sub-window and set the content
    Window subWindow = new Window("My photo");

    subWindow.setWidth("475px");

    FormLayout f = new FormLayout();
    f.setMargin(true);

    Label e = new Label();

    Image image = new Image();

    class MyUploader implements Upload.Receiver, Upload.SucceededListener {

        File file;

        public File getFile() {
            return file;
        }

        public OutputStream receiveUpload(String fileName, String mimeType) {
            // Create and return a file output stream

            System.out.println("receiveUpload(" + fileName + "," + mimeType + ")");

            FileOutputStream os = null;
            if (fileName != null && !"".equals(fileName)) {

                long id = fileId++;
                String extension = ".tmp";
                if (fileName == null || "".equals(fileName.trim()))
                    fileName = "" + id + extension;
                if (fileName.lastIndexOf(".") < fileName.length() - 1) {
                    extension = fileName.substring(fileName.lastIndexOf("."));
                    fileName = fileName.substring(0, fileName.lastIndexOf("."));
                }
                File temp = null;
                try {
                    temp = File.createTempFile(fileName, extension);
                    os = new FileOutputStream(file = temp);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return os;
        }

        public void uploadSucceeded(Upload.SucceededEvent event) {
            // Show the uploaded file in the image viewer
            image.setSource(new FileResource(file));
            System.out.println("uploadSucceeded(" + file.getAbsolutePath() + ")");

        }

        public FileLocator getFileLocator() throws IOException {

            String extension = ".tmp";
            String fileName = file.getName();

            if (file.getName() == null || "".equals(file.getName().trim()))
                fileName = "" + getId();
            if (fileName.lastIndexOf(".") < fileName.length() - 1) {
                extension = fileName.substring(fileName.lastIndexOf("."));
                fileName = fileName.substring(0, fileName.lastIndexOf(".")).replaceAll(" ", "_");
            }

            java.io.File temp = (System.getProperty("tmpdir") == null)
                    ? java.io.File.createTempFile(fileName, extension)
                    : new java.io.File(new java.io.File(System.getProperty("tmpdir")), fileName + extension);

            System.out.println("java.io.tmpdir=" + System.getProperty("java.io.tmpdir"));
            System.out.println("Temp file : " + temp.getAbsolutePath());

            if (System.getProperty("tmpdir") == null || !temp.exists()) {
                System.out.println("writing temp file to " + temp.getAbsolutePath());
                Files.copy(file, temp);
            } else {
                System.out.println("temp file already exists");
            }

            String baseUrl = System.getProperty("tmpurl");
            URL url = null;
            try {
                if (baseUrl == null) {
                    url = file.toURI().toURL();
                } else
                    url = new URL(baseUrl + "/" + file.getName());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            return new FileLocator(0, file.getName(), url.toString(), file.getAbsolutePath());
        }
    }
    ;
    MyUploader receiver = new MyUploader();

    Upload upload = new Upload(null, receiver);
    //upload.setImmediateMode(false);
    upload.addSucceededListener(receiver);

    f.addComponent(image);

    f.addComponent(upload);

    f.addComponent(e);

    VerticalLayout v = new VerticalLayout();
    v.addComponent(f);

    HorizontalLayout footer = new HorizontalLayout();
    footer.setWidth("100%");
    footer.setSpacing(true);
    footer.addStyleName(ValoTheme.WINDOW_BOTTOM_TOOLBAR);

    Label footerText = new Label("");
    footerText.setSizeUndefined();

    Button ok = new Button("Change it!", new ClickListener() {
        @Override
        public void buttonClick(ClickEvent clickEvent) {
            e.setValue("Changing photo...");
            try {
                FileLocator loc = receiver.getFileLocator();

                io.mateu.ui.core.client.app.MateuUI.getBaseService()
                        .updateFoto(getApp().getUserData().getLogin(), loc, new AsyncCallback<Void>() {

                            @Override
                            public void onFailure(Throwable caught) {
                                e.setValue("" + caught.getClass().getName() + ": " + caught.getMessage());
                            }

                            @Override
                            public void onSuccess(Void result) {
                                e.setValue("OK!");
                                getApp().getUserData().setPhoto(loc.getUrl());
                                foto = (getApp().getUserData().getPhoto() != null)
                                        ? new ExternalResource(getApp().getUserData().getPhoto())
                                        : new ClassResource("profile-pic-300px.jpg");
                                subWindow.close();

                                refreshSettings();

                            }
                        });

            } catch (IOException e1) {
                e1.printStackTrace();
                io.mateu.ui.core.client.app.MateuUI.alert("" + e1.getClass().getName() + ":" + e1.getMessage());
            }

        }
    });
    ok.addStyleName(ValoTheme.BUTTON_PRIMARY);
    ok.setClickShortcut(ShortcutAction.KeyCode.ENTER);

    Button cancel = new Button("Cancel");

    footer.addComponents(footerText, ok); //, cancel);
    footer.setExpandRatio(footerText, 1);

    v.addComponent(footer);

    subWindow.setContent(v);

    // Center it in the browser window
    subWindow.center();

    subWindow.setModal(true);

    // Open it in the UI
    UI.getCurrent().addWindow(subWindow);

    upload.focus();
}