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.engine.biomine.BiomineController.java

@ApiOperation(
        // Populates the "summary"
        value = "Index biodata (from local)",
        // Populates the "description"
        notes = "Add a biodata file to the index")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Accepted", response = Boolean.class),
        @ApiResponse(code = 400, message = "Bad Request", response = BiomineError.class),
        @ApiResponse(code = 500, message = "Internal Server Error", response = BiomineError.class),
        @ApiResponse(code = 503, message = "Service Unavailable", response = BiomineError.class) })
@RequestMapping(value = "/indexer/index/biodata/{data}", method = RequestMethod.POST, produces = {
        APPLICATION_JSON_VALUE })//from www .  ja  va  2 s. c  om
@ResponseBody
@ConfigurationProperties()
public ResponseEntity<Boolean> indexData(HttpServletResponse response,
        @ApiParam(value = "File", required = true) @RequestParam(value = "path", required = true) MultipartFile path,
        @ApiParam(value = "Collection", required = true) @RequestParam(value = "collection", required = true) String collection) {
    if (!path.isEmpty()) {
        if (IOUtil.getINSTANCE().isValidExtension(path.getOriginalFilename())) {
            logger.info("Start indexing data from path {}", path.getOriginalFilename());
            try {
                File file = new File(path.getOriginalFilename());
                file.createNewFile();
                deleteFile = false;

                FileOutputStream output = new FileOutputStream(file);
                output.write(path.getBytes());
                output.close();

                indexer.pushData(file, deleteFile, collection);

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else
            logger.info("File extension not valid. Please select a valid file.");
    } else
        logger.info("File does not exist. Please select a valid file.");
    return new ResponseEntity<Boolean>(true, HttpStatus.OK);
}

From source file:com.engine.biomine.BiomineController.java

@ApiOperation(
        // Populates the "summary"
        value = "Index multiple documents (from local)",
        // Populates the "description"
        notes = "Add multiple documents to the index (should be compressed in an archive file)")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Accepted", response = Boolean.class),
        @ApiResponse(code = 400, message = "Bad Request", response = BiomineError.class),
        @ApiResponse(code = 500, message = "Internal Server Error", response = BiomineError.class),
        @ApiResponse(code = 503, message = "Service Unavailable", response = BiomineError.class) })
@RequestMapping(value = "/indexer/index/documents", method = RequestMethod.POST, produces = {
        APPLICATION_JSON_VALUE })/*from  ww  w.j ava 2 s  .  co  m*/
