Example usage for org.springframework.web.multipart.commons CommonsMultipartFile getSize

List of usage examples for org.springframework.web.multipart.commons CommonsMultipartFile getSize

Introduction

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

Prototype

@Override
    public long getSize() 

Source Link

Usage

From source file:org.asqatasun.webapp.validator.AddScenarioFormValidator.java

/**
 * //from   w w w  .j  a v a  2 s  . c  o m
 * @param addScenarioCommand
 * @param errors 
 * @return  whether the scenario handled by the current AddScenarioCommand
 * has a correct type and size
 */
public boolean checkScenarioFileTypeAndSize(AddScenarioCommand addScenarioCommand, Errors errors) {
    if (addScenarioCommand.getScenarioFile() == null) { // if no file uploaded
        LOGGER.debug("empty Scenario File");
        errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY);
        errors.rejectValue(SCENARIO_FILE_KEY, NO_SCENARIO_UPLOADED_MSG_BUNDLE_KEY);
        return false;
    }
    Metadata metadata = new Metadata();
    MimeTypes mimeTypes = TikaConfig.getDefaultConfig().getMimeRepository();
    String mime;
    try {
        CommonsMultipartFile cmf = addScenarioCommand.getScenarioFile();
        if (cmf.getSize() > maxFileSize) {
            Long maxFileSizeInMega = maxFileSize / 1000000;
            String[] arg = { maxFileSizeInMega.toString() };
            errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY);
            errors.rejectValue(SCENARIO_FILE_KEY, FILE_SIZE_EXCEEDED_MSG_BUNDLE_KEY, arg, "{0}");
            return false;
        } else if (cmf.getSize() > 0) {
            mime = mimeTypes.detect(new BufferedInputStream(cmf.getInputStream()), metadata).toString();
            LOGGER.debug("mime  " + mime + "  " + cmf.getOriginalFilename());
            if (!authorizedMimeType.contains(mime)) {
                errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY);
                errors.rejectValue(SCENARIO_FILE_KEY, NOT_SCENARIO_MSG_BUNDLE_KEY);
                return false;
            }
        } else {
            LOGGER.debug("File with size null");
            errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY);
            errors.rejectValue(SCENARIO_FILE_KEY, NO_SCENARIO_UPLOADED_MSG_BUNDLE_KEY);
            return false;
        }
    } catch (IOException ex) {
        LOGGER.warn(ex);
        errors.rejectValue(SCENARIO_FILE_KEY, NOT_SCENARIO_MSG_BUNDLE_KEY);
        errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY);
        return false;
    }
    return true;
}

From source file:org.bibsonomy.webapp.controller.actions.JabRefImportController.java

/**
 * Writes the file of the specified layout part to disk and into the 
 * database.//from  w  w w . j  a v a2s .  c  o  m
 * 
 * @param loginUser
 * @param fileItem
 * @param layoutPart
 */
private void writeLayoutPart(final User loginUser, final CommonsMultipartFile fileItem,
        final LayoutPart layoutPart) {
    if (fileItem != null && fileItem.getSize() > 0) {
        log.debug("writing layout part " + layoutPart + " with file " + fileItem.getOriginalFilename());
        try {
            final String hashedName = JabrefLayoutUtils.userLayoutHash(loginUser.getName(), layoutPart);

            final FileUploadInterface uploadFileHandler = this.uploadFactory.getFileUploadHandler(
                    Collections.singletonList(fileItem.getFileItem()), FileUploadInterface.fileLayoutExt);
            /*
             * write file to disk
             */
            final Document uploadedFile = uploadFileHandler.writeUploadedFile(hashedName, loginUser);
            /*
             * store row in database
             */
            this.logic.createDocument(uploadedFile, null);
        } catch (Exception ex) {
            log.error("Could not add custom " + layoutPart + " layout." + ex.getMessage());
            throw new RuntimeException("Could not add custom " + layoutPart + " layout: " + ex.getMessage());
        }
    }
}

