Example usage for org.springframework.web.multipart MultipartFile getSize

List of usage examples for org.springframework.web.multipart MultipartFile getSize

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getSize.

Prototype

long getSize();

Source Link

Document

Return the size of the file in bytes.

Usage

From source file:eu.scidipes.toolkits.pawebapp.web.ItemsController.java

@RequestMapping(value = { "/edit", "/{formID}/edit", "/new" }, method = RequestMethod.POST)
public String saveItem(@ModelAttribute final SaveAction saveAction, @ModelAttribute final Form form,
        final BindingResult result, final SessionStatus status, final RedirectAttributes redirectAttrs,
        @RequestPart(value = "dataHolder", required = false) final MultipartFile dataFile,
        @MatrixVariable(value = "fn", required = false, pathVar = "datasetName") final String formName) {

    formValidator.validate(form, result);
    if (result.hasErrors()) {
        boolean fixErrors = true;

        final List<FieldError> dataHolderErrors = result.getFieldErrors("dataHolder");

        /*//from ww w.  ja  v a2  s  .  c  o m
         * Only ignore errors under very specific conditions, i.e. when there is a single no-file-supplied error and
         * a current file exists
         */
        if (result.getErrorCount() == 1 && dataHolderErrors != null && dataHolderErrors.size() == 1) {

            final FieldError dataHolderError = dataHolderErrors.get(0);
            if (FormValidator.FILE_REQ_ERR_CODE.equals(dataHolderError.getCode())
                    && !form.getDataHolderMetadata().isEmpty() && form.getDataHolderType() == BYTESTREAM) {
                fixErrors = false;
            }

        }

        if (fixErrors) {
            return "datasets/items/edit";
        }
    }

    /* Ensure that the dataHolder field is not overwritten when its an empty upload (i.e. re-save) */
    if (form.getDataHolderType() == BYTESTREAM && dataFile != null && !dataFile.isEmpty()) {
        LOG.debug("incoming dataFile: {}", dataFile);
        form.getDataHolderMetadata().put(FILE_NAME, dataFile.getOriginalFilename());
        form.getDataHolderMetadata().put(FILE_SIZE, String.valueOf(dataFile.getSize()));
        form.getDataHolderMetadata().put(FILE_MIMETYPE, dataFile.getContentType());
    } else if (form.getDataHolderType() == URI && !StringUtils.isEmpty(form.getDataHolder())) {
        LOG.debug("incoming dataHolder: {}", form.getDataHolder());
        form.getDataHolderMetadata().clear();
    }

    final FormsBundleImpl dataset = datasetRepo.findOne(form.getParentBundle().getDatasetName());

    if (saveAction == ADD_NEW) {
        dataset.addForm(form);
    } else {
        dataset.setForm(form);
    }

    final FormsBundle savedDataset = datasetRepo.save(dataset);
    final Form savedForm = savedDataset.getForms().get(savedDataset.getForms().indexOf(form));

    status.setComplete();
    redirectAttrs.addFlashAttribute("msgKey", "items.edit.messages.savesuccess");

    final String formNameMatrixVar = StringUtils.isEmpty(formName) ? "" : ";fn=" + formName;
    return "redirect:/datasets/" + savedDataset.getDatasetName() + formNameMatrixVar + "/items/"
            + savedForm.getFormID() + "/edit";
}

From source file:com.igame.app.controller.Image2Controller.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    // HttpSession
    SecUser user = (SecUser) request.getSession().getAttribute("user");
    long appid = user.getAppid();
    log.debug("uploadPost called appid:{}" + appid);
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;
    List<Image> list = new LinkedList<>();

    while (itr.hasNext()) {
        mpf = request.getFile(itr.next());
        log.debug("Uploading {}", mpf.getOriginalFilename());

        long id = IDGenerator.getKey();
        // String newFilenameBase = String.valueOf(id);
        String originalFileExtension = mpf.getOriginalFilename()
                .substring(mpf.getOriginalFilename().lastIndexOf("."));
        String newFilename = id + originalFileExtension;
        String storageDirectory = fileUploadDirectory;
        String contentType = mpf.getContentType();

        File newFile = new File(storageDirectory + "/" + "app-" + appid + "/" + newFilename);

        if (!newFile.getParentFile().exists()) {
            log.debug(" {}" + newFile.getParentFile().getPath());
            newFile.getParentFile().mkdirs();
        }//  w  w  w.j  a  v a 2  s .  c om

        try {
            mpf.transferTo(newFile);

            BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 150);
            String thumbnailFilename = id + "-thumbnail.png";
            File thumbnailFile = new File(storageDirectory + "/" + "app-" + appid + "/" + thumbnailFilename);
            ImageIO.write(thumbnail, "png", thumbnailFile);

            Image image = new Image();
            image.setId(id);
            image.setAppid(appid);
            image.setName(mpf.getOriginalFilename());
            image.setThumbnailFilename(thumbnailFilename);
            image.setNewFilename(newFilename);
            image.setContentType(contentType);
            image.setSize(mpf.getSize());
            image.setThumbnailSize(thumbnailFile.length());
            image = imageService.create(image);

            image.setUrl("app-" + appid + "/" + newFilename);
            image.setThumbnailUrl("app-" + appid + "/" + thumbnailFilename);
            image.setDeleteUrl("delete/" + image.getId());
            image.setDeleteType("DELETE");

            list.add(image);

        } catch (IOException e) {
            log.error("Could not upload file " + mpf.getOriginalFilename(), e);
        }

    }

    Map<String, Object> files = new HashMap<>();
    files.put("files", list);
    return files;
}

From source file:com.virtusa.akura.student.controller.StudentDetailController.java

/**
 * @param student - Student obj./* w  ww.  j a  v  a 2s .  c o  m*/
 * @param result - BindingResult.
 * @param session - HttpSession
 * @param model - a hashMap that contains student's data
 * @param request - represents an instance of HttpServletRequest
 * @throws AkuraAppException - AkuraAppException.
 * @return name of the view which is redirected to.
 */
