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

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

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Return whether the uploaded file is empty, that is, either no file has been chosen in the multipart form or the chosen file has no content.

Usage

From source file:csns.web.controller.SiteBlockControllerS.java

@RequestMapping(value = "/site/{qtr}/{cc}-{sn}/block/editItem", method = RequestMethod.POST)
public String editItem(@PathVariable String qtr, @PathVariable String cc, @PathVariable int sn,
        @ModelAttribute Block block, @RequestParam Long newBlockId, @ModelAttribute Item item,
        @RequestParam(value = "uploadedFile", required = false) MultipartFile uploadedFile,
        BindingResult bindingResult, SessionStatus sessionStatus) {
    itemValidator.validate(item, uploadedFile, bindingResult);
    if (bindingResult.hasErrors())
        return "site/block/editItem";

    User user = SecurityUtils.getUser();
    Resource resource = item.getResource();
    if (resource.getType() == ResourceType.FILE && uploadedFile != null && !uploadedFile.isEmpty())
        resource.setFile(fileIO.save(uploadedFile, user, true));

    if (newBlockId.equals(block.getId()))
        block = blockDao.saveBlock(block);
    else {//  w w  w  .  j a  va 2  s  . c om
        block.removeItem(item.getId());
        block = blockDao.saveBlock(block);
        Block newBlock = blockDao.getBlock(newBlockId);
        newBlock.getItems().add(item);
        newBlock = blockDao.saveBlock(newBlock);
    }
    sessionStatus.setComplete();

    logger.info(user.getUsername() + " edited item " + item.getId() + " in block " + block.getId());

    return "redirect:list";
}

From source file:csns.web.controller.SiteBlockControllerS.java

@RequestMapping(value = "/site/{qtr}/{cc}-{sn}/block/addResource", method = RequestMethod.POST)
public String addResource(@ModelAttribute Item item, @ModelAttribute Resource resource,
        @RequestParam Long blockId,
        @RequestParam(value = "uploadedFile", required = false) MultipartFile uploadedFile,
        BindingResult bindingResult, SessionStatus sessionStatus) {
    resourceValidator.validate(resource, uploadedFile, bindingResult);
    if (bindingResult.hasErrors())
        return "site/block/addResource";

    User user = SecurityUtils.getUser();
    if (resource.getType() != ResourceType.NONE) {
        if (resource.getType() == ResourceType.FILE && uploadedFile != null && !uploadedFile.isEmpty())
            resource.setFile(fileIO.save(uploadedFile, user, true));
        item.getAdditionalResources().add(resource);
        item = itemDao.saveItem(item);/* w  w w  .j  a  v a  2 s.c om*/
        logger.info(user.getUsername() + " added a resource to item " + item.getId() + " in block " + blockId);
    }
    sessionStatus.setComplete();

    return "redirect:editItem?blockId=" + blockId + "&itemId=" + item.getId();
}

From source file:com.baifendian.swordfish.webserver.service.WorkflowService.java

/**
 * ? data ???/*from   www. ja v  a  2  s .c  om*/
 *
 * @param data
 * @param file
 * @param workflowName
 * @param project
 * @return
 */
private WorkflowData workflowDataDes(String data, MultipartFile file, String workflowName, Project project) {
    WorkflowData workflowData = null;

    if (file != null && !file.isEmpty()) {
        // ?
        String filename = UUID.randomUUID().toString();
        // ,  ".zip"
        String localFilename = BaseConfig.getLocalWorkflowFilename(project.getId(), filename);
        // ?
        String localExtractDir = BaseConfig.getLocalWorkflowExtractDir(project.getId(), filename);
        // hdfs 
        String hdfsFilename = BaseConfig.getHdfsWorkflowFilename(project.getId(), workflowName);

        try {
            // 
            logger.info("save workflow file {} to local {}", workflowName, localFilename);
            fileSystemStorageService.store(file, localFilename);

            //  ?
            ZipFile zipFile = new ZipFile(localFilename);
            logger.info("ext file {} to {}", localFilename, localExtractDir);
            zipFile.extractAll(localExtractDir);
            String workflowJsonPath = MessageFormat.format("{0}/{1}", localExtractDir, WorkflowJson);
            logger.info("Start reader workflow.json: {}", workflowJsonPath);
            String jsonString = fileSystemStorageService.readFileToString(workflowJsonPath);
            workflowData = JsonUtil.parseObject(jsonString, WorkflowData.class);
            logger.info("Finish reader workflow.json!");

            //  HDFS
            if (workflowData != null) {
                logger.info("update workflow local file {} to hdfs {}", localFilename, hdfsFilename);
                HdfsClient.getInstance().copyLocalToHdfs(localFilename, hdfsFilename, true, true);
            }
        } catch (ZipException e) {
            logger.error("ext file error", e);
            return null;
        } catch (IOException e) {
            logger.error("read workflow.json error", e);
            return null;
        } catch (Exception e) {
            logger.error("workflow file process error", e);
            return null;
        }
    } else if (data != null) {
        workflowData = JsonUtil.parseObject(data, WorkflowData.class);
    }

    return workflowData;
}