From source file:org.medici.bia.validator.peoplebase.ShowUploadPortraitPersonValidator.java

/**
 * /*from   ww w. j ava2s. c o m*/
 * @param browse
 * @param errors
 */
private void validateImageToLoad(CommonsMultipartFile browse, Errors errors) {
    if (browse != null && browse.getSize() > 0) {
        if (!browse.getContentType().equals("image/jpeg") && !browse.getContentType().equals("image/png")) {
            errors.rejectValue("browse", "error.browse.invalidImage");
        }
        // MD: Verify if the upload file is too big
        if (browse.getSize() > 15000000) {
            errors.rejectValue("browse", "error.browse.fileDimension");
        }
    }

}

From source file:org.medici.bia.validator.user.ShowUploadPortraitUserValidator.java

/**
 * //from  ww  w .j  a v a 2s .c  om
 * @param browse
 * @param errors
 */
private void validateImageToLoad(CommonsMultipartFile browse, Errors errors) {
    if (browse != null && browse.getSize() > 0) {
        if (!browse.getContentType().equals("image/jpeg") && !browse.getContentType().equals("image/png")) {
            errors.reject("browse", "error.browse.invalidImage");
        }
        // MD: Verify if the upload file is too big
        if (browse.getSize() > 15000000) {
            errors.reject("browse", "error.browse.fileDimension");
        }
    }

}

From source file:org.springframework.web.multipart.commons.CommonsFileUploadSupport.java

/**
 * Parse the given List of Commons FileItems into a Spring MultipartParsingResult,
 * containing Spring MultipartFile instances and a Map of multipart parameter.
 * @param fileItems the Commons FileIterms to parse
 * @param encoding the encoding to use for form fields
 * @return the Spring MultipartParsingResult
 * @see CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem)
 *///  w  ww.j a va 2  s  .  co  m
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<>();
    Map<String, String[]> multipartParameters = new HashMap<>();
    Map<String, String> multipartParameterContentTypes = new HashMap<>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
        if (fileItem.isFormField()) {
            String value;
            String partEncoding = determineEncoding(fileItem.getContentType(), encoding);
            try {
                value = fileItem.getString(partEncoding);
            } catch (UnsupportedEncodingException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                            + "' with encoding '" + partEncoding + "': using platform default");
                }
                value = fileItem.getString();
            }
            String[] curParam = multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
            multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType());
        } else {
            // multipart file field
            CommonsMultipartFile file = createMultipartFile(fileItem);
            multipartFiles.add(file.getName(), file);
            if (logger.isDebugEnabled()) {
                logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                        + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                        + file.getStorageDescription());
            }
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes);
}

From source file:org.springframework.web.multipart.commons.CommonsMultipartResolverTests.java

