Example usage for org.apache.wicket.markup.html.form.upload FileUpload getInputStream

List of usage examples for org.apache.wicket.markup.html.form.upload FileUpload getInputStream

Introduction

In this page you can find the example usage for org.apache.wicket.markup.html.form.upload FileUpload getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Get an input stream for the file uploaded.

Usage

From source file:au.org.theark.core.dao.StudyDao.java

License:Open Source License

public List<SubjectVO> matchSubjectsFromInputFile(FileUpload subjectFileUpload, Study study) {
    List<SubjectVO> subjectVOList = new ArrayList<SubjectVO>();
    List<String> subjectUidList = new ArrayList<String>(0);

    if (subjectFileUpload != null) {
        try {/*  www .j ava 2 s . c o  m*/
            subjectUidList = CsvListReader.readColumnIntoList(subjectFileUpload.getInputStream());
        } catch (IOException e) {
            log.error("Error in Subject list file");
            return subjectVOList;
        }

        Criteria criteria = getSession().createCriteria(LinkSubjectStudy.class);
        criteria.add(Restrictions.eq("study", study));
        criteria.add(Restrictions.in("subjectUID", subjectUidList));
        List<LinkSubjectStudy> subjectList = criteria.list();

        for (Iterator<LinkSubjectStudy> iterator = subjectList.iterator(); iterator.hasNext();) {
            LinkSubjectStudy linkSubjectStudy = (LinkSubjectStudy) iterator.next();
            // Place the LinkSubjectStudy instance into a SubjectVO and add the SubjectVO into a List
            SubjectVO subject = new SubjectVO();
            subject.setSubjectUID(linkSubjectStudy.getSubjectUID());
            subject.setLinkSubjectStudy(linkSubjectStudy);
            //Person person = subject.getLinkSubjectStudy().getPerson();
            //subject.setSubjectPreviousLastname(getPreviousLastname(person));
            subjectVOList.add(subject);
        }
    }
    return subjectVOList;
}

From source file:au.org.theark.core.util.LoadCsvFileHelper.java

License:Open Source License

/**
 * Convert the specified fileUpload to CSV format, and save as a CsvBlob
 * //w  w w .  j a v a2 s  .  co m
 * @param fileUpload
 * @param delimiterCharacter
 */
public void convertToCSVAndWriteToFile(FileUpload fileUpload, char delimiterCharacter) {
    String filename = fileUpload.getClientFileName();
    String fileFormat = filename.substring(filename.lastIndexOf('.') + 1).toUpperCase();
    InputStream inputStream = null;

    try {
        // If Excel, convert to CSV for validation
        if (fileFormat.equalsIgnoreCase("XLS")) {
            inputStream = convertXlsInputStreamToCsv(fileUpload.getInputStream());
        } else {
            inputStream = fileUpload.getInputStream();
        }

        writeToTempFile(inputStream);
    } catch (IOException e) {
        log.error(".convertToCSVAndSave IOException: " + e.getMessage());
    }

    this.columnNameList = getColumnsFromHeader(inputStream, delimiterCharacter);
}

From source file:au.org.theark.lims.web.component.bioupload.BioUploadStep2.java

License:Open Source License