From source file:com.goodhuddle.huddle.service.impl.MemberServiceImpl.java

@Override
public ImportMembersResults importMembers(MultipartFile multipartFile, Long[] tagIds) {
    final ImportMembersResults results = new ImportMembersResults();
    results.setSuccess(true);/*from w  ww .j a  va  2 s  . co m*/

    try {
        final Huddle huddle = huddleService.getHuddle();

        if (!multipartFile.isEmpty()) {

            File file = fileStore.getTempFile(fileStore.createTempFile(multipartFile.getBytes()));

            final CSVReader reader = new CSVReader(new FileReader(file));
            if (reader.readNext() != null) {
                // skipped header row

                final List<Tag> tags = new ArrayList<>();
                if (tagIds != null) {
                    for (Long tagId : tagIds) {
                        tags.add(tagRepository.findByHuddleAndId(huddle, tagId));
                    }
                }

                boolean done = false;
                while (!done) {
                    TransactionTemplate txTemplate = new TransactionTemplate(txManager);
                    txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
                    done = txTemplate.execute(new TransactionCallback<Boolean>() {

                        @Override
                        public Boolean doInTransaction(TransactionStatus status) {
                            try {
                                int i = 0;
                                String[] nextLine;
                                while ((nextLine = reader.readNext()) != null) {
                                    String email = nextLine[0];
                                    String firstName = nextLine[1];
                                    String lastName = nextLine[2];
                                    String postCode = nextLine[3];
                                    String phone = nextLine[4];

                                    Member member = memberRepository.findByHuddleAndEmailIgnoreCase(huddle,
                                            email);
                                    if (member != null) {
                                        member.setFirstName(firstName);
                                        member.setLastName(lastName);
                                        member.setPostCode(postCode);
                                        member.setPhone(phone);
                                        List<Tag> memberTags = member.getTags();
                                        if (memberTags == null) {
                                            memberTags = new ArrayList<>();
                                        }
                                        outer: for (Tag tag : tags) {
                                            for (Tag memberTag : memberTags) {
                                                if (memberTag.getId() == member.getId()) {
                                                    break outer;
                                                }
                                            }
                                            memberTags.add(tag);
                                        }
                                        member.setTags(memberTags);
                                        memberRepository.save(member);
                                        results.setNumUpdated(results.getNumUpdated() + 1);
                                    } else {
                                        member = new Member();
                                        member.setHuddle(huddle);
                                        member.setEmail(email);
                                        member.setFirstName(firstName);
                                        member.setLastName(lastName);
                                        member.setPostCode(postCode);
                                        member.setPhone(phone);
                                        member.setTags(tags);
                                        memberRepository.save(member);
                                        results.setNumImported(results.getNumImported() + 1);
                                    }

                                    if (i++ > 30) {
                                        return false;
                                    }
                                }
                                return true;
                            } catch (IOException e) {
                                log.error("Error importing file: " + e, e);
                                results.setSuccess(false);
                                results.setErrorMessage("Error importing file: " + e);
                                return true;
                            }
                        }
                    });
                }

            }

        } else {
            log.info("Empty file was uploaded");
            results.setSuccess(false);
            results.setErrorMessage("Empty file was uploaded");
        }
    } catch (IOException e) {
        results.setSuccess(false);
        results.setErrorMessage("Error uploading file: " + e);
    }

    return results;
}

From source file:org.literacyapp.web.content.multimedia.image.ImageEditController.java

