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:org.pdfgal.pdfgalweb.services.impl.UnProtectServiceImpl.java

@Override
public DownloadForm unProtect(final MultipartFile file, final String password,
        final HttpServletResponse response)
        throws COSVisitorException, IOException, BadSecurityHandlerException, CryptographyException {

    DownloadForm result = new DownloadForm();

    if (!file.isEmpty() && StringUtils.isNotBlank(password)) {
        final String originalName = file.getOriginalFilename();
        final String inputUri = this.fileUtils.saveFile(file);
        final String outputUri = this.fileUtils.getAutogeneratedName(originalName);

        try {//from   www .  j a  va  2  s .  c  o m
            // File is unprotected
            this.pdfGal.unProtect(inputUri, outputUri, password);
        } catch (COSVisitorException | IOException | BadSecurityHandlerException | CryptographyException e) {
            // Temporal files are deleted from system
            this.fileUtils.delete(inputUri);
            this.fileUtils.delete(outputUri);
            throw e;
        }

        // Temporal files are deleted from system
        this.fileUtils.delete(inputUri);

        result = new DownloadForm(outputUri, originalName);
    }

    return result;
}

From source file:net.solarnetwork.node.setup.web.SettingsController.java

@RequestMapping(value = "/import", method = RequestMethod.POST)
public String importSettings(@RequestParam("file") MultipartFile file) throws IOException {
    final SettingsService service = settingsServiceTracker.service();
    if (!file.isEmpty() && service != null) {
        InputStreamReader reader = new InputStreamReader(file.getInputStream(), "UTF-8");
        service.importSettingsCSV(reader);
    }//from   w  ww. j  a v a2s.  co m
    return "redirect:/settings.do";
}

From source file:org.pdfgal.pdfgalweb.services.impl.ProtectServiceImpl.java

@Override
public DownloadForm protect(final MultipartFile file, final String password, final String repeatedPassword,
        final HttpServletResponse response)
        throws COSVisitorException, IOException, BadSecurityHandlerException {

    DownloadForm result = new DownloadForm();

    if (!file.isEmpty() && StringUtils.isNotBlank(password) && StringUtils.isNotBlank(repeatedPassword)
            && password.equals(repeatedPassword)) {

        final String originalName = file.getOriginalFilename();
        final String inputUri = this.fileUtils.saveFile(file);
        final String outputUri = this.fileUtils.getAutogeneratedName(originalName);

        try {/*from   ww  w .ja v  a  2s  .c  o  m*/
            // File is protected
            this.pdfGal.protect(inputUri, outputUri, password);
        } catch (COSVisitorException | IOException | BadSecurityHandlerException e) {
            // Temporal files are deleted from system
            this.fileUtils.delete(inputUri);
            this.fileUtils.delete(outputUri);
            throw e;
        }

        // Temporal files are deleted from system
        this.fileUtils.delete(inputUri);

        result = new DownloadForm(outputUri, originalName);
    }

    return result;
}

From source file:org.pdfgal.pdfgalweb.services.impl.SplitServiceImpl.java

@Override
public DownloadForm split(final MultipartFile file, final SplitMode splitMode, final String pages,
        final HttpServletResponse response) throws Exception {

    DownloadForm result = new DownloadForm();

    if (!file.isEmpty() && splitMode != null && StringUtils.isNotEmpty(pages)) {

        final String originalName = file.getOriginalFilename();
        final String inputUri = this.fileUtils.saveFile(file);
        String outputUri = this.fileUtils.getAutogeneratedName(originalName);
        List<String> outputUris = new ArrayList<String>();

        try {//  www .  ja  va  2 s  .  c o  m

            if (splitMode.equals(SplitMode.NUMBER_OF_PAGES)) {
                outputUris = this.splitNumberOfPages(file, pages, inputUri, outputUri);

            } else if (splitMode.equals(SplitMode.CONCRETE_PAGES_TO_SPLIT)) {
                outputUris = this.splitConcretePages(file, pages, inputUri, outputUri);

            }

            // If everything is OK, created files are put into a ZIP file
            outputUri = this.fileUtils.prepareZipFile(outputUris, originalName);
            // Temporal files are deleted from system (outputUris has
            // already been deleted).
            this.fileUtils.delete(inputUri);

            final String zipName = this.fileUtils.getFileNameWithoutExtension(originalName) + ".zip";
            result = new DownloadForm(outputUri, zipName);

        } catch (final Exception e) {
            // Temporal files are deleted from system (outputUris has
            // already been deleted).
            this.fileUtils.delete(inputUri);
            this.fileUtils.delete(outputUri);
            throw e;
        }
    }

    return result;
}

