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.SyllabusControllerS.java

private String edit(Section section, Resource syllabus, MultipartFile uploadedFile, BindingResult bindingResult,
        SessionStatus sessionStatus, ModelMap models, String redirectUrl) {
    resourceValidator.validate(syllabus, uploadedFile, bindingResult);
    if (bindingResult.hasErrors()) {
        models.put("section", section);
        return "syllabus/edit";
    }/*  w w  w  .ja v a 2  s.  c om*/

    if (syllabus.getType() == ResourceType.NONE)
        section.setSyllabus(null);
    else
        section.setSyllabus(syllabus);

    // This is a workaround for a rather weird behavior in Hibernate: when
    // FileDao.saveFile() is called, the syllabus Resource object is
    // automatically flushed with a persist(), which will cause a
    // "persisting a detached object" exception. So here we re-attach
    // syllabus first, and then save the uploaded file if there is one.
    section = sectionDao.saveSection(section);
    syllabus = section.getSyllabus();
    User user = SecurityUtils.getUser();
    if (syllabus.getType() == ResourceType.FILE && uploadedFile != null && !uploadedFile.isEmpty()) {
        File file = fileIO.save(uploadedFile, user, true);
        syllabus.setFile(file);
        sectionDao.saveSection(section);
    }
    sessionStatus.setComplete();

    logger.info(user.getUsername() + " edited the syllabus of section " + section.getId());

    return "redirect:" + redirectUrl;
}

From source file:de.hska.ld.content.controller.DocumentController.java

/**
 * This resource allows it upload a file and attach it to a document.
 * <p>/*w w  w.java  2  s .c  o  m*/
 * <pre>
 *     <b>Required roles:</b> ROLE_USER
 *     <b>Path:</b> POST /api/documents/upload?documentId=1
 * </pre>
 *
 * @param file       the Multipart file that has been uploaded
 * @param documentId the document ID to which the file shall be attached
 * @return <b>200 OK</b> if the upload has been successfully performed<br>
 * <b>400 BAD REQUEST</b> if empty file parameter<br>
 */
@Secured(Core.ROLE_USER)
@RequestMapping(method = RequestMethod.POST, value = "/upload")
public Callable uploadFile(@RequestParam MultipartFile file, @RequestParam Long documentId) {
    return () -> {
        String name = file.getOriginalFilename();
        if (!file.isEmpty()) {
            Long attachmentId = documentService.addAttachment(documentId, file, name);
            try {
                LoggingContext.put("user_email",
                        EscapeUtil.escapeJsonForLogging(Core.currentUser().getEmail()));
                LoggingContext.put("updatedAttachmentId",
                        EscapeUtil.escapeJsonForLogging(attachmentId.toString()));
                Logger.trace("User uploaded file (2).");
            } catch (Exception e) {
                Logger.error(e);
            } finally {
                LoggingContext.clear();
            }
            return new ResponseEntity<>(attachmentId, HttpStatus.OK);
        } else {
            throw new ValidationException("file");
        }
    };
}

From source file:it.smartcommunitylab.climb.domain.controller.ChildController.java

@RequestMapping(value = "/api/child/image/upload/png/{ownerId}/{objectId}", method = RequestMethod.POST)
public @ResponseBody String uploadImage(@RequestParam("file") MultipartFile file, @PathVariable String ownerId,
        @PathVariable String objectId, HttpServletRequest request) throws Exception {
    Criteria criteria = Criteria.where("objectId").is(objectId);
    Child child = storage.findOneData(Child.class, criteria, ownerId);
    if (child == null) {
        throw new EntityNotFoundException("child not found");
    }// w  w w  .jav  a  2s . c o m
    if (!validateAuthorization(ownerId, child.getInstituteId(), child.getSchoolId(), null, null,
            Const.AUTH_RES_Image, Const.AUTH_ACTION_ADD, request)) {
        throw new UnauthorizedException("Unauthorized Exception: token not valid");
    }
    String name = objectId + ".png";
    if (logger.isInfoEnabled()) {
        logger.info("uploadImage:" + name);
    }
    if (!file.isEmpty()) {
        BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File(imageUploadDir + "/" + name)));
        FileCopyUtils.copy(file.getInputStream(), stream);
        stream.close();
    }
    return "{\"status\":\"OK\"}";
}