@Override
public void onStepInNext(AbstractWizardForm<?> form, AjaxRequestTarget target) {
    try {/*from w w  w.j a va2s . c  o m*/
        FileUpload fileUpload = containerForm.getModelObject().getFileUpload();
        InputStream inputStream = fileUpload.getInputStream();//TODO : should something this big be thrown around model object in wicket?
        String filename = fileUpload.getClientFileName();
        String fileFormat = filename.substring(filename.lastIndexOf('.') + 1).toUpperCase();
        char delimChar = containerForm.getModelObject().getUpload().getDelimiterType().getDelimiterCharacter();

        // Only allow csv, txt or xls  TODO : if we are hardcoding things like this, why do we fetch file formats from db and store as a fk reference?
        if (!(fileFormat.equalsIgnoreCase("CSV") || fileFormat.equalsIgnoreCase("TXT")
                || fileFormat.equalsIgnoreCase("XLS"))) {
            throw new FileFormatException();
        }
        //TODO: remove hardcode
        if (containerForm.getModelObject().getUpload().getUploadType().getName()
                .equalsIgnoreCase("Biospecimen Custom Data")) {
            BioCustomFieldUploadValidator subjectUploadValidator = new BioCustomFieldUploadValidator(
                    iArkCommonService, iLimsService);
            validationMessages = subjectUploadValidator
                    .validateBiospecimenCustomFieldFileFormat(containerForm.getModelObject());
        } else if (containerForm.getModelObject().getUpload().getUploadType().getName()
                .equalsIgnoreCase("Biocollection Custom Data")) {
            //TODO : custom field validation
            BioCustomFieldUploadValidator customFieldUploadValidator = new BioCustomFieldUploadValidator(
                    iArkCommonService, iLimsService);
            validationMessages = customFieldUploadValidator
                    .validateBiocollectionCustomFieldFileFormat(containerForm.getModelObject());
        } else {
            //TODO : Throw error back to user
        }

        ArkExcelWorkSheetAsGrid arkExcelWorkSheetAsGrid = new ArkExcelWorkSheetAsGrid("gridView", inputStream,
                fileFormat, delimChar, fileUpload, iArkCommonService
                        .getUserConfig(au.org.theark.core.Constants.CONFIG_ROWS_PER_PAGE).getIntValue(),
                containerForm.getModelObject().getUpload().getUploadType());
        arkExcelWorkSheetAsGrid.setOutputMarkupId(true);
        WebMarkupContainer wizardDataGridKeyContainer = new WebMarkupContainer("wizardDataGridKeyContainer");
        wizardDataGridKeyContainer.setVisible(false);
        wizardDataGridKeyContainer.setOutputMarkupId(true);
        form.setArkExcelWorkSheetAsGrid(arkExcelWorkSheetAsGrid);
        form.getWizardPanelFormContainer().addOrReplace(arkExcelWorkSheetAsGrid);
        form.setArkExcelWorkSheetAsGrid(arkExcelWorkSheetAsGrid);
        form.getWizardPanelFormContainer().addOrReplace(wizardDataGridKeyContainer);
        target.add(form.getWizardPanelFormContainer());

        containerForm.getModelObject().setValidationMessages(validationMessages);
        validationMessage = containerForm.getModelObject().getValidationMessagesAsString();
        addOrReplace(new MultiLineLabel("multiLineLabel", validationMessage));

        if (validationMessage != null && validationMessage.length() > 0) {
            log.warn("validation = " + validationMessage);
            form.getNextButton().setEnabled(false);
            target.add(form.getWizardButtonContainer());
            downloadValMsgButton = new ArkDownloadAjaxButton("downloadValMsg", "ValidationMessage",
                    validationMessage, "txt") {
                private static final long serialVersionUID = 1L;

                @Override
                protected void onError(AjaxRequestTarget target, Form<?> form) {
                    this.error("Unexpected Error: Download request could not be processed");
                }
            };
            addOrReplace(downloadValMsgButton);
            target.add(downloadValMsgButton);
        }

    } catch (IOException e) {
        validationMessage = "Error attempting to display the file. Please check the file and try again.";
        addOrReplace(new MultiLineLabel("multiLineLabel", validationMessage));
        form.getNextButton().setEnabled(false);
        target.add(form.getWizardButtonContainer());
    } catch (FileFormatException ffe) {
        validationMessage = "Error uploading file. You can only upload files of type: CSV (comma separated values), TXT (text), or XLS (Microsoft Excel file)";
        addOrReplace(new MultiLineLabel("multiLineLabel", validationMessage));
        form.getNextButton().setEnabled(false);
        target.add(form.getWizardButtonContainer());
    }
    //TODO : finally?  close io?
}

From source file:au.org.theark.phenotypic.web.component.phenodataupload.PhenoDataUploadStep2.java

License:Open Source License