@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public String handleSubmit(HttpSession session, Image image, @RequestParam("bytes") MultipartFile multipartFile,
        BindingResult result, Model model) {
    logger.info("handleSubmit");

    if (StringUtils.isBlank(image.getTitle())) {
        result.rejectValue("title", "NotNull");
    } else {//from w w  w . j  av a 2 s . com
        Image existingImage = imageDao.read(image.getTitle(), image.getLocale());
        if ((existingImage != null) && !existingImage.getId().equals(image.getId())) {
            result.rejectValue("title", "NonUnique");
        }
    }

    try {
        byte[] bytes = multipartFile.getBytes();
        if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) {
            result.rejectValue("bytes", "NotNull");
        } else {
            String originalFileName = multipartFile.getOriginalFilename();
            logger.info("originalFileName: " + originalFileName);
            if (originalFileName.toLowerCase().endsWith(".png")) {
                image.setImageFormat(ImageFormat.PNG);
            } else if (originalFileName.toLowerCase().endsWith(".jpg")
                    || originalFileName.toLowerCase().endsWith(".jpeg")) {
                image.setImageFormat(ImageFormat.JPG);
            } else if (originalFileName.toLowerCase().endsWith(".gif")) {
                image.setImageFormat(ImageFormat.GIF);
            } else {
                result.rejectValue("bytes", "typeMismatch");
            }

            if (image.getImageFormat() != null) {
                String contentType = multipartFile.getContentType();
                logger.info("contentType: " + contentType);
                image.setContentType(contentType);

                image.setBytes(bytes);

                if (image.getImageFormat() != ImageFormat.GIF) {
                    int width = ImageHelper.getWidth(bytes);
                    logger.info("width: " + width + "px");

                    if (width < ImageHelper.MINIMUM_WIDTH) {
                        result.rejectValue("bytes", "image.too.small");
                        image.setBytes(null);
                    } else {
                        if (width > ImageHelper.MINIMUM_WIDTH) {
                            bytes = ImageHelper.scaleImage(bytes, ImageHelper.MINIMUM_WIDTH);
                            image.setBytes(bytes);
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }

    if (result.hasErrors()) {
        model.addAttribute("image", image);
        model.addAttribute("contentLicenses", ContentLicense.values());
        model.addAttribute("literacySkills", LiteracySkill.values());
        model.addAttribute("numeracySkills", NumeracySkill.values());
        model.addAttribute("contentCreationEvents", contentCreationEventDao.readAll(image));
        return "content/multimedia/image/edit";
    } else {
        image.setTitle(image.getTitle().toLowerCase());
        image.setTimeLastUpdate(Calendar.getInstance());
        image.setRevisionNumber(Integer.MIN_VALUE);
        imageDao.update(image);

        Contributor contributor = (Contributor) session.getAttribute("contributor");

        ContentCreationEvent contentCreationEvent = new ContentCreationEvent();
        contentCreationEvent.setContributor(contributor);
        contentCreationEvent.setContent(image);
        contentCreationEvent.setCalendar(Calendar.getInstance());
        contentCreationEventDao.update(contentCreationEvent);

        if (EnvironmentContextLoaderListener.env == Environment.PROD) {
            String text = URLEncoder
                    .encode(contributor.getFirstName() + " just edited an Image:\n" + " Language: "
                            + image.getLocale().getLanguage() + "\n" + " Title: \"" + image.getTitle()
                            + "\"\n" + " Image format: " + image.getImageFormat() + "\n" + "See ")
                    + "http://literacyapp.org/content/multimedia/image/list";
            String iconUrl = contributor.getImageUrl();
            SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/image/"
                    + image.getId() + "." + image.getImageFormat().toString().toLowerCase());
        }

        return "redirect:/content/multimedia/image/list";
    }
}

From source file:mx.edu.um.mateo.inventario.web.ProductoController.java

@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, @Valid Producto producto, 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));
    }//  w w  w  .  j  a  va 2 s.c o  m
    if (bindingResult.hasErrors()) {
        log.debug("Hubo algun error en la forma, regresando");
        return "inventario/producto/nuevo";
    }

    try {

        if (archivo != null && !archivo.isEmpty()) {
            Imagen imagen = new Imagen(archivo.getOriginalFilename(), archivo.getContentType(),
                    archivo.getSize(), archivo.getBytes());
            producto.getImagenes().add(imagen);
        }
        Usuario usuario = ambiente.obtieneUsuario();
        producto = productoDao.crea(producto, usuario);

    } catch (ConstraintViolationException e) {
        log.error("No se pudo crear el producto", e);
        errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null);

        Map<String, Object> params = new HashMap<>();
        params.put("almacen", request.getSession().getAttribute("almacenId"));
        params.put("reporte", true);
        params = tipoProductoDao.lista(params);
        modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto"));

        return "inventario/producto/nuevo";
    } catch (IOException e) {
        log.error("No se pudo crear el producto", e);
        errors.rejectValue("imagenes", "problema.con.imagen.message",
                new String[] { archivo.getOriginalFilename() }, null);

        Map<String, Object> params = new HashMap<>();
        params.put("almacen", request.getSession().getAttribute("almacenId"));
        params.put("reporte", true);
        params = tipoProductoDao.lista(params);
        modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto"));

        return "inventario/producto/nuevo";
    }

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

    return "redirect:/inventario/producto/ver/" + producto.getId();
}

