List of usage examples for org.springframework.web.multipart MultipartFile isEmpty
boolean isEmpty();
From source file:org.fao.geonet.api.registries.vocabularies.KeywordsApi.java
/** * Upload thesaurus.// w w w . java2s .c o m * * @param file the file * @param type the type * @param dir the dir * @param stylesheet the stylesheet * @param request the request * @return the element * @throws Exception the exception */ @ApiOperation(value = "Uploads a new thesaurus from a file", nickname = "uploadThesaurus", notes = "Uploads a new thesaurus.") @RequestMapping(method = RequestMethod.POST, produces = MediaType.TEXT_XML_VALUE) @ApiResponses(value = { @ApiResponse(code = 201, message = "Thesaurus uploaded in SKOS format."), @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_ONLY_REVIEWER) }) @PreAuthorize("hasRole('Reviewer')") @ResponseBody @ResponseStatus(value = HttpStatus.CREATED) public String uploadThesaurus( @ApiParam(value = "If set, do a file upload.") @RequestParam(value = "file", required = false) MultipartFile file, @ApiParam(value = "Local or external (default).") @RequestParam(value = "type", defaultValue = "external") String type, @ApiParam(value = "Type of thesaurus, usually one of the ISO thesaurus type codelist value. Default is theme.") @RequestParam(value = "dir", defaultValue = "theme") String dir, @ApiParam(value = "XSL to be use to convert the thesaurus before load. Default _none_.") @RequestParam(value = "stylesheet", defaultValue = "_none_") String stylesheet, HttpServletRequest request) throws Exception { long start = System.currentTimeMillis(); ServiceContext context = ApiUtils.createServiceContext(request); // Different options for upload boolean fileUpload = file != null && !file.isEmpty(); // Upload RDF file Path rdfFile = null; String fname = null; File tempDir = null; if (fileUpload) { Log.debug(Geonet.THESAURUS, "Uploading thesaurus file: " + file.getOriginalFilename()); tempDir = Files.createTempDirectory("thesaurus").toFile(); Path tempFilePath = tempDir.toPath().resolve(file.getOriginalFilename()); File convFile = tempFilePath.toFile(); file.transferTo(convFile); rdfFile = convFile.toPath(); fname = file.getOriginalFilename(); } else { Log.debug(Geonet.THESAURUS, "No file provided for thesaurus upload."); throw new MissingServletRequestParameterException("Thesaurus source not provided", "file"); } try { if (StringUtils.isEmpty(fname)) { throw new Exception("File upload from URL or file return null"); } long fsize; if (rdfFile != null && Files.exists(rdfFile)) { fsize = Files.size(rdfFile); } else { throw new MissingServletRequestParameterException("Thesaurus file doesn't exist", "file"); } // -- check that the archive actually has something in it if (fsize == 0) { throw new MissingServletRequestParameterException("Thesaurus file has zero size", "file"); } String extension = FilenameUtils.getExtension(fname); if (extension.equalsIgnoreCase("rdf") || extension.equalsIgnoreCase("xml")) { Log.debug(Geonet.THESAURUS, "Uploading thesaurus: " + fname); // Rename .xml to .rdf for all thesaurus fname = fname.replace(extension, "rdf"); uploadThesaurus(rdfFile, stylesheet, context, fname, type, dir); } else { Log.debug(Geonet.THESAURUS, "Incorrect extension for thesaurus named: " + fname); throw new Exception("Incorrect extension for thesaurus named: " + fname); } long end = System.currentTimeMillis(); long duration = (end - start) / 1000; return String.format("Thesaurus '%s' loaded in %d sec.", fname, duration); } finally { if (tempDir != null) { FileUtils.deleteQuietly(tempDir); } } }
From source file:org.geowebcache.sqlite.OperationsRest.java
@RequestMapping(value = "/replace", method = RequestMethod.POST) public @ResponseBody ResponseEntity<String> replace(@RequestParam(value = "layer") String layer, @RequestParam(value = "destination", required = false) String destination, @RequestParam(value = "source", required = false) String source, @RequestParam(value = "file", required = false) MultipartFile uploadedFile) { // we need to close this resources at the end File workingDirectory = null; File file = null;//w w w. j a v a 2s .co m try { // create a temporary working directory (may not be used) workingDirectory = Files.createTempDirectory("replace-operation-").toFile(); // finding the blobstore associated t our layer SqliteBlobStore blobStore = getBlobStoreForLayer(layer); if (blobStore == null) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("No SQLite store could be associated with provided layer."); } // finding the file or the directory that will be used to replace if (uploadedFile != null && !uploadedFile.isEmpty()) { // it was an upload file file = handleFileUpload(uploadedFile, workingDirectory); } else if (source != null) { // the file is already present file = new File(source); } if (file == null || !file.exists()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("Provided file is NULL or doesn't exists."); } // if we have a zip file we need to unzip it file = unzipFileIfNeeded(file, workingDirectory); if (file.isDirectory()) { // we invoke the replace directory variant blobStore.replace(file); } else { if (destination == null) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("Destination is required for single files."); } // we replace the single file blobStore.replace(file, destination); } } catch (Exception exception) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error executing the replace operation.", exception); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(exception.getMessage()); } finally { // cleaning everything FileUtils.deleteQuietly(workingDirectory); } return ResponseEntity.status(HttpStatus.OK).body(null); }
From source file:org.group2.webapp.web.mvc.ctrl.UploadController.java
@PostMapping("/upload") public @ResponseBody String uploadFileHandlerPOST(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) { String actualPath = servletContext.getRealPath(""); String fileLocation = actualPath + File.separator + "evidents"; if (!file.isEmpty()) { try {//from w w w .java 2 s . c o m byte[] bytes = file.getBytes(); File dir = new File(fileLocation); if (!dir.exists()) { dir.mkdirs(); } File serverFile = new File(dir.getAbsolutePath() + File.separator + name); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile)); stream.write(bytes); stream.close(); logger.info("Saved to: " + serverFile.getAbsolutePath()); return "You successfully uploaded file=" + name; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } } else { return "You failed to upload " + name + " because the file was empty."; } }
From source file:org.jgrades.rest.lic.LicenceManagerService.java
private static void checkFilesExisting(MultipartFile licence, MultipartFile signature) { if (licence.isEmpty()) { LOGGER.warn("Licence file is empty"); throw new IllegalArgumentException("Empty licence file"); } else if (signature.isEmpty()) { LOGGER.warn("Signature file is empty"); throw new IllegalArgumentException("Empty signature file"); }//from w w w .j a v a 2 s . c o m }
From source file:org.joget.apps.app.controller.ConsoleWebController.java
@RequestMapping(value = "/console/app/(*:appId)/(~:version)/package/upload/submit", method = RequestMethod.POST) public String consolePackageUploadSubmit(ModelMap map, @RequestParam(value = "appId") String appId, @RequestParam(value = "version", required = false) String version, HttpServletRequest request) { AppDefinition appDef = appService.getAppDefinition(appId, version); map.addAttribute("appId", appId); map.addAttribute("appVersion", appDef.getVersion()); map.addAttribute("appDefinition", appDef); MultipartFile packageXpdl; try {//w w w .j a va 2 s .c o m packageXpdl = FileStore.getFile("packageXpdl"); } catch (FileLimitException e) { map.addAttribute("errorMessage", ResourceBundleUtil.getMessage("general.error.fileSizeTooLarge", new Object[] { FileStore.getFileSizeLimit() })); return "console/apps/packageUpload"; } try { if (packageXpdl == null || packageXpdl.isEmpty()) { throw new RuntimeException("Package XPDL is empty"); } appService.deployWorkflowPackage(appId, version, packageXpdl.getBytes(), false); } catch (Throwable e) { map.addAttribute("errorMessage", e.getMessage()); return "console/apps/packageUpload"; } return "console/apps/xpdlUploadSuccess"; }
From source file:org.kaaproject.kaa.server.admin.controller.KaaAdminController.java
/** * Gets the file content./*from ww w . j a va 2s .c om*/ * * @param file * the file * @return the file content * @throws KaaAdminServiceException * the kaa admin service exception */ private byte[] getFileContent(MultipartFile file) throws KaaAdminServiceException { if (!file.isEmpty()) { LOG.debug("Uploading file with name '{}'", file.getOriginalFilename()); try { return file.getBytes(); } catch (IOException e) { throw Utils.handleException(e); } } else { LOG.error("No file found in post request!"); throw new KaaAdminServiceException("No file found in post request!", ServiceErrorCode.FILE_NOT_FOUND); } }
From source file:org.kuali.mobility.writer.controllers.WriterEditArticleController.java
/** * *///from w w w .j a v a 2s .com @RequestMapping(value = "/maintainArticle") public String maintainArticle(HttpServletRequest request, @ModelAttribute("article") Article articleObj, @RequestParam(value = "uploadVideo", required = false) MultipartFile videoFile, @RequestParam(value = "uploadImage", required = false) MultipartFile imageFile, @RequestParam(value = "pageAction", required = true) int pageAction, @RequestParam(value = "topicId", required = true) long topicId, @RequestParam(value = "articleId", required = false) Long articleId, @RequestParam(value = "removeImage", required = false, defaultValue = "false") boolean removeImage, @RequestParam(value = "removeVideo", required = false, defaultValue = "false") boolean removeVideo, @PathVariable("instance") String instance, Model uiModel) { User user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY); Article article = null; if (articleId != null) { article = this.service.getArticle(articleId); } /* * If an article for the submitted id does not exist we can submit that object. * If an article for the submitted id DOES exist, we need to get the latest copy * from the database, update the object, and persist */ if (article != null) { /* Copy all the fields from the submitted article object to the one * we need to persist */ Article original = this.service.getArticle(articleId); BeanUtils.copyProperties(articleObj, article); article.setId(original.getId()); article.setVideo(original.getVideo()); article.setImage(original.getImage()); article.setVersionNumber(original.getVersionNumber()); } else { article = articleObj; } /* * If no journalist name has been set yet, then this user * is the journalist. */ if (article.getJournalist() == null) { article.setJournalist(user.getDisplayName() == null ? user.getLoginName() : user.getDisplayName()); article.setJournalistId(user.getLoginName()); } /* * if the user is the editor we have to set the editor field. */ if (WriterPermissions.getEditorExpression(instance).evaluate(user)) { article.setEditorId(user.getLoginName()); } else { article.setEditorId(null); } article.setTimestamp(new Date()); article.setToolInstance(instance); int newState = pageAction; /* * If we are rejecting an article, we are first going to save the * article in the current editor's list. The next page will complete * setting the status to rejected, to avoid rejected articles without * a reason when the user cancels the Article Rejection Screen. */ if (pageAction == Article.STATUS_REJECTED) { newState = Article.STATUS_SAVED; } /** * If the article was submitted and saved, we need to preserve that state */ if (newState == Article.STATUS_SAVED && article.getStatus() == Article.STATUS_SUBMITTED_SAVED) { article.setStatus(Article.STATUS_SUBMITTED_SAVED); } else { article.setStatus(newState); } Topic topic = service.getTopic(topicId); article.setTopic(topic); /* Flag if there was a problem saving the media, we do not want the user to loose changes to * the article if something went wrong saving the media */ boolean mediaFailure = false; if (removeImage) { article = service.removeMedia(article, Media.MEDIA_TYPE_IMAGE); } else if (imageFile != null && !imageFile.isEmpty()) { Media image = service.uploadMediaData(imageFile, Media.MEDIA_TYPE_IMAGE); if (image != null) { article = service.updateMedia(article, image); } else { LOG.warn("There was an error saving the new image for the article"); mediaFailure = true; } } if (removeVideo) { article = service.removeMedia(article, Media.MEDIA_TYPE_VIDEO); } else if (videoFile != null && !videoFile.isEmpty()) { Media video = service.uploadMediaData(videoFile, Media.MEDIA_TYPE_VIDEO); article = service.updateMedia(article, video); } article = service.maintainArticle(article); // After persisting the content of the article, we inform the user of the media problem if (mediaFailure) { uiModel.addAttribute("backURL", "/writer/" + instance + "/editArticle/" + article.getId()); uiModel.addAttribute("errorMessage", "writer.errorUploadingMedia"); uiModel.addAttribute("errorTitle", "writer.somethingWentWrong"); return "error"; } /* * Send notification for new article */ if (pageAction == Article.STATUS_PUBLISHED) { publishService.publishArticle(article, user); // Async } if (pageAction == Article.STATUS_SAVED) {// save action return "redirect:/writer/" + instance + "/savedArticles"; } else if (pageAction == Article.STATUS_PUBLISHED) {// publish action return "redirect:/writer/" + instance + "/viewArticle?articleId=" + article.getId(); } else if (pageAction == Article.STATUS_REJECTED) {// publish action return "redirect:/writer/" + instance + "/rejectArticle?articleId=" + article.getId(); } return "redirect:/writer/" + instance + "/admin"; }
From source file:org.kuali.mobility.writer.service.WriterServiceImpl.java
public Media uploadMediaData(MultipartFile mediaFile, int mediaType) { // TODO this whole media saving code should be moved to a media store project! Media returnMedia = null;/*from w w w . j a v a 2s . co m*/ if (mediaFile != null && !mediaFile.isEmpty()) { try { String mediaExt = null; // Get the file extension from the original filename if (mediaFile.getOriginalFilename() != null) { String oName = mediaFile.getOriginalFilename(); int index = oName.lastIndexOf('.'); if (index > 0) { mediaExt = oName.substring(index + 1); } } // If the extension is still empty, we fallback to .dat if (mediaExt == null || mediaExt.length() == 0) { mediaExt = ".dat"; } InputStream originalMediaStream = mediaFile.getInputStream(); Media uploadedMedia = new Media(); uploadedMedia.setType(mediaType); IOUtils.closeQuietly(originalMediaStream); /*/ * Attempt to get the mime type of the media */ if (mediaFile.getContentType() == null || mediaFile.getContentType().length() == 0) { if (mediaType == Media.MEDIA_TYPE_VIDEO) { uploadedMedia.setMimeType("video/3gp"); // Fallback format TODO get proper mapping } } else { uploadedMedia.setMimeType(mediaFile.getContentType()); } if (mediaType == Media.MEDIA_TYPE_VIDEO) { String originalPath = this.storeMedia(mediaType, mediaExt, false, originalMediaStream); uploadedMedia.setPath(originalPath); uploadedMedia.setThumbNailPath(""); // No thumbnail for video for now } else if (mediaType == Media.MEDIA_TYPE_IMAGE) { uploadedMedia.setMimeType("image/jpeg"); // We allways save images a jpeg InputStream scaledImageStream = null; String newFilePath = null; BufferedImage originalImage = ImageIO.read(mediaFile.getInputStream()); if (originalImage == null) { LOG.error("Failed to read uploaded image - posibly incorrect file type"); return null; } // If we are saving an image, we need to resize the original to the max configured size, and also convert to jpeg if (originalImage.getWidth() > MAX_IMAGE_WIDTH || originalImage.getHeight() > MAX_IMAGE_HEIGHT) { scaledImageStream = this.resizeImage(mediaFile.getInputStream(), MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT); } // Image is small enough, just convert to jpeg else { scaledImageStream = this.convertToJPEG(mediaFile.getInputStream()); } if (scaledImageStream == null) { LOG.error("Failed to scale uploaded image - posibly incorrect file type"); return null; } newFilePath = this.storeMedia(Media.MEDIA_TYPE_IMAGE, ".jpeg", false, scaledImageStream); uploadedMedia.setPath(newFilePath); IOUtils.closeQuietly(scaledImageStream); // Create a thumbnail of the image scaledImageStream = this.resizeImage(mediaFile.getInputStream(), MAX_IMAGE_THUMB_WIDTH, MAX_IMAGE_THUMB_HEIGHT); if (scaledImageStream == null) { LOG.error("Failed to scale thumbnail of uploaded image - posibly incorrect file type"); return null; } newFilePath = this.storeMedia(Media.MEDIA_TYPE_IMAGE, ".jpeg", true, scaledImageStream); uploadedMedia.setThumbNailPath(newFilePath); IOUtils.closeQuietly(scaledImageStream); } returnMedia = this.maintainMedia(uploadedMedia); } catch (IOException e) { LOG.error("Exception trying to upload media data", e); } } return returnMedia; }
From source file:org.openlmis.fulfillment.service.TemplateService.java
private void throwIfFileIsEmpty(MultipartFile file) { if (file.isEmpty()) { throw new ReportingException(ERROR_REPORTING_FILE_EMPTY); }/*w ww . j a v a 2 s .c om*/ }
From source file:org.openlmis.reporting.service.TemplateService.java
private void throwIfFileIsEmpty(MultipartFile file) { if (file.isEmpty()) throw new DataException("report.template.error.file.empty"); }