@Override
public void onStepInNext(AbstractWizardForm<?> form, AjaxRequestTarget target) {
    if (containerForm.getModelObject().getPreviousStepOutCompleted()) {
        try {/*from   w w  w .  j ava2s .  c om*/
            FileUpload fileUpload = containerForm.getModelObject().getFileUpload();
            InputStream inputStream = fileUpload.getInputStream();//TODO : should something this big be thrown around model object in wicket?
            String filename = fileUpload.getClientFileName();
            String fileFormat = filename.substring(filename.lastIndexOf('.') + 1).toUpperCase();
            char delimChar = containerForm.getModelObject().getUpload().getDelimiterType()
                    .getDelimiterCharacter();

            // Only allow csv, txt or xls  TODO : if we are hardcoding things like this, why do we fetch file formats from db and store as a fk reference?
            if (!(fileFormat.equalsIgnoreCase("CSV") || fileFormat.equalsIgnoreCase("TXT")
                    || fileFormat.equalsIgnoreCase("XLS"))) {
                throw new FileFormatException();
            }

            PhenoDataUploadValidator phenoDataUploadValidator = new PhenoDataUploadValidator(iArkCommonService,
                    iPhenotypicService);
            PhenoDataSetCollection phenoCollectionCriteria = containerForm.getModelObject()
                    .getPhenoCollection();
            PhenoDataSetGroup cfgSelected = containerForm.getModelObject().getPhenoDataSetGroup();
            try {
                validationMessages = phenoDataUploadValidator.validateCustomFieldFileFormat(
                        containerForm.getModelObject(), phenoCollectionCriteria, cfgSelected);
            } catch (ArkBaseException arkBaseException) {
                validationMessage = arkBaseException.getMessage();
            }

            ArkExcelWorkSheetAsGrid arkExcelWorkSheetAsGrid = new ArkExcelWorkSheetAsGrid("gridView",
                    inputStream, fileFormat, delimChar, fileUpload, iArkCommonService
                            .getUserConfig(au.org.theark.core.Constants.CONFIG_ROWS_PER_PAGE).getIntValue(),
                    containerForm.getModelObject().getUpload().getUploadType());
            arkExcelWorkSheetAsGrid.setOutputMarkupId(true);
            //WebMarkupContainer wizardDataGridKeyContainer = new WebMarkupContainer("wizardDataGridKeyContainer");
            //wizardDataGridKeyContainer.setVisible(false);
            //wizardDataGridKeyContainer.setOutputMarkupId(true);
            form.setArkExcelWorkSheetAsGrid(arkExcelWorkSheetAsGrid);
            form.getWizardPanelFormContainer().addOrReplace(arkExcelWorkSheetAsGrid);
            form.setArkExcelWorkSheetAsGrid(arkExcelWorkSheetAsGrid);
            //form.getWizardPanelFormContainer().addOrReplace(wizardDataGridKeyContainer);
            target.add(form.getWizardPanelFormContainer());

            containerForm.getModelObject().setValidationMessages(validationMessages);
            validationMessage = containerForm.getModelObject().getValidationMessagesAsString();
            addOrReplace(new MultiLineLabel("multiLineLabel", validationMessage));

            if (validationMessage != null && validationMessage.length() > 0) {

                this.containerForm.getModelObject().getUpload()
                        .setUploadStatus(iArkCommonService.getUploadStatusFor(
                                au.org.theark.phenotypic.web.Constants.UPLOAD_STATUS_OF_ERROR_IN_FILE_VALIDATION));
                this.containerForm.getModelObject().getUpload().setFilename(filename);//have to reset this because the container has the file name...luckily it never changes 
                iArkCommonService.updateUpload(this.containerForm.getModelObject().getUpload());

                log.warn("validation = " + validationMessage);
                form.getNextButton().setEnabled(false);
                target.add(form.getWizardButtonContainer());
                downloadValMsgButton = new ArkDownloadAjaxButton("downloadValMsg", "ValidationMessage",
                        validationMessage, "txt") {
                    private static final long serialVersionUID = 1L;

                    @Override
                    protected void onError(AjaxRequestTarget target, Form<?> form) {
                        this.error("Unexpected Error: Download request could not be processed");
                    }
                };
                addOrReplace(downloadValMsgButton);
                target.add(downloadValMsgButton);
            }

        } catch (IOException e) {
            validationMessage = "Error attempting to display the file. Please check the file and try again.";
            addOrReplace(new MultiLineLabel("multiLineLabel", validationMessage));
            form.getNextButton().setEnabled(false);
            target.add(form.getWizardButtonContainer());
        } catch (FileFormatException ffe) {
            validationMessage = "Error uploading file. You can only upload files of type: CSV (comma separated values), TXT (text), or XLS (Microsoft Excel file)";
            addOrReplace(new MultiLineLabel("multiLineLabel", validationMessage));
            form.getNextButton().setEnabled(false);
            target.add(form.getWizardButtonContainer());
        }
    } else {
        validationMessage = "Step 1 is not completed properly.";
        addOrReplace(new MultiLineLabel("multiLineLabel", validationMessage));
        form.getNextButton().setEnabled(false);
        target.add(form.getWizardButtonContainer());
    }
    //TODO : finally?  close io?
}

