List of usage examples for java.io InputStream skip
public long skip(long n) throws IOException
n
bytes of data from this input stream. From source file:de.micromata.genome.test.web.SimHttpServletRequest.java
protected void setInputStream(final InputStream servletIs) { this.servletIs = new ServletInputStream() { public int available() throws IOException { return servletIs.available(); }/* w w w . j a v a2s. c o m*/ public void close() throws IOException { servletIs.close(); } public boolean equals(Object obj) { return servletIs.equals(obj); } public int hashCode() { return servletIs.hashCode(); } public void mark(int readlimit) { servletIs.mark(readlimit); } public boolean markSupported() { return servletIs.markSupported(); } public int read(byte[] b, int off, int len) throws IOException { return servletIs.read(b, off, len); } public int read(byte[] b) throws IOException { return servletIs.read(b); } public void reset() throws IOException { servletIs.reset(); } public long skip(long n) throws IOException { return servletIs.skip(n); } public String toString() { return servletIs.toString(); } @Override public int read() throws IOException { throw new UnsupportedOperationException(); } }; }
From source file:org.globus.replica.rls.impl.rpc.SimpleRLSConnection.java
/** Check input steam to see if bytes are (unexpectedly) waiting to be read. *//* www.j a v a 2s.c om*/ private void _checkInputStream(InputStream in) { try { while (in.available() > 0) { logger.warn( "Unexpected bytes are waiting on input steam. " + "Skipping " + in.available() + " bytes."); in.skip(in.available()); } } catch (Exception e) { logger.warn("Exception when checking for available bytes on the " + "input stream: " + e.getLocalizedMessage()); } }
From source file:com.zlfun.framework.misc.UploadUtils.java
public static boolean download(HttpServletRequest request, HttpServletResponse response, String uuid) { InputStream bis; boolean ret = false; try {/* w w w . j a va 2 s .c o m*/ byte[] voiceData = FsUtils.readFromDisk(uuid); if (voiceData != null) { long p = 0L; long toLength = 0L; long contentLength = 0L; int rangeSwitch = 0; // 0,1,?bytes=27000-2,???bytes=27000-39000 long fileLength; String rangBytes = ""; fileLength = voiceData.length; // get file content bis = new ByteArrayInputStream(voiceData); // tell the client to allow accept-ranges response.reset(); response.setHeader("Accept-Ranges", "bytes"); // client requests a file block download start byte String range = request.getHeader("Range"); if (range != null && range.trim().length() > 0 && !"null".equals(range)) { response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT); rangBytes = range.replaceAll("bytes=", ""); if (rangBytes.endsWith("-")) { // bytes=270000- rangeSwitch = 1; p = Long.parseLong(rangBytes.substring(0, rangBytes.indexOf("-"))); contentLength = fileLength - p; // 270000?bytes270000 } else { // bytes=270000-320000 rangeSwitch = 2; String temp1 = rangBytes.substring(0, rangBytes.indexOf("-")); String temp2 = rangBytes.substring(rangBytes.indexOf("-") + 1, rangBytes.length()); p = Long.parseLong(temp1); toLength = Long.parseLong(temp2); contentLength = toLength - p + 1; // // 270000-320000 // } } else { contentLength = fileLength; } // Content-Length????? // Content-Length: [?] - [?] response.setHeader("Content-Length", new Long(contentLength).toString()); // // ??: // Content-Range: bytes [?]-[? - 1]/[?] if (rangeSwitch == 1) { String contentRange = new StringBuffer("bytes ").append(new Long(p).toString()).append("-") .append(new Long(fileLength - 1).toString()).append("/") .append(new Long(fileLength).toString()).toString(); response.setHeader("Content-Range", contentRange); bis.skip(p); } else if (rangeSwitch == 2) { String contentRange = range.replace("=", " ") + "/" + new Long(fileLength).toString(); response.setHeader("Content-Range", contentRange); bis.skip(p); } else { String contentRange = new StringBuffer("bytes ").append("0-").append(fileLength - 1).append("/") .append(fileLength).toString(); response.setHeader("Content-Range", contentRange); } response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition", getContentDisposition(request, uuid)); OutputStream out = response.getOutputStream(); int n = 0; long readLength = 0; int bsize = 1024; byte[] bytes = new byte[bsize]; if (rangeSwitch == 2) { // bytes=27000-39000 27000? while (readLength <= contentLength - bsize) { n = bis.read(bytes); readLength += n; out.write(bytes, 0, n); } if (readLength <= contentLength) { n = bis.read(bytes, 0, (int) (contentLength - readLength)); out.write(bytes, 0, n); } } else { while ((n = bis.read(bytes)) != -1) { out.write(bytes, 0, n); } } out.flush(); out.close(); bis.close(); return true; } else { return false; } } catch (IOException ex) { // ClientAbortException Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (Exception ex) { Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex); return false; } }
From source file:com.github.thebigs.foscam.recorder.Recorder.java
@Override public void run() { new File(outputDir).mkdirs(); initTotalBytesSaved();//from w w w . j a v a 2 s .c o m while (!shutdown) { try { URL url = new URL(camUrl); // Open a Connection to the server URLConnection urlc = url.openConnection(); if (urlc == null) { throw new IOException("Unable to make a connection to the image source"); } // Turn off caches to force fresh reload of the jpg urlc.setUseCaches(false); urlc.connect(); // ignored if already connected. InputStream stream = urlc.getInputStream(); // Line 1: "--ipcamera" String delimiter = new String(readLine(stream)); while (!shutdown && !imageListeners.isEmpty()) { // Line 2: "Content-Type: image/jpeg" String contentType = new String(readLine(stream)).split(":")[1].trim(); // Line 3: "Content-Length: 23304" int contentLength = Integer.parseInt(new String(readLine(stream)).split(":")[1].trim()); // Line 4: <Blank Line> readLine(stream); // read image data byte[] imageData = new byte[contentLength]; for (int i = 0; i < contentLength; i++) { int readByte = stream.read(); imageData[i] = (byte) readByte; } Image image = Toolkit.getDefaultToolkit().createImage(imageData); // save the image to the current recording saveImage(image); // notify listeners synchronized (imageListeners) { for (WebCamImageListener l : imageListeners) { l.onImage(image); } } // read stream till next delimiter boolean delimiterFound = false; ByteArrayOutputStream delimiterBuffer = new ByteArrayOutputStream(); while (!delimiterFound) { int nextByte = stream.read(); if (nextByte == 0x2d) { int followingByte = stream.read(); if (followingByte == 0x2d) { // read 8 bytes into the delimiter buffer for (int i = 0; i < 8; i++) { delimiterBuffer.write(stream.read()); } if (new String(delimiterBuffer.toByteArray()).equals("ipcamera")) { delimiterFound = true; // skip CR/LF stream.skip(2); } } } } } } catch (MalformedURLException e) { System.err.println("Unable to parse URL: '" + camUrl + "'"); System.exit(-1); } catch (IOException e) { System.err .println("IO Exception: server not responding at : '" + camUrl + "'. retrying in 1 second"); // sleep for 1 sec try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } if (imageListeners.isEmpty()) { // sleep for 5 secs try { Thread.sleep(5000); } catch (InterruptedException e) { } } } }
From source file:net.pms.dlna.DLNAResource.java
/** * Returns an InputStream of this DLNAResource that starts at a given time, if possible. Very useful if video chapters are being used. * @param range/* w w w .j a va2s .co m*/ * @param mediarenderer * @return The inputstream * @throws IOException */ public InputStream getInputStream(Range range, RendererConfiguration mediarenderer) throws IOException { logger.trace("Asked stream chunk : " + range + " of " + getName() + " and player " + getPlayer()); // shagrath: small fix, regression on chapters boolean timeseek_auto = false; // Ditlew - WDTV Live // Ditlew - We convert byteoffset to timeoffset here. This needs the stream to be CBR! int cbr_video_bitrate = mediarenderer.getCBRVideoBitrate(); long low = range.isByteRange() && range.isStartOffsetAvailable() ? range.asByteRange().getStart() : 0; long high = range.isByteRange() && range.isEndLimitAvailable() ? range.asByteRange().getEnd() : -1; Range.Time timeRange = range.createTimeRange(); if (getPlayer() != null && low > 0 && cbr_video_bitrate > 0) { int used_bit_rated = (int) ((cbr_video_bitrate + 256) * 1024 / 8 * 1.04); // 1.04 = container overhead if (low > used_bit_rated) { timeRange.setStart((double) (low / (used_bit_rated))); low = 0; // WDTV Live - if set to TS it asks multiple times and ends by // asking for an invalid offset which kills MEncoder if (timeRange.getStartOrZero() > getMedia().getDurationInSeconds()) { return null; } // Should we rewind a little (in case our overhead isn't accurate enough) int rewind_secs = mediarenderer.getByteToTimeseekRewindSeconds(); timeRange.rewindStart(rewind_secs); // shagrath: timeseek_auto = true; } } // determine source of the stream if (getPlayer() == null) { // no transcoding if (this instanceof IPushOutput) { PipedOutputStream out = new PipedOutputStream(); InputStream fis = new PipedInputStream(out); ((IPushOutput) this).push(out); if (low > 0) { fis.skip(low); } // http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12035 fis = wrap(fis, high, low); return fis; } InputStream fis; if (getFormat() != null && getFormat().isImage() && getMedia() != null && getMedia().getOrientation() > 1 && mediarenderer.isAutoRotateBasedOnExif()) { // seems it's a jpeg file with an orientation setting to take care of fis = ImagesUtil.getAutoRotateInputStreamImage(getInputStream(), getMedia().getOrientation()); if (fis == null) { // error, let's return the original one fis = getInputStream(); } } else { fis = getInputStream(); } if (fis != null) { if (low > 0) { fis.skip(low); } // http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12035 fis = wrap(fis, high, low); if (timeRange.getStartOrZero() > 0 && this instanceof RealFile) { fis.skip(MpegUtil.getPositionForTimeInMpeg(((RealFile) this).getFile(), (int) timeRange.getStartOrZero())); } } return fis; } else { // pipe transcoding result OutputParams params = new OutputParams(configuration); params.aid = getMediaAudio(); params.sid = getMediaSubtitle(); params.mediaRenderer = mediarenderer; timeRange.limit(getSplitRange()); params.timeseek = timeRange.getStartOrZero(); params.timeend = timeRange.getEndOrZero(); params.shift_scr = timeseek_auto; if (this instanceof IPushOutput) { params.stdin = (IPushOutput) this; } // (re)start transcoding process if necessary if (externalProcess == null || externalProcess.isDestroyed()) { // first playback attempt => start new transcoding process logger.info("Starting transcode/remux of " + getName()); externalProcess = getPlayer().launchTranscode(this, getMedia(), params); if (params.waitbeforestart > 0) { logger.trace("Sleeping for {} milliseconds", params.waitbeforestart); try { Thread.sleep(params.waitbeforestart); } catch (InterruptedException e) { logger.error(null, e); } logger.trace("Finished sleeping for " + params.waitbeforestart + " milliseconds"); } } else if (params.timeseek > 0 && getMedia() != null && getMedia().isMediaparsed() && getMedia().getDurationInSeconds() > 0) { // time seek request => stop running transcode process and start new one logger.debug("Requesting time seek: " + params.timeseek + " seconds"); params.minBufferSize = 1; Runnable r = new Runnable() { @Override public void run() { externalProcess.stopProcess(); } }; new Thread(r, "External Process Stopper").start(); ProcessWrapper newExternalProcess = getPlayer().launchTranscode(this, getMedia(), params); try { Thread.sleep(1000); } catch (InterruptedException e) { logger.error(null, e); } if (newExternalProcess == null) { logger.trace("External process instance is null... sounds not good"); } externalProcess = newExternalProcess; } if (externalProcess == null) { return null; } InputStream is = null; int timer = 0; while (is == null && timer < 10) { is = externalProcess.getInputStream(low); timer++; if (is == null) { logger.warn("External input stream instance is null... sounds not good, waiting 500ms"); try { Thread.sleep(500); } catch (InterruptedException e) { } } } // fail fast: don't leave a process running indefinitely if it's // not producing output after params.waitbeforestart milliseconds + 5 seconds // this cleans up lingering MEncoder web video transcode processes that hang // instead of exiting if (is == null && externalProcess != null && !externalProcess.isDestroyed()) { Runnable r = new Runnable() { @Override public void run() { logger.error("External input stream instance is null... stopping process"); externalProcess.stopProcess(); } }; new Thread(r, "Hanging External Process Stopper").start(); } return is; } }
From source file:org.apache.catalina.servlets.DefaultServlet.java
/** * Copy the contents of the specified input stream to the specified * output stream, and ensure that both streams are closed before returning * (even in the face of an exception).//from w w w. j av a 2 s . c om * * @param istream The input stream to read from * @param ostream The output stream to write to * @param start Start of the range which will be copied * @param end End of the range which will be copied * @return Exception which occurred during processing */ private IOException copyRange(InputStream istream, ServletOutputStream ostream, long start, long end) { if (debug > 10) { log("Serving bytes:" + start + "-" + end); } try { istream.skip(start); } catch (IOException e) { return e; } IOException exception = null; long bytesToRead = end - start + 1; byte buffer[] = new byte[input]; int len = buffer.length; while ((bytesToRead > 0) && (len >= buffer.length)) { try { len = istream.read(buffer); if (bytesToRead >= len) { ostream.write(buffer, 0, len); bytesToRead -= len; } else { ostream.write(buffer, 0, (int) bytesToRead); bytesToRead = 0; } } catch (IOException e) { exception = e; len = -1; } if (len < buffer.length) { break; } } return exception; }
From source file:net.yacy.http.servlets.YaCyDefaultServlet.java
/** * send static content//from w w w . j a va 2s . c o m * * @param request * @param response * @param include is a include file (send without changing/adding headers) * @param resource the static content * @param reqRanges * @throws IOException */ protected void sendData(HttpServletRequest request, HttpServletResponse response, boolean include, Resource resource, Enumeration<String> reqRanges) throws IOException { final long content_length = resource.length(); // Get the output stream (or writer) OutputStream out; try { out = response.getOutputStream(); } catch (IllegalStateException e) { out = new WriterOutputStream(response.getWriter()); } // remove the last-modified field since caching otherwise does not work /* https://www.ietf.org/rfc/rfc2616.txt "if the response does have a Last-Modified time, the heuristic expiration value SHOULD be no more than some fraction of the interval since that time. A typical setting of this fraction might be 10%." */ if (response.containsHeader(HeaderFramework.LAST_MODIFIED)) { response.getHeaders(HeaderFramework.LAST_MODIFIED).clear(); // if this field is present, the reload-time is a 10% fraction of ttl and other caching headers do not work } // cache-control: allow shared caching (i.e. proxies) and set expires age for cache response.setHeader(HeaderFramework.CACHE_CONTROL, "public, max-age=" + Integer.toString(600)); // seconds; ten minutes if (reqRanges == null || !reqRanges.hasMoreElements() || content_length < 0) { // if there were no ranges, send entire entity if (include) { resource.writeTo(out, 0, content_length); } else { writeHeaders(response, resource, content_length); resource.writeTo(out, 0, content_length); } } else { // Parse the satisfiable ranges List<?> ranges = InclusiveByteRange.satisfiableRanges(reqRanges, content_length); // if there are no satisfiable ranges, send 416 response if (ranges == null || ranges.isEmpty()) { writeHeaders(response, resource, content_length); response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); response.setHeader(HttpHeader.CONTENT_RANGE.asString(), InclusiveByteRange.to416HeaderRangeString(content_length)); resource.writeTo(out, 0, content_length); out.close(); return; } // if there is only a single valid range (must be satisfiable // since were here now), send that range with a 216 response if (ranges.size() == 1) { InclusiveByteRange singleSatisfiableRange = (InclusiveByteRange) ranges.get(0); long singleLength = singleSatisfiableRange.getSize(content_length); writeHeaders(response, resource, singleLength); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); response.setHeader(HttpHeader.CONTENT_RANGE.asString(), singleSatisfiableRange.toHeaderRangeString(content_length)); resource.writeTo(out, singleSatisfiableRange.getFirst(content_length), singleLength); out.close(); return; } // multiple non-overlapping valid ranges cause a multipart // 216 response which does not require an overall // content-length header // writeHeaders(response, resource, -1); String mimetype = response.getContentType(); if (mimetype == null) { ConcurrentLog.warn("FILEHANDLER", "YaCyDefaultServlet: Unknown mimetype for " + request.getRequestURI()); } MultiPartOutputStream multi = new MultiPartOutputStream(out); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // If the request has a "Request-Range" header then we need to // send an old style multipart/x-byteranges Content-Type. This // keeps Netscape and acrobat happy. This is what Apache does. String ctp; if (request.getHeader(HttpHeader.REQUEST_RANGE.asString()) != null) { ctp = "multipart/x-byteranges; boundary="; } else { ctp = "multipart/byteranges; boundary="; } response.setContentType(ctp + multi.getBoundary()); InputStream in = resource.getInputStream(); long pos = 0; // calculate the content-length int length = 0; String[] header = new String[ranges.size()]; for (int i = 0; i < ranges.size(); i++) { InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i); header[i] = ibr.toHeaderRangeString(content_length); length += ((i > 0) ? 2 : 0) + 2 + multi.getBoundary().length() + 2 + (mimetype == null ? 0 : HeaderFramework.CONTENT_TYPE.length() + 2 + mimetype.length()) + 2 + HeaderFramework.CONTENT_RANGE.length() + 2 + header[i].length() + 2 + 2 + (ibr.getLast(content_length) - ibr.getFirst(content_length)) + 1; } length += 2 + 2 + multi.getBoundary().length() + 2 + 2; response.setContentLength(length); for (int i = 0; i < ranges.size(); i++) { InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i); multi.startPart(mimetype, new String[] { HeaderFramework.CONTENT_RANGE + ": " + header[i] }); long start = ibr.getFirst(content_length); long size = ibr.getSize(content_length); if (in != null) { // Handle non cached resource if (start < pos) { in.close(); in = resource.getInputStream(); pos = 0; } if (pos < start) { in.skip(start - pos); pos = start; } FileUtils.copy(in, multi, size); pos += size; } else // Handle cached resource { (resource).writeTo(multi, start, size); } } if (in != null) in.close(); multi.close(); } }
From source file:com.adobe.phonegap.contentsync.Sync.java
private boolean unzipSync(File targetFile, String outputDirectory, ProgressEvent progress, CallbackContext callbackContext) { Log.d(LOG_TAG, "unzipSync called"); Log.d(LOG_TAG, "zip = " + targetFile.getAbsolutePath()); InputStream inputStream = null; ZipFile zip = null;// w w w. j a va2 s .c o m boolean anyEntries = false; try { synchronized (progress) { if (progress.isAborted()) { return false; } } zip = new ZipFile(targetFile); // Since Cordova 3.3.0 and release of File plugins, files are accessed via cdvfile:// // Accept a path or a URI for the source zip. Uri zipUri = getUriForArg(targetFile.getAbsolutePath()); Uri outputUri = getUriForArg(outputDirectory); CordovaResourceApi resourceApi = webView.getResourceApi(); File tempFile = resourceApi.mapUriToFile(zipUri); if (tempFile == null || !tempFile.exists()) { sendErrorMessage("Zip file does not exist", UNZIP_ERROR, callbackContext); } File outputDir = resourceApi.mapUriToFile(outputUri); outputDirectory = outputDir.getAbsolutePath(); outputDirectory += outputDirectory.endsWith(File.separator) ? "" : File.separator; if (outputDir == null || (!outputDir.exists() && !outputDir.mkdirs())) { sendErrorMessage("Could not create output directory", UNZIP_ERROR, callbackContext); } OpenForReadResult zipFile = resourceApi.openForRead(zipUri); progress.setStatus(STATUS_EXTRACTING); progress.setLoaded(0); progress.setTotal(zip.size()); Log.d(LOG_TAG, "zip file len = " + zip.size()); inputStream = new BufferedInputStream(zipFile.inputStream); inputStream.mark(10); int magic = readInt(inputStream); if (magic != 875721283) { // CRX identifier inputStream.reset(); } else { // CRX files contain a header. This header consists of: // * 4 bytes of magic number // * 4 bytes of CRX format version, // * 4 bytes of public key length // * 4 bytes of signature length // * the public key // * the signature // and then the ordinary zip data follows. We skip over the header before creating the ZipInputStream. readInt(inputStream); // version == 2. int pubkeyLength = readInt(inputStream); int signatureLength = readInt(inputStream); inputStream.skip(pubkeyLength + signatureLength); } // The inputstream is now pointing at the start of the actual zip file content. ZipInputStream zis = new ZipInputStream(inputStream); inputStream = zis; ZipEntry ze; byte[] buffer = new byte[32 * 1024]; while ((ze = zis.getNextEntry()) != null) { synchronized (progress) { if (progress.isAborted()) { return false; } } anyEntries = true; String compressedName = ze.getName(); if (ze.getSize() > getFreeSpace()) { return false; } if (ze.isDirectory()) { File dir = new File(outputDirectory + compressedName); dir.mkdirs(); } else { File file = new File(outputDirectory + compressedName); file.getParentFile().mkdirs(); if (file.exists() || file.createNewFile()) { Log.w(LOG_TAG, "extracting: " + file.getPath()); FileOutputStream fout = new FileOutputStream(file); int count; while ((count = zis.read(buffer)) != -1) { fout.write(buffer, 0, count); } fout.close(); } } progress.addLoaded(1); updateProgress(callbackContext, progress); zis.closeEntry(); } } catch (Exception e) { String errorMessage = "An error occurred while unzipping."; sendErrorMessage(errorMessage, UNZIP_ERROR, callbackContext); Log.e(LOG_TAG, errorMessage, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } if (zip != null) { try { zip.close(); } catch (IOException e) { } } } if (anyEntries) return true; else return false; }
From source file:org.gss_project.gss.server.rest.Webdav.java
/** * Copy the contents of the specified input stream to the specified output * stream, and ensure that both streams are closed before returning (even in * the face of an exception)./* w ww .j av a2 s . co m*/ * * @param istream The input stream to read from * @param ostream The output stream to write to * @param start Start of the range which will be copied * @param end End of the range which will be copied * @return Exception which occurred during processing */ private IOException copyRange(InputStream istream, ServletOutputStream ostream, long start, long end) { if (logger.isDebugEnabled()) logger.debug("Serving bytes:" + start + "-" + end); try { istream.skip(start); } catch (IOException e) { return e; } IOException exception = null; long bytesToRead = end - start + 1; byte buffer[] = new byte[input]; int len = buffer.length; while (bytesToRead > 0 && len >= buffer.length) { try { len = istream.read(buffer); if (bytesToRead >= len) { ostream.write(buffer, 0, len); bytesToRead -= len; } else { ostream.write(buffer, 0, (int) bytesToRead); bytesToRead = 0; } } catch (IOException e) { exception = e; len = -1; } if (len < buffer.length) break; } return exception; }