@RequestMapping(REQ_MAP_SAVE_STUDENT_DETAIL)
public String onSubmit(@ModelAttribute(MODEL_ATT_STUDENT) Student student, BindingResult result,
        HttpSession session, HttpServletRequest request, ModelMap model) throws AkuraAppException {

    String returnResult = VIEW_GET_STUDENT_DETAIL_PAGE;
    studentDetailValidator.validate(student, result);
    String selectedCountryCodeRes = request.getParameter(SELECTED_COUNTRYCODE_RES);
    String selectedCountryCodeMob = request.getParameter(SELECTED_COUNTRYCODE_MOB);
    String selectedCountryCodeEmgRes = request.getParameter(SELECTED_COUNTRYCODE_EMG_RES);
    String selectedCountryCodeEmgMob = request.getParameter(SELECTED_COUNTRYCODE_EMG_MOB);
    String selectedCountryCodeEmgOff = request.getParameter(SELECTED_COUNTRYCODE_EMG_OFFICE);
    try {
        if (result.hasErrors()) {
            handleValidationError(student, model);
            resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob, selectedCountryCodeEmgRes,
                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff, model);
            return VIEW_GET_STUDENT_DETAIL_PAGE;
        }

        trimProperties(student);
        UserInfo userInfo = (UserInfo) session.getAttribute(USER);

        if (userInfo instanceof StudentDetails
                && !userInfo.getUserLevelIdentifier().equals(student.getAdmissionNo())) {
            handleValidationError(student, model);
            result.rejectValue(STUDENT_ID, ERR_TUDENT_ADMISSIONNO_VIOLATE);
            resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob, selectedCountryCodeEmgRes,
                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff, model);
            return VIEW_GET_STUDENT_DETAIL_PAGE;
        }

        // if check for initial save
        if (student != null && student.getStudentId() != 0) {

            Student stuObDB = studentService.findStudent(student.getStudentId());
            if (stuObDB == null) {
                student.setStudentId(0);
            } else {
                String admissionNoDB = stuObDB.getAdmissionNo();

                if (!admissionNoDB.equals(student.getAdmissionNo())) {
                    if (studentService.isAdmissionNoExist(student.getAdmissionNo())) {
                        handleValidationError(student, model);
                        result.rejectValue(STUDENT_ID, ERR_STUDENT_ADMISSIONNO_DUPLCATE);
                        resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob,
                                selectedCountryCodeEmgRes, selectedCountryCodeEmgMob, selectedCountryCodeEmgOff,
                                model);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    } else {

                        if (!student.getSiblingAdmitionNo().trim().isEmpty()) {
                            if (!studentService.isAdmissionNoExist(student.getSiblingAdmitionNo())
                                    || student.getAdmissionNo().equals(student.getSiblingAdmitionNo())) {
                                result.rejectValue(SIBLING_ADMISSIONNO, ERR_SIBLING_ADMISSIONNO_VIOLATE);
                                resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob,
                                        selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                        selectedCountryCodeEmgOff, model);
                                return VIEW_GET_STUDENT_DETAIL_PAGE;
                            }
                        }
                        if (!student.getResidenceNo().isEmpty() && !selectedCountryCodeRes.isEmpty()) {
                            if (student.getResidenceNo() != null
                                    && !selectedCountryCodeRes.equals(AkuraConstant.STRING_ZERO)
                                    && PhoneNumberValidateUtil.isValidPhoneNumber(student.getResidenceNo(),
                                            selectedCountryCodeRes)) {
                                displayResidencePhoneNumberDetails(student, selectedCountryCodeRes);
                            } else {
                                displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                        selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                        selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                                return VIEW_GET_STUDENT_DETAIL_PAGE;
                            }
                        }

                        if (!student.getMobileNo().isEmpty() && !selectedCountryCodeMob.isEmpty()) {
                            if (student.getMobileNo() != null
                                    && !selectedCountryCodeMob.equals(AkuraConstant.STRING_ZERO)
                                    && PhoneNumberValidateUtil.isValidPhoneNumber(student.getMobileNo(),
                                            selectedCountryCodeMob)) {
                                displayMobilePhoneNumberDetails(student, selectedCountryCodeMob);
                            } else {
                                displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                        selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                        selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                                return VIEW_GET_STUDENT_DETAIL_PAGE;
                            }
                        }

                        if (!student.getEmergencyContactResidenceNo().isEmpty()
                                && !selectedCountryCodeEmgRes.isEmpty()) {
                            if (student.getEmergencyContactResidenceNo() != null
                                    && !selectedCountryCodeEmgRes.equals(AkuraConstant.STRING_ZERO)
                                    && PhoneNumberValidateUtil.isValidPhoneNumber(
                                            student.getEmergencyContactResidenceNo(),
                                            selectedCountryCodeEmgRes)) {
                                displayEmgResidencePhoneNumberDetails(student, selectedCountryCodeEmgRes);
                            } else {
                                displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                        selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                        selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                                return VIEW_GET_STUDENT_DETAIL_PAGE;
                            }
                        }

                        if (!student.getEmergencyContactMobileNo().isEmpty()
                                && !selectedCountryCodeEmgMob.isEmpty()) {
                            if (student.getEmergencyContactMobileNo() != null
                                    && !selectedCountryCodeEmgMob.equals(AkuraConstant.STRING_ZERO)
                                    && PhoneNumberValidateUtil.isValidPhoneNumber(
                                            student.getEmergencyContactMobileNo(), selectedCountryCodeEmgMob)) {
                                displayEmgMobilePhoneNumberDetails(student, selectedCountryCodeEmgMob);
                            } else {
                                displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                        selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                        selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                                return VIEW_GET_STUDENT_DETAIL_PAGE;
                            }
                        }

                        if (!student.getEmergencyContactOfficeNo().isEmpty()
                                && !selectedCountryCodeEmgOff.isEmpty()) {
                            if (student.getEmergencyContactOfficeNo() != null
                                    && !selectedCountryCodeEmgOff.equals(AkuraConstant.STRING_ZERO)
                                    && PhoneNumberValidateUtil.isValidPhoneNumber(
                                            student.getEmergencyContactOfficeNo(), selectedCountryCodeEmgOff)) {
                                displayEmgOfficePhoneNumberDetails(student, selectedCountryCodeEmgOff);
                            } else {
                                displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                        selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                        selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                                return VIEW_GET_STUDENT_DETAIL_PAGE;
                            }
                        }
                        updateStudent(student);

                        // Update if user login exist for this student
                        UserLogin userLogin = userService
                                .getUserLoginByIdentificationNo(stuObDB.getAdmissionNo());
                        if (userLogin != null) {
                            userLogin.setUserIdentificationNo(student.getAdmissionNo());
                            userService.updateUser(userLogin);
                        }

                        // updated message pass through query string
                        String successUpdate = new ErrorMsgLoader()
                                .getErrorMessage(COMMON_MESSAGE_SUCCESSFULLY_UPDATED);
                        return VIEW_STUDENT_DETAIL + QUERY_STRING_UPDATE + successUpdate;
                    }
                } else {
                    try {
                        if (student.getMPhoto() != null) {
                            MultipartFile multipartFile = student.getMPhoto();
                            if (multipartFile.getSize() > 0) {
                                student.setPhoto(multipartFile.getBytes());
                            }
                        }
                    } catch (IOException e) {

                        LOG.error(ERROR_WHILE_RETRIEVING_FILE + e.toString());
                        throw new AkuraAppException(AkuraConstant.FILE_NOT_FOUND, e);
                    }
                    if (!student.getSiblingAdmitionNo().trim().isEmpty()) {
                        if (!studentService.isAdmissionNoExist(student.getSiblingAdmitionNo())
                                || student.getAdmissionNo().equals(student.getSiblingAdmitionNo())) {
                            result.rejectValue(SIBLING_ADMISSIONNO, ERR_SIBLING_ADMISSIONNO_VIOLATE);
                            returnResult = VIEW_GET_STUDENT_DETAIL_PAGE;
                            resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob,
                                    selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                    selectedCountryCodeEmgOff, model);
                            return VIEW_GET_STUDENT_DETAIL_PAGE;
                        }
                    }

                    if (!student.getResidenceNo().isEmpty() && !selectedCountryCodeRes.isEmpty()) {
                        if (student.getResidenceNo() != null
                                && !selectedCountryCodeRes.equals(AkuraConstant.STRING_ZERO)
                                && PhoneNumberValidateUtil.isValidPhoneNumber(student.getResidenceNo(),
                                        selectedCountryCodeRes)) {
                            displayResidencePhoneNumberDetails(student, selectedCountryCodeRes);
                        } else {
                            displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                    selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                            return VIEW_GET_STUDENT_DETAIL_PAGE;
                        }
                    }

                    if (!student.getMobileNo().isEmpty() && !selectedCountryCodeMob.isEmpty()) {
                        if (student.getMobileNo() != null
                                && !selectedCountryCodeMob.equals(AkuraConstant.STRING_ZERO)
                                && PhoneNumberValidateUtil.isValidPhoneNumber(student.getMobileNo(),
                                        selectedCountryCodeMob)) {
                            displayMobilePhoneNumberDetails(student, selectedCountryCodeMob);
                        } else {
                            displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                    selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                            return VIEW_GET_STUDENT_DETAIL_PAGE;
                        }
                    }

                    if (!student.getEmergencyContactResidenceNo().isEmpty()
                            && !selectedCountryCodeEmgRes.isEmpty()) {
                        if (student.getEmergencyContactResidenceNo() != null
                                && !selectedCountryCodeEmgRes.equals(AkuraConstant.STRING_ZERO)
                                && PhoneNumberValidateUtil.isValidPhoneNumber(
                                        student.getEmergencyContactResidenceNo(), selectedCountryCodeEmgRes)) {
                            displayEmgResidencePhoneNumberDetails(student, selectedCountryCodeEmgRes);
                        } else {
                            displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                    selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                            return VIEW_GET_STUDENT_DETAIL_PAGE;
                        }
                    }

                    if (!student.getEmergencyContactMobileNo().isEmpty()
                            && !selectedCountryCodeEmgMob.isEmpty()) {
                        if (student.getEmergencyContactMobileNo() != null
                                && !selectedCountryCodeEmgMob.equals(AkuraConstant.STRING_ZERO)
                                && PhoneNumberValidateUtil.isValidPhoneNumber(
                                        student.getEmergencyContactMobileNo(), selectedCountryCodeEmgMob)) {
                            displayEmgMobilePhoneNumberDetails(student, selectedCountryCodeEmgMob);
                        } else {
                            displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                    selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                            return VIEW_GET_STUDENT_DETAIL_PAGE;
                        }
                    }

                    if (!student.getEmergencyContactOfficeNo().isEmpty()
                            && !selectedCountryCodeEmgOff.isEmpty()) {
                        if (student.getEmergencyContactOfficeNo() != null
                                && !selectedCountryCodeEmgOff.equals(AkuraConstant.STRING_ZERO)
                                && PhoneNumberValidateUtil.isValidPhoneNumber(
                                        student.getEmergencyContactOfficeNo(), selectedCountryCodeEmgOff)) {
                            displayEmgOfficePhoneNumberDetails(student, selectedCountryCodeEmgOff);
                        } else {
                            displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                    selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                            return VIEW_GET_STUDENT_DETAIL_PAGE;
                        }
                    }
                    updateStudent(student);

                    // updated message pass through query string
                    String successUpdate = new ErrorMsgLoader()
                            .getErrorMessage(COMMON_MESSAGE_SUCCESSFULLY_UPDATED);
                    return VIEW_STUDENT_DETAIL + QUERY_STRING_UPDATE + successUpdate;
                }
            }
        }

        if (student != null && student.getStudentId() == 0) {
            if (studentService.isAdmissionNoExist(student.getAdmissionNo())) {

                model.addAttribute(MODEL_ATT_IMAGE_PATH, RESOURCES_NO_PROFILE_IMAGE);
                result.rejectValue(STUDENT_ID, ERR_STUDENT_ADMISSIONNO_DUPLCATE);
                returnResult = VIEW_GET_STUDENT_DETAIL_PAGE;
                resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob, selectedCountryCodeEmgRes,
                        selectedCountryCodeEmgMob, selectedCountryCodeEmgOff, model);
                return VIEW_GET_STUDENT_DETAIL_PAGE;
            } else {
                if (student.getMPhoto() != null) {
                    try {
                        MultipartFile multipartFile = student.getMPhoto();
                        if (multipartFile.getSize() > 0) {
                            student.setPhoto(multipartFile.getBytes());
                        }
                    } catch (IOException e) {
                        LOG.error(ERROR_WHILE_RETRIEVING_FILE + e.toString());
                        throw new AkuraAppException(AkuraConstant.FILE_NOT_FOUND, e);
                    }
                }
                if (!student.getSiblingAdmitionNo().trim().isEmpty()) {
                    if (!studentService.isAdmissionNoExist(student.getSiblingAdmitionNo())
                            || student.getAdmissionNo().equals(student.getSiblingAdmitionNo())) {
                        result.rejectValue(SIBLING_ADMISSIONNO, ERR_SIBLING_ADMISSIONNO_VIOLATE);
                        returnResult = VIEW_GET_STUDENT_DETAIL_PAGE;
                        resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob,
                                selectedCountryCodeEmgRes, selectedCountryCodeEmgMob, selectedCountryCodeEmgOff,
                                model);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    }
                }

                student.setStatusId(1);

                if (!student.getResidenceNo().isEmpty() && !selectedCountryCodeRes.isEmpty()) {
                    if (student.getResidenceNo() != null
                            && !selectedCountryCodeRes.equals(AkuraConstant.STRING_ZERO)
                            && PhoneNumberValidateUtil.isValidPhoneNumber(student.getResidenceNo(),
                                    selectedCountryCodeRes)) {
                        displayResidencePhoneNumberDetails(student, selectedCountryCodeRes);
                    } else {
                        displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                selectedCountryCodeMob, selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                selectedCountryCodeEmgOff);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    }
                }

                if (!student.getMobileNo().isEmpty() && !selectedCountryCodeMob.isEmpty()) {
                    if (student.getMobileNo() != null
                            && !selectedCountryCodeMob.equals(AkuraConstant.STRING_ZERO)
                            && PhoneNumberValidateUtil.isValidPhoneNumber(student.getMobileNo(),
                                    selectedCountryCodeMob)) {
                        displayMobilePhoneNumberDetails(student, selectedCountryCodeMob);
                    } else {
                        displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                selectedCountryCodeMob, selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                selectedCountryCodeEmgOff);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    }
                }

                if (!student.getEmergencyContactResidenceNo().isEmpty()
                        && !selectedCountryCodeEmgRes.isEmpty()) {
                    if (student.getEmergencyContactResidenceNo() != null
                            && !selectedCountryCodeEmgRes.equals(AkuraConstant.STRING_ZERO)
                            && PhoneNumberValidateUtil.isValidPhoneNumber(
                                    student.getEmergencyContactResidenceNo(), selectedCountryCodeEmgRes)) {
                        displayEmgResidencePhoneNumberDetails(student, selectedCountryCodeEmgRes);
                    } else {
                        displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                selectedCountryCodeMob, selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                selectedCountryCodeEmgOff);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    }
                }

                if (!student.getEmergencyContactMobileNo().isEmpty() && !selectedCountryCodeEmgMob.isEmpty()) {
                    if (student.getEmergencyContactMobileNo() != null
                            && !selectedCountryCodeEmgMob.equals(AkuraConstant.STRING_ZERO)
                            && PhoneNumberValidateUtil.isValidPhoneNumber(student.getEmergencyContactMobileNo(),
                                    selectedCountryCodeEmgMob)) {
                        displayEmgMobilePhoneNumberDetails(student, selectedCountryCodeEmgMob);
                    } else {
                        displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                selectedCountryCodeMob, selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                selectedCountryCodeEmgOff);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    }
                }

                if (!student.getEmergencyContactOfficeNo().isEmpty() && !selectedCountryCodeEmgOff.isEmpty()) {
                    if (student.getEmergencyContactOfficeNo() != null
                            && !selectedCountryCodeEmgOff.equals(AkuraConstant.STRING_ZERO)
                            && PhoneNumberValidateUtil.isValidPhoneNumber(student.getEmergencyContactOfficeNo(),
                                    selectedCountryCodeEmgOff)) {
                        displayEmgOfficePhoneNumberDetails(student, selectedCountryCodeEmgOff);
                    } else {
                        displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                selectedCountryCodeMob, selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                selectedCountryCodeEmgOff);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    }
                }

                studentService.saveStudent(student);
                if (checkStudentDisabilityFilled(student.getStudentDisability())) {
                    student.getStudentDisability().setStudentId(student.getStudentId());
                    trimStudentDisabilityObj(student.getStudentDisability());
                    studentService.saveStudentDisability(student.getStudentDisability());
                }
                returnResult = VIEW_NEW_STUDENT_DETAIL;
            }
        }
    } catch (AkuraAppException e) {
        if (e.getCause() instanceof TransientDataAccessResourceException) {
            String message = new ErrorMsgLoader().getErrorMessage(IMAGE_DATABASE_SIZE);
            model.addAttribute(ERROR_MESSAGE, message);
            resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob, selectedCountryCodeEmgRes,
                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff, model);
            return returnResult;
        }
    }

    return VIEW_NEW_STUDENT_DETAIL;
}