From source file:au.org.theark.study.web.component.attachments.form.DetailForm.java

License:Open Source License

@Override
protected void onSave(Form<SubjectVO> containerForm, AjaxRequestTarget target) {
    LinkSubjectStudy linkSubjectStudy = null;
    Long studyId = (Long) SecurityUtils.getSubject().getSession()
            .getAttribute(au.org.theark.core.Constants.STUDY_CONTEXT_ID);
    Study study = iArkCommonService.getStudy(studyId);
    Long sessionPersonId = (Long) SecurityUtils.getSubject().getSession()
            .getAttribute(au.org.theark.core.Constants.PERSON_CONTEXT_ID);
    String userId = SecurityUtils.getSubject().getPrincipal().toString();

    try {/* w ww.ja  v a  2 s.co m*/
        linkSubjectStudy = iArkCommonService.getSubject(sessionPersonId, study);
        containerForm.getModelObject().getSubjectFile().setLinkSubjectStudy(linkSubjectStudy);

        // Implement Save/Update
        if (containerForm.getModelObject().getSubjectFile().getId() == null) {
            // required for file uploads
            setMultiPart(true);

            // Retrieve file and store as Blob in database
            // TODO: AJAX-ified and asynchronous and hit database
            FileUpload fileSubjectFile = fileSubjectFileField.getFileUpload();

            try {
                containerForm.getModelObject().getSubjectFile()
                        .setPayload(IOUtils.toByteArray(fileSubjectFile.getInputStream()));
            } catch (IOException e) {
                log.error("IOException trying to convert inputstream" + e);
            }

            byte[] byteArray = fileSubjectFile.getMD5();
            String checksum = getHex(byteArray);

            // Set details of ConsentFile object
            containerForm.getModelObject().getSubjectFile().setChecksum(checksum);
            containerForm.getModelObject().getSubjectFile().setFilename(fileSubjectFile.getClientFileName());
            containerForm.getModelObject().getSubjectFile().setUserId(userId);

            // Save
            iStudyService.create(containerForm.getModelObject().getSubjectFile());
            this.info("Attachment " + containerForm.getModelObject().getSubjectFile().getFilename()
                    + " was created successfully");
            //            processErrors(target);
        } else {
            FileUpload fileSubjectFile = fileSubjectFileField.getFileUpload();

            try {
                containerForm.getModelObject().getSubjectFile()
                        .setPayload(IOUtils.toByteArray(fileSubjectFile.getInputStream()));
            } catch (IOException e) {
                log.error("IOException trying to convert inputstream" + e);
            }

            byte[] byteArray = fileSubjectFile.getMD5();
            String checksum = getHex(byteArray);

            // Set details of ConsentFile object
            //containerForm.getModelObject().getSubjectFile().setChecksum(checksum);
            containerForm.getModelObject().getSubjectFile().setFilename(fileSubjectFile.getClientFileName());
            containerForm.getModelObject().getSubjectFile().setUserId(userId);

            // Update
            iStudyService.update(containerForm.getModelObject().getSubjectFile(), checksum);
            this.info("Attachment " + containerForm.getModelObject().getSubjectFile().getFilename()
                    + " was updated successfully");
        }

        processErrors(target);
        onSavePostProcess(target);
        AjaxButton deleteButton = (AjaxButton) arkCrudContainerVO.getEditButtonContainer().get("delete");
        deleteButton.setEnabled(false);

    } catch (EntityNotFoundException e) {
        this.error("The record you tried to update is no longer available in the system");
    } catch (ArkSystemException e) {
        this.error("Saving the file attachment failed. Please contact The Ark administrator.");
    }
    processErrors(target);
}

