List of usage examples for java.io BufferedOutputStream flush
@Override public synchronized void flush() throws IOException
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 ww w.jav a 2 s . c o 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)/* w w w . j a v a2s .c om*/ 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:com.sun.socialsite.web.rest.servlets.ProxyServlet.java
/** * Handles the HTTP <code>POST</code> method. * @param req servlet request/*from www.j a v a2 s . co m*/ * @param resp servlet response */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { URL url = getURL(req, req.getParameter("uri")); HttpURLConnection con = (HttpURLConnection) (url.openConnection()); con.setDoOutput(true); con.setAllowUserInteraction(false); con.setUseCaches(false); // TODO: figure out why this is necessary for HTTPS URLs if (con instanceof HttpsURLConnection) { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) { return true; } else { log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return false; } } }; ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv); } // pass along all appropriate HTTP headers Enumeration headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String hname = (String) headerNames.nextElement(); if (!unproxiedHeaders.contains(hname.toLowerCase())) { con.addRequestProperty(hname, req.getHeader(hname)); } } con.connect(); // read POST data from incoming request, write to outgoing request BufferedInputStream in = new BufferedInputStream(req.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream()); byte buffer[] = new byte[8192]; for (int count = 0; count != -1;) { count = in.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } in.close(); out.close(); out.flush(); // read result headers of POST, write to response Map<String, List<String>> headers = con.getHeaderFields(); for (String key : headers.keySet()) { if (key != null) { // TODO: why is this check necessary! List<String> header = headers.get(key); if (header.size() > 0) resp.setHeader(key, header.get(0)); } } // read result data of POST, write out to response in = new BufferedInputStream(con.getInputStream()); out = new BufferedOutputStream(resp.getOutputStream()); for (int count = 0; count != -1;) { count = in.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } in.close(); out.close(); out.flush(); con.disconnect(); }
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)) {/* w w w . j a v a2s .co 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 {//from w ww. j ava2s . co m 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: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 ww w .j ava 2 s . com*/ 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()); } }
From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileSelector.java
protected File unzip3(File zf) throws FileNotFoundException { //File f = null; String rename = zf.getAbsolutePath().replaceFirst("\\.zip", identifier + ".xml");//.replaceFirst("\\.gz", ".xml"); File f = new File(rename); try {/*w w w . jav a 2 s . c om*/ FileInputStream fis = new FileInputStream(zf); ZipInputStream zin = new ZipInputStream(fis); ZipEntry ze; final byte[] content = new byte[BUFFER]; while ((ze = zin.getNextEntry()) != null) { f = new File(getCalTempPath() + File.separator + ze.getName()); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos, content.length); int n = 0; while (-1 != (n = zin.read(content))) { bos.write(content, 0, n); } bos.flush(); bos.close(); } fis.close(); zin.close(); } catch (IOException ioe) { jlog.error("Error processing Zip " + zf + " Excluding! :: " + ioe); return null; } //try again... what could go wrong /* if (checkMinFileSize(f) && retry_counter<MAX_UNGZIP_RETRIES){ retry_counter++; f.delete(); f = unzip2(zf); } */ return f; }
From source file:app.common.X3DViewer.java
/** * View an X3D file using an external X3DOM player * * @param grid//from w w w .j a v a2 s. co m * @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:org.docx4j.openpackaging.io3.stores.ZipPartStore.java
private byte[] getBytesFromInputStream(InputStream is) throws Exception { BufferedInputStream bufIn = new BufferedInputStream(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(baos); int c = bufIn.read(); while (c != -1) { bos.write(c);//from w ww . j av a 2s . com c = bufIn.read(); } bos.flush(); baos.flush(); //bufIn.close(); //don't do that, since it closes the ZipInputStream after we've read an entry! bos.close(); return baos.toByteArray(); }
From source file:net.sf.sveditor.core.tests.utils.BundleUtils.java
public void unpackBundleTarToFS(String bundle_path, File fs_path) { URL url = fBundle.getEntry(bundle_path); TestCase.assertNotNull(url);// ww w. j a va2s. c om if (!fs_path.isDirectory()) { TestCase.assertTrue(fs_path.mkdirs()); } InputStream in = null; TarArchiveInputStream tar_stream = null; try { in = url.openStream(); } catch (IOException e) { TestCase.fail("Failed to open data file " + bundle_path + " : " + e.getMessage()); } tar_stream = new TarArchiveInputStream(in); try { byte tmp[] = new byte[4 * 1024]; int cnt; ArchiveEntry te; while ((te = tar_stream.getNextEntry()) != null) { // System.out.println("Entry: \"" + ze.getName() + "\""); File entry_f = new File(fs_path, te.getName()); if (te.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 = tar_stream.read(tmp, 0, tmp.length)) > 0) { bos.write(tmp, 0, cnt); } bos.flush(); bos.close(); fos.close(); // tar_stream.closeEntry(); } tar_stream.close(); } catch (IOException e) { e.printStackTrace(); TestCase.fail("Failed to unpack tar file: " + e.getMessage()); } }