Example usage for com.vaadin.ui Upload addFinishedListener

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

Introduction

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

Prototype

public Registration addFinishedListener(FinishedListener listener) 

Source Link

Document

Adds the upload received event listener.

Usage

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

License:Apache License

protected Upload initChangePictureButton() {
    final Upload changePictureUpload = new Upload();
    changePictureUpload.setImmediate(true);
    changePictureUpload.setButtonCaption(i18nManager.getMessage(Messages.PROFILE_CHANGE_PICTURE));

    final InMemoryUploadReceiver receiver = initPictureReceiver(changePictureUpload);
    changePictureUpload.addFinishedListener(new FinishedListener() {
        private static final long serialVersionUID = 1L;

        public void uploadFinished(FinishedEvent event) {
            if (!receiver.isInterruped()) {
                picture = new Picture(receiver.getBytes(), receiver.getMimeType());
                identityService.setUserPicture(userId, picture);

                // reset picture
                imageLayout.removeAllComponents();
                initPicture();//from  www. j  a  v a 2  s .  c  o  m
            } else {
                receiver.reset();
            }
        }
    });

    return changePictureUpload;
}

From source file:com.wcs.wcslib.vaadin.widget.multifileupload.component.SmartMultiUpload.java

License:Apache License

private void initSingleUpload() {
    upload = new CustomUpload();
    Upload singleUpload = (Upload) upload;
    singleUpload.setReceiver(new Upload.Receiver() {
        @Override/*  ww w  . j av  a2s .c o m*/
        public OutputStream receiveUpload(String filename, String mimeType) {
            return handler.getOutputStream();
        }
    });
    singleUpload.setImmediate(true);

    SimpleFileUploadListener uploadEventListener = new SimpleFileUploadListener(handler);
    singleUpload.addStartedListener(uploadEventListener);
    singleUpload.addProgressListener(uploadEventListener);
    singleUpload.addFailedListener(uploadEventListener);
    singleUpload.addFinishedListener(uploadEventListener);
}

From source file:control.ExperimentImportController.java

License:Open Source License

