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:com.teasoft.teavote.controller.BackupController.java

@RequestMapping(value = "/api/teavote/verify-back-up", method = RequestMethod.POST)
@ResponseBody/*from  www  . j a  va  2 s .com*/
public JSONResponse verify(@RequestParam("file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (!file.isEmpty()) {
        byte[] fileBytes = file.getBytes();
        String pathToFileToVerify = new ConfigLocation().getConfigPath() + File.separator + "fileToVerify.sql";
        FileOutputStream fos = new FileOutputStream(pathToFileToVerify);
        fos.write(fileBytes);
        fos.close();

        if (sig.verifyFile(pathToFileToVerify)) {
            //Go ahead and restore database.
            String dbUserName = env.getProperty("teavote.user");
            String dbPassword = utilities.getPassword();
            if (!utilities.restoreDB(dbUserName, dbPassword, pathToFileToVerify)) {
                return new JSONResponse(false, 0, null,
                        Enums.JSONResponseMessage.SERVER_ERROR.toString() + ": Could not restore database");
            }
            //Delete the file
            new File(pathToFileToVerify).delete();
            return new JSONResponse(true, 0, null, Enums.JSONResponseMessage.SUCCESS.toString());
        } else {
            return new JSONResponse(false, 0, null, Enums.JSONResponseMessage.ACCESS_DENIED.toString()
                    + ": Digital Signature could not be verified");
        }
    }
    return new JSONResponse(false, 0, null, "Empty file");
}

From source file:org.jahia.modules.webflow.showcase.JobApplication.java

public void setResume(MultipartFile vita) throws IOException {
    if (vita != null && !vita.isEmpty()) {
        this.resume = copy(vita);
    }/*www . j a va 2 s  .co  m*/
}

From source file:org.openmrs.module.patientsummary.web.controller.PatientSummaryTemplateEditor.java

@RequestMapping(method = RequestMethod.POST)
public String saveTemplate(String templateUuid, String name, Class<? extends ReportRenderer> rendererType,
        String properties, String script, String scriptType, boolean enableOnPatientDashboard,
        HttpServletRequest request, ModelMap model) throws IOException {

    PatientSummaryTemplate template = getService().getPatientSummaryTemplateByUuid(templateUuid);

    PatientSummaryWebConfiguration.saveEnableTemplateOnPatientDashboard(template, enableOnPatientDashboard);

    template.getReportDesign().setName(name);
    template.getReportDesign().setRendererType(rendererType);

    if (!template.getReportDesign().getRendererType().equals(TextTemplateRenderer.class)) {
        MultipartHttpServletRequest mpr = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> files = mpr.getFileMap();

        MultipartFile resource = files.values().iterator().next();

        if (resource != null && !resource.isEmpty()) {
            ReportDesignResource designResource = new ReportDesignResource();
            designResource.setReportDesign(template.getReportDesign());
            designResource.setContents(resource.getBytes());
            designResource.setContentType(resource.getContentType());

            String fileName = resource.getOriginalFilename();
            int index = fileName.lastIndexOf(".");
            designResource.setName(fileName.substring(0, index));
            designResource.setExtension(fileName.substring(index + 1));

            template.getReportDesign().addResource(designResource);
        }//from w w  w. j av a2 s  .  c o  m

        WidgetHandler propHandler = HandlerUtil.getPreferredHandler(WidgetHandler.class, Properties.class);
        Properties props = (Properties) propHandler.parse(properties, Properties.class);
        template.getReportDesign().setProperties(props);
    } else {
        template.getReportDesign().getProperties().clear();
        template.getReportDesign().getResources().clear();

        ReportDesignResource designResource = new ReportDesignResource();
        designResource.setReportDesign(template.getReportDesign());
        designResource.setName("template");
        designResource.setContentType("text/html");
        designResource.setContents(script.getBytes("UTF-8"));

        template.getReportDesign().addResource(designResource);

        template.getReportDesign().addPropertyValue(TextTemplateRenderer.TEMPLATE_TYPE, scriptType);
    }

    getService().savePatientSummaryTemplate(template);

    model.put("templateUuid", template.getUuid());

    return "redirect:" + PatientSummaryWebConstants.MODULE_URL + "editTemplate.form";
}