From source file:au.org.theark.study.web.component.consent.form.DetailForm.java

License:Open Source License

private void createConsentFile() throws ArkSystemException {
    FileUpload fileSubjectFile = fileUploadField.getFileUpload();

    if (fileSubjectFile != null) {
        LinkSubjectStudy linkSubjectStudy = null;
        Long studyId = (Long) SecurityUtils.getSubject().getSession()
                .getAttribute(au.org.theark.core.Constants.STUDY_CONTEXT_ID);
        Study study = iArkCommonService.getStudy(studyId);
        Long sessionPersonId = (Long) SecurityUtils.getSubject().getSession()
                .getAttribute(au.org.theark.core.Constants.PERSON_CONTEXT_ID);

        try {//from www  .j  av  a2 s  . co m
            linkSubjectStudy = iArkCommonService.getSubject(sessionPersonId, study);
            containerForm.getModelObject().getSubjectFile().setLinkSubjectStudy(linkSubjectStudy);

            containerForm.getModelObject().getSubjectFile()
                    .setPayload(IOUtils.toByteArray(fileSubjectFile.getInputStream()));

            byte[] byteArray = fileSubjectFile.getMD5();
            String checksum = getHex(byteArray);

            // Set details of Consent File object
            containerForm.getModelObject().getSubjectFile()
                    .setStudyComp(containerForm.getModelObject().getConsent().getStudyComp());
            containerForm.getModelObject().getSubjectFile()
                    .setComments(containerForm.getModelObject().getConsent().getComments());
            containerForm.getModelObject().getSubjectFile().setChecksum(checksum);
            containerForm.getModelObject().getSubjectFile().setFilename(fileSubjectFile.getClientFileName());
            containerForm.getModelObject().getSubjectFile()
                    .setUserId(SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal().toString());

            // Save
            iStudyService.create(containerForm.getModelObject().getSubjectFile());
            this.info("Consent file: " + containerForm.getModelObject().getSubjectFile().getFilename()
                    + " was created successfully");
        } catch (IOException ioe) {
            log.error("Failed to save the uploaded file: " + ioe);
        } catch (EntityNotFoundException e) {
            log.error(e.getMessage());
        }
    }
}

From source file:au.org.theark.study.web.component.managestudy.form.DetailForm.java

License:Open Source License