From source file:org.literacyapp.web.content.multimedia.audio.AudioEditController.java

@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public String handleSubmit(HttpSession session, Audio audio, @RequestParam("bytes") MultipartFile multipartFile,
        BindingResult result, Model model) {
    logger.info("handleSubmit");

    if (StringUtils.isBlank(audio.getTranscription())) {
        result.rejectValue("transcription", "NotNull");
    } else {//from   w ww.  j  a va2 s.co m
        Audio existingAudio = audioDao.read(audio.getTranscription(), audio.getLocale());
        if ((existingAudio != null) && !existingAudio.getId().equals(audio.getId())) {
            result.rejectValue("transcription", "NonUnique");
        }
    }

    try {
        byte[] bytes = multipartFile.getBytes();
        if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) {
            result.rejectValue("bytes", "NotNull");
        } else {
            String originalFileName = multipartFile.getOriginalFilename();
            logger.info("originalFileName: " + originalFileName);
            if (originalFileName.toLowerCase().endsWith(".mp3")) {
                audio.setAudioFormat(AudioFormat.MP3);
            } else if (originalFileName.toLowerCase().endsWith(".ogg")) {
                audio.setAudioFormat(AudioFormat.OGG);
            } else if (originalFileName.toLowerCase().endsWith(".wav")) {
                audio.setAudioFormat(AudioFormat.WAV);
            } else {
                result.rejectValue("bytes", "typeMismatch");
            }

            if (audio.getAudioFormat() != null) {
                String contentType = multipartFile.getContentType();
                logger.info("contentType: " + contentType);
                audio.setContentType(contentType);

                audio.setBytes(bytes);

                // TODO: convert to a default audio format?
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }

    if (result.hasErrors()) {
        model.addAttribute("audio", audio);
        model.addAttribute("contentLicenses", ContentLicense.values());
        model.addAttribute("literacySkills", LiteracySkill.values());
        model.addAttribute("numeracySkills", NumeracySkill.values());
        model.addAttribute("contentCreationEvents", contentCreationEventDao.readAll(audio));
        return "content/multimedia/audio/edit";
    } else {
        audio.setTranscription(audio.getTranscription().toLowerCase());
        audio.setTimeLastUpdate(Calendar.getInstance());
        audio.setRevisionNumber(Integer.MIN_VALUE);
        audioDao.update(audio);

        Contributor contributor = (Contributor) session.getAttribute("contributor");

        ContentCreationEvent contentCreationEvent = new ContentCreationEvent();
        contentCreationEvent.setContributor(contributor);
        contentCreationEvent.setContent(audio);
        contentCreationEvent.setCalendar(Calendar.getInstance());
        contentCreationEventDao.update(contentCreationEvent);

        if (EnvironmentContextLoaderListener.env == Environment.PROD) {
            String text = URLEncoder.encode(contributor.getFirstName() + " just edited an Audio:\n"
                    + " Language: " + audio.getLocale().getLanguage() + "\n" + " Transcription: \""
                    + audio.getTranscription() + "\"\n" + " Audio format: " + audio.getAudioFormat() + "\n"
                    + "See ") + "http://literacyapp.org/content/multimedia/audio/list";
            String iconUrl = contributor.getImageUrl();
            SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/audio/"
                    + audio.getId() + "." + audio.getAudioFormat().toString().toLowerCase());
        }

        return "redirect:/content/multimedia/audio/list";
    }
}

From source file:csns.web.controller.ProfileControllerS.java