From source file:eu.domibus.web.controller.AdminGUIController.java

/**
 * Upload single file using Spring Controller
 *//*  ww w  .  java2  s.  co  m*/
@ResponseBody
@RequestMapping(value = "/home/updatepmode", method = RequestMethod.POST)
public String uploadFileHandler(@RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            this.pModeProvider.updatePModes(bytes);
            return "You successfully uploaded the PMode file.";
        } catch (Exception e) {
            AdminGUIController.LOG.error("", e);
            return "You failed to upload the PMode file. => " + e.getMessage();
        }
    } else {
        return "You failed to upload the PMode file. The file was empty.";
    }
}

From source file:com.card.loop.xyz.controller.LearningElementController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ModelAndView upload(@RequestParam("title") String title, @RequestParam("author") String author,
        @RequestParam("subject") String subject, @RequestParam("description") String description,
        @RequestParam("file") MultipartFile file, @RequestParam("type") String type) {
    if (!file.isEmpty()) {
        try {/*from w  w  w.j av a2 s. co  m*/
            byte[] bytes = file.getBytes();
            File fil = new File(AppConfig.USER_VARIABLE + AppConfig.LE_FILE_PATH + file.getOriginalFilename());

            if (!fil.getParentFile().exists()) {
                fil.getParentFile().mkdirs();
            }

            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fil));
            stream.write(bytes);
            stream.close();

            LearningElement le = new LearningElement();
            le.setTitle(title);
            le.setUploadedBy(author);
            le.setDescription(description);
            le.setDownloads(0);
            le.setStatus(1);
            le.setRating(1);
            le.setUploadDate(new Date());
            le.setSubject(subject);
            le.setFilePath(AppConfig.LE_FILE_PATH);
            le.setFilename(file.getOriginalFilename());
            le.setContentType(file.getOriginalFilename().split("\\.")[1]);
            dao.addLearningElement(le);

            System.out.println("UPLOAD LE FINISHED");

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    } else {
        System.err.println("EMPTY FILE.");
    }
    return new ModelAndView("developer-le-loop-redirect");
}

From source file:com.wipro.ats.bdre.md.rest.TDUploaderAPI.java

@RequestMapping(value = "/uploadtr/{processIdValue}", method = RequestMethod.POST)
@ResponseBody//from   w  w  w  .  j a v a  2  s  .  c  om
public RestWrapper uploadInTeradata(@PathVariable("processIdValue") Integer processIdValue,
        @RequestParam("file") MultipartFile file, Principal principal) {

    if (!file.isEmpty()) {
        try {

            String uploadedFilesDirectory = MDConfig.getProperty(UPLOADBASEDIRECTORY);
            String name = file.getOriginalFilename();
            byte[] bytes = file.getBytes();
            String monitorPath = null;
            LOGGER.info("processIDvalue is " + processIdValue);
            com.wipro.ats.bdre.md.dao.jpa.Process process = processDAO.get(processIdValue);
            LOGGER.info("Process fetched = " + process.getProcessId());
            List<Properties> propertiesList = propertiesDAO.getByProcessId(process);
            LOGGER.info("No.of Properties fetched= " + propertiesList.size());
            for (Properties property : propertiesList) {
                LOGGER.debug(
                        "property fetched is " + property.getId().getPropKey() + " " + property.getPropValue());
                if ("monitored-dir-name".equals(property.getId().getPropKey())) {
                    monitorPath = property.getPropValue();
                }
            }
            String uploadLocation = monitorPath;
            LOGGER.info("Upload location: " + uploadLocation);
            File fileDir = new File(uploadLocation);
            fileDir.mkdirs();
            File fileToBeSaved = new File(uploadLocation + "/" + name);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileToBeSaved));
            stream.write(bytes);
            stream.close();
            LOGGER.debug("Uploaded file: " + fileToBeSaved);

            //Populating Uploaded file bean to return in RestWrapper
            UploadedFile uploadedFile = new UploadedFile();
            uploadedFile.setParentProcessId(processIdValue);
            // uploadedFile.setSubDir(subDir);
            uploadedFile.setFileName(name);
            uploadedFile.setFileSize(fileToBeSaved.length());
            LOGGER.debug("The UploadedFile bean:" + uploadedFile);
            LOGGER.info("File uploaded : " + uploadedFile + " uploaded by User:" + principal.getName());

            return new RestWrapper(uploadedFile, RestWrapper.OK);
        } catch (Exception e) {
            LOGGER.error(e);
            return new RestWrapper(e.getMessage(), RestWrapper.ERROR);
        }
    } else {
        return new RestWrapper("You failed to upload because the file was empty.", RestWrapper.ERROR);

    }
}