@Override
protected void onSave(Form<StudyModelVO> containerForm, AjaxRequestTarget target) {
    try {/*  w ww.j av  a2s . c o m*/
        String message = "Estimated Year of Completion must be greater than Date Of Application";

        boolean customValidationFlag = false;

        if (containerForm.getModelObject().getStudy().getEstimatedYearOfCompletion() != null) {
            customValidationFlag = validateEstYearOfComp(
                    containerForm.getModelObject().getStudy().getEstimatedYearOfCompletion(),
                    containerForm.getModelObject().getStudy().getDateOfApplication(), message, target);
        }

        // Store Study logo image
        if (fileUploadField != null && fileUploadField.getFileUpload() != null) {
            // Retrieve file and store as Blob in databasse
            FileUpload fileUpload = fileUploadField.getFileUpload();

            // Copy file to Blob object
            Blob payload = util.createBlob(fileUpload.getInputStream(), fileUpload.getSize());
            containerForm.getModelObject().getStudy().setStudyLogoBlob(payload);
            containerForm.getModelObject().getStudy().setFilename(fileUpload.getClientFileName());
        }

        if (subjectFileUploadField != null && subjectFileUploadField.getFileUpload() != null) {
            FileUpload subjectFileUpload = subjectFileUploadField.getFileUpload();
            Collection<SubjectVO> selectedSubjects = iArkCommonService.matchSubjectsFromInputFile(
                    subjectFileUpload, containerForm.getModelObject().getStudy().getParentStudy());
            // Link subjects in file to the selected study (where matched)
            containerForm.getModelObject().setSelectedSubjects(selectedSubjects);
        }

        if (containerForm.getModelObject().getStudy().getEstimatedYearOfCompletion() != null
                && customValidationFlag) {
            // If there was a value provided then upon successful validation proceed with save or update
            processSaveUpdate(containerForm.getModelObject(), target);
        } else if (containerForm.getModelObject().getStudy().getEstimatedYearOfCompletion() == null) {
            // If the value for estimate year of completion was not provided then we can proceed with save or update.
            processSaveUpdate(containerForm.getModelObject(), target);
        }
    } catch (EntityExistsException e) {
        this.error("The specified study already exists in the system.");
        log.error(e.getMessage());
    } catch (EntityCannotBeRemoved e) {
        this.error("The Study cannot be removed from the system.There are participants linked to the study");
        log.error(e.getMessage());
    } catch (IOException e) {
        this.error("There was an error transferring the specified Study logo image.");
        log.error(e.getMessage());
    } catch (ArkSystemException e) {
        this.error("A System exception has occurred. Please contact Support");
        log.error(e.getMessage());
    } catch (UnAuthorizedOperation e) {
        this.error("You (logged in user) is unauthorised to create/update or archive this study.");
        log.error(e.getMessage());
    } catch (CannotRemoveArkModuleException e) {
        this.error(
                "You cannot remove the modules as part of the update. There are System Users who are associated with this study and modules.");
        log.error(e.getMessage());
    }
}

From source file:au.org.theark.study.web.component.managestudy.StudyLogoValidator.java

License:Open Source License

