Java Code Examples for java.nio.ByteBuffer.remaining()
The following are Jave code examples for showing how to use
remaining() of the
java.nio.ByteBuffer
class.
You can vote up the examples you like. Your votes will be used in our system to get
more good examples.
+ Save this method
Example 1
Project: hadoop File: JceAesCtrCryptoCodec.java View Source Code | 6 votes |
private void process(ByteBuffer inBuffer, ByteBuffer outBuffer) throws IOException { try { int inputSize = inBuffer.remaining(); // Cipher#update will maintain crypto context. int n = cipher.update(inBuffer, outBuffer); if (n < inputSize) { /** * Typically code will not get here. Cipher#update will consume all * input data and put result in outBuffer. * Cipher#doFinal will reset the crypto context. */ contextReset = true; cipher.doFinal(inBuffer, outBuffer); } } catch (Exception e) { throw new IOException(e); } }
Example 2
Project: AI-Powered-Intelligent-Banking-Platform File: EncodedAudioRecorder.java View Source Code | 6 votes |
/** * Save the encoded (output) buffer into the complete encoded recording. * TODO: copy directly (without the intermediate byte array) */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void dequeueOutputBuffer(MediaCodec codec, ByteBuffer[] outputBuffers, int index, MediaCodec.BufferInfo info) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { ByteBuffer buffer = outputBuffers[index]; Log.i("size/remaining: " + info.size + "/" + buffer.remaining()); if (info.size <= buffer.remaining()) { final byte[] bufferCopied = new byte[info.size]; buffer.get(bufferCopied); // TODO: catch BufferUnderflow // TODO: do we need to clear? // on N5: always size == remaining(), clearing is not needed // on SGS2: remaining decreases until it becomes less than size, which results in BufferUnderflow // (but SGS2 records only zeros anyway) //buffer.clear(); codec.releaseOutputBuffer(index, false); addEncoded(bufferCopied); if (Log.DEBUG) { AudioUtils.showSomeBytes("out", bufferCopied); } } else { Log.e("size > remaining"); codec.releaseOutputBuffer(index, false); } } }
Example 3
Project: incubator-netbeans File: Archive.java View Source Code | 6 votes |
/** * Sweep through the master buffer and remember all the entries */ private void parse(ByteBuffer master, long after) throws Exception { if (master.remaining() < 16) throw new IllegalStateException("Cache invalid"); if (master.getLong() != magic) throw new IllegalStateException("Wrong format"); if (master.getLong() < after) throw new IllegalStateException("Cache outdated"); int srcCounter = 0; while (master.remaining() > 0) { int type = master.get(); switch (type) { case 1: // source header String name = parseString(master); sources.put(name, srcCounter++); break; case 2: Entry en = new Entry(master); // shifts the buffer entries.put(en, en); break; default: throw new IllegalStateException("Cache invalid"); } } master.rewind(); }
Example 4
Project: hadoop File: ZlibDecompressor.java View Source Code | 5 votes |
int inflateDirect(ByteBuffer src, ByteBuffer dst) throws IOException { assert (this instanceof ZlibDirectDecompressor); ByteBuffer presliced = dst; if (dst.position() > 0) { presliced = dst; dst = dst.slice(); } Buffer originalCompressed = compressedDirectBuf; Buffer originalUncompressed = uncompressedDirectBuf; int originalBufferSize = directBufferSize; compressedDirectBuf = src; compressedDirectBufOff = src.position(); compressedDirectBufLen = src.remaining(); uncompressedDirectBuf = dst; directBufferSize = dst.remaining(); int n = 0; try { n = inflateBytesDirect(); presliced.position(presliced.position() + n); if (compressedDirectBufLen > 0) { src.position(compressedDirectBufOff); } else { src.position(src.limit()); } } finally { compressedDirectBuf = originalCompressed; uncompressedDirectBuf = originalUncompressed; compressedDirectBufOff = 0; compressedDirectBufLen = 0; directBufferSize = originalBufferSize; } return n; }
Example 5
Project: live_master File: FullContainerBox.java View Source Code | 5 votes |
protected final void parseChildBoxes(ByteBuffer content) { try { while (content.remaining() >= 8) { // 8 is the minimal size for a sane box boxes.add(boxParser.parseBox(new ByteBufferByteChannel(content), this)); } if (content.remaining() != 0) { setDeadBytes(content.slice()); LOG.severe("Some sizes are wrong"); } } catch (IOException e) { throw new RuntimeException(e); } }
Example 6
Project: openjdk-jdk10 File: TestBase64.java View Source Code | 5 votes |
private static final void testEncode(Base64.Encoder enc, ByteBuffer bin, byte[] expected) throws Throwable { ByteBuffer bout = enc.encode(bin); byte[] buf = new byte[bout.remaining()]; bout.get(buf); if (bin.hasRemaining()) { throw new RuntimeException( "Base64 enc.encode(ByteBuffer) failed!"); } checkEqual(buf, expected, "Base64 enc.encode(bf, bf) failed!"); }
Example 7
Project: lams File: WebSocketUtils.java View Source Code | 5 votes |
public static String toUtf8String(ByteBuffer buffer) { if (!buffer.hasRemaining()) { return EMPTY; } if (buffer.hasArray()) { return new String(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining(), UTF_8); } else { byte[] content = new byte[buffer.remaining()]; buffer.get(content); return new String(content, UTF_8); } }
Example 8
Project: dble File: FileStore.java View Source Code | 5 votes |
public int read(ByteBuffer buffer, long endPos) { long remained = endPos - filePos; if (remained <= 0) return 0; if (remained < buffer.remaining()) { int newLimit = (int) (buffer.position() + remained); buffer.limit(newLimit); } return read(buffer); }
Example 9
Project: s3-channels File: ByteBufferUtils.java View Source Code | 5 votes |
/** * Reads data from given input stream into byte buffer. * This helper does not overflow destination byte buffer. * Bytes are read until input stream have those or until byte buffer has remaining space for them. * * @param src source input stream * @param dest destination byte buffer * @param closeStream whereas to close src input stream * @return number of read (from input stream) / written (to buffer) bytes * @throws IOException - if any error occurs during input stream read */ public static int readFromInputStream(InputStream src, ByteBuffer dest, boolean closeStream) throws IOException { try { int chunkSize = dest.remaining() > _16_KB ? _16_KB : dest.remaining(); byte[] chunk = new byte[chunkSize]; int read; int written = 0; while ((read = src.read(chunk)) != -1) { if (!dest.hasRemaining()) { return written; } if (read > dest.remaining()) { read = dest.remaining(); } written += read; dest.put(chunk, 0, read); } return written; } finally { if (closeStream) { src.close(); } } }
Example 10
Project: Elasticsearch File: MysqlChannel.java View Source Code | 5 votes |
private void realNetSend(ByteBuffer buffer) throws IOException { long bufLen = buffer.remaining(); long writeLen = channel.write(buffer); if (bufLen != writeLen) { throw new IOException("Write mysql packet failed.[write=" + writeLen + ", needToWrite=" + bufLen + "]"); } channel.write(buffer); isSend = true; }
Example 11
Project: openjdk-jdk10 File: ISO_8859_1.java View Source Code | 5 votes |
public void read(ByteBuffer source, Appendable destination) { for (int i = 0, len = source.remaining(); i < len; i++) { char c = (char) (source.get() & 0xff); try { destination.append(c); } catch (IOException e) { throw new UncheckedIOException ("Error appending to the destination", e); } } }
Example 12
Project: tomcat7 File: WsRemoteEndpointImplBase.java View Source Code | 5 votes |
@Override public void sendPong(ByteBuffer applicationData) throws IOException, IllegalArgumentException { if (applicationData.remaining() > 125) { throw new IllegalArgumentException(sm.getString("wsRemoteEndpoint.tooMuchData")); } startMessageBlock(Constants.OPCODE_PONG, applicationData, true); }
Example 13
Project: sstable-adaptor File: CBUtil.java View Source Code | 5 votes |
private static String decodeString(ByteBuffer src) throws CharacterCodingException { // the decoder needs to be reset every time we use it, hence the copy per thread CharsetDecoder theDecoder = TL_UTF8_DECODER.get(); theDecoder.reset(); CharBuffer dst = TL_CHAR_BUFFER.get(); int capacity = (int) ((double) src.remaining() * theDecoder.maxCharsPerByte()); if (dst == null) { capacity = Math.max(capacity, 4096); dst = CharBuffer.allocate(capacity); TL_CHAR_BUFFER.set(dst); } else { dst.clear(); if (dst.capacity() < capacity) { dst = CharBuffer.allocate(capacity); TL_CHAR_BUFFER.set(dst); } } CoderResult cr = theDecoder.decode(src, dst, true); if (!cr.isUnderflow()) cr.throwException(); return dst.flip().toString(); }
Example 14
Project: LightComm4J File: DataBag.java View Source Code | 5 votes |
/** * read data from byte buffer * @param buffer * read from this buffer * @return * buffer's current position */ public int readFrom(ByteBuffer buffer) { int start = buffer.position(); byte[] data = new byte[buffer.remaining()]; buffer.get(data); int pos = readFromBytes(data); buffer.position(start + pos); return pos; }
Example 15
Project: GitHub File: GifBytesTestUtil.java View Source Code | 4 votes |
private static void verifyRemaining(ByteBuffer buffer, int expected) { if (buffer.remaining() < expected) { throw new IllegalArgumentException("Must have at least " + expected + " bytes to write"); } }
Example 16
Project: https-github.com-apache-zookeeper File: TraceFormatter.java View Source Code | 4 votes |
/** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("USAGE: TraceFormatter trace_file"); System.exit(2); } FileChannel fc = new FileInputStream(args[0]).getChannel(); while (true) { ByteBuffer bb = ByteBuffer.allocate(41); fc.read(bb); bb.flip(); byte app = bb.get(); long time = bb.getLong(); long id = bb.getLong(); int cxid = bb.getInt(); long zxid = bb.getLong(); int txnType = bb.getInt(); int type = bb.getInt(); int len = bb.getInt(); bb = ByteBuffer.allocate(len); fc.read(bb); bb.flip(); String path = "n/a"; if (bb.remaining() > 0) { if (type != OpCode.createSession) { int pathLen = bb.getInt(); byte b[] = new byte[pathLen]; bb.get(b); path = new String(b); } } System.out.println(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(new Date(time)) + ": " + (char) app + " id=0x" + Long.toHexString(id) + " cxid=" + cxid + " op=" + op2String(type) + " zxid=0x" + Long.toHexString(zxid) + " txnType=" + txnType + " len=" + len + " path=" + path); } }
Example 17
Project: BiglyBT File: BTMessageDecoder.java View Source Code | 4 votes |
private int preReadProcess( int allowed ) { if( allowed < 1 ) { Debug.out( "allowed < 1" ); } decode_array[ 0 ] = payload_buffer == null ? null : payload_buffer.getBuffer( SS ); //ensure the decode array has the latest payload pointer int bytes_available = 0; boolean shrink_remaining_buffers = false; int start_buff = reading_length_mode ? 1 : 0; boolean marked = false; for( int i = start_buff; i < 2; i++ ) { //set buffer limits according to bytes allowed ByteBuffer bb = decode_array[ i ]; if( bb == null ) { Debug.out( "preReadProcess:: bb["+i+"] == null, decoder destroyed=" +destroyed ); throw( new RuntimeException( "decoder destroyed" )); } if( shrink_remaining_buffers ) { bb.limit( 0 ); //ensure no read into this next buffer is possible } else { int remaining = bb.remaining(); if( remaining < 1 ) continue; //skip full buffer if( !marked ) { pre_read_start_buffer = i; pre_read_start_position = bb.position(); marked = true; } if( remaining > allowed ) { //read only part of this buffer bb.limit( bb.position() + allowed ); //limit current buffer bytes_available += bb.remaining(); shrink_remaining_buffers = true; //shrink any tail buffers } else { //full buffer is allowed to be read bytes_available += remaining; allowed -= remaining; //count this buffer toward allowed and move on to the next } } } return bytes_available; }
Example 18
Project: webtrekk-android-sdk File: NanoHTTPD.java View Source Code | 4 votes |
/** * Find the byte positions where multipart boundaries start. This reads * a large block at a time and uses a temporary buffer to optimize * (memory mapped) file access. */ private int[] getBoundaryPositions(ByteBuffer b, byte[] boundary) { int[] res = new int[0]; if (b.remaining() < boundary.length) { return res; } int search_window_pos = 0; byte[] search_window = new byte[4 * 1024 + boundary.length]; int first_fill = (b.remaining() < search_window.length) ? b.remaining() : search_window.length; b.get(search_window, 0, first_fill); int new_bytes = first_fill - boundary.length; do { // Search the search_window for (int j = 0; j < new_bytes; j++) { for (int i = 0; i < boundary.length; i++) { if (search_window[j + i] != boundary[i]) break; if (i == boundary.length - 1) { // Match found, add it to results int[] new_res = new int[res.length + 1]; System.arraycopy(res, 0, new_res, 0, res.length); new_res[res.length] = search_window_pos + j; res = new_res; } } } search_window_pos += new_bytes; // Copy the end of the buffer to the start System.arraycopy(search_window, search_window.length - boundary.length, search_window, 0, boundary.length); // Refill search_window new_bytes = search_window.length - boundary.length; new_bytes = (b.remaining() < new_bytes) ? b.remaining() : new_bytes; b.get(search_window, boundary.length, new_bytes); } while (new_bytes > 0); return res; }
Example 19
Project: sstable-adaptor File: ShortSerializer.java View Source Code | 4 votes |
public void validate(ByteBuffer bytes) throws MarshalException { if (bytes.remaining() != 2) throw new MarshalException(String.format("Expected 2 bytes for a smallint (%d)", bytes.remaining())); }
Example 20
Project: kafka-0.11.0.0-src-with-comment File: Utils.java View Source Code | 3 votes |
/** * Read data from the channel to the given byte buffer until there are no bytes remaining in the buffer. If the end * of the file is reached while there are bytes remaining in the buffer, an EOFException is thrown. * * @param channel File channel containing the data to read from * @param destinationBuffer The buffer into which bytes are to be transferred * @param position The file position at which the transfer is to begin; it must be non-negative * @param description A description of what is being read, this will be included in the EOFException if it is thrown * * @throws IllegalArgumentException If position is negative * @throws EOFException If the end of the file is reached while there are remaining bytes in the destination buffer * @throws IOException If an I/O error occurs, see {@link FileChannel#read(ByteBuffer, long)} for details on the * possible exceptions */ public static void readFullyOrFail(FileChannel channel, ByteBuffer destinationBuffer, long position, String description) throws IOException { if (position < 0) { throw new IllegalArgumentException("The file channel position cannot be negative, but it is " + position); } int expectedReadBytes = destinationBuffer.remaining(); readFully(channel, destinationBuffer, position); if (destinationBuffer.hasRemaining()) { throw new EOFException(String.format("Failed to read `%s` from file channel `%s`. Expected to read %d bytes, " + "but reached end of file after reading %d bytes. Started read from position %d.", description, channel, expectedReadBytes, expectedReadBytes - destinationBuffer.remaining(), position)); } }