@ResponseBody
public ResponseEntity<Boolean> indexDocuments(
        @ApiParam(value = "File path", required = true) @RequestParam(value = "path", required = true) MultipartFile path,
        @ApiParam(value = "Collection", required = true) @RequestParam(value = "collection", required = true) String collection) {
    if (!path.isEmpty()) {
        if (IOUtil.getINSTANCE().isValidExtension(path.getOriginalFilename())) {
            logger.info("Start indexing data from path {}", path.getOriginalFilename());
            try {
                File file = new File(path.getOriginalFilename());
                file.createNewFile();

                FileOutputStream output = new FileOutputStream(file);
                output.write(path.getBytes());
                output.close();

                indexer.pushData(file, deleteFile, collection);

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else
            logger.info("File extension not valid. Please select a valid file.");
    } else
        logger.info("File does not exist. Please select a valid file.");
    return new ResponseEntity<Boolean>(true, HttpStatus.OK);
}

From source file:ca.intelliware.ihtsdo.mlds.web.rest.ReleasePackagesResource.java

@RequestMapping(value = Routes.RELEASE_PACKAGE_LICENSE, method = RequestMethod.POST, headers = "content-type=multipart/*", produces = "application/json")
@RolesAllowed({ AuthoritiesConstants.STAFF, AuthoritiesConstants.ADMIN })
@Transactional//from   ww w.  ja v a 2s.  com
@Timed
public ResponseEntity<?> updateReleasePackageLicense(@PathVariable long releasePackageId,
        @RequestParam(value = "file", required = false) MultipartFile multipartFile) throws IOException {
    ReleasePackage releasePackage = releasePackageRepository.findOne(releasePackageId);
    if (releasePackage == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    if (multipartFile != null && !multipartFile.isEmpty()) {
        File licenseFile = updateFile(multipartFile, releasePackage.getLicenceFile());
        releasePackage.setLicenceFile(licenseFile);
    }

    releasePackageRepository.save(releasePackage);

    return new ResponseEntity<>(HttpStatus.OK);
}

From source file:com.engine.biomine.BiomineController.java

@ApiOperation(
        // Populates the "summary"
        value = "Index a doc (from local)",
        // Populates the "description"
        notes = "Add a single xml doc to the index")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Accepted", response = Boolean.class),
        @ApiResponse(code = 400, message = "Bad Request", response = BiomineError.class),
        @ApiResponse(code = 500, message = "Internal Server Error", response = BiomineError.class),
        @ApiResponse(code = 503, message = "Service Unavailable", response = BiomineError.class) })
@RequestMapping(value = "/indexer/index/documents/{doc}", method = RequestMethod.POST, produces = {
        APPLICATION_JSON_VALUE })// ww w . j a v a2  s  . c o m
@ResponseBody
@ConfigurationProperties()
public ResponseEntity<Boolean> indexDocument(HttpServletResponse response,
        @ApiParam(value = "File path", required = true) @RequestParam(value = "path", required = true) MultipartFile path,
        @ApiParam(value = "Collection", required = true) @RequestParam(value = "collection", required = true) String collection) {
    if (!path.isEmpty()) {
        if (IOUtil.getINSTANCE().isValidExtension(path.getOriginalFilename())) {
            logger.info("Start indexing data from path {}", path.getOriginalFilename());
            try {
                File file = new File(path.getOriginalFilename());
                file.createNewFile();
                deleteFile = true;

                FileOutputStream output = new FileOutputStream(file);
                output.write(path.getBytes());
                output.close();

                indexer.pushData(file, deleteFile, collection);

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else
            logger.info("File extension not valid. Please select a valid file.");
    } else
        logger.info("File does not exist. Please select a valid file.");
    return new ResponseEntity<Boolean>(true, HttpStatus.OK);
}

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

/**
 * ?//from   w  w w .  j  av a 2s . c  om
 *
 * @param operator
 * @param projectName
 * @param name
 * @param desc
 * @param file
 * @return
 */
@Transactional(value = "TransactionManager")
public Resource modifyResource(User operator, String projectName, String name, String desc,
        MultipartFile file) {
    verifyDesc(desc);

    // 
    if (file != null && file.isEmpty()) {
        logger.error("File does not null but empty: {}", file.getOriginalFilename());
        throw new ParameterException("file");
    }

    Project project = projectMapper.queryByName(projectName);
    if (project == null) {
        logger.error("Project does not exist: {}", projectName);
        throw new NotFoundException("Not found project \"{0}\"", projectName);
    }

    // ? project ??
    if (!projectService.hasWritePerm(operator.getId(), project)) {
        logger.error("User {} has no right permission for the project {}", operator.getName(),
                project.getName());
        throw new PermissionException("User \"{0}\" is not has project \"{1}\" write permission",
                operator.getName(), project.getName());
    }

    Resource resource = resourceMapper.queryResource(project.getId(), name);

    if (resource == null) {
        logger.error("Download file not exist, project {}, resource {}", project.getName(), name);
        throw new NotFoundException("Download file not exist, project {0}, resource {1}", project.getName(),
                name);
    }

    Date now = new Date();

    if (file != null) {
        resource.setOriginFilename(file.getOriginalFilename());
    }

    if (desc != null) {
        resource.setDesc(desc);
    }

    resource.setOwnerId(operator.getId());
    resource.setModifyTime(now);

    int count = resourceMapper.update(resource);

    if (count <= 0) {
        logger.error("Resource {} upload failed", name);
        throw new ServerErrorException("Not resource update count");
    }

    // ??
    if (file != null && !upload(project, name, file)) {
        logger.error("upload resource: {} file: {} failed.", name, file.getOriginalFilename());
        throw new ServerErrorException("upload resource: {} file: {} failed.", name,
                file.getOriginalFilename());
    }

    return resource;
}

From source file:cn.newgxu.lab.info.controller.NoticeController.java

@RequestMapping(value = "/notices/{notice_id}", method = RequestMethod.POST)
public String modify(Notice notice, HttpSession session, RedirectAttributes attributes,
        @PathVariable("notice_id") long nid, @RequestParam("name") String fileName,
        @RequestParam("file") MultipartFile file) {
    AuthorizedUser au = checkLogin(session);
    Notice persistentNotice = noticeService.find(nid);
    Assert.notNull("????", persistentNotice);
    if (!persistentNotice.getUser().equals(au)) {
        throw new SecurityException("???");
    }//from   w  w w . j  a  v  a 2  s .c o m
    if (!file.isEmpty()) {
        fileDelete(persistentNotice);
    }
    persistentNotice.setTitle(notice.getTitle());
    persistentNotice.setContent(notice.getContent());

    fileUpload(notice, fileName, file);
    persistentNotice.setDocName(notice.getDocName());
    persistentNotice.setDocUrl(notice.getDocUrl());

    noticeService.update(persistentNotice);

    attributes.addAttribute("from", -1);
    attributes.addAttribute("status", "ok");
    return "redirect:/" + Config.APP + "/notices/" + nid;
}

From source file:com.sccl.attech.modules.sys.web.LoginController.java

@RequestMapping("upload.htm/{referenceId}/{tableName}/{businessType}/{pathName}/{num}")
@ResponseBody/*  w ww  .  jav  a  2 s  .c o  m*/
public String upload(MultipartFile file, @RequestParam(defaultValue = "other", required = false) String group,
        @PathVariable("referenceId") String referenceId, @PathVariable("tableName") String tableName,
        @PathVariable("businessType") String businessType, @PathVariable("pathName") String pathName,
        @PathVariable("num") String num) {
    String fileName = "";
    if (null == file || file.isEmpty()) {
        System.out.println("");
    } else {
        /*System.out.println(referenceId);
        System.out.println(tableName);
        System.out.println(EncodedUtil.encodeValue(businessType));
        System.out.println(EncodedUtil.encodeValue(pathName));*/

        //String realPath = SpringContextHolder.getRootRealPath() + Global.getCkBaseDir();
        String realPath = Global.getCkBaseDir();

        if ("".equals(pathName) || pathName == null) {
            fileName = group + File.separator + DateUtils.getDate("yyyyMM") + File.separator
                    + DateUtils.getDay() + File.separator + RandomUtils.nextLong() + "."
                    + FilenameUtils.getExtension(file.getOriginalFilename());
        } else {
            fileName = EncodedUtil.encodeValue(pathName) + File.separator + DateUtils.getDate("yyyyMM")
                    + File.separator + DateUtils.getDay() + File.separator + RandomUtils.nextLong() + "."
                    + FilenameUtils.getExtension(file.getOriginalFilename());
        }

        // ??IO?FileUtils.copyInputStreamToFile()IO?????
        try {

            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, fileName));
            fileName = Global.getCkBaseDir() + fileName.replace("\\", "/");

        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }
    return fileName;
}

From source file:org.shaf.server.controller.CmdActionController.java

/**
 * Puts data to the server./*from w  w w  .j  a v  a  2s.c  o m*/
 * 
 * @param storage
 *            the storage type.
 * @param alias
 *            the data alias.
 * @param data
 *            the data to upload.
 * @throws NetworkContentException
 * @throws Exception
 *             if an error occurs.
 */
@RequestMapping(value = "/upload/{storage}/{alias}", method = RequestMethod.POST)
public void onUpload(@PathVariable String storage, @PathVariable String alias, @RequestBody MultipartFile data)
        throws Exception {
    LOG.debug("CALL service: /cmd/upload/{" + storage + "}/{" + alias + "} with attached data.");
    LOG.trace("The attached data: " + data);

    if (data.isEmpty()) {
        LOG.warn("There no providing data.");
    } else {
        Firewall firewall = super.getFirewall();
        String username = super.getUserName();
        StorageDriver driver = OPER.getStorageDriver(firewall, username, StorageType.PROVIDER, storage);

        LOG.trace("Driver for uploading: " + driver);
        LOG.trace("Uploading data name: " + data.getName());
        LOG.trace("Uploading data size: " + data.getSize());

        try (InputStream in = data.getInputStream(); OutputStream out = driver.getOutputStream(alias)) {
            ByteStreams.copy(in, out);
        } catch (IOException exc) {
            throw exc;
        }
    }
}

From source file:controllers.ProcessController.java

@RequestMapping("management/staffs/edit")
public ModelAndView editStaff(@RequestParam("id") String id, @RequestParam("name") String name,
        @RequestParam("gender") String genderString, @RequestParam("birthday") String birthdayString,
        @RequestParam("avatar") MultipartFile avatar, @RequestParam("email") String email,
        @RequestParam("phone") String phone, @RequestParam("salary") String salaryString,
        @RequestParam("note") String notes, @RequestParam("depart") String departId) throws IOException {
    String avatarFileName = "";
    if (!avatar.isEmpty()) {
        String avatarPath = context.getRealPath("/resources/images/" + avatar.getOriginalFilename());
        avatar.transferTo(new File(avatarPath));
        avatarFileName = new File(avatarPath).getName();
    }/* ww  w .  j  av a2  s  .  co m*/
    StaffsDAO staffsDAO = new StaffsDAO();
    staffsDAO.editStaff(id, name, genderString, birthdayString, avatarFileName, email, phone, salaryString,
            notes, departId);
    return new ModelAndView("redirect:../staffs.htm");
}

From source file:org.shareok.data.webserv.JournalDataController.java

@RequestMapping(value = "/dspace/journal/{publisher}/upload", method = RequestMethod.POST)
public ModelAndView journalDataUpload(@RequestParam("file") MultipartFile file,
        @PathVariable("publisher") String publisher) {

    if (!file.isEmpty()) {
        try {/*from  ww w .j  ava 2  s .  co  m*/
            String filePath = DspaceJournalServiceManager.getDspaceJournalDataService(publisher)
                    .getDsapceJournalLoadingFiles(file);
            // Some logic to process the file path to get download links:
            Map downloadLinks = DspaceJournalDataUtil.getDspaceJournalDownloadLinks(filePath);
            String downloadLink = (String) downloadLinks.get("loadingFile");
            String sampleDublinCoreLink = DspaceJournalDataUtil.getJournalSampleDublinCoreLink();
            String uploadFileLink = downloadLink.split("/journal/" + publisher + "/")[1];
            uploadFileLink = uploadFileLink.substring(0, uploadFileLink.length() - 1);
            ModelAndView model = new ModelAndView();
            model = WebUtil.getServerList(model, serverService);
            model.setViewName("journalDataUpload");
            model.addObject("oldFile", (String) downloadLinks.get("oldFile"));
            model.addObject("loadingFile", downloadLink);
            model.addObject("sampleDublinCore", sampleDublinCoreLink);
            model.addObject("publisher", publisher);
            model.addObject("uploadFile", uploadFileLink);
            return model;
        } catch (Exception e) {
            Logger.getLogger(JournalDataController.class.getName()).log(Level.SEVERE, null, e);
        }
    } else {
        return null;
    }
    return null;
}