List of usage examples for java.io BufferedOutputStream close
@Override public void close() throws IOException
From source file:org.broadleafcommerce.admin.util.controllers.FileUploadController.java
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws ServletException, IOException { // cast the bean FileUploadBean bean = (FileUploadBean) command; // let's see if there's content there MultipartFile file = bean.getFile(); if (file == null) { // hmm, that's strange, the user did not upload anything }/* w w w.j a v a 2 s . c o m*/ try { String basepath = request.getPathTranslated().substring(0, request.getPathTranslated().indexOf(File.separator + "upload")); String absoluteFilename = basepath + File.separator + bean.getDirectory() + File.separator + file.getOriginalFilename(); FileSystemResource fileResource = new FileSystemResource(absoluteFilename); checkDirectory(basepath + File.separator + bean.getDirectory()); backupExistingFile(fileResource, basepath + bean.getDirectory()); FileOutputStream fout = new FileOutputStream(new FileSystemResource( basepath + File.separator + bean.getDirectory() + File.separator + file.getOriginalFilename()) .getFile()); BufferedOutputStream bout = new BufferedOutputStream(fout); BufferedInputStream bin = new BufferedInputStream(file.getInputStream()); int x; while ((x = bin.read()) != -1) { bout.write(x); } bout.flush(); bout.close(); bin.close(); return super.onSubmit(request, response, command, errors); } catch (Exception e) { //Exception occured; e.printStackTrace(); throw new RuntimeException(e); // return null; } }
From source file:org.caboclo.clients.ApiClient.java
protected void downloadURL(String url, File file, Map<String, String> headers) throws IllegalStateException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); for (String key : headers.keySet()) { String value = headers.get(key); httpget.setHeader(key, value);//from w w w . j av a 2s . co m } HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { try { InputStream instream = entity.getContent(); BufferedInputStream bis = new BufferedInputStream(instream); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); int inByte; while ((inByte = bis.read()) != -1) { bos.write(inByte); } bis.close(); bos.close(); } catch (IOException ex) { throw ex; } catch (IllegalStateException ex) { httpget.abort(); throw ex; } httpclient.getConnectionManager().shutdown(); } }
From source file:com.gsr.myschool.server.reporting.bilan.SummaryController.java
@RequestMapping(method = RequestMethod.GET, produces = "application/vnd.ms-excel") @ResponseStatus(HttpStatus.OK)/*from ww w . jav a 2s .co m*/ public void generateBilan(@RequestParam(required = false) String annee, HttpServletResponse response) { ValueList anneeScolaire; try { anneeScolaire = valueListRepos.findByValueAndValueTypeCode(annee, ValueTypeCode.SCHOOL_YEAR); if (anneeScolaire == null) { anneeScolaire = getCurrentScholarYear(); } } catch (Exception e) { return; } List<SummaryExcelDTO> dto = getReportSummary(anneeScolaire); try { response.addHeader("Content-Disposition", "attachment; filename=summary.xls"); BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); xlsExportService.saveSpreadsheetRecords(SummaryExcelDTO.class, dto, outputStream); outputStream.flush(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.company.project.web.controller.FileUploadController.java
@RequestMapping(value = "/multipleSave", method = RequestMethod.POST) public @ResponseBody String multipleSave(@RequestParam("file") MultipartFile[] files) { String fileName = null;/* w ww. j a v a 2s . c o m*/ String msg = ""; if (files != null && files.length > 0) { for (int i = 0; i < files.length; i++) { try { fileName = files[i].getOriginalFilename(); byte[] bytes = files[i].getBytes(); BufferedOutputStream buffStream = new BufferedOutputStream( new FileOutputStream(new File("C:/cp/" + fileName))); buffStream.write(bytes); buffStream.close(); msg += "You have successfully uploaded " + fileName + "<br/>"; } catch (Exception e) { return "You failed to upload " + fileName + ": " + e.getMessage() + "<br/>"; } } return msg; } else { return "Unable to upload. File is empty."; } }
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)) {/*from w ww . j a v a 2 s.co m*/ 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.groupon.odo.controllers.BackupController.java
/** * Set client server configuration and overrides according to backup * * @param fileData File containing profile overrides and server configuration * @param profileID Profile to update for client * @param clientUUID Client to apply overrides to * @param odoImport Param to determine if an odo config will be imported with the overrides import * @return// w w w.j a va2 s . c o m * @throws Exception */ @RequestMapping(value = "/api/backup/profile/{profileID}/{clientUUID}", method = RequestMethod.POST) public @ResponseBody ResponseEntity<String> processSingleProfileBackup( @RequestParam("fileData") MultipartFile fileData, @PathVariable int profileID, @PathVariable String clientUUID, @RequestParam(value = "odoImport", defaultValue = "false") boolean odoImport) throws Exception { if (!fileData.isEmpty()) { try { // Read in file InputStream inputStream = fileData.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String singleLine; String fullFileString = ""; while ((singleLine = bufferedReader.readLine()) != null) { fullFileString += singleLine; } JSONObject fileBackup = new JSONObject(fullFileString); if (odoImport) { JSONObject odoBackup = fileBackup.getJSONObject("odoBackup"); byte[] bytes = odoBackup.toString().getBytes(); // Save to second file to be used in importing odo configuration BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File("backup-uploaded.json"))); stream.write(bytes); stream.close(); File f = new File("backup-uploaded.json"); BackupService.getInstance().restoreBackupData(new FileInputStream(f)); } // Get profile backup if json contained both profile backup and odo backup if (fileBackup.has("profileBackup")) { fileBackup = fileBackup.getJSONObject("profileBackup"); } // Import profile overrides BackupService.getInstance().setProfileFromBackup(fileBackup, profileID, clientUUID); } catch (Exception e) { try { JSONArray errorArray = new JSONArray(e.getMessage()); return new ResponseEntity<>(errorArray.toString(), HttpStatus.BAD_REQUEST); } catch (Exception k) { // Catch for exceptions other than ones defined in backup service return new ResponseEntity<>("[{\"error\" : \"Upload Error\"}]", HttpStatus.BAD_REQUEST); } } } return new ResponseEntity<>(HttpStatus.OK); }
From source file:eu.scape_project.planning.plato.wf.ValidatePlan.java
public void deployPlan(String endpoint, String user, String password) throws PlanningException { SCAPEPlanManagementClient planManagement = new SCAPEPlanManagementClient(endpoint, user, password); String planIdentifier;/*from ww w . j a va 2s. c o m*/ try { planIdentifier = planManagement.reservePlanIdentifier(); } catch (Exception e) { throw new PlanningException("Could not reserve Identifier.", e); } catch (Throwable e) { throw new PlanningException("Could not reserve Identifier.", e); } this.plan.getPlanProperties().setRepositoryIdentifier(planIdentifier); saveWithoutModifyingPlanState(); String binarydataTempPath = OS.getTmpPath() + planIdentifier + "/"; File binarydataTempDir = new File(binarydataTempPath); binarydataTempDir.mkdirs(); File planFile = new File(binarydataTempPath + "plan.xml"); try { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(planFile)); projectExport.exportComplete(plan.getPlanProperties().getId(), out, binarydataTempPath); out.flush(); out.close(); planManagement.deployPlan(planIdentifier, new FileInputStream(planFile)); } catch (Exception e) { throw new PlanningException("Failed to generate plan.", e); } } finally { OS.deleteDirectory(binarydataTempDir); } }
From source file:org.kievguide.controller.UserController.java
@RequestMapping(value = "/settingssave", method = RequestMethod.POST) public ModelAndView settingsSave(@CookieValue(value = "userstatus", defaultValue = "guest") String useremail, @RequestParam("firstname") String firstname, @RequestParam("lastname") String lastname, @RequestParam("email") String email, @RequestParam("password") String password, @RequestParam("photosrc") MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws FileNotFoundException, IOException { ModelAndView modelAndView = new ModelAndView(); SecureRandom random = new SecureRandom(); String photoname = new BigInteger(130, random).toString(32); Place place = new Place(); User user = userService.searchUser(useremail); user.setFirstname(firstname);//www . jav a 2 s . c om user.setLastname(lastname); user.setPassword(password); user.setEmail(email); if (!file.isEmpty()) { String folder = request.getSession().getServletContext().getRealPath(""); folder = folder.substring(0, 30); BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(folder + "/src/main/webapp/img/" + photoname + ".jpg"))); FileCopyUtils.copy(file.getInputStream(), stream); stream.close(); user.setPhotosrc("img/" + photoname + ".jpg"); } userService.addUser(user); Cookie userCookie = new Cookie("userstatus", user.getEmail()); response.addCookie(userCookie); String userStatus = Util.userPanel(user.getEmail()); modelAndView.addObject("userstatus", userStatus); return new ModelAndView("redirect:" + "firstrequest"); }
From source file:org.openmrs.module.bannerprototype.web.controller.bannerprototypeManageController.java
@RequestMapping(value = "/module/bannerprototype/upload", method = RequestMethod.POST) public @ResponseBody String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) throws IOException { String path = new ClassPathResource("taggers/").getURL().getPath(); if (!file.isEmpty()) { try {/*from ww w . java 2s.c o m*/ byte[] bytes = file.getBytes(); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(path + name))); stream.write(bytes); stream.close(); return "You successfully uploaded " + name + "!\n<a href=manage.form>back</a>"; } catch (FileNotFoundException ex) { ex.printStackTrace(); return "ERROR: Please name your file"; } catch (Exception e) { e.printStackTrace(); return "You failed to upload " + name + " => " + e.getMessage(); } } else { return "You failed to upload " + name + " because the file was empty."; } }
From source file:echopoint.tucana.event.DefaultUploadCallback.java
/** * Over-ridden to save the contents of the uploaded file to {@link #directory}. * Client-code should ideally wrap this method in a try-catch clause to * handle file copying errors and update the UI as appropriate. * * {@inheritDoc}/*from ww w .j av a2s . co m*/ * @throws RuntimeException If errors are encountered while copying the * uploaded file to the specified directory. */ @Override public void uploadSucceeded(final UploadFinishEvent event) { final File temp = getTempFile(); final File file = getFileName(event.getFileName()); try { event.getFileItem().write(temp); if (!temp.renameTo(file)) { final BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(temp)); IOUtils.copy(bis, bos); bis.close(); bos.close(); temp.delete(); logger.log(level, "Rename of temp file to " + file.getAbsolutePath() + " failed. Recopied from source."); } event.getFileItem().delete(); logger.log(level, "Copied upload file contents to: " + file.getAbsolutePath()); } catch (Exception e) { throw new RuntimeException("Error copying uploaded file!", e); } super.uploadSucceeded(event); }