From source file:controllers.SceneController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file,
        @RequestParam(value = "sceneId", required = true) Long sceneId, RedirectAttributes ras) {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {/*from  ww w  .  ja v a 2 s  . c om*/
        File newFile = new File("/usr/local/etc/sceneParamsList");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            sceneService.updateFromXml(newFile, sceneId);
            ras.addFlashAttribute("error", sceneService.getResult().getErrors());
        } catch (Exception e) {
            ras.addFlashAttribute("error",
                    "updateFromXml" + StringAdapter.getStackTraceException(e)/*e.getMessage()*/);
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    ras.addAttribute("sceneId", sceneId);
    return "redirect:/Scene/show";
}

From source file:org.openmrs.module.feedback.web.AddFeedbackFormController.java

@Override
protected Boolean formBackingObject(HttpServletRequest request) throws Exception {

    /* To check wheather or not the subject , severity and feedback is empty or not */
    Boolean feedbackMessage = false;
    String text = "";
    String subject = request.getParameter("subject");
    String severity = request.getParameter("severity");
    String feedback = request.getParameter("feedback");

    if (StringUtils.hasLength(subject) && StringUtils.hasLength(severity) && StringUtils.hasLength(severity)) {
        Object o = Context.getService(FeedbackService.class);
        FeedbackService service = (FeedbackService) o;
        Feedback s = new Feedback();

        s.setSubject(request.getParameter("subject"));
        s.setSeverity(request.getParameter("severity"));

        /* To get the Stacktrace of the page from which the feedback is submitted */
        StackTraceElement[] c = Thread.currentThread().getStackTrace();

        if ("Yes".equals(request.getParameter("pagecontext"))) {
            for (int i = 0; i < c.length; i++) {
                feedback = feedback + System.getProperty("line.separator") + c[i].getFileName()
                        + c[i].getMethodName() + c[i].getClass() + c[i].getLineNumber();
            }// ww w.j a v a  2s.  com
        }

        s.setContent(feedback);

        /* file upload in multiplerequest */
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = (MultipartFile) multipartRequest.getFile("file");

            if (!file.isEmpty()) {
                if (file.getSize() <= 5242880) {
                    if (file.getOriginalFilename().endsWith(".jpeg")
                            || file.getOriginalFilename().endsWith(".jpg")
                            || file.getOriginalFilename().endsWith(".gif")
                            || file.getOriginalFilename().endsWith(".png")) {
                        s.setMessage(file.getBytes());
                    } else {
                        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                                "feedback.notification.feedback.error");

                        return false;
                    }
                } else {
                    request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "feedback.notification.feedback.error");

                    return false;
                }
            }
        }

        /* Save the Feedback */
        service.saveFeedback(s);
        request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                Context.getAdministrationService().getGlobalProperty("feedback.ui.notification"));

        if ("Yes".equals(Context.getUserContext().getAuthenticatedUser()
                .getUserProperty("feedback_notificationReceipt"))) {
            try {

                // Create Message
                Message message = new Message();

                message.setSender(
                        Context.getAdministrationService().getGlobalProperty("feedback.notification.email"));
                message.setRecipients(
                        Context.getUserContext().getAuthenticatedUser().getUserProperty("feedback_email"));
                message.setSubject("Feedback submission confirmation mail");
                message.setContent(Context.getAdministrationService().getGlobalProperty("feedback.notification")
                        + "Ticket Number: " + s.getFeedbackId() + " Subject :" + s.getSubject());
                message.setSentDate(new Date());

                // Send message
                Context.getMessageService().send(message);
            } catch (Exception e) {
                log.error("Unable to sent the email to the Email : "
                        + Context.getUserContext().getAuthenticatedUser().getUserProperty("feedback_email"));
            }
        }

        try {

            // Create Message
            Message message = new Message();

            message.setSender(
                    Context.getAdministrationService().getGlobalProperty("feedback.notification.email"));
            message.setRecipients(
                    Context.getAdministrationService().getGlobalProperty("feedback.admin.notification.email"));
            message.setSubject("New feedback submitted");
            message.setContent(
                    Context.getAdministrationService().getGlobalProperty("feedback.admin.notification")
                            + "Ticket Number: " + s.getFeedbackId() + " Subject : " + s.getSubject()
                            + " Take Action :" + request.getScheme() + "://" + request.getServerName() + ":"
                            + request.getServerPort() + request.getContextPath()
                            + "/module/feedback/feedback.form?feedbackId=" + s.getFeedbackId() + "#command");
            message.setSentDate(new Date());

            // Send message
            Context.getMessageService().send(message);
        } catch (Exception e) {
            log.error("Unable to sent the email to the Email : " + Context.getUserContext()
                    .getAuthenticatedUser().getUserProperty("feedback.admin.notification.email"));
        }

        feedbackMessage = true;
    }

    /* Reserved for future use for showing that the data is saved and the feedback is submitted */
    log.debug("Returning hello world text: " + text);

    return feedbackMessage;
}