@RequestMapping(value = "/profile/edit", method = RequestMethod.POST)
public String edit(@ModelAttribute("user") User cmd,
        @RequestParam(value = "file", required = false) MultipartFile uploadedFile, HttpServletRequest request,
        BindingResult bindingResult, SessionStatus sessionStatus) {
    editUserValidator.validate(cmd, bindingResult);
    if (bindingResult.hasErrors())
        return "profile/edit";

    User user = userDao.getUser(SecurityUtils.getUser().getId());
    user.copySelfEditableFieldsFrom(cmd);
    String password = cmd.getPassword1();
    if (StringUtils.hasText(password))
        user.setPassword(passwordEncoder.encodePassword(password, null));
    user = userDao.saveUser(user);//from w  w w  . ja v  a  2  s .c  o  m

    logger.info(user.getUsername() + " edited profile.");

    if (uploadedFile != null && !uploadedFile.isEmpty()) {
        File picture0 = fileIO.save(uploadedFile, user, true);
        File picture1 = imageUtils.resizeToProfilePicture(picture0);
        File picture2 = imageUtils.resizeToProfileThumbnail(picture0);
        user.setOriginalPicture(picture0);
        user.setProfilePicture(picture1);
        user.setProfileThumbnail(picture2);
        user = userDao.saveUser(user);

        logger.info("Saved profile picture for " + user.getUsername());
    }

    sessionStatus.setComplete();
    return "redirect:/profile";
}

From source file:com.dp2345.controller.admin.SettingController.java

/**
 * //from  w w w . j  av a 2  s  .c om
 */
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(Setting setting, MultipartFile watermarkImageFile, RedirectAttributes redirectAttributes) {
    if (!isValid(setting)) {
        return ERROR_VIEW;
    }
    if (setting.getUsernameMinLength() > setting.getUsernameMaxLength()
            || setting.getPasswordMinLength() > setting.getPasswordMinLength()) {
        return ERROR_VIEW;
    }
    Setting srcSetting = SettingUtils.get();
    if (StringUtils.isEmpty(setting.getSmtpPassword())) {
        setting.setSmtpPassword(srcSetting.getSmtpPassword());
    }
    if (watermarkImageFile != null && !watermarkImageFile.isEmpty()) {
        if (!fileService.isValid(FileType.image, watermarkImageFile)) {
            addFlashMessage(redirectAttributes, Message.error("admin.upload.invalid"));
            return "redirect:edit.jhtml";
        }
        String watermarkImage = fileService.uploadLocal(FileType.image, watermarkImageFile);
        setting.setWatermarkImage(watermarkImage);
    } else {
        setting.setWatermarkImage(srcSetting.getWatermarkImage());
    }
    setting.setCnzzSiteId(srcSetting.getCnzzSiteId());
    setting.setCnzzPassword(srcSetting.getCnzzPassword());
    SettingUtils.set(setting);
    cacheService.clear();
    staticService.buildIndex();
    staticService.buildOther();

    OutputStream outputStream = null;
    try {
        org.springframework.core.io.Resource resource = new ClassPathResource(
                CommonAttributes.DP2345_PROPERTIES_PATH);
        Properties properties = PropertiesLoaderUtils.loadProperties(resource);
        String templateUpdateDelay = properties.getProperty("template.update_delay");
        String messageCacheSeconds = properties.getProperty("message.cache_seconds");
        if (setting.getIsDevelopmentEnabled()) {
            if (!templateUpdateDelay.equals("0") || !messageCacheSeconds.equals("0")) {
                outputStream = new FileOutputStream(resource.getFile());
                properties.setProperty("template.update_delay", "0");
                properties.setProperty("message.cache_seconds", "0");
                properties.store(outputStream, "DP2345 PROPERTIES");
            }
        } else {
            if (templateUpdateDelay.equals("0") || messageCacheSeconds.equals("0")) {
                outputStream = new FileOutputStream(resource.getFile());
                properties.setProperty("template.update_delay", "3600");
                properties.setProperty("message.cache_seconds", "3600");
                properties.store(outputStream, "DP2345 PROPERTIES");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:edit.jhtml";
}

From source file:com.mbv.web.rest.controller.VpGdnController.java

/**
 * @??excel//from   www.  j a v a 2s .co  m
 * @2015916
 * @param
 * @version
 */
@RequestMapping(value = "/importGdn", method = RequestMethod.POST)
@ResponseBody
public void importVpGdnAddBill(
        @RequestParam(value = "add_vpGdn_importedFile", required = false) MultipartFile file,
        HttpServletRequest request, HttpServletResponse response) throws IOException {
    JSONObject json = new JSONObject();
    try {
        // ?
        if (file.isEmpty()) {
            throw new MbvException("??");
        }
        // ??
        if (file.getSize() > 20971520) {
            throw new Exception("?20M?");
        }
        json = importFile(file);
    } catch (MbvException me) {
        me.printStackTrace();
        json.put("success", false);
        json.put("msg", me.getMessage());
    } catch (RuntimeException re) {
        re.printStackTrace();
        json.put("success", false);
        json.put("msg", re.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        json.put("success", false);
        json.put("msg", e.getMessage());
    }
    // ???
    outPrintJson(response, json.toString());
}