List of usage examples for org.springframework.web.multipart MultipartHttpServletRequest getFileMap
Map<String, MultipartFile> getFileMap();
From source file:egovframework.rte.tex.gds.service.impl.EgovGoodsServiceImpl.java
/** * ? ? ./* w w w . ja v a2s .co m*/ * @param request * @param goodsVO * @throws Exception */ public void updateGoods(GoodsVO goodsVO, final HttpServletRequest request) throws Exception { final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; GoodsImageVO[] imageList = new GoodsImageVO[2]; // extract files final Map<String, MultipartFile> files = multiRequest.getFileMap(); // process files String uploadLastPath = fileUploadProperties.getProperty("file.upload.path"); String uploadPath = request.getSession().getServletContext().getRealPath("/") + uploadLastPath; File saveFolder = new File(uploadPath); // ? boolean isDir = false; if (!saveFolder.exists() || saveFolder.isFile()) { saveFolder.mkdirs(); } if (!isDir) { Iterator<Entry<String, MultipartFile>> itr = files.entrySet().iterator(); MultipartFile file; String filePath; int i = 0; // goodsImage,detailImage index while (itr.hasNext()) { // ?? Entry<String, MultipartFile> entry = itr.next(); file = entry.getValue(); if (!"".equals(file.getOriginalFilename())) { String saveFileName; if (i == 0) { saveFileName = goodsVO.getGoodsImageVO().getGoodsImageId(); } else { saveFileName = goodsVO.getDetailImageVO().getGoodsImageId(); } imageList[i] = new GoodsImageVO(saveFileName, file.getOriginalFilename()); // ? filePath = uploadPath + "\\" + saveFileName; file.transferTo(new File(filePath)); } i++; } } if (imageList[0] != null) goodsVO.setGoodsImageVO(imageList[0]); if (imageList[1] != null) goodsVO.setDetailImageVO(imageList[1]); goodsDAO.updateGoods(goodsVO); }
From source file:org.dataone.proto.trove.mn.rest.v1.ErrorController.java
@RequestMapping(value = { "/v1/error/", "/v1/error" }, method = RequestMethod.POST) public void fail(MultipartHttpServletRequest fileRequest, HttpServletResponse response) throws InvalidSystemMetadata, InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, InsufficientResources, NotImplemented, InvalidRequest { Session session = new Session(); MultipartFile messageMultipart = null; SynchronizationFailed message;//from www . j a va 2 s . com Set<String> keys = fileRequest.getFileMap().keySet(); for (String key : keys) { if (key.equalsIgnoreCase("message")) { messageMultipart = fileRequest.getFileMap().get(key); } } if (messageMultipart != null) { try { message = (SynchronizationFailed) ExceptionHandler.deserializeXml(messageMultipart.getInputStream(), "something broke"); } catch (IOException ex) { throw new InvalidSystemMetadata("15001", ex.getMessage()); } catch (SAXException ex) { throw new InvalidSystemMetadata("15001", ex.getMessage()); } catch (ParserConfigurationException ex) { throw new InvalidSystemMetadata("15001", ex.getMessage()); } } else { throw new InvalidSystemMetadata("15005", "System Metadata was not found as Part of Multipart Mime message"); } mnRead.synchronizationFailed(session, message); }
From source file:com.glaf.jbpm.web.springmvc.MxJbpmDeployController.java
@RequestMapping(value = "/reconfig", method = RequestMethod.POST) public ModelAndView reconfig(HttpServletRequest request) { String actorId = RequestUtils.getActorId(request); String archive = request.getParameter("archive"); if (LogUtils.isDebug()) { logger.debug("deploying archive " + archive); }/* w ww .java2s. co m*/ MultipartHttpServletRequest req = (MultipartHttpServletRequest) request; JbpmExtensionReader reader = new JbpmExtensionReader(); JbpmContext jbpmContext = null; try { jbpmContext = ProcessContainer.getContainer().createJbpmContext(); Map<String, MultipartFile> fileMap = req.getFileMap(); Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet(); for (Entry<String, MultipartFile> entry : entrySet) { MultipartFile mFile = entry.getValue(); if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) { List<Extension> extensions = reader.readTasks(mFile.getInputStream()); if (extensions != null && extensions.size() > 0) { Iterator<Extension> iter = extensions.iterator(); while (iter.hasNext()) { Extension extension = iter.next(); extension.setCreateActorId(actorId); } JbpmExtensionManager jbpmExtensionManager = ProcessContainer.getContainer() .getJbpmExtensionManager(); jbpmExtensionManager.reconfig(jbpmContext, extensions); request.setAttribute("message", "???"); } } } } catch (Exception ex) { if (jbpmContext != null) { jbpmContext.setRollbackOnly(); } request.setAttribute("error_code", 9913); request.setAttribute("error_message", ""); return new ModelAndView("/error"); } finally { Context.close(jbpmContext); } String jx_view = request.getParameter("jx_view"); if (StringUtils.isNotEmpty(jx_view)) { return new ModelAndView(jx_view); } String x_view = ViewProperties.getString("jbpm_deploy.configFinish"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view); } return new ModelAndView("/jbpm/deploy/configFinish"); }
From source file:com.glaf.jbpm.web.rest.MxJbpmDeployResource.java
@POST @Path("deploy") @Produces({ MediaType.APPLICATION_OCTET_STREAM }) @ResponseBody/* w ww . j av a 2 s . co m*/ public byte[] deploy(@Context HttpServletRequest request) { MultipartHttpServletRequest req = (MultipartHttpServletRequest) request; Map<String, Object> paramMap = RequestUtils.getParameterMap(req); if (LogUtils.isDebug()) { logger.debug(paramMap); } int status_code = 0; String cause = null; Map<String, MultipartFile> fileMap = req.getFileMap(); Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet(); for (Entry<String, MultipartFile> entry : entrySet) { MultipartFile mFile = entry.getValue(); String filename = mFile.getOriginalFilename(); long filesize = mFile.getSize(); if (filename == null || filesize <= 0) { continue; } if (filename.endsWith(".jar") || filename.endsWith(".zip")) { JbpmContext jbpmContext = null; MxJbpmProcessDeployer deployer = new MxJbpmProcessDeployer(); try { jbpmContext = ProcessContainer.getContainer().createJbpmContext(); if (jbpmContext != null && jbpmContext.getSession() != null) { deployer.deploy(jbpmContext, mFile.getBytes()); status_code = 200; } } catch (Exception ex) { if (jbpmContext != null) { jbpmContext.setRollbackOnly(); } status_code = 500; throw new JbpmException(ex); } finally { com.glaf.jbpm.context.Context.close(jbpmContext); } } } Map<String, Object> jsonMap = new java.util.HashMap<String, Object>(); if (status_code == 200) { jsonMap.put("statusCode", 200); jsonMap.put("message", "???"); } else if (status_code == 401) { jsonMap.put("statusCode", 401); jsonMap.put("message", "????"); } else if (status_code == 500) { jsonMap.put("statusCode", 500); jsonMap.put("message", "?????"); jsonMap.put("cause", cause); } else { jsonMap.put("statusCode", status_code); jsonMap.put("message", "??????"); } JSONObject jsonObject = new JSONObject(jsonMap); try { return jsonObject.toString().getBytes("UTF-8"); } catch (IOException e) { return jsonObject.toString().getBytes(); } }
From source file:egovframework.oe1.cms.arc.web.EgovOe1ScrinController.java
/** * ?? ?.//w ww. j av a 2 s . co m * @param ? scrinVO, request, model * @return forward:/cms/arc/selectScrin.do"; * @exception Exception */ @RequestMapping(value = "/cms/arc/excelScrinRegist.do") public String insertExcelScrin(@ModelAttribute("scrinVO") EgovOe1ScrinVO scrinVO, final HttpServletRequest request, Map commandMap, Model model) throws Exception { // Spring Security Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated(); if (!isAuthenticated) { return "/cms/com/EgovLoginUsr"; // ? ?? } // EgovOe1LoginVO user = (EgovOe1LoginVO) EgovUserDetailsHelper.getAuthenticatedUser(); scrinVO.setFrstRegisterId(user.getMberId()); String sCmd = commandMap.get("cmd") == null ? "" : (String) commandMap.get("cmd"); if (sCmd.equals("")) { return "/cms/arc/EgovExcelScrinRegist"; } final MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; final Map<String, MultipartFile> files = multiRequest.getFileMap(); Iterator<Entry<String, MultipartFile>> itr = files.entrySet().iterator(); MultipartFile file; while (itr.hasNext()) { Entry<String, MultipartFile> entry = itr.next(); file = entry.getValue(); if (!"".equals(file.getOriginalFilename())) { // ? ?? . egovOe1ScrinService.deleteExcelScrin(); InputStream is = null; try { is = file.getInputStream(); excelService.uploadExcel("egovOe1ScrinDAO.inserExceltScrin", is, 4); } catch (Exception e) { throw e; } finally { try { if (is != null) { is.close(); } } catch (Exception e) { // log none log.info(e.getMessage()); } } } } return "forward:/cms/arc/selectScrin.do"; }
From source file:com.github.zhanhb.ckfinder.connector.handlers.command.FileUploadCommand.java
/** * * @param request http request//w w w . ja v a2 s . co m * @param param the parameter * @param context ckfinder context * @throws ConnectorException when error occurs */ private void fileUpload(HttpServletRequest request, FileUploadParameter param, CKFinderContext context) throws ConnectorException { MultipartResolver multipartResolver = StandardHolder.RESOLVER; try { boolean multipart = multipartResolver.isMultipart(request); if (multipart) { log.debug("prepare resolveMultipart"); MultipartHttpServletRequest resolveMultipart = multipartResolver.resolveMultipart(request); log.debug("finish resolveMultipart"); try { Collection<MultipartFile> parts = resolveMultipart.getFileMap().values(); for (MultipartFile part : parts) { Path path = getPath(param.getType().getPath(), param.getCurrentFolder()); param.setFileName(getFileItemName(part)); validateUploadItem(part, path, param, context); saveTemporaryFile(path, part, param, context); return; } } finally { multipartResolver.cleanupMultipart(resolveMultipart); } } param.throwException("No file provided in the request."); } catch (MultipartException e) { log.debug("catch MultipartException", e); param.throwException(ErrorCode.UPLOADED_TOO_BIG); } catch (IOException e) { log.debug("catch IOException", e); param.throwException(ErrorCode.ACCESS_DENIED); } }
From source file:com.jaspersoft.jasperserver.rest.utils.Utils.java
/** * Extract the attachments from the request and put the in the list of * input attachments of the service./*from ww w.j a v a 2s . co m*/ * * The method returns the currenst HttpServletRequest if the message is not * multipart, otherwise it returns a MultipartHttpServletRequest * * * @param service * @param hRequest */ public HttpServletRequest extractAttachments(LegacyRunReportService service, HttpServletRequest hRequest) { //Check whether we're dealing with a multipart request MultipartResolver resolver = new CommonsMultipartResolver(); // handles the PUT multipart requests if (isMultipartContent(hRequest) && hRequest.getContentLength() != -1) { MultipartHttpServletRequest mreq = resolver.resolveMultipart(hRequest); if (mreq != null && mreq.getFileMap().size() != 0) { Iterator iterator = mreq.getFileNames(); String fieldName = null; while (iterator.hasNext()) { fieldName = (String) iterator.next(); MultipartFile file = mreq.getFile(fieldName); if (file != null) { DataSource ds = new MultipartFileDataSource(file); service.getInputAttachments().put(fieldName, ds); } } if (log.isDebugEnabled()) { log.debug(service.getInputAttachments().size() + " attachments were extracted from the PUT"); } return mreq; } // handles the POST multipart requests else { if (hRequest instanceof DefaultMultipartHttpServletRequest) { DefaultMultipartHttpServletRequest dmServletRequest = (DefaultMultipartHttpServletRequest) hRequest; Iterator iterator = ((DefaultMultipartHttpServletRequest) hRequest).getFileNames(); String fieldName = null; while (iterator.hasNext()) { fieldName = (String) iterator.next(); MultipartFile file = dmServletRequest.getFile(fieldName); if (file != null) { DataSource ds = new MultipartFileDataSource(file); service.getInputAttachments().put(fieldName, ds); } } } } } if (log.isDebugEnabled()) { log.debug(service.getInputAttachments().size() + " attachments were extracted from the POST"); } return hRequest; }
From source file:com.glaf.template.web.springmvc.MxSystemTemplateController.java
@RequestMapping("/save") public ModelAndView save(HttpServletRequest request, ModelMap modelMap) throws IOException { LoginContext loginContext = RequestUtils.getLoginContext(request); String templateId = request.getParameter("templateId"); Template template = null;/* w ww .j av a 2 s. c om*/ if (StringUtils.isNotEmpty(templateId)) { template = templateService.getTemplate(templateId); } if (template == null) { template = new Template(); template.setCreateBy(loginContext.getActorId()); } MultipartHttpServletRequest req = (MultipartHttpServletRequest) request; Map<String, Object> paramMap = RequestUtils.getParameterMap(req); Tools.populate(template, paramMap); String nodeId = ParamUtils.getString(paramMap, "nodeId"); if (nodeId != null) { } Map<String, MultipartFile> fileMap = req.getFileMap(); Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet(); for (Entry<String, MultipartFile> entry : entrySet) { MultipartFile mFile = entry.getValue(); String filename = mFile.getOriginalFilename(); if (mFile.getSize() > 0) { template.setFileSize(mFile.getSize()); int fileType = 0; if (filename.endsWith(".java")) { fileType = 50; template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".jsp")) { fileType = 51; template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".ftl")) { fileType = 52; template.setLanguage("freemarker"); template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".vm")) { fileType = 54; template.setLanguage("velocity"); template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".xml")) { fileType = 60; template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".htm") || filename.endsWith(".html")) { fileType = 80; template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".js")) { fileType = 82; template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".css")) { fileType = 84; template.setContent(new String(mFile.getBytes())); } else if (filename.endsWith(".txt")) { fileType = 85; template.setContent(new String(mFile.getBytes())); } template.setDataFile(filename); template.setFileType(fileType); template.setCreateDate(new Date()); template.setData(mFile.getBytes()); template.setLastModified(System.currentTimeMillis()); template.setTemplateType(FileUtils.getFileExt(filename)); break; } } templateService.saveTemplate(template); return this.list(request, modelMap); }
From source file:egovframework.oe1.cms.arc.web.EgovOe1ScrinController.java
/** * ./*from ww w . j ava2 s.c o m*/ * @param ? scrinVO, multiRequest * @return "forward:/cms/arc/getScrin.do"; * @exception Exception */ @RequestMapping(value = "/cms/arc/updtScrin.do") public String updateScrin(final MultipartHttpServletRequest multiRequest, @ModelAttribute("scrinVO") EgovOe1ScrinVO scrinVO, ModelMap model) throws Exception { try { String _atchFileId = scrinVO.getAtchFileId();// ? ? ? // ? ? ID . final Map<String, MultipartFile> files = multiRequest.getFileMap(); if (!files.isEmpty()) { if ("".equals(_atchFileId) || _atchFileId == null) { List<EgovOe1FileVO> _result = fileUtil.parseFileInf(files, "", 0, _atchFileId, ""); _atchFileId = fileMngService.insertFileInfs(_result); // ? // ? // ID // . scrinVO.setAtchFileId(_atchFileId); // ? ? ?? // ? ID . } else { EgovOe1FileVO fvo = new EgovOe1FileVO(); fvo.setAtchFileId(_atchFileId); // ? ? ?? VO? // ? ID . int _cnt = fileMngService.getMaxFileSN(fvo); // ? ID? // ? ? // ? ??. List<EgovOe1FileVO> _result = fileUtil.parseFileInf(files, "", _cnt, _atchFileId, ""); fileMngService.updateFileInfs(_result); } } // Spring Security Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated(); if (!isAuthenticated) { return "/cms/com/EgovLoginUsr"; // ? ?? } // EgovOe1LoginVO user = (EgovOe1LoginVO) EgovUserDetailsHelper.getAuthenticatedUser(); scrinVO.setFrstRegisterId(user.getMberId()); egovOe1ScrinService.updateScrin(scrinVO); model.addAttribute("resultMsg", "?."); // status.setComplete(); return "forward:/cms/arc/getScrin.do"; } catch (Exception ex) { // ex.printStackTrace(); throw ex; } }
From source file:cz.zcu.kiv.eegdatabase.logic.controller.experiment.AddExperimentWizardController.java
@Override protected ModelAndView processFinish(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object command, BindException e) throws Exception { log.debug("Processing measuration form - adding new measuration"); ModelAndView mav = new ModelAndView("redirect:/experiments/my-experiments.html"); mav.addObject("userIsExperimenter", auth.userIsExperimenter()); AddExperimentWizardCommand data = (AddExperimentWizardCommand) command; Experiment experiment;/*from w ww . j a va 2s . c o m*/ log.debug("Checking the permission level."); if (!auth.userIsExperimenter()) { log.debug("User is not experimenter - unable to add experiment. Returning MAV."); mav.setViewName("redirect:experiments/userNotExperimenter"); return mav; } log.debug("Creating new Measuration object"); experiment = new Experiment(); // This assignment is commited only when new experiment is being created log.debug("Setting the owner to the logged user."); experiment.setPersonByOwnerId(personDao.getLoggedPerson()); log.debug("Setting the group, which is the new experiment being added into."); ResearchGroup researchGroup = new ResearchGroup(); researchGroup.setResearchGroupId(data.getResearchGroup()); experiment.setResearchGroup(researchGroup); log.debug("Setting Weather object - ID " + data.getWeather()); Weather weather = new Weather(); weather.setWeatherId(data.getWeather()); experiment.setWeather(weather); log.debug("Setting Scenario object - ID " + data.getScenario()); Scenario scenario = new Scenario(); scenario.setScenarioId(data.getScenario()); experiment.setScenario(scenario); log.debug("Setting Person object (measured person) - ID " + data.getSubjectPerson()); Person subjectPerson = new Person(); subjectPerson.setPersonId(data.getSubjectPerson()); experiment.setPersonBySubjectPersonId(subjectPerson); Date startDate = ControllerUtils.getDateFormatWithTime() .parse(data.getStartDate() + " " + data.getStartTime()); experiment.setStartTime(new Timestamp(startDate.getTime())); log.debug("Setting start date - " + startDate); Date endDate = ControllerUtils.getDateFormatWithTime().parse(data.getEndDate() + " " + data.getEndTime()); experiment.setEndTime(new Timestamp(endDate.getTime())); log.debug("Setting end date - " + endDate); log.debug("Setting the temperature - " + data.getTemperature()); experiment.setTemperature(Integer.parseInt(data.getTemperature())); log.debug("Setting the weather note - " + data.getWeatherNote()); experiment.setEnvironmentNote(data.getWeatherNote()); log.debug("Started setting the Hardware objects"); int[] hardwareArray = data.getHardware(); Set<Hardware> hardwareSet = new HashSet<Hardware>(); for (int hardwareId : hardwareArray) { System.out.println("hardwareId " + hardwareId); Hardware tempHardware = hardwareDao.read(hardwareId); hardwareSet.add(tempHardware); tempHardware.getExperiments().add(experiment); log.debug("Added Hardware object - ID " + hardwareId); } log.debug("Setting Hardware list to Measuration object"); experiment.setHardwares(hardwareSet); log.debug("Started setting the Person objects (coExperimenters)"); int[] coExperimentersArray = data.getCoExperimenters(); Set<Person> coExperimenterSet = new HashSet<Person>(); for (int personId : coExperimentersArray) { Person tempExperimenter = personDao.read(personId); coExperimenterSet.add(tempExperimenter); tempExperimenter.getExperiments().add(experiment); log.debug("Added Person object - ID " + tempExperimenter.getPersonId()); } log.debug("Setting Person list to Measuration object"); experiment.setPersons(coExperimenterSet); log.debug("Setting private/public access"); experiment.setPrivateExperiment(data.isPrivateNote()); float samplingRate = Float.parseFloat(data.getSamplingRate()); Digitization digitization = digitizationDao.getDigitizationByParams(samplingRate, -1, "NotKnown"); if (digitization == null) { digitization = new Digitization(); digitization.setFilter("NotKnown"); digitization.setGain(-1); digitization.setSamplingRate(samplingRate); digitizationDao.create(digitization); } experiment.setDigitization(digitization); experiment.setArtifact(artifactDao.read(1)); experiment.setElectrodeConf(electrodeConfDao.read(1)); experiment.setSubjectGroup(subjectGroupDao.read(1)); //default subject group if (data.getMeasurationId() > 0) { // editing existing measuration log.debug("Saving the Measuration object to database using DAO - update()"); experimentDao.update(experiment); } else { // creating new measuration log.debug("Saving the Measuration object to database using DAO - create()"); experimentDao.create(experiment); } // log.debug("Creating measuration with ID " + addDataCommand.getMeasurationId()); // experiment.setExperimentId(addDataCommand.getMeasurationId()); log.debug("Creating new Data object."); MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) httpServletRequest; // the map containing file names mapped to files Map m = mpRequest.getFileMap(); Set set = m.keySet(); for (Object key : set) { MultipartFile file = (MultipartFile) m.get(key); if (file.getOriginalFilename().endsWith(".zip")) { ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(file.getBytes())); ZipEntry en = zis.getNextEntry(); while (en != null) { if (en.isDirectory()) { en = zis.getNextEntry(); continue; } DataFile dataFile = new DataFile(); dataFile.setExperiment(experiment); String name[] = en.getName().split("/"); dataFile.setFilename(name[name.length - 1]); data.setFileDescription(data.getFileDescription()); dataFile.setFileContent(Hibernate.createBlob(zis)); String[] partOfName = en.getName().split("[.]"); dataFile.setMimetype(partOfName[partOfName.length - 1]); dataFileDao.create(dataFile); en = zis.getNextEntry(); } } else { DataFile dataFile = new DataFile(); dataFile.setExperiment(experiment); log.debug("Original name of uploaded file: " + file.getOriginalFilename()); String filename = file.getOriginalFilename().replace(" ", "_"); dataFile.setFilename(filename); log.debug("MIME type of the uploaded file: " + file.getContentType()); if (file.getContentType().length() > MAX_MIMETYPE_LENGTH) { int index = filename.lastIndexOf("."); dataFile.setMimetype(filename.substring(index)); } else { dataFile.setMimetype(file.getContentType()); } log.debug("Parsing the sapmling rate."); dataFile.setDescription(data.getFileDescription()); log.debug("Setting the binary data to object."); dataFile.setFileContent(Hibernate.createBlob(file.getBytes())); dataFileDao.create(dataFile); log.debug("Data stored into database."); } } log.debug("Returning MAV object"); return mav; }