From source file:org.openxdata.server.servlet.MultimediaServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String formId = request.getParameter("formId");
    String xpath = request.getParameter("xpath");

    CommonsMultipartResolver multipartResover = new CommonsMultipartResolver(/*this.getServletContext()*/);
    if (multipartResover.isMultipart(request)) {
        MultipartHttpServletRequest multipartRequest = multipartResover.resolveMultipart(request);
        MultipartFile uploadedFile = multipartRequest.getFile("filecontents");
        if (uploadedFile != null && !uploadedFile.isEmpty()) {
            byte[] postData = uploadedFile.getBytes();
            response.getOutputStream().print(new String(Base64.encodeBase64(postData)));

            setSessionData(request, formId, KEY_MULTIMEDIA_POST_CONTENT_TYPE + getFieldKey(formId, xpath),
                    uploadedFile.getContentType());
            setSessionData(request, formId, KEY_MULTIMEDIA_POST_DATA + getFieldKey(formId, xpath), postData);
        }//from  ww  w .j  av  a 2 s  .com
    }
}

From source file:service.ArticleService.java

public ServiceResult save(Article obj, MultipartFile file) throws IOException {
    ServiceResult result = new ServiceResult();
    validateSave(obj, dao, result);//from ww w.j a va 2s  . com
    if (result.hasErrors()) {
        if (file != null && !file.isEmpty()) {
            ArticleFile articleFile = new ArticleFile();
            articleFile.setArticle(obj);
            articleFile.setRusname(file.getOriginalFilename());
            saveFile(articleFile, file);
        }
    }
    return result;
}

From source file:cs545.proj.controller.MemberController.java

@RequestMapping(value = "/new", method = RequestMethod.POST)
public String memberUpdateWithLicense(@Valid @ModelAttribute("editMember") Member editMember,
        BindingResult result, HttpSession session) throws IllegalStateException, IOException {
    if (result.hasErrors()) {
        return "editMemberTile";
    }//from w w  w  .ja  v  a 2 s.  c  o m

    MultipartFile licenseFile = editMember.getLicenseMultipart();
    if ((licenseFile != null) && (!licenseFile.isEmpty())) {
        String newFilename = sdf.format(new Date()) + licenseFile.getOriginalFilename();
        String rootDirectory = session.getServletContext().getRealPath("/");
        licenseFile.transferTo(new File(rootDirectory + licensePath + newFilename));
        editMember.setLicenseFileName(newFilename);
    }

    Member savedMember = memberService.saveOrMerge(editMember);
    Set<Category> categorySet = new HashSet<Category>();
    for (Category category : savedMember.getSelectedCategories()) {
        categorySet.add(category);
    }
    for (Category category : categorySet) {
        savedMember.removeCategory(category);
    }
    List<Integer> checkedIDs = editMember.getCheckedCategoryIDs();
    if (checkedIDs != null) {
        for (Integer categoryId : checkedIDs) {
            savedMember.addCategory(categoryService.getCategoryById(categoryId));
        }
    }
    savedMember = memberService.saveOrMerge(savedMember);
    return "redirect:/member/detail";
}

From source file:com.github.carlomicieli.nerdmovies.controllers.MovieController.java

@RequestMapping(value = "/{movie}/update", method = RequestMethod.POST)
public String update(@Valid @ModelAttribute Movie movie, @RequestParam("file") MultipartFile file,
        BindingResult result) throws IOException {
    if (result.hasErrors()) {
        return "movie/edit";
    }/*w w w. ja va  2  s . c  om*/

    if (!file.isEmpty()) {
        movie.setPoster(convert(file));
        movie.setThumb(createThumbnail(file, 100));
    }

    movieService.save(movie);
    return "redirect:../../movies";
}