List of usage examples for java.io BufferedOutputStream close
@Override public void close() throws IOException
From source file:com.cloudseal.spring.client.namespace.CloudSealLogoutImageFilter.java
public void writeContent(HttpServletResponse response, String contentType, InputStream content) throws IOException { response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setContentType(contentType); BufferedInputStream input = null; BufferedOutputStream output = null; try {/*w ww . jav a 2 s.co m*/ input = new BufferedInputStream(content, DEFAULT_BUFFER_SIZE); output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int length = 0; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } } finally { output.close(); input.close(); } }
From source file:de.thorstenberger.examServer.service.impl.ConfigManagerImpl.java
private void save() { try {//from w ww .j a v a2 s.c o m final Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true)); final BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(this.configFile)); marshaller.marshal(config, bos); bos.close(); } catch (final JAXBException e) { throw new RuntimeException(e); } catch (final IOException e1) { throw new RuntimeException(e1); } }
From source file:de.tudarmstadt.ukp.dkpro.core.io.mmax2.MMAXWriter.java
/** * Copies a source folder/file to a target folder/file. Used to duplicate the template project and template files. * @param source/*ww w. j a v a 2 s . co m*/ * @param target * @throws IOException */ private void copy(File source, File target) throws IOException { if (source.isFile() && !target.exists()) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); int i; while ((i = in.read()) != -1) { out.write(i); } in.close(); out.close(); log.trace(target.getName() + " copied."); } if (source.isDirectory()) { target.mkdirs(); File[] files = source.listFiles(); for (File file : files) { if (!file.getName().endsWith(".svn")) { // do not copy svn files! copy(file, new File(target, file.getName())); } } } }
From source file:org.iti.agrimarket.service.CategoryRestController.java
/** * Responsible for adding new category/* ww w . j a v a 2 s.c o m*/ * * @param paramJsoncontains Json object of the category's data, and parent * category id * @param user Name of the user sending the request * @param key Encrypted key using the user's key * @param file The image of the product * @return Json {"success":1} if added successfully or status code with the * error */ @RequestMapping(value = Constants.ADD_CATEGORY_URL, method = RequestMethod.POST) public Response addCategory(@RequestBody String paramJson) { //Parse the parameter Category category = paramExtractor.getParam(paramJson, Category.class); //Validate category if (category == null || ((category.getNameAr() == null || category.getNameAr().isEmpty()) && (category.getNameEn() == null || category.getNameEn().isEmpty())) || ((category.getNameAr() != null && category.getNameAr().length() > 44) || (category.getNameEn() != null && category.getNameEn().length() > 44))) { logger.trace(Constants.INVALID_PARAM); return Response.status(Constants.PARAM_ERROR).entity(Constants.INVALID_PARAM).build(); } //Check parent category if (category.getCategory() == null) { category.setCategory(category); } else { Category parent = categoryService.getCategory(category.getCategory().getId()); if (parent == null) { logger.trace(NO_CATEGORY); return Response.status(Constants.PARAM_ERROR).entity(NO_CATEGORY).build(); } category.setCategory(parent); } //Add category categoryService.addCategory(category); if (category == null || category.getId() == -1) { logger.trace(Constants.DB_ERROR); return Response.status(Constants.DB_ERROR).build(); } //Use the generated id to form the image name String name = category.getId() + String.valueOf(new Date().getTime()); //Save image if not empty file if (category.getImage() != null) { try { byte[] bytes = category.getImage(); MagicMatch match = Magic.getMagicMatch(bytes); final String ext = "." + match.getExtension(); File parentDir = new File(Constants.IMAGE_PATH + Constants.CATEGORY_PATH); if (!parentDir.isDirectory()) { parentDir.mkdirs(); } BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(Constants.IMAGE_PATH + Constants.CATEGORY_PATH + name))); stream.write(bytes); stream.close(); //Set the image url in the db category.setImageUrl(Constants.IMAGE_PRE_URL + Constants.CATEGORY_PATH + name + ext); categoryService.updateCategory(category); } catch (Exception e) { logger.error(e.getMessage()); categoryService.deleteCategory(category.getId()); // delete the category if something goes wrong return Response.status(Constants.SERVER_ERROR).entity(Constants.IMAGE_UPLOAD_ERROR).build(); } } else { categoryService.deleteCategory(category.getId()); // delete the category if something goes wrong return Response.status(Constants.SERVER_ERROR).entity(Constants.IMAGE_UPLOAD_ERROR).build(); } return Response.ok(Constants.SUCCESS_JSON, MediaType.APPLICATION_JSON).build(); }
From source file:fr.eoidb.util.ImageDownloader.java
private void flushSingleCacheFileToDisk(Bitmap bitmap, String cacheIconName, Context context) throws IOException { File cacheIconFile = new File(context.getCacheDir(), cacheIconName); if (!cacheIconFile.exists()) { if (BuildConfig.DEBUG) Log.v(LOG_TAG, "Flushing bitmap " + cacheIconName + " to disk..."); cacheIconFile.createNewFile();//from w ww. ja v a 2 s. co m BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(cacheIconFile)); bitmap.compress(CompressFormat.PNG, 100, bos); bos.flush(); bos.close(); } }
From source file:com.oakesville.mythling.util.HttpHelper.java
private void writeRequestBytes(OutputStream os) throws IOException { BufferedOutputStream bos = null; try {/*from w w w.j a va 2 s . c om*/ bos = new BufferedOutputStream(os); bos.write(postContent); } finally { if (bos != null) bos.close(); } }
From source file:com.gsr.myschool.server.reporting.bilan.BilanController.java
@RequestMapping(method = RequestMethod.GET, produces = "application/pdf") @ResponseStatus(HttpStatus.OK)//from w ww. j a v a 2 s. c o m public void generateBilan(@RequestParam(defaultValue = "") String status, @RequestParam String type, @RequestParam(required = false) String annee, @RequestParam(required = false) Boolean historic, HttpServletResponse response) { ReportDTO dto = null; Integer bilanType; DossierStatus dossierStatus = null; ValueList anneeScolaire; try { bilanType = Integer.parseInt(type); if (!Strings.isNullOrEmpty(status)) { dossierStatus = DossierStatus.valueOf(status); } anneeScolaire = valueListRepos.findByValueAndValueTypeCode(annee, ValueTypeCode.SCHOOL_YEAR); if (anneeScolaire == null) { anneeScolaire = getCurrentScholarYear(); } } catch (Exception e) { return; } if (historic) { if (BilanType.CYCLE.ordinal() == bilanType) { dto = getReportCycleHistoric(status, dossierStatus, anneeScolaire); } else if (BilanType.NIVEAU_ETUDE.ordinal() == bilanType) { dto = getReportNiveauEtudeHistoric(status, dossierStatus, anneeScolaire); } } else { if (BilanType.CYCLE.ordinal() == bilanType) { dto = getReportCycle(status, dossierStatus, anneeScolaire); } else if (BilanType.NIVEAU_ETUDE.ordinal() == bilanType) { dto = getReportNiveauEtude(status, dossierStatus, anneeScolaire); } } try { response.addHeader("Content-Disposition", "attachment; filename=" + dto.getFileName()); BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); byte[] result = reportService.generatePdf(dto); outputStream.write(result, 0, result.length); outputStream.flush(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.balero.controllers.UploadController.java
/** * Upload file on server/*w ww . j av a 2s .co m*/ * * @param file HTML <input type="file"> content * @param baleroAdmin Magic cookie * @return home view */ @RequestMapping(method = RequestMethod.POST) public String upload(@RequestParam("file") MultipartFile file, @CookieValue(value = "baleroAdmin", defaultValue = "init") String baleroAdmin, HttpServletRequest request) { // Security UsersAuth security = new UsersAuth(); security.setCredentials(baleroAdmin, UsersDAO); boolean securityFlag = security.auth(baleroAdmin, security.getLocalUsername(), security.getLocalPassword()); if (!securityFlag) return "hacking"; String inputFileName = file.getOriginalFilename(); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // Creating the directory to store file //String rootPath = System.getProperty("catalina.home"); File dir = new File("../webapps/media/uploads"); if (!dir.exists()) dir.mkdirs(); String[] ext = new String[9]; // Add your extension here ext[0] = ".jpg"; ext[1] = ".png"; ext[2] = ".bmp"; ext[3] = ".jpeg"; for (int i = 0; i < ext.length; i++) { int intIndex = inputFileName.indexOf(ext[i]); if (intIndex == -1) { System.out.println("File extension is not valid"); } else { // Create the file on server File serverFile = new File(dir.getAbsolutePath() + File.separator + inputFileName); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile)); stream.write(bytes); stream.close(); } } System.out.println("You successfully uploaded file"); } catch (Exception e) { System.out.println("You failed to upload => " + e.getMessage()); } } else { System.out.println("You failed to upload because the file was empty."); } String referer = request.getHeader("Referer"); return "redirect:" + referer; }
From source file:autonomouspathplanner.ftp.FTP.java
/** * Downloads a file from the server/*from ww w.j a va 2s .co m*/ * @param downloadFile the location to download to * @param initialFile the file location on the server * @return the File that was downloaded, null if operation fails */ public File downloadFromServer(File downloadFile, String initialFile) { try { if (client == null) { if (!connectToServer()) return null; } BufferedOutputStream st = new BufferedOutputStream(new FileOutputStream(downloadFile)); boolean sc = client.retrieveFile(initialFile, st); if (sc) { System.out.println("Download Completed Successfully"); } else System.out.println("Download Failed"); st.close(); } catch (IOException ex) { Logger.getLogger(FTP.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (client.isConnected()) { client.logout(); client.disconnect(); client = null; } } catch (IOException ex) { ex.printStackTrace(); } } return downloadFile; }
From source file:com.balero.controllers.UploadController.java
/** * Upload image from CKEDITOR to server/*from w ww . ja v a 2 s . c o m*/ * * Source: http://alfonsoml.blogspot.mx/2013/08/a-basic- * upload-script-for-ckeditor.html * * @param file HTML <input> * @param model Framework model layer * @param request HTTP headers * @param baleroAdmin Magic cookie * @return view */ @RequestMapping(value = "/picture", method = RequestMethod.POST) public String uploadPicture(@RequestParam("upload") MultipartFile file, Model model, HttpServletRequest request, @CookieValue(value = "baleroAdmin", defaultValue = "init") String baleroAdmin) { // Security UsersAuth security = new UsersAuth(); security.setCredentials(baleroAdmin, UsersDAO); boolean securityFlag = security.auth(baleroAdmin, security.getLocalUsername(), security.getLocalPassword()); if (!securityFlag) return "hacking"; String CKEditorFuncNum = request.getParameter("CKEditorFuncNum"); String inputFileName = file.getOriginalFilename(); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // Creating the directory to store file //String rootPath = System.getProperty("catalina.home"); File dir = new File("../webapps/media/pictures"); if (!dir.exists()) dir.mkdirs(); String[] ext = new String[9]; // Add your extension here ext[0] = ".jpg"; ext[1] = ".png"; ext[2] = ".bmp"; ext[3] = ".jpeg"; for (int i = 0; i < ext.length; i++) { int intIndex = inputFileName.indexOf(ext[i]); if (intIndex == -1) { System.out.println("File extension is not valid"); } else { // Create the file on server File serverFile = new File(dir.getAbsolutePath() + File.separator + inputFileName); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile)); stream.write(bytes); stream.close(); } } System.out.println("You successfully uploaded file"); } catch (Exception e) { System.out.println("You failed to upload => " + e.getMessage()); } } else { System.out.println("You failed to upload because the file was empty."); } //String url = request.getLocalAddr(); model.addAttribute("url", "/media/pictures/" + inputFileName); model.addAttribute("CKEditorFuncNum", CKEditorFuncNum); return "upload"; }