List of usage examples for org.springframework.web.multipart MultipartFile isEmpty
boolean isEmpty();
From source file:com.mbv.web.rest.controller.VpGdnController.java
/** * @??excel// www . j a v a 2 s .co m * @2015916 * @param * @version */ @RequestMapping(value = "/importUpdateGdn", method = RequestMethod.POST) @ResponseBody public void importVpGdnUpdateBill( @RequestParam(value = "update_vpGdn_importedFile", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException { JSONObject json = new JSONObject(); try { // ? if (file.isEmpty()) { throw new MbvException("??"); } // ?? if (file.getSize() > 20971520) { throw new Exception("?20M?"); } json = importFile(file); } catch (MbvException me) { me.printStackTrace(); json.put("success", false); json.put("msg", me.getMessage()); } catch (RuntimeException re) { re.printStackTrace(); json.put("success", false); json.put("msg", re.getMessage()); } catch (Exception e) { e.printStackTrace(); json.put("success", false); json.put("msg", e.getMessage()); } // ??? outPrintJson(response, json.toString()); }
From source file:com.newline.view.company.controller.CompanyController.java
/** * //from ww w .j av a2 s. c o m * ? * * @param request * @param response * @param file * @see * @author 2015-9-14?1:29:31 * @since 1.0 */ @RequestMapping(value = "/uploadImg", method = RequestMethod.POST) public void uploadImg(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file", required = false) MultipartFile file) { NlMemberEntity member = getMember(request); try { if (member != null && !file.isEmpty()) { NlCompanyEntity company = companyService.getCompanyByMemberid(member.getId()); String newFileName = QiNiuUtils.uploadImg(file); if (StringUtils.isNotBlank(newFileName)) { if (StringUtils.isNotBlank(company.getAlbum())) { company.setAlbum(company.getAlbum() + "," + newFileName); } else { company.setAlbum(newFileName); } companyService.updateCompany(company); response.getWriter().write(newFileName); } else { log.error(""); } } else { log.error(""); } } catch (Exception e) { log.error("?" + e.getMessage()); } }
From source file:cz.zcu.kiv.eegdatabase.logic.controller.scenario.AddScenarioSchemaController.java
@Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException bindException) throws Exception { ModelAndView mav = new ModelAndView(getSuccessView()); log.debug("Processing form data"); AddScenarioSchemaCommand data = (AddScenarioSchemaCommand) command; String idString = request.getParameter("id"); int id = 0;/*w w w . j a v a 2 s.co m*/ if (idString != null) { id = Integer.parseInt(idString); } MultipartFile schemaFile = data.getSchemaFile(); ScenarioSchemas scenarioSchema; if (id > 0) { // Editing existing log.debug("Editing existing scenario schema."); scenarioSchema = scenarioSchemasDao.read(id); } else { // Creating new log.debug("Creating new scenario schema object"); scenarioSchema = new ScenarioSchemas(); } log.debug("Setting scenario schema description: " + data.getSchemaDescription()); scenarioSchema.setDescription(data.getSchemaDescription()); //set scenario schema file if ((schemaFile != null) && (!schemaFile.isEmpty())) { log.debug("Setting the scenario schema file"); String schemaName = schemaFile.getOriginalFilename(); scenarioSchema.setSchemaName(schemaName); byte[] schemaContent = schemaFile.getBytes(); //Clob schemaContent = Hibernate.createClob(schemaFile.getBytes().toString()); int newSchemaId = scenarioSchemasDao.getNextSchemaId(); System.out.println(newSchemaId); ScenarioSchemaGenerator schemaGenerator = new ScenarioSchemaGenerator(newSchemaId, schemaName, schemaContent); String sql = schemaGenerator.generateSql(); String hbmXml = schemaGenerator.generateHbmXml(); String pojo = schemaGenerator.generatePojo(); String bean = schemaGenerator.generateBean(); scenarioSchema.setSql(Hibernate.createClob(sql)); scenarioSchema.setHbmXml(Hibernate.createClob(hbmXml)); scenarioSchema.setPojo(Hibernate.createClob(pojo)); scenarioSchema.setBean(bean); scenarioSchema.setApproved('n'); } log.debug("Saving scenario schema object"); if (id > 0) { // Editing existing scenarioSchemasDao.update(scenarioSchema); } else { // Creating new scenarioSchemasDao.create(scenarioSchema); } log.debug("Returning MAV"); return mav; }
From source file:it.smartcommunitylab.climb.contextstore.controller.ChildController.java
@RequestMapping(value = "/api/image/upload/png/{ownerId}/{objectId}", method = RequestMethod.POST) public @ResponseBody String uploadImage(@RequestParam("file") MultipartFile file, @PathVariable String ownerId, @PathVariable String objectId, HttpServletRequest request) throws Exception { Criteria criteria = Criteria.where("objectId").is(objectId); Child child = storage.findOneData(Child.class, criteria, ownerId); if (!validateAuthorizationByExp(ownerId, child.getInstituteId(), child.getSchoolId(), null, "ALL", request)) {/*ww w . j a v a 2 s . c om*/ throw new UnauthorizedException("Unauthorized Exception: token not valid"); } String name = objectId + ".png"; if (logger.isInfoEnabled()) { logger.info("uploadImage:" + name); } if (!file.isEmpty()) { BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(imageUploadDir + "/" + name))); FileCopyUtils.copy(file.getInputStream(), stream); stream.close(); } return "{\"status\":\"OK\"}"; }
From source file:com.uwca.operation.modules.api.company.web.CompanyController.java
@RequestMapping(value = "modifyCompanyInfo") @ResponseBody//from w ww . j ava 2 s. c om public CompanyVo modifyCompanyInfo(@RequestParam("token") String token, @RequestParam("companyname") String companyname, @RequestParam("legalperson") String legalperson, @RequestParam("organizationcode") String organizationcode, @RequestParam("fax") String fax, @RequestParam("mail") String mail, @RequestParam("website") String website, @RequestParam("address") String address, @RequestParam("businesslicense") MultipartFile businesslicense, @RequestParam("sign") String sign) { CompanyVo companyVo = new CompanyVo(); Result result = companyVo.new Result(); try { if (StringUtils.isEmpty(token) || StringUtils.isEmpty(sign)) { companyVo.setReturncode(1); companyVo.setMessage("??"); companyVo.setResult(result); return companyVo; } String newFileName = ""; if (businesslicense != null && !businesslicense.isEmpty()) { String fileName = businesslicense.getOriginalFilename(); String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1); newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName; try { saveFile(newFileName, businesslicense); } catch (Exception e) { companyVo.setReturncode(1); companyVo.setMessage("??"); companyVo.setResult(result); return companyVo; } } Map<String, Object> map = new HashMap<String, Object>(); String companyid = TokenTool.getCompanyid(token); map.put("id", companyid); map.put("userid", TokenTool.getUserid(token)); map.put("companyname", companyname); map.put("legalperson", legalperson); map.put("organizationcode", organizationcode); map.put("businesslicense", newFileName); map.put("fax", fax); map.put("mail", mail); map.put("address", address); map.put("website", website); map.put("state", 1); companyService.updateCompany(map); Company company = companyService.getCompanyInfoById(companyid); CompanyResult companyResult = new CompanyResult(); if (null != company) { BeanUtils.copyProperties(company, companyResult); } result.setCompanyResult(companyResult); companyVo.setReturncode(0); companyVo.setMessage("ok"); return companyVo; } catch (Exception e) { companyVo.setReturncode(1); companyVo.setMessage("??"); companyVo.setResult(result); e.printStackTrace(); return companyVo; } }
From source file:org.shareok.data.kernel.api.services.job.TaskManagerImpl.java
/** * //from ww w . j av a2s. co m * @param uid : user ID * @param handler : handler of job execution * @param localFile : uploaded file from local computer * @param remoteFilePath : remote resource of the file * @return : path to the report file */ @Override public RedisJob execute(long uid, JobHandler handler, MultipartFile localFile, String remoteFilePath) { try { RedisJob newJob = redisJobService.createJob(uid, handler.getJobType(), handler.outputJobDataByJobType()); long jobId = newJob.getJobId(); String jobFilePath = DataHandlersUtil.getJobReportPath(DataUtil.JOB_TYPES[handler.getJobType()], jobId); DataService ds = ServiceUtil.getDataService(handler.getJobType()); String filePath = ""; String reportFilePath = jobFilePath + File.separator + String.valueOf(jobId) + "-report.txt"; if (null != localFile && !localFile.isEmpty()) { filePath = ServiceUtil.saveUploadedFile(localFile, jobFilePath); } else if (null != remoteFilePath && !"".equals(remoteFilePath)) { filePath = processRemoteFileByJobType(handler.getJobType(), redisJobService, jobFilePath, remoteFilePath); } handler.setFilePath(filePath); handler.setReportFilePath(reportFilePath); ds.setUserId(uid); ds.setHandler(handler); redisJobService.updateJob(jobId, "status", "0"); redisJobService.updateJob(jobId, "filePath", filePath); //Handle the job queue stuff: String queueName = RedisUtil.getJobQueueName(uid, DataUtil.JOB_TYPES[handler.getJobType()], handler.getServerName()); Thread thread = ServiceUtil.getThreadByName(queueName); if (jobQueueService.isJobQueueEmpty(queueName)) { if (null != thread && !thread.isInterrupted()) { try { Thread.sleep(100); } catch (InterruptedException ex) { logger.debug("Current thread is interrupted while sleeping", ex); } if (!thread.isInterrupted()) { jobQueueService.addJobIntoQueue(jobId, queueName); redisJobService.updateJob(jobId, "status", "7"); } else { // try { // thread.join(); // } catch (InterruptedException ex) { // logger.debug("Current thread is interrupted while sleeping", ex); // } jobQueueService.addJobIntoQueue(jobId, queueName); redisJobService.updateJob(jobId, "status", "7"); Thread newThread = new Thread(ds, queueName); newThread.start(); } } else { // if(null != thread && thread.isInterrupted()){ // while(thread.isAlive()){ // try { // Thread.sleep(50L); // } catch (InterruptedException ex) { // Logger.getLogger(TaskManagerImpl.class.getName()).log(Level.SEVERE, null, ex); // } // } // // } jobQueueService.addJobIntoQueue(jobId, queueName); redisJobService.updateJob(jobId, "status", "7"); Thread newThread = new Thread(ds, queueName); newThread.start(); } } else { jobQueueService.addJobIntoQueue(jobId, queueName); redisJobService.updateJob(jobId, "status", "7"); if (null == thread) { Thread newThread = new Thread(ds, queueName); newThread.start(); } } return redisJobService.findJobByJobId(jobId); } catch (BeansException | NumberFormatException | EmptyUploadedPackagePathOfSshUploadJobException ex) { // logger.error("Cannot exectue the job with type "+DataUtil.JOB_TYPES[handler.get]+" for repository "+DataUtil.REPO_TYPES[repoType], ex); logger.error("Cannot exectue the job with type.", ex); } return null; }
From source file:csns.web.controller.SiteBlockControllerS.java
@RequestMapping(value = "/site/{qtr}/{cc}-{sn}/block/addItem", method = RequestMethod.POST) public String addItem(@PathVariable String qtr, @PathVariable String cc, @PathVariable int sn, @ModelAttribute Item item, @RequestParam Long blockId, @RequestParam(value = "uploadedFile", required = false) MultipartFile uploadedFile, BindingResult bindingResult, SessionStatus sessionStatus) { itemValidator.validate(item, uploadedFile, bindingResult); if (bindingResult.hasErrors()) return "site/block/addItem"; User user = SecurityUtils.getUser(); Block block = blockDao.getBlock(blockId); Resource resource = item.getResource(); if (resource.getType() != ResourceType.NONE) { if (resource.getType() == ResourceType.FILE && uploadedFile != null && !uploadedFile.isEmpty()) resource.setFile(fileIO.save(uploadedFile, user, true)); block.getItems().add(item);//from ww w . j a v a 2s . com block = blockDao.saveBlock(block); sessionStatus.setComplete(); logger.info(user.getUsername() + " added an item to block " + block.getId()); } return "redirect:list"; }
From source file:org.kew.rmf.reconciliation.ws.MatchController.java
/** * Matches the records in the uploaded file. * * Results are put into a temporary file (available for download) and also shown in the web page. *//*from w ww . j a va 2s .c o m*/ @RequestMapping(value = "/filematch/{configName}", method = RequestMethod.POST) public String doFileMatch(@PathVariable String configName, @RequestParam("file") MultipartFile file, HttpServletResponse response, Model model) { logger.info("{}: File match query {}", configName, file); // Map of matches // Key is the ID of supplied records // Entries are a List of Map<String,String> Map<String, List<Map<String, String>>> matches = new HashMap<String, List<Map<String, String>>>(); // Map of supplied data (useful for display) List<Map<String, String>> suppliedData = new ArrayList<Map<String, String>>(); // Temporary file for results File resultsFile; List<String> properties = new ArrayList<String>(); if (!file.isEmpty()) { try { logger.debug("Looking for : " + configName); LuceneMatcher matcher = reconciliationService.getMatcher(configName); if (matcher != null) { resultsFile = File.createTempFile("match-results-", ".csv"); OutputStreamWriter resultsFileWriter = new OutputStreamWriter(new FileOutputStream(resultsFile), "UTF-8"); resultsFileWriter.write("queryId,matchId\n"); // TODO: attempt to use same line ending as input file // Save the property names: for (Property p : matcher.getConfig().getProperties()) { properties.add(p.getQueryColumnName()); } CsvPreference customCsvPref = new CsvPreference.Builder('"', ',', "\n").build(); CsvMapReader mr = new CsvMapReader(new InputStreamReader(file.getInputStream(), "UTF-8"), customCsvPref); final String[] header = mr.getHeader(true); Map<String, String> record = null; while ((record = mr.read(header)) != null) { logger.debug("Next record is {}", record); suppliedData.add(record); try { List<Map<String, String>> theseMatches = matcher.getMatches(record); // Just write out some matches to std out: if (theseMatches != null) { logger.debug("Record ID {}, matched: {}", record.get("id"), theseMatches.size()); } else { logger.debug("Record ID {}, matched: null", record.get("id")); } matches.put(record.get("id"), theseMatches); // Append matche results to file StringBuilder sb = new StringBuilder(); for (Map<String, String> result : theseMatches) { if (sb.length() > 0) sb.append('|'); sb.append(result.get("id")); } sb.insert(0, ',').insert(0, record.get("id")).append("\n"); resultsFileWriter.write(sb.toString()); } catch (TooManyMatchesException | MatchExecutionException e) { logger.error("Problem handling match", e); } } mr.close(); resultsFileWriter.close(); logger.debug("got file's bytes"); model.addAttribute("resultsFile", resultsFile.getName()); response.setHeader("X-File-Download", resultsFile.getName()); // Putting this in a header saves the unit tests from needing to parse the HTML. } model.addAttribute("suppliedData", suppliedData); model.addAttribute("matches", matches); model.addAttribute("properties", properties); } catch (Exception e) { logger.error("Problem reading file", e); } } return "file-matcher-results"; }
From source file:csns.web.controller.SubmissionController.java
@RequestMapping(value = "/submission/upload", method = RequestMethod.POST) public String upload(@RequestParam Long id, @RequestParam boolean additional, @RequestParam MultipartFile uploadedFile, ModelMap models) { User user = SecurityUtils.getUser(); Submission submission = submissionDao.getSubmission(id); boolean isInstructor = submission.getAssignment().getSection().isInstructor(user); String view = additional && isInstructor ? "/submission/add?id=" + id : "/submission/view?id=" + id; if (!isInstructor && submission.isPastDue()) { models.put("message", "error.assignment.pastdue"); models.put("backUrl", view); return "error"; }/* w ww . j a v a 2 s. c om*/ if (!uploadedFile.isEmpty()) { String fileName = uploadedFile.getOriginalFilename(); if (!isInstructor && !submission.getAssignment().isFileExtensionAllowed(File.getFileExtension(fileName))) { models.put("message", "error.assignment.file.type"); models.put("backUrl", view); return "error"; } File file = new File(); file.setName(fileName); file.setType(uploadedFile.getContentType()); file.setSize(uploadedFile.getSize()); file.setDate(new Date()); file.setOwner(submission.getStudent()); file.setSubmission(submission); file = fileDao.saveFile(file); fileIO.save(file, uploadedFile); submission.incrementFileCount(); submissionDao.saveSubmission(submission); logger.info(user.getUsername() + " uploaded file " + file.getId()); } return "redirect:" + view; }