From source file:org.openmrs.module.logmanager.web.controller.ConfigController.java

/**
 * Handles an import configuration request
 * @param request the http request//from  ww w .  j a v a2s .c  o m
 */
private void importConfiguration(HttpServletRequest request) {
    if (request instanceof MultipartHttpServletRequest) {
        // Spring will have detected a multipart request and wrapped it
        MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;
        MultipartFile importFile = mpRequest.getFile("importFile");

        // Check file exists and isn't empty
        if (importFile == null || importFile.isEmpty()) {
            log.error("Uploaded file is empty or invalid");
            return;
        }

        String filename = importFile.getOriginalFilename();

        // Check for xml extension
        if (!filename.toLowerCase().endsWith(".xml")) {
            WebUtils.setErrorMessage(request, Constants.MODULE_ID + ".error.invalidConfigurationFile",
                    new Object[] { filename });
            return;
        }

        // Parse as an XML configuration
        try {
            LogManagerService svc = Context.getService(LogManagerService.class);
            Reader reader = new InputStreamReader(importFile.getInputStream());
            Document document = LogManagerUtils.readDocument(reader, new Log4jEntityResolver());
            reader.close();

            StringWriter str = new StringWriter();
            LogManagerUtils.writeDocument(document, str);

            log.warn(str.toString());

            if (document != null) {
                svc.loadConfiguration(document);

                WebUtils.setInfoMessage(request, Constants.MODULE_ID + ".config.importSuccess",
                        new Object[] { filename });
            } else
                WebUtils.setErrorMessage(request, Constants.MODULE_ID + ".error.invalidConfigurationFile",
                        new Object[] { filename });
        } catch (IOException e) {
            log.error(e);
        }
    }
}

From source file:hu.bme.iit.quiz.service.QuizServiceImpl.java

@Override
public String validateAndCreateQuizForUserFromFile(MultipartFile file, String quizName, String loginName) {
    String originalFileName = file.getOriginalFilename();
    if (!file.isEmpty()) {
        try {// w  w w .java2s .co m
            byte[] bytes = file.getBytes();

            //Only XML files, no mime check, basic check
            if (!file.getOriginalFilename().toLowerCase().endsWith(".xml")) {
                return "You failed to upload " + originalFileName + " because it's not an XML file.";
            }

            // Creating the directory to store file
            String rootPath = System.getProperty("catalina.home");
            File dir = new File(rootPath + File.separator + "tmpFiles");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd-HH-mm-ss");
            Date now = new Date();
            String innerFileLocation = dateFormat.format(now) + "_" + originalFileName;

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + innerFileLocation);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

            //Persist it in db
            Quiz quiz = new Quiz();
            quiz.setName(quizName);
            quiz.setBlobdata(bytes);
            quiz.setLocation(innerFileLocation);
            quiz.setUploaded(new Date());
            quiz.setInnerkey(UUID.randomUUID().toString());
            quiz.setOwner(userDAO.getUser(loginName));

            if (getQuizDataFromXML(quiz) != null) {
                quizDAO.addQuiz(quiz);
            } else {
                return "Invalid XML file!";
            }

            logger.info("XML file uploaded: " + originalFileName);
            return "You successfully uploaded '" + originalFileName + "'";
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            return "You failed to upload " + originalFileName + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + originalFileName + " because the file was empty.";
    }
}

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

private UploadedFile copy(MultipartFile multipartFile) throws IOException {
    UploadedFile uploaded = null;/* w w w  .  j a v a 2 s .  c o  m*/
    if (multipartFile != null && !multipartFile.isEmpty()) {
        String originalFilename = multipartFile.getOriginalFilename();
        File tmp = File.createTempFile(FilenameUtils.getBaseName(originalFilename),
                "." + FilenameUtils.getExtension(originalFilename));
        multipartFile.transferTo(tmp);
        uploaded = new UploadedFile(originalFilename, multipartFile.getContentType(), tmp);
    }

    return uploaded;
}