From source file:com.vmware.appfactory.application.controller.AppApiController.java

/**
 * Step 2: Upload the installer and create the new file share application.
 *
 * Failure or success will respond with a json with a success flag. The Http status type does not
 * matter much, as this response is recieved in an iframe, and is not transposed over to the js callback.
 *
 * Docs: http://jquery.malsup.com/form/#file-upload
 *
 * @param uploadFile - multipart file being uploaded.
 * @param request - HttpServletRequest/*from w  w  w.ja  v  a2  s. c  om*/
 */
@ResponseBody
@RequestMapping(value = "/apps/upload", method = RequestMethod.POST)
public ResponseEntity<String> uploadAndCreate(@RequestParam("uploadFile") MultipartFile uploadFile,
        HttpServletRequest request) {
    ApplicationCreateRequest uploadApp = null;
    try {
        // Load and validate required fields.
        uploadApp = loadSessionUploadApp(uploadFile, request);
        final List<String> installerDirs = generateFolderNameListForUploadApp(uploadApp);

        // Get the destination ds and copy the installer.
        DsDatastore ds = _dsClient.findDatastore(uploadApp.getDsId(), true);

        // Developer mode! Copy the upload file to a local directory.
        if (_af.isDevModeDeploy() && StringUtils.isNotEmpty(_af.getDevModeUploadDir())) {

            // Path to file's directory
            String newPath = _af.getDevModeUploadDir();
            for (String dir : installerDirs) {
                newPath = FileHelper.constructFilePath2(File.separator, newPath, dir);
            }
            FileUtils.forceMkdir(new File(newPath));

            // Full path to file
            String newFile = FileHelper.constructFilePath2(File.separator, newPath,
                    uploadFile.getOriginalFilename());

            _log.debug("DEV MODE! Uploading " + uploadFile.getOriginalFilename() + " size "
                    + uploadFile.getSize() + " to " + newFile);

            // Copy it
            uploadFile.transferTo(new File(newFile));
        } else { // Production mode! Copy the upload file to the datastore.
            // Full path to directory where file will be copied to.
            String destFile = ds.createDirsIfNotExists(installerDirs.toArray(new String[installerDirs.size()]));
            destFile = destFile + uploadFile.getOriginalFilename();

            _log.debug("Uploading " + uploadFile.getOriginalFilename() + " size " + uploadFile.getSize()
                    + " to " + destFile);

            ds.copy(uploadFile, destFile, null);
        }

        // create the application now that uploaded installer has been copied.
        createUploadApp(installerDirs, uploadFile.getOriginalFilename(), request, uploadApp);
        _log.info("upload file & app: {} creation complete.", uploadApp.getAppName());
        return respondUploadMessage("Installer was uploaded and saved.", true, request);

    } catch (AfBadRequestException e) {
        _log.error("Saving file to ds error: " + e.getMessage(), e);
        return respondUploadMessage("Selected datastore couldnt not be accessed.", false, request);
    } catch (URISyntaxException urie) {
        _log.error("Application create error: " + urie.getMessage(), urie);
        return respondUploadMessage("Saving the application after installer upload failed.", false, request);
    } catch (IllegalStateException e) {
        _log.error("Save file to ds error: " + e.getMessage(), e);
        return respondUploadMessage("Installer couldnt be saved onto the datastore.", false, request);
    } catch (IOException e) {
        _log.error("Create folder /save file to ds error: " + e.getMessage(), e);
        return respondUploadMessage("Installer couldnt be saved onto the datastore.", false, request);
    } catch (DsException ds) {
        _log.error("Saving file to ds error: " + ds.getMessage(), ds);
        return respondUploadMessage("Selected datastore could not be accessed.", false, request);
    } catch (RuntimeException rts) {
        // This is the default runtime exception case that needs to be handled. The client handler can only
        // handle json response, and hence we catch all other runtime exceptions here.
        _log.error("Uploading installer failed with error: " + rts.getMessage(), rts);
        return respondUploadMessage("Uploading and creating an application failed.", false, request);
    } finally {
        if (uploadApp != null) {
            // Cleanup the progress listener session variable.
            ProgressReporter.removeProgressListener(request, uploadApp.getUploadId());
        }
    }
}

