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:org.apache.fontbox.ttf.TTFSubsetter.java
private byte[] buildHmtxTable() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); HorizontalHeaderTable h = ttf.getHorizontalHeader(); HorizontalMetricsTable hm = ttf.getHorizontalMetrics(); InputStream is = ttf.getOriginalData(); // more info: https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6hmtx.html int lastgid = h.getNumberOfHMetrics() - 1; // true if lastgid is not in the set: we'll need its width (but not its left side bearing) later boolean needLastGidWidth = false; if (glyphIds.last() > lastgid && !glyphIds.contains(lastgid)) { needLastGidWidth = true;//from www .j a v a 2s. co m } try { is.skip(hm.getOffset()); long lastOffset = 0; for (Integer glyphId : glyphIds) { // offset in original file long offset; if (glyphId <= lastgid) { // copy width and lsb offset = glyphId * 4; lastOffset = copyBytes(is, bos, offset, lastOffset, 4); } else { if (needLastGidWidth) { // one time only: copy width from lastgid, whose width applies // to all later glyphs needLastGidWidth = false; offset = lastgid * 4; lastOffset = copyBytes(is, bos, offset, lastOffset, 2); // then go on with lsb from actual glyph (lsb are individual even in monotype fonts) } // copy lsb only, as we are beyond numOfHMetrics offset = h.getNumberOfHMetrics() * 4 + (glyphId - h.getNumberOfHMetrics()) * 2; lastOffset = copyBytes(is, bos, offset, lastOffset, 2); } } return bos.toByteArray(); } finally { is.close(); } }
From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java
protected void sendData(HttpServletRequest request, HttpServletResponse response, String pathInContext, Resource resource) throws IOException { long resLength = resource.length(); boolean include = request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) != null; // Get the output stream (or writer) OutputStream out = null;// www . j ava 2s .c om try { out = response.getOutputStream(); } catch (IllegalStateException e) { out = new WriterOutputStream(response.getWriter()); } // see if there are any range headers Enumeration reqRanges = include ? null : request.getHeaders(HttpFields.__Range); if (reqRanges == null || !reqRanges.hasMoreElements()) { // if there were no ranges, send entire entity Resource data = resource; if (!include) { // look for a gziped content. if (_minGzipLength > 0) { String accept = request.getHeader(HttpFields.__AcceptEncoding); if (accept != null && resLength > _minGzipLength && !pathInContext.endsWith(".gz")) { Resource gz = getResource(pathInContext + ".gz"); if (gz.exists() && accept.indexOf("gzip") >= 0 && request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) == null) { response.setHeader(HttpFields.__ContentEncoding, "gzip"); data = gz; resLength = data.length(); } } } writeHeaders(response, resource, resLength); } data.writeTo(out, 0, resLength); return; } // Parse the satisfiable ranges List ranges = InclusiveByteRange.satisfiableRanges(reqRanges, resLength); // if there are no satisfiable ranges, send 416 response if (ranges == null || ranges.size() == 0) { writeHeaders(response, resource, resLength); response.setStatus(HttpResponse.__416_Requested_Range_Not_Satisfiable); response.setHeader(HttpFields.__ContentRange, InclusiveByteRange.to416HeaderRangeString(resLength)); resource.writeTo(out, 0, resLength); 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(resLength); writeHeaders(response, resource, singleLength); response.setStatus(HttpResponse.__206_Partial_Content); response.setHeader(HttpFields.__ContentRange, singleSatisfiableRange.toHeaderRangeString(resLength)); resource.writeTo(out, singleSatisfiableRange.getFirst(resLength), singleLength); return; } // multiple non-overlapping valid ranges cause a multipart // 216 response which does not require an overall // content-length header // writeHeaders(response, resource, -1); ResourceCache.ResourceMetaData metaData = _httpContext.getResourceMetaData(resource); String encoding = metaData.getMimeType(); MultiPartResponse multi = new MultiPartResponse(response.getOutputStream()); response.setStatus(HttpResponse.__206_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(HttpFields.__RequestRange) != null) ctp = "multipart/x-byteranges; boundary="; else ctp = "multipart/byteranges; boundary="; response.setContentType(ctp + multi.getBoundary()); InputStream in = (resource instanceof CachedResource) ? null : resource.getInputStream(); long pos = 0; for (int i = 0; i < ranges.size(); i++) { InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i); String header = HttpFields.__ContentRange + ": " + ibr.toHeaderRangeString(resLength); multi.startPart(encoding, new String[] { header }); long start = ibr.getFirst(resLength); long size = ibr.getSize(resLength); 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; } IO.copy(in, out, size); pos += size; } else // Handle cached resource (resource).writeTo(out, start, size); } if (in != null) in.close(); multi.close(); return; }
From source file:ch.cyberduck.core.Path.java
/** * Will copy from in to out. Will attempt to skip Status#getCurrent * from the inputstream but not from the outputstream. The outputstream * is asssumed to append to a already existing file if * Status#getCurrent > 0// w w w . j a v a 2 s . c om * * @param out The stream to write to * @param in The stream to read from * @param throttle The bandwidth limit * @param l The stream listener to notify about bytes received and sent * @param offset Start reading at offset in file * @param limit Transfer only up to this length * @param status Transfer status * @throws IOResumeException If the input stream fails to skip the appropriate * number of bytes * @throws IOException Write not completed due to a I/O problem * @throws ConnectionCanceledException When transfer is interrupted by user setting the * status flag to cancel. */ protected void upload(final OutputStream out, final InputStream in, final BandwidthThrottle throttle, final StreamListener l, long offset, final long limit, final TransferStatus status) throws IOException { if (log.isDebugEnabled()) { log.debug("upload(" + out.toString() + ", " + in.toString()); } this.getSession() .message(MessageFormat.format(Locale.localizedString("Uploading {0}", "Status"), this.getName())); if (offset > 0) { long skipped = in.skip(offset); if (log.isInfoEnabled()) { log.info(String.format("Skipping %d bytes", skipped)); } if (skipped < status.getCurrent()) { throw new IOResumeException( String.format("Skipped %d bytes instead of %d", skipped, status.getCurrent())); } } this.transfer(in, new ThrottledOutputStream(out, throttle), l, limit, status); }
From source file:org.openhab.binding.samsungtv.internal.protocol.RemoteController.java
/** * Open Connection to Samsung TV./*from w w w .ja va 2 s .co m*/ * * @throws RemoteControllerException */ public void openConnection() throws RemoteControllerException { logger.debug("Open connection to host '{}:{}'", host, port); socket = new Socket(); try { socket.connect(new InetSocketAddress(host, port), TIMEOUT); } catch (Exception e) { throw new RemoteControllerException("Connection failed", e); } logger.debug("Connection successfully opened...quering access"); try { /* @formatter:off * * offset value and description * ------ --------------------- * 0x00 0x00 - datagram type? * 0x01 0x0013 - string length (little endian) * 0x03 "iphone.iapp.samsung" - string content * 0x16 0x0038 - payload size (little endian) * 0x18 payload * * Payload starts with 2 bytes: 0x64 and 0x00, then comes 3 strings * encoded with base64 algorithm. Every string is preceded by * 2-bytes field containing encoded string length. * * These three strings are as follow: * * remote control device IP, unique ID value to distinguish * controllers, name it will be displayed as controller name. * * @formatter:on */ writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); writer.append((char) 0x00); writeString(writer, APP_STRING); writeString(writer, createRegistrationPayload(socket.getLocalAddress().getHostAddress())); writer.flush(); try { /* @formatter:off * * offset value and description * ------ --------------------- * 0x00 don't know, it it always 0x00 or 0x02 * 0x01 0x000c - string length (little endian) * 0x03 "iapp.samsung" - string content * 0x0f 0x0006 - payload size (little endian) * 0x11 payload * * @formatter:on */ InputStream in = socket.getInputStream(); reader = new InputStreamReader(in); reader.skip(1); readString(reader); char[] result = readCharArray(reader); if (Arrays.equals(result, ACCESS_GRANTED_RESP)) { logger.debug("Access granted"); } else if (Arrays.equals(result, ACCESS_DENIED_RESP)) { throw new RemoteControllerException("Access denied"); } else if (Arrays.equals(result, ACCESS_TIMEOUT_RESP)) { throw new RemoteControllerException("Registration timed out"); } else if (Arrays.equals(result, WAITING_USER_GRANT_RESP)) { throw new RemoteControllerException("Waiting for user to grant access"); } else { throw new RemoteControllerException("Unknown response received for access query"); } int i; while ((i = in.available()) > 0) { in.skip(i); } } catch (IOException e) { throw new RemoteControllerException(e); } } catch (IOException e) { throw new RemoteControllerException(e); } }
From source file:org.beangle.web.io.SplitStreamDownloader.java
@Override public void download(HttpServletRequest request, HttpServletResponse response, InputStream input, String name, String display) {/*from w ww . j a v a2 s . c om*/ String attach = getAttachName(name, display); response.reset(); addContent(request, response, attach); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("connection", "Keep-Alive"); int length = 0; long start = 0L; long begin = 0L; long stop = 0L; StopWatch watch = new StopWatch(); watch.start(); try { length = input.available(); stop = length - 1; response.setContentLength(length); String rangestr = request.getHeader("Range"); if (null != rangestr) { String[] readlength = StringUtils.substringAfter(rangestr, "bytes=").split("-"); start = Long.parseLong(readlength[0]); if (readlength.length > 1 && StringUtils.isNotEmpty(readlength[1])) { stop = Long.parseLong(readlength[1]); } if (start != 0) { response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); String crange = "bytes " + start + "-" + stop + "/" + length; response.setHeader("Content-Range", crange); } } OutputStream output = response.getOutputStream(); input.skip(start); begin = start; int size = 4 * 1024; byte[] buffer = new byte[size]; for (int step = maxStep(start, stop, size); step > 0; step = maxStep(start, stop, size)) { int readed = input.read(buffer, 0, step); if (readed == -1) break; output.write(buffer, 0, readed); start += readed; } } catch (IOException e) { } catch (Exception e) { logger.warn("download file error " + attach, e); } finally { IOUtils.closeQuietly(input); if (logger.isDebugEnabled()) { String percent = null; if (length == 0) { percent = "100%"; } else { percent = ((int) (((start - begin) * 1.0 / length) * 10000)) / 100.0f + "%"; } long time = watch.getTime(); int rate = 0; if (start - begin > 0) { rate = (int) (((start - begin) * 1.0 / time * 1000) / 1024); } logger.debug("{}({}-{}/{}) download {}[{}] in {} ms with {} KB/s", array(attach, begin, stop, length, start - begin, percent, time, rate)); } } }
From source file:org.apache.geode.cache.lucene.internal.filesystem.FileSystemJUnitTest.java
/** * A test of reading and writing to a file. *//* w w w .j av a 2 s. co m*/ @Test public void testReadWriteBytes() throws Exception { long start = System.currentTimeMillis(); File file1 = system.createFile("testFile1"); assertEquals(0, file1.getLength()); OutputStream outputStream1 = file1.getOutputStream(); // Write some random data. Make sure it fills several chunks outputStream1.write(2); byte[] data = new byte[LARGE_CHUNK]; rand.nextBytes(data); outputStream1.write(data); outputStream1.write(44); outputStream1.close(); assertEquals(2 + LARGE_CHUNK, file1.getLength()); assertTrue(file1.getModified() >= start); // Append to the file with a new outputstream OutputStream outputStream2 = file1.getOutputStream(); outputStream2.write(123); byte[] data2 = new byte[SMALL_CHUNK]; rand.nextBytes(data2); outputStream2.write(data2); outputStream2.close(); assertEquals(3 + LARGE_CHUNK + SMALL_CHUNK, file1.getLength()); // Make sure we can read all of the data back and it matches InputStream is = file1.getInputStream(); assertEquals(2, is.read()); byte[] resultData = new byte[LARGE_CHUNK]; assertEquals(LARGE_CHUNK, is.read(resultData)); assertArrayEquals(data, resultData); assertEquals(44, is.read()); assertEquals(123, is.read()); // Test read to an offset Arrays.fill(resultData, (byte) 0); assertEquals(SMALL_CHUNK, is.read(resultData, 50, SMALL_CHUNK)); // Make sure the data read matches byte[] expectedData = new byte[LARGE_CHUNK]; Arrays.fill(expectedData, (byte) 0); System.arraycopy(data2, 0, expectedData, 50, data2.length); assertArrayEquals(expectedData, resultData); assertEquals(-1, is.read()); assertEquals(-1, is.read(data)); is.close(); // Test the skip interface is = file1.getInputStream(); is.skip(LARGE_CHUNK + 3); Arrays.fill(resultData, (byte) 0); assertEquals(SMALL_CHUNK, is.read(resultData)); Arrays.fill(expectedData, (byte) 0); System.arraycopy(data2, 0, expectedData, 0, data2.length); assertArrayEquals(expectedData, resultData); assertEquals(-1, is.read()); }
From source file:com.gemstone.gemfire.cache.lucene.internal.filesystem.FileSystemJUnitTest.java
/** * A test of reading and writing to a file. */// w w w. j a va 2 s . c o m @Test public void testReadWriteBytes() throws Exception { long start = System.currentTimeMillis(); File file1 = system.createFile("testFile1"); assertEquals(0, file1.getLength()); OutputStream outputStream1 = file1.getOutputStream(); //Write some random data. Make sure it fills several chunks outputStream1.write(2); byte[] data = new byte[LARGE_CHUNK]; rand.nextBytes(data); outputStream1.write(data); outputStream1.write(44); outputStream1.close(); assertEquals(2 + LARGE_CHUNK, file1.getLength()); assertTrue(file1.getModified() >= start); //Append to the file with a new outputstream OutputStream outputStream2 = file1.getOutputStream(); outputStream2.write(123); byte[] data2 = new byte[SMALL_CHUNK]; rand.nextBytes(data2); outputStream2.write(data2); outputStream2.close(); assertEquals(3 + LARGE_CHUNK + SMALL_CHUNK, file1.getLength()); //Make sure we can read all of the data back and it matches InputStream is = file1.getInputStream(); assertEquals(2, is.read()); byte[] resultData = new byte[LARGE_CHUNK]; assertEquals(LARGE_CHUNK, is.read(resultData)); assertArrayEquals(data, resultData); assertEquals(44, is.read()); assertEquals(123, is.read()); //Test read to an offset Arrays.fill(resultData, (byte) 0); assertEquals(SMALL_CHUNK, is.read(resultData, 50, SMALL_CHUNK)); //Make sure the data read matches byte[] expectedData = new byte[LARGE_CHUNK]; Arrays.fill(expectedData, (byte) 0); System.arraycopy(data2, 0, expectedData, 50, data2.length); assertArrayEquals(expectedData, resultData); assertEquals(-1, is.read()); assertEquals(-1, is.read(data)); is.close(); //Test the skip interface is = file1.getInputStream(); is.skip(LARGE_CHUNK + 3); Arrays.fill(resultData, (byte) 0); assertEquals(SMALL_CHUNK, is.read(resultData)); Arrays.fill(expectedData, (byte) 0); System.arraycopy(data2, 0, expectedData, 0, data2.length); assertArrayEquals(expectedData, resultData); assertEquals(-1, is.read()); }
From source file:uk.ac.ox.webauth.crypto.Des3CbcSha1Kd.java
@Override public ASN1Encodable decrypt(byte[] cipherData) throws IOException, GeneralSecurityException { // derive our decryption and hmac keys as per RFC 3961 // first work out the "well known constant"s for the different keys byte[] wkcKe = new byte[5]; wkcKe[0] = (byte) ((keyUsage >> 24) & 0xFF); wkcKe[1] = (byte) ((keyUsage >> 16) & 0xFF); wkcKe[2] = (byte) ((keyUsage >> 8) & 0xFF); wkcKe[3] = (byte) (keyUsage & 0xFF); wkcKe[4] = (byte) 0xAA; byte[] wkcKi = (byte[]) wkcKe.clone(); wkcKi[4] = (byte) 0x55; // then make the keys // RFC 3961: Derived Key = DK(Base Key, Well-Known Constant) SecretKey ke = new SecretKeySpec(dk(key.getEncoded(), wkcKe), "DESede"); SecretKey ki = new SecretKeySpec(dk(key.getEncoded(), wkcKi), "DESede"); // set up the HMAC object so we can get the length Mac hmacSHA1 = Mac.getInstance("HmacSHA1"); hmacSHA1.init(ki);//w ww. ja va 2 s.c o m int hmacLength = hmacSHA1.getMacLength(); // first split the checksum off the data InputStream is = new ByteArrayInputStream(cipherData); byte[] data = new byte[cipherData.length - hmacLength]; if (is.read(data) != data.length) { throw new IOException("Couldn't read all the encrypted data."); } byte[] checksum = new byte[hmacLength]; if (is.read(checksum) != checksum.length) { throw new IOException("Couldn't read all the checksum data."); } // then decrypt the data Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding"); cipher.init(DECRYPT_MODE, ke, IV); byte[] decrypted = cipher.doFinal(data); // check the HMAC byte[] newChecksum = hmacSHA1.doFinal(decrypted); if (!Arrays.equals(checksum, newChecksum)) { throw new GeneralSecurityException("Checksum failure."); //System.out.println("Checksum failed."); } // throw away the confounder and then return an ASN.1 encodable object is = new ByteArrayInputStream(decrypted); is.skip(cipher.getBlockSize()); ASN1InputStream ais = new ASN1InputStream(is); return (ASN1Encodable) ais.readObject(); }
From source file:no.nordicsemi.android.nrftoolbox.dfu.HexInputStream.java
/** * Reads new line from the input stream. Input stream must be a HEX file. The first line is always skipped. * //from w w w .ja v a2 s.c o m * @return the number of data bytes in the new line. 0 if end of file. * @throws IOException * if this stream is closed or another IOException occurs. */ private int readLine() throws IOException { // end of file reached if (pos == -1) return 0; final InputStream in = this.in; // temporary value int b = 0; int lineSize, type; do { // skip end of line while (true) { b = in.read(); pos++; if (b != '\n' && b != '\r') { break; } } /* * Each line starts with comma (':') * Data is written in HEX, so each 2 ASCII letters give one byte. * After the comma there is one byte (2 HEX signs) with line length (normally 10 -> 0x10 -> 16 bytes -> 32 HEX characters) * After that there is a 4 byte of an address. This part may be skipped. * There is a packet type after the address (1 byte = 2 HEX characters). 00 is the valid data. Other values can be skipped when * converting to BIN file. * Then goes n bytes of data followed by 1 byte (2 HEX chars) of checksum, which is also skipped in BIN file. */ checkComma(b); // checking the comma at the beginning lineSize = readByte(in); // reading the length of the data in this line pos += 2; pos += in.skip(4); // skipping address part type = readByte(in); // reading the line type pos += 2; // if the line type is no longer data type (0x00), we've reached the end of the file switch (type) { case 0x00: // data type break; case 0x01: // end of file pos = -1; return 0; case 0x02: // extended segment address case 0x04: // extended linear address default: pos += in.skip(lineSize * 2 /* 2 hex per one byte */ + 2 /* check sum */); break; } } while (type != 0); // otherwise read lineSize bytes or fill the whole buffer for (int i = 0; i < localBuf.length && i < lineSize; ++i) { b = readByte(in); pos += 2; localBuf[i] = (byte) b; } pos += in.skip(2); // skip the checksum localPos = 0; return lineSize; }