From source file:de.hska.ld.content.controller.DocumentController.java

@Secured(Core.ROLE_USER)
@RequestMapping(method = RequestMethod.POST, value = "/uploadmain")
public Callable uploadMainFile(@RequestParam MultipartFile file, @RequestParam Long documentId) {
    return () -> {
        String name = file.getOriginalFilename();
        if (!file.isEmpty()) {
            Document document = documentService.findById(documentId);
            if (document == null) {
                throw new NotFoundException("documentId");
            }/* ww  w .j ava2s .c om*/
            Attachment attachment = document.getAttachmentList().get(0);
            Long attachmentId = documentService.updateAttachment(documentId, attachment.getId(), file, name);
            try {
                LoggingContext.put("user_email",
                        EscapeUtil.escapeJsonForLogging(Core.currentUser().getEmail()));
                LoggingContext.put("updatedAttachmentId",
                        EscapeUtil.escapeJsonForLogging(attachmentId.toString()));
                Logger.trace("User uploaded main file.");
            } catch (Exception e) {
                Logger.error(e);
            } finally {
                LoggingContext.clear();
            }
            return new ResponseEntity<>(attachmentId, HttpStatus.OK);
        } else {
            throw new ValidationException("file");
        }
    };
}

From source file:de.hska.ld.content.controller.DocumentController.java

/**
 * This resource allows it to update of a file content.
 * <p>/*from w  w  w. java 2  s.com*/
 * <pre>
 *     <b>Required roles:</b> ROLE_USER
 *     <b>Path:</b> POST /api/documents/upload/{attachmentId}
 * </pre>
 *
 * @param file         the Multipart file that has been uploaded
 * @param documentId   the document ID to which the file shall be attached
 * @param attachmentId the attachment id of the attachment that shall be updated
 * @return <b>200 OK</b> if the upload has been successfully performed<br>
 * <b>400 BAD REQUEST</b> if empty file parameter<br>
 */
@Secured(Core.ROLE_USER)
@RequestMapping(method = RequestMethod.POST, value = "/upload/{attachmentId}")
public Callable uploadFile(@RequestParam MultipartFile file, @PathVariable Long attachmentId,
        @RequestParam Long documentId) {
    return () -> {
        String name = file.getOriginalFilename();
        if (!file.isEmpty()) {
            Long updatedAttachmentId = documentService.updateAttachment(documentId, attachmentId, file, name);
            try {
                LoggingContext.put("user_email",
                        EscapeUtil.escapeJsonForLogging(Core.currentUser().getEmail()));
                LoggingContext.put("updatedAttachmentId",
                        EscapeUtil.escapeJsonForLogging(updatedAttachmentId.toString()));
                Logger.trace("User uploaded file.");
            } catch (Exception e) {
                Logger.error(e);
            } finally {
                LoggingContext.clear();
            }
            return new ResponseEntity<>(updatedAttachmentId, HttpStatus.OK);
        } else {
            throw new ValidationException("file");
        }
    };
}

From source file:org.onebusaway.nyc.vehicle_tracking.webapp.controllers.VehicleLocationSimulationController.java

@RequestMapping(value = "/vehicle-location-simulation!upload-trace.do", method = RequestMethod.POST)
public ModelAndView uploadTrace(@RequestParam("file") MultipartFile file,
        @RequestParam(value = "realtime", required = false, defaultValue = "false") boolean realtime,
        @RequestParam(value = "pauseOnStart", required = false, defaultValue = "false") boolean pauseOnStart,
        @RequestParam(value = "shiftStartTime", required = false, defaultValue = "false") boolean shiftStartTime,
        @RequestParam(value = "minimumRecordInterval", required = false, defaultValue = "0") int minimumRecordInterval,
        @RequestParam(value = "traceType", required = true) String traceType,
        @RequestParam(required = false, defaultValue = "false") boolean bypassInference,
        @RequestParam(required = false, defaultValue = "false") boolean fillActualProperties,
        @RequestParam(value = "loop", required = false, defaultValue = "false") boolean loop,
        @RequestParam(required = false, defaultValue = "false") boolean returnId) throws IOException {

    int taskId = -1;

    if (!file.isEmpty()) {

        String name = file.getOriginalFilename();
        InputStream in = file.getInputStream();

        if (name.endsWith(".gz"))
            in = new GZIPInputStream(in);

        taskId = _vehicleLocationSimulationService.simulateLocationsFromTrace(traceType, in, realtime,
                pauseOnStart, shiftStartTime, minimumRecordInterval, bypassInference, fillActualProperties,
                loop);/*from   w ww  .j a v a  2 s  .  c  o m*/
    }

    if (returnId) {
        return new ModelAndView("vehicle-location-simulation-taskId.jspx", "taskId", taskId);
    } else {
        return new ModelAndView("redirect:/vehicle-location-simulation.do");
    }
}