From source file:fr.univrouen.poste.web.candidat.MyPosteCandidatureController.java

@RequestMapping(value = "/{id}/addFile", method = RequestMethod.POST, produces = "text/html")
@PreAuthorize("hasPermission(#id, 'manage')")
public String addFile(@PathVariable("id") Long id, @Valid PosteCandidatureFile posteCandidatureFile,
        BindingResult bindingResult, Model uiModel, HttpServletRequest request) throws IOException {
    if (bindingResult.hasErrors()) {
        logger.warn(bindingResult.getAllErrors());
        return "redirect:/postecandidatures/" + id.toString();
    }//  ww w. java2 s . co m
    uiModel.asMap().clear();

    // get PosteCandidature from id
    PosteCandidature posteCandidature = PosteCandidature.findPosteCandidature(id);

    // upload file
    MultipartFile file = posteCandidatureFile.getFile();

    // sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ?
    if (file != null) {
        String filename = file.getOriginalFilename();

        boolean filenameAlreadyUsed = false;
        for (PosteCandidatureFile pcFile : posteCandidature.getCandidatureFiles()) {
            if (pcFile.getFilename().equals(filename)) {
                filenameAlreadyUsed = true;
                break;
            }
        }

        if (filenameAlreadyUsed) {
            uiModel.addAttribute("filename_already_used", filename);
            logger.warn("Upload Restriction sur '" + filename
                    + "' un fichier de mme nom existe dj pour une candidature de "
                    + posteCandidature.getCandidat().getEmailAddress());
        } else {

            Long fileSize = file.getSize();

            if (fileSize != 0) {
                String contentType = file.getContentType();
                // cf https://github.com/EsupPortail/esup-dematec/issues/8 - workaround pour viter mimetype erron comme application/text-plain:formatted
                contentType = contentType.replaceAll(":.*", "");

                logger.info("Try to upload file '" + filename + "' with size=" + fileSize + " and contentType="
                        + contentType);

                Long maxFileMoSize = posteCandidatureFile.getFileType().getCandidatureFileMoSizeMax();
                Long maxFileSize = maxFileMoSize * 1024 * 1024;
                String mimeTypeRegexp = posteCandidatureFile.getFileType()
                        .getCandidatureContentTypeRestrictionRegexp();
                String filenameRegexp = posteCandidatureFile.getFileType()
                        .getCandidatureFilenameRestrictionRegexp();

                boolean sizeRestriction = maxFileSize > 0 && fileSize > maxFileSize;
                boolean contentTypeRestriction = !contentType.matches(mimeTypeRegexp);
                boolean filenameRestriction = !filename.matches(filenameRegexp);

                if (sizeRestriction || contentTypeRestriction || filenameRestriction) {
                    String restriction = sizeRestriction ? "SizeRestriction" : "";
                    restriction = contentTypeRestriction || filenameRestriction
                            ? restriction + "ContentTypeRestriction"
                            : restriction;
                    uiModel.addAttribute("upload_restricion_size_contentype", restriction);
                    logger.info("addFile - upload restriction sur " + filename + "' avec taille=" + fileSize
                            + " et contentType=" + contentType + " pour une candidature de "
                            + posteCandidature.getCandidat().getEmailAddress());
                } else {
                    InputStream inputStream = file.getInputStream();
                    //byte[] bytes = IOUtils.toByteArray(inputStream);

                    posteCandidatureFile.setFilename(filename);
                    posteCandidatureFile.setFileSize(fileSize);
                    posteCandidatureFile.setContentType(contentType);
                    logger.info("Upload and set file in DB with filesize = " + fileSize);
                    posteCandidatureFile.getBigFile().setBinaryFileStream(inputStream, fileSize);
                    posteCandidatureFile.getBigFile().persist();

                    Calendar cal = Calendar.getInstance();
                    Date currentTime = cal.getTime();
                    posteCandidatureFile.setSendTime(currentTime);

                    posteCandidature.getCandidatureFiles().add(posteCandidatureFile);

                    posteCandidature.setModification(currentTime);

                    posteCandidature.persist();

                    logService.logActionFile(LogService.UPLOAD_ACTION, posteCandidature, posteCandidatureFile,
                            request, currentTime);
                    returnReceiptService.logActionFile(LogService.UPLOAD_ACTION, posteCandidature,
                            posteCandidatureFile, request, currentTime);

                    pdfService.updateNbPages(posteCandidatureFile.getId());
                }
            }
        }
    } else {
        String userId = SecurityContextHolder.getContext().getAuthentication().getName();
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logger.warn(userId + "[" + ip + "] tried to add a 'null file' ... his userAgent is : " + userAgent);
    }

    return "redirect:/postecandidatures/" + id.toString();
}

