List of usage examples for java.io BufferedOutputStream flush
@Override public synchronized void flush() throws IOException
From source file:com.vtls.opensource.jhove.JHOVEDocumentFactory.java
/** * Get a JHOVE Document from a {@link URL} source * @param _uri a resource URL// w w w . jav a 2 s. co m * @param _stream an input stream code * @return a JDOM Document * @throws IOException * @throws JDOMException */ public Document getDocument(InputStream _stream, String _uri) throws IOException, JDOMException { RepInfo representation = new RepInfo(_uri); File file = File.createTempFile("vtls-jhove-", ""); file.deleteOnExit(); BufferedOutputStream output_stream = new BufferedOutputStream(new FileOutputStream(file)); BufferedInputStream input_stream = new BufferedInputStream(_stream); int stream_byte; while ((stream_byte = input_stream.read()) != -1) { output_stream.write(stream_byte); } output_stream.flush(); output_stream.close(); input_stream.close(); representation.setSize(file.length()); representation.setLastModified(new Date()); populateRepresentation(representation, file); file.delete(); return getDocumentFromRepresentation(representation); }
From source file:org.codelabor.system.file.web.spring.controller.FileController.java
@RequestMapping("/view") public void view(@RequestParam("fileId") String fileId, HttpServletResponse response) throws Exception { StringBuilder stringBuilder = null; FileDTO fileDTO;//from w w w . j av a 2 s . com fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); InputStream inputStream = null; if (StringUtils.isNotEmpty(repositoryPath)) { // FILE_SYSTEM stringBuilder = new StringBuilder(); stringBuilder.append(repositoryPath); if (!repositoryPath.endsWith(File.separator)) { stringBuilder.append(File.separator); } stringBuilder.append(uniqueFilename); File file = new File(stringBuilder.toString()); inputStream = new FileInputStream(file); } else { // DATABASE byte[] bytes = new byte[] {}; if (fileDTO.getFileSize() > 0) { bytes = fileDTO.getBytes(); } inputStream = new ByteArrayInputStream(bytes); } response.setContentType(fileDTO.getContentType()); // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream); int bytesRead; byte buffer[] = new byte[2048]; while ((bytesRead = bufferdInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } // flush stream bufferedOutputStream.flush(); // close stream inputStream.close(); bufferdInputStream.close(); servletOutputStream.close(); bufferedOutputStream.close(); }
From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java
private void extractBody(Part Mess, cfArrayData AD, String attachURI, String attachDIR) throws Exception { if (Mess.isMimeType("multipart/*")) { Multipart mp = (Multipart) Mess.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) extractBody(mp.getBodyPart(i), AD, attachURI, attachDIR); } else {/*from www . j a v a 2 s. c o m*/ cfStructData sd = new cfStructData(); String tmp = Mess.getContentType(); if (tmp.indexOf(";") != -1) tmp = tmp.substring(0, tmp.indexOf(";")); sd.setData("mimetype", new cfStringData(tmp)); String filename = getFilename(Mess); String dispos = getDisposition(Mess); MimeType messtype = new MimeType(tmp); // Note that we can't use Mess.isMimeType() here due to bug #2080 if ((dispos == null || dispos.equalsIgnoreCase(Part.INLINE)) && messtype.match("text/*")) { Object content; String contentType = Mess.getContentType().toLowerCase(); // support aliases of UTF-7 - UTF7, UNICODE-1-1-UTF-7, csUnicode11UTF7, UNICODE-2-0-UTF-7 if (contentType.indexOf("utf-7") != -1 || contentType.indexOf("utf7") != -1) { InputStream ins = Mess.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(ins, bos); content = new String(UTF7Converter.convert(bos.toByteArray())); } else { try { content = Mess.getContent(); } catch (UnsupportedEncodingException e) { content = Mess.getInputStream(); } catch (IOException ioe) { // This will happen on BD/Java when the attachment has no content // NOTE: this is the fix for bug NA#3198. content = ""; } } if (content instanceof InputStream) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy((InputStream) content, bos); sd.setData("content", new cfStringData(new String(bos.toByteArray()))); } else { sd.setData("content", new cfStringData(content.toString())); } sd.setData("file", cfBooleanData.FALSE); sd.setData("filename", new cfStringData(filename == null ? "" : filename)); } else if (attachDIR != null) { sd.setData("content", new cfStringData("")); if (filename == null || filename.length() == 0) filename = "unknownfile"; filename = getAttachedFilename(attachDIR, filename); //--[ An attachment, save it out to disk try { BufferedInputStream in = new BufferedInputStream(Mess.getInputStream()); BufferedOutputStream out = new BufferedOutputStream( cfEngine.thisPlatform.getFileIO().getFileOutputStream(new File(attachDIR + filename))); IOUtils.copy(in, out); out.flush(); out.close(); in.close(); sd.setData("file", cfBooleanData.TRUE); sd.setData("filename", new cfStringData(filename)); if (attachURI.charAt(attachURI.length() - 1) != '/') sd.setData("url", new cfStringData(attachURI + '/' + filename)); else sd.setData("url", new cfStringData(attachURI + filename)); sd.setData("size", new cfNumberData((int) new File(attachDIR + filename).length())); } catch (Exception ignoreException) { // NOTE: this could happen when we don't have permission to write to the specified directory // so let's log an error message to make this easier to debug. cfEngine.log("-] Failed to save attachment to " + attachDIR + filename + ", exception=[" + ignoreException.toString() + "]"); } } else { sd.setData("file", cfBooleanData.FALSE); sd.setData("content", new cfStringData("")); } AD.addElement(sd); } }
From source file:org.codelabor.system.file.web.spring.controller.FileController.java
@RequestMapping("/download") public void download(@RequestHeader("User-Agent") String userAgent, @RequestParam("fileId") String fileId, HttpServletResponse response) throws Exception { FileDTO fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); InputStream inputStream = null; StringBuilder sb = new StringBuilder(); if (StringUtils.isNotEmpty(repositoryPath)) { // FILE_SYSTEM sb.append(repositoryPath);/*from w ww . ja v a2s .co m*/ if (!repositoryPath.endsWith(File.separator)) { sb.append(File.separator); } sb.append(uniqueFilename); File file = new File(sb.toString()); inputStream = new FileInputStream(file); } else { // DATABASE byte[] bytes = new byte[] {}; if (fileDTO.getFileSize() > 0) { bytes = fileDTO.getBytes(); } inputStream = new ByteArrayInputStream(bytes); } // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE); sb.setLength(0); if (userAgent.indexOf("MSIE5.5") > -1) { sb.append("filename="); } else { sb.append("attachment; filename="); } sb.append(encodedRealFilename); response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString()); logger.debug("header: {}", sb.toString()); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream); int bytesRead; byte buffer[] = new byte[2048]; while ((bytesRead = bufferdInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } // flush stream bufferedOutputStream.flush(); // close stream inputStream.close(); bufferdInputStream.close(); servletOutputStream.close(); bufferedOutputStream.close(); }
From source file:org.fcrepo.localservices.imagemanip.ImageManipulation.java
/** * Method automatically called by browser to handle image manipulations. * /*from ww w. j a v a2 s .co m*/ * @param req * Browser request to servlet res Response sent back to browser after * image manipulation * @throws IOException * If an input or output exception occurred ServletException If a * servlet exception occurred */ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { System.setProperty("java.awt.headless", "true"); // collect all possible parameters for servlet String url = req.getParameter("url"); String op = req.getParameter("op"); String newWidth = req.getParameter("newWidth"); String brightAmt = req.getParameter("brightAmt"); String zoomAmt = req.getParameter("zoomAmt"); String wmText = req.getParameter("wmText"); String cropX = req.getParameter("cropX"); String cropY = req.getParameter("cropY"); String cropWidth = req.getParameter("cropWidth"); String cropHeight = req.getParameter("cropHeight"); String convertTo = req.getParameter("convertTo"); if (convertTo != null) { convertTo = convertTo.toLowerCase(); } try { if (op == null) { throw new ServletException("op parameter not specified."); } String outputMimeType; // get the image via url and put it into the ImagePlus processor. BufferedImage img = getImage(url); // do watermarking stuff if (op.equals("watermark")) { if (wmText == null) { throw new ServletException("Must specify wmText."); } Graphics g = img.getGraphics(); int fontSize = img.getWidth() * 3 / 100; if (fontSize < 10) { fontSize = 10; } g.setFont(new Font("Lucida Sans", Font.BOLD, fontSize)); FontMetrics fm = g.getFontMetrics(); int stringWidth = (int) fm.getStringBounds(wmText, g).getWidth(); int x = img.getWidth() / 2 - stringWidth / 2; int y = img.getHeight() - fm.getHeight(); g.setColor(new Color(180, 180, 180)); g.fill3DRect(x - 10, y - fm.getHeight() - 4, stringWidth + 20, fm.getHeight() + 12, true); g.setColor(new Color(100, 100, 100)); g.drawString(wmText, x + 2, y + 2); g.setColor(new Color(240, 240, 240)); g.drawString(wmText, x, y); } ImageProcessor ip = new ImagePlus("temp", img).getProcessor(); // if the inputMimeType is image/gif, need to convert to RGB in any case if (inputMimeType.equals("image/gif")) { ip = ip.convertToRGB(); alreadyConvertedToRGB = true; } // causes scale() and resize() to do bilinear interpolation ip.setInterpolate(true); if (!op.equals("convert")) { if (op.equals("resize")) { ip = resize(ip, newWidth); } else if (op.equals("zoom")) { ip = zoom(ip, zoomAmt); } else if (op.equals("brightness")) { ip = brightness(ip, brightAmt); } else if (op.equals("watermark")) { // this is now taken care of beforehand (see above) } else if (op.equals("grayscale")) { ip = grayscale(ip); } else if (op.equals("crop")) { ip = crop(ip, cropX, cropY, cropWidth, cropHeight); } else { throw new ServletException("Invalid operation: " + op); } outputMimeType = inputMimeType; } else { if (convertTo == null) { throw new ServletException("Neither op nor convertTo was specified."); } if (convertTo.equals("jpg") || convertTo.equals("jpeg")) { outputMimeType = "image/jpeg"; } else if (convertTo.equals("gif")) { outputMimeType = "image/gif"; } else if (convertTo.equals("tiff")) { outputMimeType = "image/tiff"; } else if (convertTo.equals("bmp")) { outputMimeType = "image/bmp"; } else if (convertTo.equals("png")) { outputMimeType = "image/png"; } else { throw new ServletException("Invalid format: " + convertTo); } } res.setContentType(outputMimeType); BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream()); outputImage(ip, out, outputMimeType); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getClass().getName() + ": " + e.getMessage()); } }
From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileSelector.java
/** * extract tarfile to constituent parts processing gzips along the way * yyyyMMdd.tar->/yyyyMMdd/INode-CH_RNC01/A2010...gz *//*from ww w. ja v a 2 s. com*/ protected void untar(File tf) throws FileNotFoundException { try { TarArchiveInputStream tais = new TarArchiveInputStream(new FileInputStream(tf)); TarArchiveEntry t1 = null; while ((t1 = tais.getNextTarEntry()) != null) { if (t1.isDirectory()) { if (t1.getName().contains("account")) identifier = ".vcc"; else identifier = ""; } else { String fn = t1.getName().substring(t1.getName().lastIndexOf("/")); File f = new File(getCalTempPath() + fn); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER); int n = 0; byte[] content = new byte[BUFFER]; while (-1 != (n = tais.read(content))) { fos.write(content, 0, n); } bos.flush(); bos.close(); fos.close(); File unz = null; if (f.getName().endsWith("zip")) unz = unzip3(f); else unz = ungzip(f); if (unz != null) allfiles.add(unz); f.delete(); } } tais.close(); } catch (IOException ioe) { jlog.fatal("IO read error :: " + ioe); } }
From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileSelector.java
/** * Top unzip method. extract tarfile to constituent parts processing gzips * along the way e.g. yyyyMMdd.zip->/yyyyMMdd/INode-CH_RNC01/A2010...zip */// w ww . jav a2s. co m protected void unzip1(File zipfile) throws FileNotFoundException { try { ZipArchiveInputStream zais = new ZipArchiveInputStream(new FileInputStream(zipfile)); ZipArchiveEntry z1 = null; while ((z1 = zais.getNextZipEntry()) != null) { if (z1.isDirectory()) { /*hack to add vcc identifier because fucking ops cant rename a simple file*/ if (z1.getName().contains("account")) identifier = ".vcc"; else identifier = ""; } else { String fn = z1.getName().substring(z1.getName().lastIndexOf("/")); File f = new File(getCalTempPath() + fn); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER); int n = 0; byte[] content = new byte[BUFFER]; while (-1 != (n = zais.read(content))) { fos.write(content, 0, n); } bos.flush(); bos.close(); fos.close(); File unz = null; if (f.getName().endsWith("zip")) unz = unzip3(f); else unz = ungzip(f); if (unz != null) allfiles.add(unz); f.delete(); } } zais.close(); } catch (IOException ioe) { jlog.fatal("IO read error :: " + ioe); } }
From source file:org.apache.flex.utilities.converter.retrievers.BaseRetriever.java
protected void unpack(File inputArchive, File targetDirectory) throws RetrieverException { if (!targetDirectory.mkdirs()) { throw new RetrieverException( "Unable to create extraction directory " + targetDirectory.getAbsolutePath()); }/* w ww. j av a 2 s . co m*/ ArchiveInputStream archiveInputStream = null; ArchiveEntry entry; try { final CountingInputStream inputStream = new CountingInputStream(new FileInputStream(inputArchive)); final long inputFileSize = inputArchive.length(); if (inputArchive.getName().endsWith(".tbz2")) { archiveInputStream = new TarArchiveInputStream(new BZip2CompressorInputStream(inputStream)); } else { archiveInputStream = new ArchiveStreamFactory() .createArchiveInputStream(new BufferedInputStream(inputStream)); } final ProgressBar progressBar = new ProgressBar(inputFileSize); while ((entry = archiveInputStream.getNextEntry()) != null) { final File outputFile = new File(targetDirectory, entry.getName()); // Entry is a directory. if (entry.isDirectory()) { if (!outputFile.exists()) { if (!outputFile.mkdirs()) { throw new RetrieverException( "Could not create output directory " + outputFile.getAbsolutePath()); } } } // Entry is a file. else { final byte[] data = new byte[BUFFER_MAX]; final FileOutputStream fos = new FileOutputStream(outputFile); BufferedOutputStream dest = null; try { dest = new BufferedOutputStream(fos, BUFFER_MAX); int count; while ((count = archiveInputStream.read(data, 0, BUFFER_MAX)) != -1) { dest.write(data, 0, count); progressBar.updateProgress(inputStream.getBytesRead()); } } finally { if (dest != null) { dest.flush(); dest.close(); } } } progressBar.updateProgress(inputStream.getBytesRead()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ArchiveException e) { e.printStackTrace(); } finally { if (archiveInputStream != null) { try { archiveInputStream.close(); } catch (Exception e) { // Ignore... } } } }
From source file:com.fluidops.iwb.deepzoom.ImageLoader.java
/** * Loads an image from a URL to a local file * @param uri - The URL from which to obtain the image * @param file - The file to store the image to * @return/*from w w w . ja v a2 s . com*/ */ public boolean loadGoogleImage(URI uri, Map<URI, Set<Value>> facets, File file) { String url; URL u; InputStream is = null; BufferedInputStream dis = null; int b; try { URL googleUrl; ReadDataManager dm = EndpointImpl.api().getDataManager(); String label = dm.getLabel(uri); // TODO: currently hard coded logic for data sets // should find more flexible logic if (uri.stringValue().startsWith("http://www.ckan.net/")) label += " logo"; googleUrl = new URL("http://ajax.googleapis.com/ajax/services/search/images?v=1.0&" + "q=" + URLEncoder.encode(label, "UTF-8")); URLConnection connection = googleUrl.openConnection(); connection.addRequestProperty("Referer", "http://iwb.fluidops.com/"); String content = GenUtil.readUrl(connection.getInputStream()); try { JSONObject json = new JSONObject(content); JSONObject response = json.getJSONObject("responseData"); JSONArray results = response.getJSONArray("results"); JSONObject result = results.getJSONObject(0); url = result.getString("unescapedUrl"); } catch (JSONException e) { return false; } u = new URL(url); try { is = u.openStream(); } catch (IOException e) { System.out.println("File could not be found: " + url); // quick fix: 200px-Image n/a, try smaller pic (for Wikipedia images) url = url.replace("200px", "94px"); u = new URL(url); try { is = u.openStream(); } catch (IOException e2) { System.out.println("also smaller image not available"); return false; } } dis = new BufferedInputStream(is); BufferedOutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); while ((b = dis.read()) != -1) { out.write(b); } out.flush(); } finally { IOUtils.closeQuietly(out); } } catch (MalformedURLException mue) { logger.error(mue.getMessage(), mue); return false; } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); return false; } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(dis); } return true; }
From source file:com.phonegap.plugin.files.ExtractZipFilePlugin.java
@Override public boolean execute(String action, JSONArray args, CallbackContext cbc) { PluginResult.Status status = PluginResult.Status.OK; try {/*from www . ja v a 2 s . c o m*/ String filename = args.getString(0); URL url; try { url = new URL(filename); } catch (MalformedURLException e) { throw new RuntimeException(e); } File file = new File(url.getFile()); String[] dirToSplit = url.getFile().split(File.separator); String dirToInsert = ""; for (int i = 0; i < dirToSplit.length - 1; i++) { dirToInsert += dirToSplit[i] + File.separator; } ZipEntry entry; ZipFile zipfile; try { zipfile = new ZipFile(file); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); BufferedInputStream is = null; try { is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[102222]; String fileName = dirToInsert + entry.getName(); File outFile = new File(fileName); if (entry.isDirectory()) { if (!outFile.exists() && !outFile.mkdirs()) { Log.v("info", "Unable to create directories: " + outFile.getAbsolutePath()); cbc.sendPluginResult(new PluginResult(IO_EXCEPTION)); return false; } } else { File parent = outFile.getParentFile(); if (parent.mkdirs()) { Log.v("info", "created directory leading to file"); } FileOutputStream fos = null; BufferedOutputStream dest = null; try { fos = new FileOutputStream(outFile); dest = new BufferedOutputStream(fos, 102222); while ((count = is.read(data, 0, 102222)) != -1) { dest.write(data, 0, count); } } finally { if (dest != null) { dest.flush(); dest.close(); } if (fos != null) { fos.close(); } } } } finally { if (is != null) { is.close(); } } } } catch (ZipException e1) { Log.v("error", e1.getMessage(), e1); cbc.sendPluginResult(new PluginResult(MALFORMED_URL_EXCEPTION)); return false; } catch (IOException e1) { Log.v("error", e1.getMessage(), e1); cbc.sendPluginResult(new PluginResult(IO_EXCEPTION)); return false; } } catch (JSONException e) { cbc.sendPluginResult(new PluginResult(JSON_EXCEPTION)); return false; } cbc.sendPluginResult(new PluginResult(status)); return true; }