From source file:org.iti.agrimarket.view.UpdateOfferController.java

/**
 * upload image and form data/*from   w ww.  j  a va  2s .  com*/
 *
 */
@RequestMapping(method = RequestMethod.POST, value = { "/updateoffer.htm" })
public String updateOffer(@RequestParam("description") String description,
        @RequestParam("quantity") float quantity, @RequestParam("quantityunit") int quantityunit,
        @RequestParam("unitprice") int unitprice, @RequestParam("price") float price,
        @RequestParam("mobile") String mobile, @RequestParam("governerate") String governerate,
        @RequestParam("product") int product, @RequestParam("file") MultipartFile file,
        @RequestParam("offerId") int offerId, @ModelAttribute("user") User userFromSession,
        RedirectAttributes redirectAttributes, Model model, HttpServletRequest request) {

    System.out.println("product id PPPPPPPPPPPPPPPPPPPPPP:" + product);

    UserOfferProductFixed userOfferProductFixed = offerService.findUserOfferProductFixed(offerId);
    if (userOfferProductFixed != null) {
        userOfferProductFixed.setDescription(description);
        userOfferProductFixed.setPrice(price);
        userOfferProductFixed.setQuantity(quantity);
        userOfferProductFixed.setProduct(productService.getProduct(product));
        userOfferProductFixed.setUnitByUnitId(unitService.getUnit(quantityunit));
        userOfferProductFixed.setUnitByPricePerUnitId(unitService.getUnit(unitprice));
        userOfferProductFixed.setUser(userFromSession);
        userOfferProductFixed.setUserLocation(governerate);
        userOfferProductFixed.setUserPhone(mobile);

        offerService.updateOffer(userOfferProductFixed);

    }
    if (!file.isEmpty()) {

        String fileName = userOfferProductFixed.getId() + String.valueOf(new Date().getTime());

        try {

            System.out.println("fileName   :" + fileName);
            byte[] bytes = file.getBytes();

            System.out.println(new String(bytes));
            MagicMatch match = Magic.getMagicMatch(bytes);
            final String ext = "." + match.getExtension();

            File parentDir = new File(Constants.IMAGE_PATH + Constants.OFFER_PATH);
            if (!parentDir.isDirectory()) {
                parentDir.mkdirs();
            }
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(
                    new File(Constants.IMAGE_PATH + Constants.USER_PATH + fileName + ext)));
            stream.write(bytes);
            stream.close();
            userOfferProductFixed.setImageUrl(Constants.IMAGE_PRE_URL + Constants.USER_PATH + fileName + ext);
            System.out.println("image url" + userOfferProductFixed.getImageUrl());

            offerService.updateOffer(userOfferProductFixed);

        } catch (Exception e) {
            //                  logger.error(e.getMessage());
            offerService.deleteOffer(userOfferProductFixed.getId()); // delete the category if something goes wrong

            redirectAttributes.addFlashAttribute("message", "You failed to upload  because the file was empty");
            return "redirect:/web/updateoffer.htm";
        }

    } else {
        redirectAttributes.addFlashAttribute("message", "You failed to upload  because the file was empty");
    }

    //User user =  userService.getUserByEmail(userFromSession.getMail());
    //           model.addAttribute("user", user);
    User oldUser = (User) request.getSession().getAttribute("user");
    if (oldUser != null) {
        User user = userService.getUserEager(oldUser.getId());
        request.getSession().setAttribute("user", user);
        model.addAttribute("user", user);
    }

    return "profile";
}