public void init(final String user) {
    ExperimentImportController control = this;
    Upload upload = new Upload("Upload your file here", uploader);
    view.initView(upload);/*from  w  w  w  .j a  v  a 2  s . com*/
    upload.setButtonCaption("Upload");
    // Listen for events regarding the success of upload.
    upload.addFailedListener(uploader);
    upload.addSucceededListener(uploader);
    FinishedListener uploadFinListener = new FinishedListener() {
        /**
         * 
         */
        private static final long serialVersionUID = -8413963075202260180L;

        public void uploadFinished(FinishedEvent event) {
            String uploadError = uploader.getError();
            File file = uploader.getFile();
            view.resetAfterUpload();
            if (file.getPath().endsWith("up_")) {
                String msg = "No file selected.";
                logger.warn(msg);
                Styles.notification("Failed to read file.", msg, NotificationType.ERROR);
                if (!file.delete())
                    logger.error("uploaded tmp file " + file.getAbsolutePath() + " could not be deleted!");
            } else {
                if (uploadError == null || uploadError.isEmpty()) {
                    String msg = "Upload successful!";
                    logger.info(msg);
                    try {
                        view.setRegEnabled(false);
                        prep = new SamplePreparator();
                        Map<String, Set<String>> experimentTypeVocabularies = new HashMap<String, Set<String>>();
                        experimentTypeVocabularies.put("Q_ANTIBODY", vocabs.getAntibodiesMap().keySet());
                        experimentTypeVocabularies.put("Q_CHROMATOGRAPHY_TYPE",
                                vocabs.getChromTypesMap().keySet());
                        experimentTypeVocabularies.put("Q_MS_DEVICE",
                                new HashSet<String>(vocabs.getDeviceMap().values()));
                        experimentTypeVocabularies.put("Q_MS_LCMS_METHOD",
                                new HashSet<String>(vocabs.getLcmsMethods()));

                        VocabularyValidator validator = new VocabularyValidator(experimentTypeVocabularies);
                        boolean readSuccess = prep.processTSV(file, getImportType());
                        boolean vocabValid = false;
                        if (readSuccess) {
                            msProperties = prep.getSpecialExperimentsOfTypeOrNull("Q_MS_MEASUREMENT");
                            mhcProperties = prep.getSpecialExperimentsOfTypeOrNull("Q_MHC_LIGAND_EXTRACTION");
                            List<Map<String, Object>> metadataList = new ArrayList<Map<String, Object>>();
                            if (msProperties != null)
                                metadataList.addAll(msProperties.values());
                            if (mhcProperties != null)
                                metadataList.addAll(mhcProperties.values());
                            vocabValid = validator.validateExperimentMetadata(metadataList);
                        }
                        if (readSuccess && vocabValid) {
                            List<SampleSummaryBean> summaries = prep.getSummary();
                            for (SampleSummaryBean s : summaries) {
                                String translation = reverseTaxMap.get(s.getFullSampleContent());
                                if (translation != null)
                                    s.setSampleContent(translation);
                            }
                            Styles.notification("Upload successful",
                                    "Experiment was successfully uploaded and read.", NotificationType.SUCCESS);
                            switch (getImportType()) {
                            // Standard hierarchic QBiC design
                            case QBIC:
                                view.setSummary(summaries);
                                view.setProcessed(prep.getProcessed());
                                view.setRegEnabled(true);
                                projectInfo = prep.getProjectInfo();
                                break;
                            // Standard non-hierarchic design without QBiC specific keywords
                            case Standard:
                                Map<String, List<String>> catToVocabulary = new HashMap<String, List<String>>();
                                catToVocabulary.put("Species", new ArrayList<String>(taxMap.keySet()));
                                catToVocabulary.put("Tissues", new ArrayList<String>(tissueMap.keySet()));
                                catToVocabulary.put("Analytes", new ArrayList<String>(analytesVocabulary));
                                Map<String, List<String>> missingCategoryToValues = new HashMap<String, List<String>>();
                                missingCategoryToValues.put("Species",
                                        new ArrayList<String>(prep.getSpeciesSet()));
                                missingCategoryToValues.put("Tissues",
                                        new ArrayList<String>(prep.getTissueSet()));
                                missingCategoryToValues.put("Analytes",
                                        new ArrayList<String>(prep.getAnalyteSet()));
                                initMissingInfoListener(prep, missingCategoryToValues, catToVocabulary);
                                break;
                            // MHC Ligands that have already been measured (Filenames exist)
                            case MHC_Ligands_Finished:
                                catToVocabulary = new HashMap<String, List<String>>();
                                catToVocabulary.put("Species", new ArrayList<String>(taxMap.keySet()));
                                catToVocabulary.put("Tissues", new ArrayList<String>(tissueMap.keySet()));
                                catToVocabulary.put("Analytes", new ArrayList<String>(analytesVocabulary));
                                missingCategoryToValues = new HashMap<String, List<String>>();
                                missingCategoryToValues.put("Species",
                                        new ArrayList<String>(prep.getSpeciesSet()));
                                missingCategoryToValues.put("Tissues",
                                        new ArrayList<String>(prep.getTissueSet()));
                                missingCategoryToValues.put("Analytes",
                                        new ArrayList<String>(prep.getAnalyteSet()));
                                initMissingInfoListener(prep, missingCategoryToValues, catToVocabulary);
                                break;
                            default:
                                logger.error("Error parsing tsv: " + prep.getError());
                                // view.showError(prep.getError());
                                Styles.notification("Failed to read file.", prep.getError(),
                                        NotificationType.ERROR);
                                break;
                            }
                        } else {
                            if (!readSuccess) {
                                String error = prep.getError();
                                Styles.notification("Failed to read file.", error, NotificationType.ERROR);
                            } else {
                                String error = validator.getError();
                                Styles.notification("Failed to process file.", error, NotificationType.ERROR);
                            }
                            if (!file.delete())
                                logger.error("uploaded tmp file " + file.getAbsolutePath()
                                        + " could not be deleted!");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    // view.showError(error);
                    Styles.notification("Failed to upload file.", uploadError, NotificationType.ERROR);
                    if (!file.delete())
                        logger.error("uploaded tmp file " + file.getAbsolutePath() + " could not be deleted!");
                }
            }
        }
    };
    upload.addFinishedListener(uploadFinListener);
    // view.initUpload(upload);

    Button.ClickListener cl = new Button.ClickListener() {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        /**
         * 
         */

        @Override
        public void buttonClick(ClickEvent event) {
            String src = event.getButton().getCaption();
            if (src.equals("Register All")) {
                view.getRegisterButton().setEnabled(false);
                view.showRegistration();
                // collect experiment information
                complexExperiments = new ArrayList<OpenbisExperiment>();
                complexExperiments
                        .addAll(collectComplexExperiments(msProperties, ExperimentType.Q_MS_MEASUREMENT));
                complexExperiments.addAll(
                        collectComplexExperiments(mhcProperties, ExperimentType.Q_MHC_LIGAND_EXTRACTION));
                openbisCreator.registerProjectWithExperimentsAndSamplesBatchWise(view.getSamples(),
                        projectInfo.getDescription(), complexExperiments, view.getProgressBar(),
                        view.getProgressLabel(), new RegisteredSamplesReadyRunnable(view, control), user,
                        projectInfo.isPilot());
                List<String> tsv = prep.getOriginalTSV();
                switch (getImportType()) {
                case Standard:
                case MHC_Ligands_Finished:
                    String tsvContent = addBarcodesToTSV(tsv, view.getSamples(), getImportType());
                    view.setTSVWithBarcodes(tsvContent,
                            uploader.getFileNameWithoutExtension() + "_with_barcodes");
                    break;
                default:
                    break;
                }
            }
        }

        private Collection<? extends OpenbisExperiment> collectComplexExperiments(
                Map<String, Map<String, Object>> propsMap, ExperimentType type) {
            List<OpenbisExperiment> res = new ArrayList<OpenbisExperiment>();
            if (propsMap != null) {
                for (String code : propsMap.keySet())
                    res.add(new OpenbisExperiment(code, type, propsMap.get(code)));
            }
            return res;
        }
    };
    view.getRegisterButton().addClickListener(cl);
}

From source file:de.unioninvestment.eai.portal.portlet.crud.mvp.views.DefaultRowEditingFormView.java

License:Apache License

private Upload buildUpload(final ContainerRow row, final ContainerBlob containerBlob,
        final FileMetadata metadata, final Link downloadLink) {
    final Upload upload = new Upload();
    if (metadata.getUploadCaption() != null) {
        upload.setButtonCaption(metadata.getUploadCaption());
    } else {//w  w w .  j a v a2 s. c om
        upload.setButtonCaption("Upload");
    }
    upload.setImmediate(true);
    upload.setReceiver(new BlobUploadReceiver());

    upload.addFinishedListener(new Upload.FinishedListener() {

        private static final long serialVersionUID = 1L;

        @Override
        public void uploadFinished(FinishedEvent event) {
            BlobUploadReceiver receiver = (BlobUploadReceiver) upload.getReceiver();
            if (receiver.getBaos().size() <= 0 || receiver.getBaos().size() <= metadata.getMaxFileSize()) {
                containerBlob.setValue(receiver.getBaos().toByteArray());
                if (metadata.getFilenameColumn() != null) {
                    row.getValues().put(metadata.getFilenameColumn(), receiver.getFilename());

                }
                if (metadata.getMimetypeColumn() != null) {
                    row.getValues().put(metadata.getMimetypeColumn(), receiver.getMimetype());
                }
                updateDownloadLink(row, containerBlob, metadata, downloadLink);

            } else {
                Notification.show(
                        "Ein Datei darauf nicht grer als " + metadata.getMaxFileSize() + " Bytes sein.",
                        Notification.Type.ERROR_MESSAGE);
            }
        }
    });
    return upload;
}

From source file:nz.co.senanque.workflowui.AttachmentPopup.java

License:Apache License

public void load(final long pid) {
    panel.removeAllComponents();//from w  w w . java2 s.  c  o m
    final Upload upload = new Upload(null, receiver);
    upload.setImmediate(true);
    upload.setButtonCaption(m_messageSourceAccessor.getMessage("upload.file", "Upload File"));
    checkbox = new CheckBox(m_messageSourceAccessor.getMessage("upload.protected", "Protected"));
    comment = new TextField(m_messageSourceAccessor.getMessage("upload.comment", "Comment"));
    panel.addComponent(comment);
    panel.addComponent(checkbox);
    panel.addComponent(upload);

    upload.addFinishedListener(new Upload.FinishedListener() {

        private static final long serialVersionUID = 1L;

        public void uploadFinished(FinishedEvent event) {
            Attachment attachment = receiver.getWrapper().getCurrentAttachment();
            attachment.setProcessInstanceId(pid);
            attachment.setComment((String) comment.getValue());
            attachment.setProtectedDocument((boolean) checkbox.getValue());
            m_workflowDAO.addAttachment(attachment);
            close();
        }
    });

    if (getParent() == null) {
        UI.getCurrent().addWindow(this);
        this.center();
    }
}

From source file:org.eclipse.hawkbit.ui.artifacts.upload.UploadLayout.java

License:Open Source License

private void buildLayout() {

    final Upload upload = new Upload();
    final UploadHandler uploadHandler = new UploadHandler(null, 0, this,
            multipartConfigElement.getMaxFileSize(), upload, null, null, softwareModuleManagement);
    upload.setButtonCaption(i18n.getMessage("upload.file"));
    upload.setImmediate(true);// w  w w . ja  v  a 2  s .com
    upload.setReceiver(uploadHandler);
    upload.addSucceededListener(uploadHandler);
    upload.addFailedListener(uploadHandler);
    upload.addFinishedListener(uploadHandler);
    upload.addProgressListener(uploadHandler);
    upload.addStartedListener(uploadHandler);
    upload.addStyleName(SPUIStyleDefinitions.ACTION_BUTTON);
    upload.addStyleName("no-border");

    fileUploadLayout = new HorizontalLayout();
    fileUploadLayout.setSpacing(true);
    fileUploadLayout.addStyleName(SPUIStyleDefinitions.FOOTER_LAYOUT);
    fileUploadLayout.addComponent(upload);
    fileUploadLayout.setComponentAlignment(upload, Alignment.MIDDLE_LEFT);
    fileUploadLayout.addComponent(processBtn);
    fileUploadLayout.setComponentAlignment(processBtn, Alignment.MIDDLE_RIGHT);
    fileUploadLayout.addComponent(discardBtn);
    fileUploadLayout.setComponentAlignment(discardBtn, Alignment.MIDDLE_RIGHT);
    fileUploadLayout.addComponent(uploadStatusButton);
    fileUploadLayout.setComponentAlignment(uploadStatusButton, Alignment.MIDDLE_RIGHT);
    setMargin(false);

    /* create drag-drop wrapper for drop area */
    dropAreaWrapper = new DragAndDropWrapper(createDropAreaLayout());
    dropAreaWrapper.setDropHandler(new DropAreahandler());
    setSizeFull();
    setSpacing(true);
}

From source file:org.hip.vif.web.util.UploadComponent.java

License:Open Source License

private Upload createUpload(final IBibliographyTask inTask) {
    final Upload outUpload = new Upload();
    outUpload.setWidthUndefined();//from  w  w  w. j av  a 2 s  . com
    outUpload.setReceiver(new Upload.Receiver() {
        @Override
        public OutputStream receiveUpload(final String inFilename, // NOPMD
                final String inMimeType) {
            return createStream(inFilename);
        }
    });

    final String lCaption = Activator.getMessages().getMessage("ui.upload.button.lbl"); //$NON-NLS-1$
    outUpload.setButtonCaption(lCaption);
    outUpload.setImmediate(true);
    outUpload.setStyleName("vif-upload"); //$NON-NLS-1$

    outUpload.addStartedListener(new Upload.StartedListener() {
        @Override
        public void uploadStarted(final StartedEvent inEvent) { // NOPMD
            fileInfo = new FileInfo(inEvent.getFilename(), inEvent.getMIMEType());
            tempUpload = null; // NOPMD
            uploadFinished = false;
            outUpload.setVisible(false);
            if (hasDownloads) {
                dialog.setVisible(true); // FF
            }
        }
    });
    outUpload.addFinishedListener(new Upload.FinishedListener() {
        @Override
        public void uploadFinished(final FinishedEvent inEvent) { // NOPMD
            uploadFinished = true;
            outUpload.setVisible(true);
        }
    });
    outUpload.addSucceededListener(new Upload.SucceededListener() {
        @Override
        public void uploadSucceeded(final SucceededEvent inEvent) { // NOPMD
            if (!hasDownloads) {
                handleUpload(inTask, false);
            }
        }
    });
    outUpload.addFailedListener(new Upload.FailedListener() {
        @Override
        public void uploadFailed(final FailedEvent inEvent) { // NOPMD
            handleDeleteTemp();
        }
    });

    return outUpload;
}

From source file:org.ikasan.dashboard.ui.mappingconfiguration.window.MappingConfigurationImportWindow.java

License:BSD License

/**
 * Helper method to initialise this object.
 *//*  w ww .j av  a 2s  .co  m*/
protected void init() {
    this.setModal(true);
    super.setHeight(40.0f, Unit.PERCENTAGE);
    super.setWidth(40.0f, Unit.PERCENTAGE);
    super.center();
    super.setStyleName("ikasan");

    progressLayout.setSpacing(true);
    progressLayout.setVisible(false);
    progressLayout.addComponent(uploadLabel);

    final Upload upload = new Upload("", receiver);
    upload.addSucceededListener(receiver);

    upload.addFinishedListener(new Upload.FinishedListener() {
        public void uploadFinished(FinishedEvent event) {
            upload.setVisible(false);
            try {
                parseUploadFile();
            } catch (Exception e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);

                Notification.show("Caught exception trying to import a Mapping Configuration!\n", sw.toString(),
                        Notification.Type.ERROR_MESSAGE);
            }
        }
    });

    final Button importButton = new Button("Import");
    importButton.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            upload.interruptUpload();
        }
    });

    upload.addStartedListener(new Upload.StartedListener() {
        public void uploadStarted(StartedEvent event) {
            // This method gets called immediately after upload is started
            upload.setVisible(false);
        }
    });

    upload.addProgressListener(new Upload.ProgressListener() {
        public void updateProgress(long readBytes, long contentLength) {
            // This method gets called several times during the update

        }

    });

    importButton.setStyleName(ValoTheme.BUTTON_SMALL);
    importButton.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            try {
                saveImportedMappingConfiguration();
                mappingConfiguration = null;
                progressLayout.setVisible(false);
                upload.setVisible(true);

                IkasanAuthentication authentication = (IkasanAuthentication) VaadinService.getCurrentRequest()
                        .getWrappedSession().getAttribute(DashboardSessionValueConstants.USER);

                systemEventService.logSystemEvent(MappingConfigurationConstants.MAPPING_CONFIGURATION_SERVICE,
                        "Imported mapping configuration: [Client="
                                + mappingConfiguration.getConfigurationServiceClient().getName()
                                + "] [Source Context=" + mappingConfiguration.getSourceContext().getName()
                                + "] [Target Context=" + mappingConfiguration.getTargetContext().getName()
                                + "] [Type=" + mappingConfiguration.getConfigurationType().getName() + "]",
                        authentication.getName());
            } catch (MappingConfigurationServiceException e) {
                if (e.getCause() instanceof DataIntegrityViolationException) {
                    Notification.show("Caught exception trying to save an imported Mapping Configuration!",
                            "This is due to the fact "
                                    + "that, combined, the client, type, source and target context values are unique for a Mapping Configuration. The values"
                                    + " that are being imported and not unique.",
                            Notification.Type.ERROR_MESSAGE);
                } else {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);

                    Notification.show("Caught exception trying to save an imported Mapping Configuration!\n",
                            sw.toString(), Notification.Type.ERROR_MESSAGE);
                }
            }

            close();
        }
    });

    progressLayout.addComponent(importButton);

    VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    layout.addComponent(new Label("Select file to upload mapping configurations."));
    layout.addComponent(upload);

    layout.addComponent(progressLayout);

    Button cancelButton = new Button("Cancel");
    cancelButton.setStyleName(ValoTheme.BUTTON_SMALL);

    cancelButton.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            mappingConfiguration = null;
            progressLayout.setVisible(false);
            upload.setVisible(true);
            close();
        }
    });

    HorizontalLayout hlayout = new HorizontalLayout();
    hlayout.addComponent(cancelButton);

    layout.addComponent(hlayout);

    super.setContent(layout);
}