From source file:com.tela.pms.PatientController.java

/**
 * createPatient will create a new patient and save in the cloud db
 *///from  www.  j  av  a  2 s  .  c om
@RequestMapping(value = "/createPatient", method = RequestMethod.POST)
public String createPatient(HttpServletRequest request, HttpServletResponse response, Model model,
        @RequestParam("file") MultipartFile file) {
    String view = "patient";

    //Creating a new patient object
    String firstName = request.getParameter("fName");
    String lastName = request.getParameter("lName");
    String age = request.getParameter("age");
    String nic = request.getParameter("nic");
    String address = request.getParameter("address");
    String gender = request.getParameter("gender");
    String contactNo = request.getParameter("contactNo");
    String email = request.getParameter("email");
    String formatedString = request.getParameter("tags");
    String tags = formatedString.toString().replace("[", "") //remove the right bracket
            .replace("]", "");
    String patientName = firstName + " " + lastName;

    //Validating Empty fields
    if (nic.equals("") || nic == null) {
        nic = "Not Available";
    }
    if (address.equals("") || address == null) {
        address = "Not Available";
    }
    if (contactNo.equals("") || contactNo == null) {
        contactNo = "Not Available";
    }
    if (email.equals("") || email == null) {
        email = "Not@Available";
    }
    if (tags.equals("") || tags == null) {
        tags = "Not Available";
    }

    //Generating an unique id
    int id = 1001;
    List<Patient> pasList = patientService.retrieveAllPatients();

    if (pasList != null) {

        if (pasList.size() > 1) {

            Collections.sort(pasList, new Comparator<Patient>() {
                @Override
                public int compare(Patient p1, Patient p2) {
                    if (p1.getPatient_Id() > p1.getPatient_Id())
                        return 1;
                    if (p1.getPatient_Id() < p2.getPatient_Id())
                        return -1;
                    return 0;
                }
            });

            id = pasList.get(pasList.size() - 1).getPatient_Id() + 1;
        } else if (pasList.size() == 1) {

            id = pasList.get(0).getPatient_Id() + 1;

        } else {

            id = 1001;
        }

    } else {

        id = 78 * new Date().getDay() * new Date().getSeconds();

    }

    //Creating DateTime
    SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd  hh:mm  a", Locale.US);
    String createdAt = DATE_FORMAT.format(new Date());

    //Retrieving uploaded files
    MultipartFile patientPhoto = file;
    //byte[] bFile_patientPhoto = null;
    String imagePath = "N/A";

    String extensionFile = FilenameUtils.getExtension(patientPhoto.getOriginalFilename());
    System.out.println(extensionFile);
    boolean value = extensionFile.equals("jpeg") || extensionFile.equals("jpg") || extensionFile.equals("JPG")
            || extensionFile.equals("JPEG");
    if (patientPhoto != null && value) {
        File cloud_file = null;
        try {
            cloud_file = convertFile(patientPhoto);
        } catch (IOException e1) {
            logger.info("something went wrong in coverting the file @" + new Date());
            e1.printStackTrace();
        }

        /*
        try {
           //bFile_patientPhoto = new byte[(int) patientPhoto.getSize()];
           //InputStream inputStream_patientPhoto = patientPhoto.getInputStream();
           //inputStream_patientPhoto.read(bFile_patientPhoto);
           //inputStream_patientPhoto.close();            
                     
        } catch (IOException e) {         
           e.printStackTrace();
        }      */
        String extension = FilenameUtils.getExtension(patientPhoto.getOriginalFilename());
        Long fileSize = patientPhoto.getSize();

        if (extension.equals("JPG") || extension.equals("jpg") || extension.equals("jpeg")
                || extension.equals("JPEG")) {
            try {
                File catalinaBase = new File(System.getProperty("catalina.base")).getAbsoluteFile();
                logger.info("catalinaBase:" + catalinaBase.getAbsolutePath());

                InputStream inputStream = patientPhoto.getInputStream();
                String imageId = "patient-" + Integer.toString(id);
                String fileName = imageId + "." + "jpg";
                File newFile = new File(catalinaBase,
                        "webapps/pms/WEB-INF/views/images/Uploaded_images/Patients/" + fileName);

                if (!newFile.exists()) {
                    newFile.createNewFile();
                }
                OutputStream outputStream = new FileOutputStream(newFile);
                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                imagePath = "resources/images/Uploaded_images/Patients/" + fileName;
                logger.info("Patient image successfully uploaded to local repo @" + new Date());
            } catch (FileNotFoundException e) {
                logger.info("something went wrong when patient photo uploading @" + new Date());
                e.printStackTrace();
            } catch (IOException e) {
                logger.info("something went wrong when patient photo uploading @" + new Date());
                e.printStackTrace();
            }

        } else {
            logger.info("Uploaded file is not a jpg or png " + new Date());
            if (gender.equals("Female")) {
                imagePath = "resources/images/patient-female.png";
            } else {
                imagePath = "resources/images/patient-male.png";
            }
        }

    } else {

        if (gender.equals("Female")) {
            imagePath = "resources/images/patient-female.png";
        } else {
            imagePath = "resources/images/patient-male.png";
        }

    }

    Patient patient = new Patient();

    patient.setPatient_Id(id);
    patient.setPatient_Name(patientName);
    patient.setPatient_Age(age);
    patient.setPatient_Address(address);
    patient.setPatient_ContactNo(contactNo);
    patient.setPatient_Gender(gender);
    patient.setPatient_Email(email);
    patient.setPatient_NIC(nic);
    patient.setPatient_CreatedAt(createdAt);
    patient.setPatient_Photo(imagePath);
    patient.setPatient_tags(tags);

    //System.out.println(patientName+"  "+age+"   "+patientPhoto.getOriginalFilename()+"   "+nic+"   "+address+"   "+gender+"   "+contactNo+"   "+email);

    List<Patient> palist = patientService.retrieveAllPatients();
    if (palist.size() == 0) {
        patientService.persistPatient(patient);
        logger.info("A New Patient " + id + " created @ " + new Date());
    } else {
        if (palist != null && palist.size() > 0) {
            boolean isNewPatient = true;
            boolean isNotExistingPatient = true;
            for (Patient pati : palist) {
                if (pati.getPatient_Id() == id) {
                    isNewPatient = false;
                    logger.info("Similar patient with same id exists.  " + id);
                    view = "error1";
                }
                if (pati.getPatient_Name().equals(patientName) && pati.getPatient_Photo().equals(imagePath)
                        && pati.getPatient_Age().equals(age)) {
                    logger.info("Similar patient exists.");
                    view = "error1";
                    isNotExistingPatient = false;
                    isNewPatient = false;
                }
            }
            if (isNewPatient || isNotExistingPatient) {
                patientService.persistPatient(patient);
                logger.info("A New Patient " + id + " created @ " + new Date());
            }
        }
    }

    Patient newPatient = patientService.findPatientById(id);
    model.addAttribute("patient", newPatient);

    List<Prescription> prescriptions = prescriptionService.retrieveAllPrescriptionsByPatientId(id);
    model.addAttribute("prescriptions", prescriptions);

    logger.info("New Patient " + id + " retrieved @ " + new Date());
    logger.info("Prescription list " + prescriptions + " retrieved @ " + new Date());
    model.addAttribute("status", "<strong>Great !</strong> A New Patient created successfully");
    model.addAttribute("style", "style=\"display:block;margin-top: 5px;\"");
    return view;
}