private void doTestFiles(MultipartHttpServletRequest request) throws IOException {
    Set<String> fileNames = new HashSet<>();
    Iterator<String> fileIter = request.getFileNames();
    while (fileIter.hasNext()) {
        fileNames.add(fileIter.next());//ww w  .  j  a  va2 s .  c  o  m
    }
    assertEquals(3, fileNames.size());
    assertTrue(fileNames.contains("field1"));
    assertTrue(fileNames.contains("field2"));
    assertTrue(fileNames.contains("field2x"));
    CommonsMultipartFile file1 = (CommonsMultipartFile) request.getFile("field1");
    CommonsMultipartFile file2 = (CommonsMultipartFile) request.getFile("field2");
    CommonsMultipartFile file2x = (CommonsMultipartFile) request.getFile("field2x");

    Map<String, MultipartFile> fileMap = request.getFileMap();
    assertEquals(3, fileMap.size());
    assertTrue(fileMap.containsKey("field1"));
    assertTrue(fileMap.containsKey("field2"));
    assertTrue(fileMap.containsKey("field2x"));
    assertEquals(file1, fileMap.get("field1"));
    assertEquals(file2, fileMap.get("field2"));
    assertEquals(file2x, fileMap.get("field2x"));

    MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
    assertEquals(3, multiFileMap.size());
    assertTrue(multiFileMap.containsKey("field1"));
    assertTrue(multiFileMap.containsKey("field2"));
    assertTrue(multiFileMap.containsKey("field2x"));
    List<MultipartFile> field1Files = multiFileMap.get("field1");
    assertEquals(2, field1Files.size());
    assertTrue(field1Files.contains(file1));
    assertEquals(file1, multiFileMap.getFirst("field1"));
    assertEquals(file2, multiFileMap.getFirst("field2"));
    assertEquals(file2x, multiFileMap.getFirst("field2x"));

    assertEquals("type1", file1.getContentType());
    assertEquals("type2", file2.getContentType());
    assertEquals("type2", file2x.getContentType());
    assertEquals("field1.txt", file1.getOriginalFilename());
    assertEquals("field2.txt", file2.getOriginalFilename());
    assertEquals("field2x.txt", file2x.getOriginalFilename());
    assertEquals("text1", new String(file1.getBytes()));
    assertEquals("text2", new String(file2.getBytes()));
    assertEquals(5, file1.getSize());
    assertEquals(5, file2.getSize());
    assertTrue(file1.getInputStream() instanceof ByteArrayInputStream);
    assertTrue(file2.getInputStream() instanceof ByteArrayInputStream);
    File transfer1 = new File("C:/transfer1");
    file1.transferTo(transfer1);
    File transfer2 = new File("C:/transfer2");
    file2.transferTo(transfer2);
    assertEquals(transfer1, ((MockFileItem) file1.getFileItem()).writtenFile);
    assertEquals(transfer2, ((MockFileItem) file2.getFileItem()).writtenFile);

}

From source file:org.webcurator.ui.tools.controller.TreeToolController.java

