List of usage examples for org.springframework.web.multipart MultipartFile getOriginalFilename
@Nullable String getOriginalFilename();
From source file:fr.treeptik.cloudunit.manager.impl.ApplicationManagerImpl.java
/** * Deployment for an archive/*w w w.j a v a2 s.c om*/ * * @param fileUpload * @param application */ public void deploy(MultipartFile fileUpload, Application application) throws ServiceException, CheckException { try { logger.debug(application.toString()); // Deployment processus with verification for format file if (FilesUtils.isAuthorizedFileForDeployment(fileUpload.getOriginalFilename())) { File file = File.createTempFile("deployment-", FilesUtils.setSuffix(fileUpload.getOriginalFilename())); fileUpload.transferTo(file); if (application.getStatus().equals(Status.STOP)) { throw new CheckException(messageSource.getMessage("app.stop", null, Locale.ENGLISH)); } // Application busy applicationService.setStatus(application, Status.PENDING); // Deployment applicationService.deploy(file, application); // application is started applicationService.setStatus(application, Status.START); } else { throw new CheckException(messageSource.getMessage("check.war.ear", null, Locale.ENGLISH)); } } catch (IOException e) { applicationService.setStatus(application, Status.FAIL); throw new ServiceException(e.getMessage()); } }
From source file:org.openmrs.module.logmanager.web.controller.ConfigController.java
/** * Handles an import configuration request * @param request the http request//from w w w . j ava 2 s. 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:cherry.foundation.async.AsyncFileProcessHandlerImplTest.java
@Test public void testLaunchFileProcess_exception() throws Exception { AsyncFileProcessHandlerImpl impl = createImpl(); LocalDateTime now = LocalDateTime.now(); when(bizDateTime.now()).thenReturn(now); when(asyncProcessStore.createFileProcess("a", now, "b", "c", "d", "e", 100L, "f")).thenReturn(10L); IOException exception = new IOException(); InputStream in = mock(InputStream.class); when(in.read((byte[]) any())).thenThrow(exception); MultipartFile file = mock(MultipartFile.class); when(file.getName()).thenReturn("c"); when(file.getOriginalFilename()).thenReturn("d"); when(file.getContentType()).thenReturn("e"); when(file.getSize()).thenReturn(100L); when(file.getInputStream()).thenReturn(in); try {/* w w w.jav a2 s . co m*/ impl.launchFileProcess("a", "b", file, "f"); fail("Exception must be thrown"); } catch (IllegalStateException ex) { verify(asyncProcessStore).createFileProcess("a", now, "b", "c", "d", "e", 100L, "f"); verify(asyncProcessStore).finishWithException(10L, now, exception); } }
From source file:de.topicmapslab.majortom.server.topicmaps.TopicMapsHandler.java
/** * {@inheritDoc}// w w w.j a v a 2s . c om */ @Override public void loadFromFileUpload(String id, final MultipartFile file) { logger.info("Start Loading file: " + file.getOriginalFilename()); final TopicMap topicMap = (TopicMap) topicMapMap.get(id); if (topicMap == null) return; if (file.getOriginalFilename().length() == 0) return; if (((ITopicMap) topicMap).getStore() instanceof InMemoryTopicMapStore) { InMemoryTopicMapStore store = (InMemoryTopicMapStore) ((ITopicMap) topicMap).getStore(); try { if (file.getOriginalFilename().toLowerCase().endsWith("xtm")) { Importer.importStream(store, file.getInputStream(), topicMap.getLocator().toExternalForm(), Format.XTM); } else if (file.getOriginalFilename().toLowerCase().endsWith("ctm")) { Importer.importStream(store, file.getInputStream(), topicMap.getLocator().toExternalForm(), Format.CTM); } else { throw new IllegalArgumentException("Only XTM or CTM files allowed."); } logger.info("Finished Loading file: " + file.getOriginalFilename()); logger.info("Start removing duplicates"); ((ITopicMap) topicMap).removeDuplicates(); logger.info("Finished removing duplicates"); // indexing stuff indexTopicMap(topicMap); } catch (Exception e) { throw new IllegalArgumentException("Only XTM or CTM files allowed.", e); } return; } try { TopicMapReader reader = null; if (file.getOriginalFilename().toLowerCase().endsWith("xtm")) { reader = new XTMTopicMapReader(topicMap, file.getInputStream(), topicMap.getLocator().toExternalForm()); } else if (file.getOriginalFilename().toLowerCase().endsWith("ctm")) { reader = new CTMTopicMapReader(topicMap, file.getInputStream(), topicMap.getLocator().toExternalForm()); } else { throw new IllegalArgumentException("Only XTM or CTM files allowed."); } reader.read(); logger.info("Start removing duplicates"); ((ITopicMap) topicMap).removeDuplicates(); logger.info("Finished removing duplicates"); logger.info("Finished Loading file: " + file.getOriginalFilename()); } catch (IOException e) { logger.error("Could not load topic map", e); } }
From source file:com.github.zhanhb.ckfinder.connector.handlers.command.FileUploadCommand.java
/** * validates uploaded file.// w ww. java 2 s .c om * * @param item uploaded item. * @param path file path * @param param the parameter * @param context ckfinder context * @throws ConnectorException when error occurs */ private void validateUploadItem(MultipartFile item, Path path, FileUploadParameter param, CKFinderContext context) throws ConnectorException { if (item.getOriginalFilename() == null || item.getOriginalFilename().length() <= 0) { param.throwException(ErrorCode.UPLOADED_INVALID); } param.setFileName(getFileItemName(item)); param.setNewFileName(param.getFileName()); param.setNewFileName(UNSAFE_FILE_NAME_PATTERN.matcher(param.getNewFileName()).replaceAll("_")); if (context.isDisallowUnsafeCharacters()) { param.setNewFileName(param.getNewFileName().replace(';', '_')); } if (context.isForceAscii()) { param.setNewFileName(FileUtils.convertToAscii(param.getNewFileName())); } if (!param.getNewFileName().equals(param.getFileName())) { param.setErrorCode(ErrorCode.UPLOADED_INVALID_NAME_RENAMED); } if (context.isDirectoryHidden(param.getCurrentFolder())) { param.throwException(ErrorCode.INVALID_REQUEST); } if (!FileUtils.isFileNameValid(param.getNewFileName()) || context.isFileHidden(param.getNewFileName())) { param.throwException(ErrorCode.INVALID_NAME); } final ResourceType resourceType = param.getType(); if (!FileUtils.isFileExtensionAllowed(param.getNewFileName(), resourceType)) { param.throwException(ErrorCode.INVALID_EXTENSION); } if (context.isCheckDoubleFileExtensions()) { param.setNewFileName(FileUtils.renameFileWithBadExt(resourceType, param.getNewFileName())); } Path file = getPath(path, getFinalFileName(path, param)); if ((!ImageUtils.isImageExtension(file) || !context.isCheckSizeAfterScaling()) && !FileUtils.isFileSizeInRange(resourceType, item.getSize())) { param.throwException(ErrorCode.UPLOADED_TOO_BIG); } if (context.isSecureImageUploads() && ImageUtils.isImageExtension(file) && !ImageUtils.isValid(item)) { param.throwException(ErrorCode.UPLOADED_CORRUPT); } }
From source file:org.openmrs.module.sdmxhdintegration.web.controller.MessageUploadFormController.java
/** * Handles form submission/*from w w w.j ava2s . c om*/ * @param request the request * @param message the message * @param result the binding result * @param status the session status * @return the view * @throws IllegalStateException */ @RequestMapping(method = RequestMethod.POST) public String handleSubmission(HttpServletRequest request, @ModelAttribute("message") SDMXHDMessage message, BindingResult result, SessionStatus status) throws IllegalStateException { DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request; MultipartFile file = req.getFile("sdmxhdMessage"); File destFile = null; if (!(file.getSize() <= 0)) { AdministrationService as = Context.getAdministrationService(); String dir = as.getGlobalProperty("sdmxhdintegration.messageUploadDir"); String filename = file.getOriginalFilename(); filename = "_" + (new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss")).format(new Date()) + "_" + filename; destFile = new File(dir + File.separator + filename); destFile.mkdirs(); try { file.transferTo(destFile); } catch (IOException e) { HttpSession session = request.getSession(); session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Could not save file. Make sure you have setup the upload directory using the configuration page and that the directory is readable by the tomcat user."); return "/module/sdmxhdintegration/messageUpload"; } message.setZipFilename(filename); } new SDMXHDMessageValidator().validate(message, result); if (result.hasErrors()) { log.error("SDMXHDMessage object failed validation"); if (destFile != null) { destFile.delete(); } return "/module/sdmxhdintegration/messageUpload"; } SDMXHDService service = Context.getService(SDMXHDService.class); ReportDefinitionService rds = Context.getService(ReportDefinitionService.class); service.saveMessage(message); // delete all existing mappings and reports List<KeyFamilyMapping> allKeyFamilyMappingsForMsg = service.getKeyFamilyMappingsFromMessage(message); for (Iterator<KeyFamilyMapping> iterator = allKeyFamilyMappingsForMsg.iterator(); iterator.hasNext();) { KeyFamilyMapping kfm = iterator.next(); Integer reportDefinitionId = kfm.getReportDefinitionId(); service.deleteKeyFamilyMapping(kfm); if (reportDefinitionId != null) { rds.purgeDefinition(rds.getDefinition(reportDefinitionId)); } } // create initial keyFamilyMappings try { DSD dsd = Utils.getDataSetDefinition(message); List<KeyFamily> keyFamilies = dsd.getKeyFamilies(); for (Iterator<KeyFamily> iterator = keyFamilies.iterator(); iterator.hasNext();) { KeyFamily keyFamily = iterator.next(); KeyFamilyMapping kfm = new KeyFamilyMapping(); kfm.setKeyFamilyId(keyFamily.getId()); kfm.setMessage(message); service.saveKeyFamilyMapping(kfm); } } catch (Exception e) { log.error("Error parsing SDMX-HD Message: " + e, e); if (destFile != null) { destFile.delete(); } service.deleteMessage(message); result.rejectValue("sdmxhdZipFileName", "upload.file.rejected", "This file is not a valid zip file or it does not contain a valid SDMX-HD DataSetDefinition"); return "/module/sdmxhdintegration/messageUpload"; } return "redirect:messages.list"; }
From source file:org.openmrs.module.drawing.web.controller.ManageTemplatesController.java
@RequestMapping(value = "/module/drawing/manageTemplates", method = RequestMethod.POST) public void manage(@RequestParam(value = "templateName", required = false) String templateName, @RequestParam(value = "template", required = true) MultipartFile file, ModelMap model, HttpSession session) {/*from w w w . ja va 2 s . c om*/ model.addAttribute("encodedTemplateNames", DrawingUtil.getAllTemplateNames()); if (file == null || file.getSize() == 0) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Please Fill All The Fields"); return; } else if (!DrawingUtil.isImage(file.getOriginalFilename())) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "File Format Not Supported"); return; } if (StringUtils.isBlank(templateName)) templateName = file.getOriginalFilename(); else templateName = templateName + "." + DrawingUtil.getExtension(file.getOriginalFilename()); try { BufferedImage bi = ImageIO.read(new ByteArrayInputStream(file.getBytes())); Boolean saved = DrawingUtil.saveFile(templateName, bi); if (saved) { session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Template Saved"); model.addAttribute("encodedTemplateNames", DrawingUtil.getAllTemplateNames()); } else session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Error Saving Template"); } catch (IOException e) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Unable To Save Uploaded File"); log.error("Unable to read uploadedFile", e); } }
From source file:cherry.foundation.async.AsyncFileProcessHandlerImplTest.java
@Test public void testLaunchFileProcess_NO_ARG() throws Exception { AsyncFileProcessHandlerImpl impl = createImpl(); LocalDateTime now = LocalDateTime.now(); when(bizDateTime.now()).thenReturn(now); when(asyncProcessStore.createFileProcess("a", now, "b", "c", "d", "e", 100L, "f")).thenReturn(10L); MultipartFile file = mock(MultipartFile.class); when(file.getName()).thenReturn("c"); when(file.getOriginalFilename()).thenReturn("d"); when(file.getContentType()).thenReturn("e"); when(file.getSize()).thenReturn(100L); when(file.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[0])); @SuppressWarnings("rawtypes") ArgumentCaptor<Map> message = ArgumentCaptor.forClass(Map.class); long asyncId = impl.launchFileProcess("a", "b", file, "f"); assertEquals(10L, asyncId);/*from w w w .jav a 2 s. com*/ verify(jmsOperations).convertAndSend(message.capture(), eq(messagePostProcessor)); assertEquals("10", message.getValue().get("asyncId")); String fileName = (String) message.getValue().get("file"); assertTrue(fileName.startsWith((new File(tempDir, "prefix_")).getAbsolutePath())); assertTrue(fileName.endsWith(".csv")); assertEquals("c", message.getValue().get("name")); assertEquals("d", message.getValue().get("originalFilename")); assertEquals("e", message.getValue().get("contentType")); assertEquals("100", message.getValue().get("size")); assertEquals("f", message.getValue().get("handlerName")); verify(asyncProcessStore).createFileProcess("a", now, "b", "c", "d", "e", 100L, "f"); verify(asyncProcessStore).updateToLaunched(10L, now); }
From source file:com.dlshouwen.wzgl.video.controller.VideoController.java
/** * // w w w .ja va2 s. c o m * * @param request * @return * @throws Exception */ @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public AjaxResponse uploadVideo(HttpServletRequest request, HttpServletResponse response) throws Exception { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartRequest.getFile("file"); String fileName = multipartFile.getOriginalFilename(); //? String path = null; String videoCoverPath = null; String videoTime = null; if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) { JSONObject jobj = FileUploadClient.upFile(request, fileName, multipartFile.getInputStream()); if (jobj.getString("responseMessage").equals("OK")) { path = jobj.getString("fpath"); videoCoverPath = jobj.getString("videoCoverPath"); videoTime = jobj.getString("videoTime"); } } /* int pos = fileName.lastIndexOf("."); fileName = fileName.substring(pos); String fileDirPath = request.getSession().getServletContext().getRealPath("/"); String path = fileDirPath.substring(0, fileDirPath.lastIndexOf(File.separator)) + CONFIG.UPLOAD_VIDEO_PATH;; Date date = new Date(); fileName = String.valueOf(date.getTime()) + fileName; File file = new File(path); if (!file.exists()) { file.mkdirs(); } file = new File(path + "/" + fileName); if (!file.exists()) { file.createNewFile(); } path = path + "/" + fileName; FileOutputStream fos = null; InputStream s = null; try { fos = new FileOutputStream(file); s = multipartFile.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; while ((read = s.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { fos.close(); } if (s != null) { s.close(); } } */ AjaxResponse ajaxResponse = new AjaxResponse(); if (StringUtils.isNotEmpty(path)) { WebUtil.addCookie(request, response, "videoPath", path, -1); WebUtil.addCookie(request, response, "videoCoverPath", videoCoverPath, -1); WebUtil.addCookie(request, response, "videoTime", videoTime, -1); // ? ajaxResponse.setSuccess(true); ajaxResponse.setSuccessMessage("??"); } else { // ? ajaxResponse.setError(true); ajaxResponse.setErrorMessage("?"); } // ? LogUtils.updateOperationLog(request, OperationType.UPDATE, "??" + fileName); return ajaxResponse; }
From source file:fr.olympicinsa.riocognized.ImageController.java
@RequestMapping(value = "/save", method = RequestMethod.POST) public String save(@ModelAttribute("image") Image image, @RequestParam("file") MultipartFile file) { System.out.println("Name:" + image.getName()); System.out.println("Desc:" + image.getDescription()); System.out.println("File:" + file.getName()); System.out.println("ContentType:" + file.getContentType()); try {/*from w w w . j av a 2 s . c om*/ byte[] blob = IOUtils.toByteArray(file.getInputStream()); image.setFilename(file.getOriginalFilename()); image.setContent(blob); image.setContentType(file.getContentType()); } catch (IOException e) { e.printStackTrace(); } try { imageRepository.save(image); } catch (Exception e) { e.printStackTrace(); } return "redirect:/image"; }