From source file:mx.edu.um.mateo.activos.web.ActivoController.java

@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response, @Valid Activo activo,
        BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes,
        @RequestParam(value = "imagen", required = false) MultipartFile archivo) {
    for (String nombre : request.getParameterMap().keySet()) {
        log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
    }//ww  w.  j  av  a2s .com
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");

        Long empresaId = (Long) request.getSession().getAttribute("empresaId");

        List<String> motivos = new ArrayList<>();
        motivos.add("COMPRA");
        motivos.add("DONACION");
        modelo.addAttribute("motivos", motivos);

        Map<String, Object> params = new HashMap<>();
        params.put("empresa", empresaId);
        params.put("reporte", true);
        params = tipoActivoDao.lista(params);
        modelo.addAttribute("tiposDeActivo", params.get("tiposDeActivo"));

        List<CentroCosto> centrosDeCosto = centroCostoDao.listaPorEmpresa(ambiente.obtieneUsuario());
        modelo.addAttribute("centrosDeCosto", centrosDeCosto);

        return "activoFijo/activo/nuevo";
    }

    try {
        Usuario usuario = ambiente.obtieneUsuario();
        if (archivo != null && !archivo.isEmpty()) {
            Imagen imagen = new Imagen(archivo.getOriginalFilename(), archivo.getContentType(),
                    archivo.getSize(), archivo.getBytes());
            activo.getImagenes().add(imagen);
        }
        log.debug("TipoActivo: {}", activo.getTipoActivo().getId());
        activo = activoDao.crea(activo, usuario);
    } catch (ConstraintViolationException | IOException e) {
        log.error("No se pudo crear al activo", e);
        errors.rejectValue("codigo", "campo.duplicado.message", new String[] { "codigo" }, null);

        Long empresaId = (Long) request.getSession().getAttribute("empresaId");

        List<String> motivos = new ArrayList<>();
        motivos.add("COMPRA");
        motivos.add("DONACION");
        modelo.addAttribute("motivos", motivos);

        Map<String, Object> params = new HashMap<>();
        params.put("empresa", empresaId);
        params.put("reporte", true);
        params = tipoActivoDao.lista(params);
        modelo.addAttribute("tiposDeActivo", params.get("tiposDeActivo"));

        List<CentroCosto> centrosDeCosto = centroCostoDao.listaPorEmpresa(ambiente.obtieneUsuario());
        modelo.addAttribute("centrosDeCosto", centrosDeCosto);

        return "activoFijo/activo/nuevo";
    }

    redirectAttributes.addFlashAttribute("message", "activo.creado.message");
    redirectAttributes.addFlashAttribute("messageAttrs", new String[] { activo.getFolio() });

    return "redirect:/activoFijo/activo/ver/" + activo.getId();
}