From source file:org.ikasan.dashboard.ui.mappingconfiguration.window.MappingConfigurationValuesImportWindow.java

License:BSD License

/**
 * Helper method to initialise this object.
 *//*ww w.  java 2 s.  c o  m*/
protected void init() {
    this.setModal(true);
    super.setHeight(40.0f, Unit.PERCENTAGE);
    super.setWidth(40.0f, Unit.PERCENTAGE);
    super.center();
    super.setStyleName("ikasan");

    progressLayout.setSpacing(true);
    progressLayout.setVisible(false);
    progressLayout.addComponent(uploadLabel);

    final Upload upload = new Upload("", receiver);
    upload.addSucceededListener(receiver);

    upload.addFinishedListener(new Upload.FinishedListener() {
        public void uploadFinished(FinishedEvent event) {
            upload.setVisible(false);
            parseUploadFile();
        }
    });

    final Button importButton = new Button("Import");
    importButton.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            upload.interruptUpload();
        }
    });

    upload.addStartedListener(new Upload.StartedListener() {
        public void uploadStarted(StartedEvent event) {
            // This method gets called immediately after upload is started
            upload.setVisible(false);
        }
    });

    upload.addProgressListener(new Upload.ProgressListener() {
        public void updateProgress(long readBytes, long contentLength) {
            // This method gets called several times during the update

        }

    });

    importButton.setStyleName(ValoTheme.BUTTON_SMALL);
    importButton.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            try {
                saveImportedMappingConfigurationValues();

                IkasanAuthentication authentication = (IkasanAuthentication) VaadinService.getCurrentRequest()
                        .getWrappedSession().getAttribute(DashboardSessionValueConstants.USER);

                systemEventService.logSystemEvent(MappingConfigurationConstants.MAPPING_CONFIGURATION_SERVICE,
                        "Imported mapping configuration values for mapping configuration: [Client="
                                + mappingConfiguration.getConfigurationServiceClient().getName()
                                + "] [Source Context=" + mappingConfiguration.getSourceContext().getName()
                                + "] [Target Context=" + mappingConfiguration.getTargetContext().getName()
                                + "] [Type=" + mappingConfiguration.getConfigurationType().getName() + "]",
                        authentication.getName());

                logger.info("User: " + authentication.getName()
                        + " successfully imported the following Mapping Configuration: "
                        + mappingConfiguration);
            } catch (Exception e) {
                Notification.show(
                        "An error occurred trying to import a mapping configuration: " + e.getMessage(),
                        Notification.Type.ERROR_MESSAGE);
            }
            mappingConfigurationConfigurationValuesTable.populateTable(mappingConfiguration);
            close();
        }
    });

    progressLayout.addComponent(importButton);

    VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    layout.addComponent(new Label("Select file to upload mapping configurations."));
    layout.addComponent(upload);

    layout.addComponent(progressLayout);

    Button cancelButton = new Button("Cancel");
    cancelButton.setStyleName(ValoTheme.BUTTON_SMALL);

    cancelButton.addClickListener(new Button.ClickListener() {
        public void buttonClick(ClickEvent event) {
            close();
        }
    });

    HorizontalLayout hlayout = new HorizontalLayout();
    hlayout.addComponent(cancelButton);

    layout.addComponent(hlayout);

    super.setContent(layout);
}

