List of usage examples for java.io BufferedOutputStream close
@Override public void close() throws IOException
From source file:com.gsr.myschool.server.reporting.convocation.ConvocationServiceImpl.java
@Override public File generateConvocation(Dossier dossier) { DossierSession dossierSession = dossierSessionRepos.findByDossierId(dossier.getId()); List<InfoParent> parents = infoParentRepos.findByDossierId(dossier.getId()); NiveauEtude niveauEtude = dossier.getNiveauEtude(); SessionExamen session = dossierSession.getSessionExamen(); if (niveauEtude == null || session == null) return null; List<SessionNiveauEtude> matieres = sessionExamenNERepos .findBySessionExamenIdAndNiveauEtudeId(session.getId(), niveauEtude.getId()); SimpleDateFormat dateFormat = new SimpleDateFormat(GlobalParameters.DATE_FORMAT); ReportDTO dto;// w ww . j ava 2 s . c om Map<String, Object> myMap = new HashMap<String, Object>(); myMap.put("date", dateFormat.format(new Date())); if (session.getDateSession() != null) { myMap.put("dateTest", dateFormat.format(session.getDateSession())); } else { myMap.put("dateTest", "8:00"); } myMap.put("heureAccueilDebut", session.getWelcomKids()); myMap.put("heureAccueilFin", "8:00"); myMap.put("heureDebut", session.getDebutTest()); myMap.put("heureRecuperation", session.getGatherKids()); myMap.put("niveauEtude", niveauEtude.getNom()); myMap.put("section", niveauEtude.getFiliere().getNom()); myMap.put("adresse", session.getAdresse()); myMap.put("phone", session.getTelephone()); for (InfoParent parent : parents) { if (!Strings.isNullOrEmpty(parent.getNom())) { myMap.put("nomParent", parent.getNom()); } } myMap.put("prenomEnfant", dossier.getCandidat().getFirstname()); if (niveauEtude.getAnnee() <= 5) { dto = new ReportDTO(reportMSGS); } else if (niveauEtude.getAnnee() >= 6 && niveauEtude.getAnnee() <= 10) { dto = new ReportDTO(reportCP); List<Map> myList = new ArrayList<Map>(); for (SessionNiveauEtude matiere : matieres) { myList.add(matiere.getReportsAttributes()); } myMap.put("matieres", myList); } else if (niveauEtude.getAnnee() >= 11 && niveauEtude.getAnnee() <= 17) { dto = new ReportDTO(reportSeconde); List<Map> myList = new ArrayList<Map>(); for (SessionNiveauEtude matiere : matieres) { myList.add(matiere.getReportsAttributes()); } myMap.put("matieres", myList); } else { dto = new ReportDTO(convocationPrepa); List<Map> myList = new ArrayList<Map>(); for (SessionNiveauEtude matiere : matieres) { myList.add(matiere.getReportsAttributes()); } myMap.put("matieres", myList); myMap.put("prenomEnfant", dossier.getCandidat().getFirstname() + " " + dossier.getCandidat().getLastname()); if (dossier.getCandidat().getBacSerie() != null) { myMap.put("typeBac", dossier.getCandidat().getBacSerie().getValue()); } myMap.put("anneeScolaire", DateUtils.currentYear() + "-" + (DateUtils.currentYear() + 1)); myMap.put("session", session.getNom()); } dto.setReportParameters(myMap); try { File convocation = new File("convocation_" + dossier.getGeneratedNumDossier() + ".pdf"); FileOutputStream fs = new FileOutputStream(convocation); BufferedOutputStream outputStream = new BufferedOutputStream(fs); byte[] result = reportService.generatePdf(dto); outputStream.write(result, 0, result.length); outputStream.flush(); outputStream.close(); return convocation; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:edu.cloud.iot.reception.ocr.FaceRecognitionActivity.java
public void saveImage(String pPath, String pDir, Bitmap img) { try {/* w ww. java 2 s . c om*/ FileOutputStream fos = new FileOutputStream(pPath + pDir); BufferedOutputStream bos = new BufferedOutputStream(fos); // Compress Bitmap Image image.compress(Bitmap.CompressFormat.JPEG, 50, bos); bos.flush(); bos.close(); } catch (Exception ex) { ex.printStackTrace(); Log.v("EDebug::FaceRecognitionActivity", ex.getMessage()); } }
From source file:julie.com.mikaelson.file.controller.FileInfoController.java
@RequestMapping(value = "/uploadfile", method = RequestMethod.POST) @ResponseBody/* w ww .ja v a2 s . c o m*/ public Map<String, Object> handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = request.getParameter("image_file"); fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8"); String overFlg = request.getParameter("over"); // 0:go on;1:over System.out.println("get: " + fileName); byte[] buf = new byte[1024]; File file = new File("./" + /* * "[" + * UUID.randomUUID().toString() + * "]" + */fileName); InputStream is = null; BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(file, true)); try { is = request.getInputStream(); while (true) { int bytesIn = is.read(buf, 0, 1024); System.out.println(bytesIn); if (bytesIn == -1) { break; } else { fileOut.write(buf, 0, bytesIn); } } fileOut.flush(); fileOut.close(); System.out.println(file.getAbsolutePath()); } catch (IOException e) { System.out.println("error info"); } Map<String, Object> map = new HashMap<String, Object>(); map.put("over", overFlg); map.put("data", fileName); return map; }
From source file:com.fluidops.iwb.deepzoom.ImageLoader.java
private void generateIDCard(URI uri, Map<URI, Set<Value>> facets, String url, File file) { int width = 200; int height = 200; BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D ig2 = bi.createGraphics(); ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ig2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); /* Special ID card handling for certain entity types */ /* TODO: special images based on type if(facets.containsKey(RDF.TYPE)) {/*from w w w . j av a 2 s .c o m*/ Set<Value> facet = facets.get(RDF.TYPE); for(Value v : facet) { if(v.equals(Vocabulary.DCAT_DATASET)) { Image img = null; try { img = ImageIO.read( new File( "webapps/ROOT/images/rdf.jpg" ) ); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error("Could not get image"); } ig2.drawImage( img, 0, 0, null ); break; } } } */ String label = EndpointImpl.api().getDataManager().getLabel(uri); Font font = new Font(Font.SANS_SERIF, Font.BOLD, 20); ig2.setFont(font); FontMetrics fontMetrics = ig2.getFontMetrics(); int labelwidth = fontMetrics.stringWidth(label); if (labelwidth >= width) { int fontsize = 20 * width / labelwidth; font = new Font(Font.SANS_SERIF, Font.BOLD, fontsize); ig2.setFont(font); fontMetrics = ig2.getFontMetrics(); } int x = (width - fontMetrics.stringWidth(label)) / 2; int y = (fontMetrics.getAscent() + (height - (fontMetrics.getAscent() + fontMetrics.getDescent())) / 2); ig2.setPaint(Color.black); ig2.drawString(label, x, y); BufferedOutputStream out; try { out = new BufferedOutputStream(new FileOutputStream(file)); ImageIO.write(bi, "PNG", out); out.flush(); out.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } }
From source file:com.glaf.core.util.ZipUtils.java
public static byte[] getZipBytes(Map<String, InputStream> dataMap) { byte[] bytes = null; try {/* w w w . j av a2 s. c om*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(baos); JarOutputStream jos = new JarOutputStream(bos); if (dataMap != null) { Set<Entry<String, InputStream>> entrySet = dataMap.entrySet(); for (Entry<String, InputStream> entry : entrySet) { String name = entry.getKey(); InputStream inputStream = entry.getValue(); if (name != null && inputStream != null) { BufferedInputStream bis = new BufferedInputStream(inputStream); JarEntry jarEntry = new JarEntry(name); jos.putNextEntry(jarEntry); while ((len = bis.read(buf)) >= 0) { jos.write(buf, 0, len); } bis.close(); jos.closeEntry(); } } } jos.flush(); jos.close(); bos.flush(); bos.close(); bytes = baos.toByteArray(); baos.close(); return bytes; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.gsr.myschool.server.reporting.excel.ExcelController.java
@RequestMapping(method = RequestMethod.GET, value = "/excel", produces = "application/vnd.ms-excel") @ResponseStatus(HttpStatus.OK)/*from w w w. j a v a 2s . co m*/ public void generateExcel(@RequestParam String fileName, HttpServletRequest request, HttpServletResponse response) { try { final int buffersize = 1024; final byte[] buffer = new byte[buffersize]; response.addHeader("Content-Disposition", "attachment; filename=recherche.xls"); File file = new File( request.getSession().getServletContext().getRealPath("/") + TMP_FOLDER_PATH + fileName); InputStream inputStream = new FileInputStream(file); BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); int available = 0; while ((available = inputStream.read(buffer)) >= 0) { outputStream.write(buffer, 0, available); } inputStream.close(); outputStream.flush(); outputStream.close(); file.delete(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.gsr.myschool.server.reporting.excel.ExcelController.java
@RequestMapping(method = RequestMethod.GET, value = "/dossierconvoques", produces = "application/vnd.ms-excel") @ResponseStatus(HttpStatus.OK)/*www .j a v a2s.c o m*/ public void generateDossierConvoquesExcel(@RequestParam String fileName, HttpServletRequest request, HttpServletResponse response) { try { final int buffersize = 1024; final byte[] buffer = new byte[buffersize]; response.addHeader("Content-Disposition", "attachment; filename=dossierconvoques.xls"); File file = new File( request.getSession().getServletContext().getRealPath("/") + TMP_FOLDER_PATH + fileName); InputStream inputStream = new FileInputStream(file); BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); int available = 0; while ((available = inputStream.read(buffer)) >= 0) { outputStream.write(buffer, 0, available); } inputStream.close(); outputStream.flush(); outputStream.close(); file.delete(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:app.common.X3DViewer.java
/** * View an X3D file using an external X3DOM player * * @param grid//from w w w . ja v a2s . c om * @param smoothSteps * @param maxDecimateError * @throws IOException */ public static void viewX3DOM(Grid grid, int smoothSteps, double maxDecimateError) throws IOException { // TODO: Make thread safe using tempDir String dest = "/tmp/ringpopper/"; File dir = new File(dest); dir.mkdirs(); String pf = "x3dom/x3dom.css"; String dest_pf = dest + pf; File dest_file = new File(dest_pf); File src_file = new File("src/html/" + pf); if (!dest_file.exists()) { System.out.println("Copying file: " + src_file + " to dir: " + dest); FileUtils.copyFile(src_file, dest_file, true); } pf = "x3dom/x3dom.js"; dest_pf = dest + pf; dest_file = new File(dest_pf); src_file = new File("src/html/" + pf); if (!dest_file.exists()) { System.out.println("Copying file: " + src_file + " to dir: " + dest); FileUtils.copyFile(src_file, dest_file, true); } File f = new File("/tmp/ringpopper/out.xhtml"); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos); PrintStream ps = new PrintStream(bos); try { ps.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); ps.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); ps.println("<head>"); ps.println("<meta http-equiv=\"X-UA-Compatible\" content=\"chrome=1\" />"); ps.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />"); ps.println("<title>Ring Popper Demo</title>"); // ps.println("<link rel='stylesheet' type='text/css' href='http://www.x3dom.org/x3dom/release/x3dom.css'></link>"); ps.println("<link rel='stylesheet' type='text/css' href='x3dom/x3dom.css'></link>"); ps.println("</head>"); ps.println("<body>"); ps.println("<p class='case'>"); GridSaver.writeIsosurfaceMaker(grid, bos, "x3d", smoothSteps, maxDecimateError); // ps.println("<script type='text/javascript' src='http://www.x3dom.org/x3dom/release/x3dom.js'></script>"); ps.println("<script type='text/javascript' src='x3dom/x3dom.js'></script>"); ps.println("</p>"); ps.println("</body></html>"); } finally { bos.flush(); bos.close(); fos.close(); } Desktop.getDesktop().browse(f.toURI()); }
From source file:com.cognitivabrasil.repositorio.web.FileController.java
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) @ResponseBody/*from w w w. ja v a2s. c om*/ public String upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, org.apache.commons.fileupload.FileUploadException { if (file == null) { file = new Files(); file.setSizeInBytes(0L); } Integer docId = null; String docPath = null; String responseString = RESP_SUCCESS; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { try { ServletFileUpload x = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem> items = x.parseRequest(request); for (FileItem item : items) { InputStream input = item.getInputStream(); // Handle a form field. if (item.isFormField()) { String attribute = item.getFieldName(); String value = Streams.asString(input); switch (attribute) { case "chunks": this.chunks = Integer.parseInt(value); break; case "chunk": this.chunk = Integer.parseInt(value); break; case "filename": file.setName(value); break; case "docId": if (value.isEmpty()) { throw new org.apache.commons.fileupload.FileUploadException( "No foi informado o id do documento."); } docId = Integer.parseInt(value); docPath = Config.FILE_PATH + "/" + docId; File documentPath = new File(docPath); // cria o diretorio documentPath.mkdirs(); break; default: break; } } // Handle a multi-part MIME encoded file. else { try { File uploadFile = new File(docPath, item.getName()); BufferedOutputStream bufferedOutput; bufferedOutput = new BufferedOutputStream(new FileOutputStream(uploadFile, true)); byte[] data = item.get(); bufferedOutput.write(data); bufferedOutput.close(); } catch (Exception e) { LOG.error("Erro ao salvar o arquivo.", e); file = null; throw e; } finally { if (input != null) { try { input.close(); } catch (IOException e) { LOG.error("Erro ao fechar o ImputStream", e); } } file.setName(item.getName()); file.setContentType(item.getContentType()); file.setPartialSize(item.getSize()); } } } if ((this.chunk == this.chunks - 1) || this.chunks == 0) { file.setLocation(docPath + "/" + file.getName()); if (docId != null) { file.setDocument(documentsService.get(docId)); } fileService.save(file); file = null; } } catch (org.apache.commons.fileupload.FileUploadException | IOException | NumberFormatException e) { responseString = RESP_ERROR; LOG.error("Erro ao salvar o arquivo", e); file = null; throw e; } } // Not a multi-part MIME request. else { responseString = RESP_ERROR; } response.setContentType("application/json"); byte[] responseBytes = responseString.getBytes(); response.setContentLength(responseBytes.length); ServletOutputStream output = response.getOutputStream(); output.write(responseBytes); output.flush(); return responseString; }
From source file:net.sf.sveditor.core.tests.utils.BundleUtils.java
public void unpackBundleZipToFS(String bundle_path, File fs_path) { URL zip_url = fBundle.getEntry(bundle_path); TestCase.assertNotNull(zip_url);/*from w w w . ja va 2 s . c o m*/ if (!fs_path.isDirectory()) { TestCase.assertTrue(fs_path.mkdirs()); } try { InputStream in = zip_url.openStream(); TestCase.assertNotNull(in); byte tmp[] = new byte[4 * 1024]; int cnt; ZipInputStream zin = new ZipInputStream(in); ZipEntry ze; while ((ze = zin.getNextEntry()) != null) { // System.out.println("Entry: \"" + ze.getName() + "\""); File entry_f = new File(fs_path, ze.getName()); if (ze.getName().endsWith("/")) { // Directory continue; } if (!entry_f.getParentFile().exists()) { TestCase.assertTrue(entry_f.getParentFile().mkdirs()); } FileOutputStream fos = new FileOutputStream(entry_f); BufferedOutputStream bos = new BufferedOutputStream(fos, tmp.length); while ((cnt = zin.read(tmp, 0, tmp.length)) > 0) { bos.write(tmp, 0, cnt); } bos.flush(); bos.close(); fos.close(); zin.closeEntry(); } zin.close(); } catch (IOException e) { e.printStackTrace(); TestCase.fail("Failed to unpack zip file: " + e.getMessage()); } }