From source file:com.siblinks.ws.service.impl.UploadEssayServiceImpl.java

/**
 * validate essay type//from   w ww .j a  v a  2s.c  om
 *
 * @param file
 *            File input
 * @return Name file type
 */
private String validateEssay(final MultipartFile file) {
    String error = "";
    String name = "";
    String sample = env.getProperty("file.upload.essay.type");
    String limitSize = env.getProperty("file.upload.essay.size");
    if (file != null) {
        name = file.getOriginalFilename();
        if (!StringUtil.isNull(name)) {
            // if (isUTF8MisInterpreted(name, "Windows-1252")) {
            String nameExt = FilenameUtils.getExtension(name.toLowerCase());
            boolean status = sample.contains(nameExt);
            if (!status) {
                return "Error Format";
            }
            // } else {
            // error = "File name is not valid";
            // }
        }
        if (file.getSize() > Long.parseLong(limitSize)) {
            error = "File over 5MB";
        }
    } else {
        error = "File is empty";
    }
    return error;
}

From source file:com.devnexus.ting.web.controller.admin.PresentationController.java

@RequestMapping(value = "/s/admin/{eventKey}/presentation/{presentationId}", method = RequestMethod.POST)
public String editPresentation(@PathVariable("presentationId") Long presentationId,
        @RequestParam MultipartFile uploadedFile, @Valid Presentation presentation, BindingResult result,
        HttpServletRequest request, RedirectAttributes redirectAttributes) {

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/admin/{eventKey}/presentations";
    }/*  ww  w.  j av  a2  s  .  c om*/

    if (result.hasErrors()) {
        return "/admin/add-presentation";
    }

    final Presentation presentationFromDb = businessService.getPresentation(presentationId);

    if (request.getParameter("delete") != null) {
        businessService.deletePresentation(presentationFromDb);

        redirectAttributes.addFlashAttribute("successMessage", String
                .format("The presentation '%s' was deleted successfully.", presentationFromDb.getTitle()));
        return "redirect:/s/admin/{eventKey}/presentations";
    }

    presentationFromDb.setAudioLink(presentation.getAudioLink());
    presentationFromDb.setDescription(presentation.getDescription());
    presentationFromDb.setPresentationLink(presentation.getPresentationLink());
    presentationFromDb.setTitle(presentation.getTitle());

    presentationFromDb.setSkillLevel(presentation.getSkillLevel());

    if (presentation.getTrack().getId() != null) {
        final Track trackFromDb = businessService.getTrack(presentation.getTrack().getId());
        presentationFromDb.setTrack(trackFromDb);
    }

    presentationFromDb.setPresentationType(presentation.getPresentationType());

    final Set<PresentationTag> presentationTagsToSave = businessService
            .processPresentationTags(presentation.getTagsAsText());
    presentationFromDb.getPresentationTags().clear();
    presentationFromDb.getPresentationTags().addAll(presentationTagsToSave);

    if (uploadedFile != null && uploadedFile.getSize() > 0) {

        final FileData presentationData;
        if (presentationFromDb.getPresentationFile() == null) {
            presentationData = new FileData();
        } else {
            presentationData = presentationFromDb.getPresentationFile();
        }

        try {

            presentationData.setFileData(IOUtils.toByteArray(uploadedFile.getInputStream()));
            presentationData.setFileSize(uploadedFile.getSize());
            presentationData.setFileModified(new Date());
            presentationData.setName(uploadedFile.getOriginalFilename());
            presentationData.setType(uploadedFile.getContentType());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        presentationFromDb.setPresentationFile(presentationData);

        String message = "File '" + presentationData.getName() + "' uploaded successfully";
        redirectAttributes.addFlashAttribute("successMessage", message);
    }

    final List<Speaker> goodSpeakers = new ArrayList<>();

    if (presentation.getSpeakers() != null) {
        for (Speaker speaker : presentation.getSpeakers()) {
            if (speaker != null && speaker.getId() != null) {
                Speaker speakerFromDb = businessService.getSpeaker(speaker.getId());
                goodSpeakers.add(speakerFromDb);
            }
        }
    }

    if (goodSpeakers.size() > 0) {
        presentationFromDb.getSpeakers().clear();
        presentationFromDb.getSpeakers().addAll(goodSpeakers);
    }

    businessService.savePresentation(presentationFromDb);

    redirectAttributes.addFlashAttribute("successMessage",
            String.format("The presentation '%s' was edited successfully.", presentationFromDb.getTitle()));

    return "redirect:/s/admin/{eventKey}/presentations";
}