From source file:views.BatchUpload.java

License:Open Source License

public BatchUpload() {
    setMargin(true);//w w  w.j a v  a 2 s. co  m
    setSpacing(true);

    // file upload component
    Upload upload = new Upload("Upload your file here", uploader);
    addComponent(this.upload);
    upload.setEnabled(false);

    // sample registration button
    register = new Button("Register People");
    register.setVisible(false);
    addComponent(register);

    upload.setButtonCaption("Upload");
    // Listen for events regarding the success of upload.
    upload.addFailedListener(uploader);
    upload.addSucceededListener(uploader);
    FinishedListener uploadFinListener = new FinishedListener() {
        /**
         * 
         */
        private static final long serialVersionUID = -8413963075202260180L;

        public void uploadFinished(FinishedEvent event) {
            String uploadError = uploader.getError();
            File file = uploader.getFile();
            if (file.getPath().endsWith("up_")) {
                String msg = "No file selected.";
                logger.warn(msg);
                Styles.notification("Failed to read file.", msg, NotificationType.ERROR);
                if (!file.delete())
                    logger.error("uploaded tmp file " + file.getAbsolutePath() + " could not be deleted!");
            } else {
                if (uploadError == null || uploadError.isEmpty()) {
                    String msg = "Upload successful!";
                    logger.info(msg);
                    //            try {
                    setRegEnabled(false);
                    SQLBatchParser parser = new SQLBatchParser();
                    if (parser.processTSV()) {
                        // TODO = prep.getObjects();
                        Styles.notification("Upload successful",
                                "New people information successfully uploaded and read.",
                                NotificationType.SUCCESS);
                    } else {
                        String error = parser.getError();
                        Styles.notification("Failed to read file.", error, NotificationType.ERROR);
                        if (!file.delete())
                            logger.error(
                                    "uploaded tmp file " + file.getAbsolutePath() + " could not be deleted!");
                    }
                    //            } catch (IOException e) {
                    //              e.printStackTrace();
                    //            }
                } else {
                    Styles.notification("Failed to upload file.", uploadError, NotificationType.ERROR);
                    if (!file.delete())
                        logger.error("uploaded tmp file " + file.getAbsolutePath() + " could not be deleted!");
                }
            }
        }
    };
    upload.addFinishedListener(uploadFinListener);
    // view.initUpload(upload);

    Button.ClickListener cl = new Button.ClickListener() {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        /**
         * 
         */

        @Override
        public void buttonClick(ClickEvent event) {
            String src = event.getButton().getCaption();
            if (src.equals("Register People")) {
                register.setEnabled(false);
            }
        }
    };
    register.addClickListener(cl);
}