@SuppressWarnings("unchecked")
@Override/*from w  ww .ja v a2 s .com*/
protected ModelAndView handle(HttpServletRequest req, HttpServletResponse res, Object comm,
        BindException errors) throws Exception {

    TreeToolCommand command = (TreeToolCommand) comm;
    TargetInstance ti = (TargetInstance) req.getSession().getAttribute("sessionTargetInstance");

    // If the tree is not loaded then load the tree into session
    // data and then load any AQA 'importable items' into session data.
    if (command.getLoadTree() != null) {

        // load the tree..
        log.info("Generating Tree");
        HarvestResourceNodeTreeBuilder treeBuilder = qualityReviewFacade
                .getHarvestResultTree(command.getLoadTree());
        WCTNodeTree tree = treeBuilder.getTree();
        req.getSession().setAttribute("tree", tree);
        command.setHrOid(command.getLoadTree());
        log.info("Tree complete");

        if (autoQAUrl != null && autoQAUrl.length() > 0) {

            List<AQAElement> candidateElements = new ArrayList<AQAElement>();

            // load AQA 'importable items' (if any)..
            File xmlFile;
            try {
                xmlFile = harvestLogManager.getLogfile(ti, command.getLogFileName());
            } catch (Exception e) {
                xmlFile = null;
                log.info("Missing AQA report file: " + command.getLogFileName());
            }

            if (xmlFile != null) {

                Document aqaResult = readXMLDocument(xmlFile);
                NodeList parentElementsNode = aqaResult.getElementsByTagName("missingElements");
                if (parentElementsNode.getLength() > 0) {
                    NodeList elementNodes = ((Element) parentElementsNode.item(0))
                            .getElementsByTagName("element");
                    for (int i = 0; i < elementNodes.getLength(); i++) {
                        Element element = (Element) elementNodes.item(i);
                        if (element.getAttribute("statuscode").equals("200")) {
                            candidateElements.add(new AQAElement(element.getAttribute("url"),
                                    element.getAttribute("contentfile"), element.getAttribute("contentType"),
                                    Long.parseLong(element.getAttribute("contentLength"))));
                        }
                    }
                }
                req.getSession().setAttribute("aqaImports", candidateElements);
            }
        }
    }

    // Load the tree items from the session.
    WCTNodeTree tree = (WCTNodeTree) req.getSession().getAttribute("tree");
    List<AQAElement> imports = (List<AQAElement>) req.getSession().getAttribute("aqaImports");

    // Go back to the page if there were validation errors.
    if (errors.hasErrors()) {
        ModelAndView mav = new ModelAndView(getSuccessView());
        mav.addObject("tree", tree);
        mav.addObject("command", command);
        mav.addObject("aqaImports", imports);
        mav.addObject(Constants.GBL_ERRORS, errors);
        if (autoQAUrl != null && autoQAUrl.length() > 0) {
            mav.addObject("showAQAOption", 1);
        } else {
            mav.addObject("showAQAOption", 0);
        }

        return mav;
    }

    // Handle any tree actions.
    else if (command.isAction(TreeToolCommand.ACTION_TREE_ACTION)) {

        // If we are toggling things open/closed..
        if (command.getToggleId() != null) {
            tree.toggle(command.getToggleId());
        }

        // if we're pruning..
        if (command.getMarkForDelete() != null) {
            tree.markForDelete(command.getMarkForDelete(), command.getPropagateDelete());
        }

        // if we're importing single items..
        if (command.getTargetURL() != null) {

            HarvestResourceNodeTreeBuilder tb = new HarvestResourceNodeTreeBuilder();
            try {
                URL parentUrl = tb.getParent(new URL(command.getTargetURL()));
            } catch (MalformedURLException me) {
                errors.reject("tools.errors.invalidtargeturl");
                ModelAndView mav = new ModelAndView(getSuccessView());
                mav.addObject("tree", tree);
                mav.addObject("command", command);
                mav.addObject("aqaImports", imports);
                mav.addObject(Constants.GBL_ERRORS, errors);
                if (autoQAUrl != null && autoQAUrl.length() > 0) {
                    mav.addObject("showAQAOption", 1);
                } else {
                    mav.addObject("showAQAOption", 0);
                }
                return mav;
            }

            if (command.getImportType().equals(TreeToolCommand.IMPORT_FILE)) {

                // We're importing a file from the user's file system, uploaded
                // via their browser. We need to store the file so it can be added
                // to the archive when the SAVE command is eventually issued.
                // We also need to add a node to the tree-view in such a way that the
                // user can distinguish imported files from pruned files and 
                // original files.

                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
                CommonsMultipartFile uploadedFile = (CommonsMultipartFile) multipartRequest
                        .getFile("sourceFile");

                // save uploaded file as tempFileName in configured uploadedFilesDir
                String tempFileName = UUID.randomUUID().toString();

                File xfrFile = new File(uploadedFilesDir + tempFileName);

                StringBuffer buf = new StringBuffer();
                buf.append("HTTP/1.1 200 OK\n");
                buf.append("Content-Type: ");
                buf.append(uploadedFile.getContentType() + "\n");
                buf.append("Content-Length: ");
                buf.append(uploadedFile.getSize() + "\n");
                buf.append("Connection: close\n\n");

                FileOutputStream fos = new FileOutputStream(xfrFile);
                fos.write(buf.toString().getBytes());
                fos.write(uploadedFile.getBytes());

                fos.close();

                tree.insert(command.getTargetURL(), xfrFile.length(), tempFileName,
                        uploadedFile.getContentType());
            }
            if (command.getImportType().equals(TreeToolCommand.IMPORT_URL)) {

                // We're importing a file via a URL that the user has specified, we
                // need to use the URL to do a HTTP GET and store the resultant
                // down-loaded file so it can be added to the archive when the 
                // SAVE command is eventually issued.
                // We also need to add a node to the tree-view in such a way that the
                // user can distinguish imported files from pruned files and 
                // original files.

                // save uploaded file as tempFileName in configured uploadedFilesDir
                String tempFileName = UUID.randomUUID().toString();

                File xfrFile = new File(uploadedFilesDir + tempFileName);
                FileOutputStream fos = new FileOutputStream(xfrFile);

                //String contentType = null;
                String outStrings[] = new String[1];

                try {
                    fos.write(fetchHTTPResponse(command.getSourceURL(), outStrings));
                } catch (HTTPGetException ge) {
                    errors.reject("tools.errors.httpgeterror",
                            new Object[] { command.getSourceURL(), ge.getMessage() }, "");
                    ModelAndView mav = new ModelAndView(getSuccessView());
                    mav.addObject("tree", tree);
                    mav.addObject("aqaImports", imports);
                    mav.addObject("command", command);
                    mav.addObject(Constants.GBL_ERRORS, errors);
                    if (autoQAUrl != null && autoQAUrl.length() > 0) {
                        mav.addObject("showAQAOption", 1);
                    } else {
                        mav.addObject("showAQAOption", 0);
                    }
                    return mav;
                } finally {
                    fos.close();
                }

                tree.insert(command.getTargetURL(), xfrFile.length(), tempFileName, outStrings[0]);
            }
        }

        ModelAndView mav = new ModelAndView(getSuccessView());
        mav.addObject("tree", tree);
        mav.addObject("aqaImports", imports);
        mav.addObject("command", command);
        if (autoQAUrl != null && autoQAUrl.length() > 0) {
            mav.addObject("showAQAOption", 1);
        } else {
            mav.addObject("showAQAOption", 0);
        }
        return mav;
    }

    // Handle browse action.
    else if (command.isAction(TreeToolCommand.ACTION_VIEW)) {
        HarvestResource resource = tree.getNodeCache().get(command.getSelectedRow()).getSubject();
        Long resultOid = resource.getResult().getOid();
        String url = resource.getName();

        if (enableAccessTool && harvestResourceUrlMapper != null) {
            return new ModelAndView("redirect:"
                    + harvestResourceUrlMapper.generateUrl(resource.getResult(), resource.buildDTO()));
        } else {
            return new ModelAndView("redirect:/curator/tools/browse/" + resultOid + "/" + url);
        }

    }

    // Handle show hop path action.
    else if (command.isAction(TreeToolCommand.ACTION_SHOW_HOP_PATH)) {

        TargetInstance tinst = (TargetInstance) req.getSession().getAttribute("sessionTargetInstance");
        Long instanceOid = tinst.getOid();
        String url = command.getSelectedUrl();

        return new ModelAndView("redirect:/curator/target/show-hop-path.html?targetInstanceOid=" + instanceOid
                + "&logFileName=sortedcrawl.log&url=" + url);
    }

    // handle import of one or more AQA items..
    else if (command.isAction(TreeToolCommand.IMPORT_AQA_FILE)) {

        // iterate over the selected (checked) items..
        if (command.getAqaImports() != null) {

            List<AQAElement> removeElements = new ArrayList<AQAElement>();

            String[] aqaImportUrls = command.getAqaImports();
            for (int i = 0; i < aqaImportUrls.length; i++) {

                String aqaUrl = aqaImportUrls[i];

                for (Iterator iter = imports.iterator(); iter.hasNext();) {
                    AQAElement elem = (AQAElement) iter.next();
                    if (elem.getUrl().equals(aqaUrl)) {

                        // We're importing a missing file, captured by the AQA process.
                        // We need to store the file with HTTP header info so it can be added
                        // to the archive when the SAVE command is eventually issued.
                        // We also need to add a node to the tree-view in such a way that the
                        // user can distinguish imported files from pruned files and 
                        // original files.

                        File aqaFile = null;
                        try {
                            aqaFile = harvestLogManager.getLogfile(ti, elem.getContentFile());

                            // save imported file using a random tempFileName in configured uploadedFilesDir
                            String tempFileName = UUID.randomUUID().toString();

                            File xfrFile = new File(uploadedFilesDir + tempFileName);

                            StringBuffer buf = new StringBuffer();
                            buf.append("HTTP/1.1 200 OK\n");
                            buf.append("Content-Type: ");
                            buf.append(elem.getContentType() + "\n");
                            buf.append("Content-Length: ");
                            buf.append(elem.getContentLength() + "\n");
                            buf.append("Connection: close\n\n");

                            FileOutputStream fos = new FileOutputStream(xfrFile);
                            fos.write(buf.toString().getBytes());

                            FileInputStream fin = new FileInputStream(aqaFile);
                            byte[] bytes = new byte[8192];
                            int len = 0;
                            while ((len = fin.read(bytes)) >= 0) {
                                fos.write(bytes, 0, len);
                            }

                            fos.close();
                            fin.close();

                            tree.insert(aqaUrl, xfrFile.length(), tempFileName, elem.getContentType());
                            removeElements.add(elem);
                        } catch (Exception e) {
                            log.info("Missing AQA import file: " + elem.getContentFile());
                        }
                    }
                }
            }
            ; //end for
            for (Iterator remit = removeElements.iterator(); remit.hasNext();) {
                AQAElement rem = (AQAElement) remit.next();
                imports.remove(rem);
            }
        }
        ;

        ModelAndView mav = new ModelAndView(getSuccessView());
        mav.addObject("tree", tree);
        mav.addObject("aqaImports", imports);
        mav.addObject("command", command);
        if (autoQAUrl != null && autoQAUrl.length() > 0) {
            mav.addObject("showAQAOption", 1);
        } else {
            mav.addObject("showAQAOption", 0);
        }
        return mav;

    }

    // Handle the save action.
    else if (command.isAction(TreeToolCommand.ACTION_SAVE)) {
        List<String> uris = new LinkedList<String>();
        for (WCTNode node : tree.getPrunedNodes()) {
            if (node.getSubject() != null) {
                uris.add(node.getSubject().getName());
            }
        }
        List<HarvestResourceDTO> hrs = new LinkedList<HarvestResourceDTO>();
        for (HarvestResourceDTO dto : tree.getImportedNodes()) {
            hrs.add(dto);
        }

        HarvestResult result = qualityReviewFacade.copyAndPrune(command.getHrOid(), uris, hrs,
                command.getProvenanceNote(), tree.getModificationNotes());

        // Make sure that the tree is removed from memory.         
        removeTree(req);
        removeAQAImports(req);

        return new ModelAndView("redirect:/" + Constants.CNTRL_TI + "?targetInstanceId="
                + result.getTargetInstance().getOid() + "&cmd=edit&init_tab=RESULTS");
    }

    else if (command.isAction(TreeToolCommand.ACTION_CANCEL)) {

        // Make sure that objects removed from memory.
        removeTree(req);
        removeAQAImports(req);

        TargetInstance tinst = (TargetInstance) req.getSession().getAttribute("sessionTargetInstance");

        return new ModelAndView("redirect:/curator/target/quality-review-toc.html?targetInstanceOid="
                + tinst.getOid() + "&harvestResultId=" + command.getHrOid());

    }

    // Handle an unknown action?
    else {
        ModelAndView mav = new ModelAndView(getSuccessView());
        mav.addObject("tree", tree);
        mav.addObject("command", command);
        mav.addObject("aqaImports", imports);
        mav.addObject(Constants.GBL_ERRORS, errors);
        if (autoQAUrl != null && autoQAUrl.length() > 0) {
            mav.addObject("showAQAOption", 1);
        } else {
            mav.addObject("showAQAOption", 0);
        }
        return mav;
    }
}