From source file:com.github.zhanhb.ckfinder.connector.handlers.command.FileUploadCommand.java

/**
 * validates uploaded file.//from  w ww  .  ja  va 2s .com
 *
 * @param item uploaded item.
 * @param path file path
 * @param param the parameter
 * @param context ckfinder context
 * @throws ConnectorException when error occurs
 */
private void validateUploadItem(MultipartFile item, Path path, FileUploadParameter param,
        CKFinderContext context) throws ConnectorException {
    if (item.getOriginalFilename() == null || item.getOriginalFilename().length() <= 0) {
        param.throwException(ErrorCode.UPLOADED_INVALID);
    }
    param.setFileName(getFileItemName(item));
    param.setNewFileName(param.getFileName());

    param.setNewFileName(UNSAFE_FILE_NAME_PATTERN.matcher(param.getNewFileName()).replaceAll("_"));

    if (context.isDisallowUnsafeCharacters()) {
        param.setNewFileName(param.getNewFileName().replace(';', '_'));
    }
    if (context.isForceAscii()) {
        param.setNewFileName(FileUtils.convertToAscii(param.getNewFileName()));
    }
    if (!param.getNewFileName().equals(param.getFileName())) {
        param.setErrorCode(ErrorCode.UPLOADED_INVALID_NAME_RENAMED);
    }

    if (context.isDirectoryHidden(param.getCurrentFolder())) {
        param.throwException(ErrorCode.INVALID_REQUEST);
    }
    if (!FileUtils.isFileNameValid(param.getNewFileName()) || context.isFileHidden(param.getNewFileName())) {
        param.throwException(ErrorCode.INVALID_NAME);
    }
    final ResourceType resourceType = param.getType();
    if (!FileUtils.isFileExtensionAllowed(param.getNewFileName(), resourceType)) {
        param.throwException(ErrorCode.INVALID_EXTENSION);
    }
    if (context.isCheckDoubleFileExtensions()) {
        param.setNewFileName(FileUtils.renameFileWithBadExt(resourceType, param.getNewFileName()));
    }

    Path file = getPath(path, getFinalFileName(path, param));
    if ((!ImageUtils.isImageExtension(file) || !context.isCheckSizeAfterScaling())
            && !FileUtils.isFileSizeInRange(resourceType, item.getSize())) {
        param.throwException(ErrorCode.UPLOADED_TOO_BIG);
    }

    if (context.isSecureImageUploads() && ImageUtils.isImageExtension(file) && !ImageUtils.isValid(item)) {
        param.throwException(ErrorCode.UPLOADED_CORRUPT);
    }
}