From source file:com.jd.survey.web.settings.DataSetController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html")
public String importDatasetItems(@RequestParam("file") MultipartFile file, @RequestParam("id") Long dataSetId,
        @RequestParam("ignoreFirstRow") Boolean ignoreFirstRow,
        @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {

    try {//  w  ww.  ja  v a2  s.c  om
        String login = principal.getName();
        User user = userService.user_findByLogin(login);

        if (!user.isAdmin()) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }
        if (proceed != null) {
            log.info(file.getContentType());
            //if file is empty OR the file type is incorrect the upload page is returned with an error message.
            if (file.isEmpty() || !((file.getContentType().equalsIgnoreCase("text/csv"))
                    || (file.getContentType().equals("application/vnd.ms-excel"))
                    || (file.getContentType().equals("text/plain")))) {
                uiModel.addAttribute("dataSet", surveySettingsService.dataSet_findById(dataSetId));
                uiModel.addAttribute("emptyFileError", true);
                return "settings/datasets/upload";
            }
            try {
                CSVReader csvReader;
                csvReader = new CSVReader(new InputStreamReader(file.getInputStream()));
                surveySettingsService.importDatasetItems(csvReader, dataSetId, ignoreFirstRow);
                //done Redirect to the set view page
                return "redirect:/settings/datasets/"
                        + encodeUrlPathSegment(dataSetId.toString(), httpServletRequest) + "?page=1&size=15";
            }

            catch (Exception e) {
                log.error(e.getMessage(), e);
                uiModel.addAttribute("dataSet", surveySettingsService.dataSet_findById(dataSetId));
                uiModel.addAttribute("emptyFileError", true);
                return "settings/datasets/upload";
            }

        } else {

            return "redirect:/settings/datasets/"
                    + encodeUrlPathSegment(dataSetId.toString(), httpServletRequest);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.scenario.AddScenarioController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException bindException) throws Exception {
    ModelAndView mav = new ModelAndView(getSuccessView());
    log.debug("Processing form data");
    AddScenarioCommand data = (AddScenarioCommand) command;

    String idString = request.getParameter("id");
    int id = 0;/*w  ww. jav a  2s  . co  m*/
    if (idString != null) {
        id = Integer.parseInt(idString);
    }
    if (!auth.isAdmin()) {
        if ((id > 0) && (!auth.userIsOwnerOfScenario(id))) {
            // Editing existing scenario and user is not owner
            mav.setViewName("redirect:/scenarios/list.html");
            return mav;
        }

        if (!auth.userIsExperimenter()) {
            mav.setViewName("scenario/userNotExperimenter");
            return mav;
        }
    }

    MultipartFile file = data.getDataFile();
    MultipartFile xmlFile = data.getDataFileXml();

    Scenario scenario;
    if (id > 0) {
        // Editing existing
        log.debug("Editing existing scenario.");
        scenario = scenarioDao.read(id);
    } else {
        // Creating new
        log.debug("Creating new scenario object");
        scenario = new Scenario();

        log.debug("Setting owner to the logged user.");
        scenario.setPerson(personDao.getLoggedPerson());

    }

    log.debug("Setting research group.");
    ResearchGroup group = new ResearchGroup();
    group.setResearchGroupId(data.getResearchGroup());
    scenario.setResearchGroup(group);

    log.debug("Setting scenario title: " + data.getTitle());
    scenario.setTitle(data.getTitle());

    log.debug("Setting scenario description: " + data.getDescription());
    scenario.setDescription(data.getDescription());

    log.debug("Setting scenario length: " + data.getLength());
    scenario.setScenarioLength(Integer.parseInt(data.getLength()));
    //loading non-XML
    if ((file != null) && (!file.isEmpty())) {

    }

    //loading XML
    if ((xmlFile != null) && (!xmlFile.isEmpty())) {

    }

    log.debug("Setting private/public access");
    scenario.setPrivateScenario(data.getPrivateNote());

    log.debug("Saving scenario object");
    if (!data.isDataFileAvailable()) {

    }
    if (id > 0) {
        // Editing existing
        scenarioDao.update(scenario);
    } else {
        // Creating new

        scenarioDao.create(scenario);
    }

    log.debug("Returning MAV");
    return mav;
}