public void validate(IValidatable<List<FileUpload>> pValidatable) {

    List<FileUpload> fileUploadList = pValidatable.getValue();

    for (FileUpload fileUploadImage : fileUploadList) {

        String fileExtension = StringUtils.getFilenameExtension(fileUploadImage.getClientFileName());
        ValidationError error = new ValidationError();

        try {//from  www .j a va  2  s  .  co m
            // Check extension ok
            if (fileExtension != null && !fileExtensions.contains(fileExtension.toLowerCase())) {
                error.addMessageKey("study.studyLogoFileType");
                error.setVariable("extensions", fileExtensions.toString());
                pValidatable.error(error);
            } // Check size ok
            else if (fileUploadImage.getSize() > fileSize.bytes()) {
                error.addMessageKey("study.studyLogoFileSize");
                pValidatable.error(error);
            } else {
                // Read image, to work out width and height
                image = new SerializableBufferedImage(ImageIO.read(fileUploadImage.getInputStream()));

                if (image.getHeight() > 100) {
                    error.addMessageKey("study.studyLogoPixelSize");
                    pValidatable.error(error);
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
            error.addMessageKey("study.studyLogoImageError");
            pValidatable.error(error);
        }

    }

}

From source file:au.org.theark.study.web.component.subjectUpload.SubjectUploadStep2.java

License:Open Source License

@Override
public void onStepInNext(AbstractWizardForm<?> form, AjaxRequestTarget target) {
    try {/*from ww  w. j  a  v a2s.  c o m*/
        FileUpload fileUpload = containerForm.getModelObject().getFileUpload();
        InputStream inputStream = fileUpload.getInputStream();//TODO : should something this big be thrown around model object in wicket?
        String filename = fileUpload.getClientFileName();
        String fileFormat = filename.substring(filename.lastIndexOf('.') + 1).toUpperCase();
        char delimChar = containerForm.getModelObject().getUpload().getDelimiterType().getDelimiterCharacter();

        // Only allow csv, txt, xls Or ped  TODO : if we are hardcoding things like this, why do we fetch file formats from db and store as a fk reference?
        if (!(fileFormat.equalsIgnoreCase("CSV") || fileFormat.equalsIgnoreCase("TXT")
                || fileFormat.equalsIgnoreCase("XLS") || fileFormat.equalsIgnoreCase("PED"))) {
            throw new FileFormatException();
        }

        //Create Upload
        iArkCommonService.createUpload(containerForm.getModelObject().getUpload());

        if (containerForm.getModelObject().getUpload().getUploadType().getName()
                .equalsIgnoreCase(Constants.SUBJECT_DEMOGRAPHIC_DATA)) {
            SubjectUploadValidator subjectUploadValidator = new SubjectUploadValidator(iArkCommonService);
            validationMessages = subjectUploadValidator
                    .validateSubjectFileFormat(containerForm.getModelObject());
        } else if (containerForm.getModelObject().getUpload().getUploadType().getName()
                .equalsIgnoreCase(Constants.STUDY_SPECIFIC_CUSTOM_DATA)) {
            //TODO : custom field validation
            CustomFieldUploadValidator customFieldUploadValidator = new CustomFieldUploadValidator(
                    iArkCommonService);
            validationMessages = customFieldUploadValidator
                    .validateCustomFieldFileFormat(containerForm.getModelObject());
        } else if (containerForm.getModelObject().getUpload().getUploadType().getName()
                .equalsIgnoreCase(Constants.SUBJECT_CONSENT_DATA)) {
            SubjectConsentUploadValidator subjectConsentUploadValidator = new SubjectConsentUploadValidator();
            validationMessages = subjectConsentUploadValidator
                    .validateSubjectConsentFileFormat(containerForm.getModelObject());
        } else if (containerForm.getModelObject().getUpload().getUploadType().getName()
                .equalsIgnoreCase(Constants.PEDIGREE_DATA)) {
            PedigreeUploadValidator subjectConsentUploadValidator = new PedigreeUploadValidator();
            validationMessages = subjectConsentUploadValidator
                    .validatePedigreeFileFormat(containerForm.getModelObject());
        } else if (containerForm.getModelObject().getUpload().getUploadType().getName()
                .equalsIgnoreCase(Constants.SUBJECT_ATTACHMENT_DATA)) {
            SubjectAttachmentValidator subjectAttachmentValidator = new SubjectAttachmentValidator();
            validationMessages = subjectAttachmentValidator
                    .validateSubjectAttachmentFileFormat(containerForm.getModelObject());
        } else {
            //TODO : Throw error back to user
        }

        ArkExcelWorkSheetAsGrid arkExcelWorkSheetAsGrid = null;
        if (Constants.PEDIGREE_DATA
                .equalsIgnoreCase(containerForm.getModelObject().getUpload().getUploadType().getName())) {
            arkExcelWorkSheetAsGrid = new ArkExcelWorkSheetAsGrid("gridView", inputStream, fileFormat,
                    delimChar, fileUpload, iArkCommonService
                            .getUserConfig(au.org.theark.core.Constants.CONFIG_ROWS_PER_PAGE).getIntValue(),
                    containerForm.getModelObject().getUpload().getUploadType(), false);
        } else {
            arkExcelWorkSheetAsGrid = new ArkExcelWorkSheetAsGrid("gridView", inputStream, fileFormat,
                    delimChar, fileUpload, iArkCommonService
                            .getUserConfig(au.org.theark.core.Constants.CONFIG_ROWS_PER_PAGE).getIntValue(),
                    containerForm.getModelObject().getUpload().getUploadType());
        }
        arkExcelWorkSheetAsGrid.setOutputMarkupId(true);
        WebMarkupContainer wizardDataGridKeyContainer = new WebMarkupContainer("wizardDataGridKeyContainer");
        wizardDataGridKeyContainer.setVisible(false);
        wizardDataGridKeyContainer.setOutputMarkupId(true);
        form.setArkExcelWorkSheetAsGrid(arkExcelWorkSheetAsGrid);
        form.getWizardPanelFormContainer().addOrReplace(arkExcelWorkSheetAsGrid);
        form.setArkExcelWorkSheetAsGrid(arkExcelWorkSheetAsGrid);
        form.getWizardPanelFormContainer().addOrReplace(wizardDataGridKeyContainer);
        target.add(form.getWizardPanelFormContainer());

        containerForm.getModelObject().setValidationMessages(validationMessages);
        validationMessage = containerForm.getModelObject().getValidationMessagesAsString();
        addOrReplace(new MultiLineLabel("multiLineLabel", validationMessage));

        if (validationMessage != null && validationMessage.length() > 0) {

            this.containerForm.getModelObject().getUpload()
                    .setUploadStatus(iArkCommonService.getUploadStatusFor(
                            au.org.theark.study.web.Constants.UPLOAD_STATUS_OF_ERROR_IN_FILE_VALIDATION));
            this.containerForm.getModelObject().getUpload().setFilename(filename);//have to reset this because the container has the file name...luckily it never changes 
            iArkCommonService.updateUpload(this.containerForm.getModelObject().getUpload());

            log.warn("validation = " + validationMessage);
            form.getNextButton().setEnabled(false);
            target.add(form.getWizardButtonContainer());
            downloadValMsgButton = new ArkDownloadAjaxButton("downloadValMsg", "ValidationMessage",
                    validationMessage, "txt") {
                private static final long serialVersionUID = 1L;

                @Override
                protected void onError(AjaxRequestTarget target, Form<?> form) {
                    this.error("Unexpected Error: Download request could not be processed");
                }
            };
            addOrReplace(downloadValMsgButton);
            target.add(downloadValMsgButton);
        }
        /*else{
           this.containerForm.getModelObject().getUpload().setUploadStatus(iArkCommonService.getUploadStatusFor(au.org.theark.study.web.Constants.UPLOAD_STATUS_OF_VALIDATED));
           this.containerForm.getModelObject().getUpload().setFilename(filename);//have to reset this because the container has the file name...luckily it never changes 
           iArkCommonService.updateUpload(this.containerForm.getModelObject().getUpload());
        }*/

    } catch (IOException e) {
        validationMessage = "Error attempting to display the file. Please check the file and try again.";
        addOrReplace(new MultiLineLabel("multiLineLabel", validationMessage));
        form.getNextButton().setEnabled(false);
        target.add(form.getWizardButtonContainer());
    } catch (FileFormatException ffe) {
        validationMessage = "Error uploading file. You can only upload files of type: CSV (comma separated values), TXT (text), or XLS (Microsoft Excel file)";
        addOrReplace(new MultiLineLabel("multiLineLabel", validationMessage));
        form.getNextButton().setEnabled(false);
        target.add(form.getWizardButtonContainer());
    } catch (Exception e) {
        log.error("unexpected exception, not shown to user...INVESTIGATE :\n", e);
        validationMessage = "Error attempting to validate the file. Please contact your system administrator.";
        addOrReplace(new MultiLineLabel("multiLineLabel", validationMessage));
        form.getNextButton().setEnabled(false);
        target.add(form.getWizardButtonContainer());
    }
    //TODO : finally?  close io?
}

From source file:com.apachecon.memories.service.DefaultImageService.java

License:Apache License

@Override
public void newFile(FileUpload upload) throws Exception {
    String ext = upload.getClientFileName().substring(upload.getClientFileName().lastIndexOf('.'));
    File file = new File(archiveDirectory, UUID.randomUUID() + ext);

    InputStream is = upload.getInputStream();
    FileOutputStream os = new FileOutputStream(file);

    byte[] buffer = new byte[512];
    int length = 0;
    while ((length = is.read(buffer)) > 0) {
        os.write(buffer, 0, length);/*w  w  w  .  j  a va 2s  . com*/
    }
    os.close();
    is.close();
}