List of usage examples for java.nio ByteBuffer limit
public final Buffer limit(int newLimit)
From source file:eu.stratosphere.arraymodel.io.StringInputFormat.java
public boolean readRecord(Value[] target, byte[] bytes, int offset, int numBytes) { StringValue str = this.theString; if (this.ascii) { str.setValueAscii(bytes, offset, numBytes); } else {//from w ww . ja v a 2s.c om ByteBuffer byteWrapper = this.byteWrapper; if (bytes != byteWrapper.array()) { byteWrapper = ByteBuffer.wrap(bytes, 0, bytes.length); this.byteWrapper = byteWrapper; } byteWrapper.clear(); byteWrapper.position(offset); byteWrapper.limit(offset + numBytes); try { CharBuffer result = this.decoder.decode(byteWrapper); str.setValue(result); } catch (CharacterCodingException e) { byte[] copy = new byte[numBytes]; System.arraycopy(bytes, offset, copy, 0, numBytes); LOG.warn("Line could not be encoded: " + Arrays.toString(copy), e); return false; } } target[0] = str; return true; }
From source file:eu.stratosphere.pact.array.io.StringInputFormat.java
public boolean readRecord(Value[] target, byte[] bytes, int offset, int numBytes) { PactString str = this.theString; if (this.ascii) { str.setValueAscii(bytes, offset, numBytes); } else {//w w w . j a v a 2 s .c o m ByteBuffer byteWrapper = this.byteWrapper; if (bytes != byteWrapper.array()) { byteWrapper = ByteBuffer.wrap(bytes, 0, bytes.length); this.byteWrapper = byteWrapper; } byteWrapper.clear(); byteWrapper.position(offset); byteWrapper.limit(offset + numBytes); try { CharBuffer result = this.decoder.decode(byteWrapper); str.setValue(result); } catch (CharacterCodingException e) { byte[] copy = new byte[numBytes]; System.arraycopy(bytes, offset, copy, 0, numBytes); LOG.warn("Line could not be encoded: " + Arrays.toString(copy), e); return false; } } target[0] = str; return true; }
From source file:com.ery.ertc.estorm.util.ByteBufferArray.java
/** * Access(read or write) this buffer array with a position and length as the given array. Here we will only lock one buffer even if it * may be need visit several buffers. The consistency is guaranteed by the caller. * /*from www.ja v a 2 s .c o m*/ * @param start * start offset of this buffer array * @param len * The maximum number of bytes to be accessed * @param array * The array from/to which bytes are to be read/written * @param arrayOffset * The offset within the given array of the first byte to be read or written * @param visitor * implement of how to visit the byte buffer */ void multiple(long start, int len, byte[] array, int arrayOffset, Visitor visitor) { assert len >= 0; long end = start + len; int startBuffer = (int) (start / bufferSize), startOffset = (int) (start % bufferSize); int endBuffer = (int) (end / bufferSize), endOffset = (int) (end % bufferSize); assert array.length >= len + arrayOffset; assert startBuffer >= 0 && startBuffer < bufferCount; assert endBuffer >= 0 && endBuffer < bufferCount || (endBuffer == bufferCount && endOffset == 0); if (startBuffer >= locks.length || startBuffer < 0) { String msg = "Failed multiple, start=" + start + ",startBuffer=" + startBuffer + ",bufferSize=" + bufferSize; LOG.error(msg); throw new RuntimeException(msg); } int srcIndex = 0, cnt = -1; for (int i = startBuffer; i <= endBuffer; ++i) { Lock lock = locks[i]; lock.lock(); try { ByteBuffer bb = buffers[i]; if (i == startBuffer) { cnt = bufferSize - startOffset; if (cnt > len) cnt = len; bb.limit(startOffset + cnt).position(startOffset); } else if (i == endBuffer) { cnt = endOffset; bb.limit(cnt).position(0); } else { cnt = bufferSize; bb.limit(cnt).position(0); } visitor.visit(bb, array, srcIndex + arrayOffset, cnt); srcIndex += cnt; } finally { lock.unlock(); } } assert srcIndex == len; }
From source file:org.apache.htrace.impl.PackedBufferManager.java
private void readAndValidateResponseFrame(SelectionKey sockKey, ByteBuffer buf, long expectedSeq, int expectedMethodId) throws IOException { buf.clear();//from www . j av a 2 s . c o m buf.limit(PackedBuffer.HRPC_RESP_FRAME_LENGTH); doRecv(sockKey, buf); buf.flip(); buf.order(ByteOrder.LITTLE_ENDIAN); long seq = buf.getLong(); if (seq != expectedSeq) { throw new IOException("Expected sequence number " + expectedSeq + ", but got sequence number " + seq); } int methodId = buf.getInt(); if (expectedMethodId != methodId) { throw new IOException("Expected method id " + expectedMethodId + ", but got " + methodId); } int errorLength = buf.getInt(); buf.getInt(); if ((errorLength < 0) || (errorLength > PackedBuffer.MAX_HRPC_ERROR_LENGTH)) { throw new IOException("Got server error with invalid length " + errorLength); } else if (errorLength > 0) { buf.clear(); buf.limit(errorLength); doRecv(sockKey, buf); buf.flip(); CharBuffer charBuf = StandardCharsets.UTF_8.decode(buf); String serverErrorStr = charBuf.toString(); throw new IOException("Got server error " + serverErrorStr); } }
From source file:org.eclipse.packagedrone.utils.rpm.parse.RpmInputStream.java
protected RpmLead readLead() throws IOException { final byte[] magic = readComplete(4); if (!Arrays.equals(magic, Rpms.LEAD_MAGIC)) { throw new IOException(String.format("File corrupt: Expected magic %s, read: %s", Arrays.toString(Rpms.LEAD_MAGIC), Arrays.toString(magic))); }// w w w . j a v a2 s .c o m final byte[] version = readComplete(2); final short type = this.in.readShort(); final short arch = this.in.readShort(); final byte[] nameData = readComplete(66); // NAME final ByteBuffer nameBuffer = ByteBuffer.wrap(nameData); for (int i = 0; i < nameData.length; i++) { if (nameData[i] == 0) { nameBuffer.limit(i); break; } } final String name = StandardCharsets.UTF_8.decode(nameBuffer).toString(); final short os = this.in.readShort(); final int sigType = this.in.readUnsignedShort(); skipFully(16); // RESERVED return new RpmLead(version[0], version[1], name, sigType, type, arch, os); }
From source file:com.yobidrive.diskmap.needles.Needle.java
public void putNeedleInBuffer(ByteBuffer result) throws Exception { int startPosition = result.position(); result.limit(result.capacity()); result.putInt(MAGICSTART);//from w ww .j a v a 2 s . co m result.putLong(needleNumber); result.put(flags); result.putInt(keyBytes.length); result.put(keyBytes); result.putInt(version == null ? 0 : version.toBytes().length); if (version != null) result.put(version.toBytes()); result.putInt(previousNeedle == null ? -1 : previousNeedle.getNeedleFileNumber()); // Chaining result.putLong(previousNeedle == null ? -1L : previousNeedle.getNeedleOffset()); // Chaining result.putInt(originalFileNumber); // Original needle location (for cleaning) result.putInt(originalSize); // Original needle size (for cleaning) result.putInt(data == null ? 0 : data.length); if (data != null) result.put(data); result.putInt(MAGICEND); result.put(hashMD5()); while (((result.position() - startPosition) % 256) > 0) { result.put(PADDING); } result.flip(); }
From source file:org.apache.camel.component.file.FileOperations.java
private void writeFileByStream(InputStream in, File target) throws IOException { FileChannel out = null;// w ww . j a va 2s. co m try { out = prepareOutputFileChannel(target, out); if (LOG.isTraceEnabled()) { LOG.trace("Using InputStream to transfer from: " + in + " to: " + out); } int size = endpoint.getBufferSize(); byte[] buffer = new byte[size]; ByteBuffer byteBuffer = ByteBuffer.wrap(buffer); int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { if (bytesRead < size) { byteBuffer.limit(bytesRead); } out.write(byteBuffer); byteBuffer.clear(); } } finally { IOHelper.close(in, target.getName(), LOG); IOHelper.close(out, target.getName(), LOG); } }
From source file:org.apache.hadoop.hdfs.RemoteBlockReader2.java
@Override public int read(ByteBuffer buf) throws IOException { if (curDataSlice == null || curDataSlice.remaining() == 0 && bytesNeededToFinish > 0) { try (TraceScope ignored = tracer.newScope("RemoteBlockReader2#readNextPacket(" + blockId + ")")) { readNextPacket();/*from w ww . ja va 2s . com*/ } } if (curDataSlice.remaining() == 0) { // we're at EOF now return -1; } int nRead = Math.min(curDataSlice.remaining(), buf.remaining()); ByteBuffer writeSlice = curDataSlice.duplicate(); writeSlice.limit(writeSlice.position() + nRead); buf.put(writeSlice); curDataSlice.position(writeSlice.position()); return nRead; }
From source file:client.MultiplexingClient.java
/** * Creates a new packet with a size chosen randomly between * MIN_SIZE and MAX_SIZE. /*from w w w . java2s .c o m*/ */ private ByteBuffer generateNextPacket() { // Generate a random size between int size = MIN_SIZE + r.nextInt(maxPcktSize - MIN_SIZE); ByteBuffer buffer = ByteBuffer.allocate(size); buffer.put(SimpleProtocolDecoder.STX); for (int i = 0; i < size - 2; i++) { buffer.put((byte) ('0' + (i % 10))); } buffer.put(SimpleProtocolDecoder.ETX); buffer.limit(buffer.position()); buffer.flip(); return buffer; }
From source file:com.google.flatbuffers.Table.java
/** * Get a whole vector as a ByteBuffer./*from w w w.j a va 2s . c o m*/ * * This is efficient, since it only allocates a new {@link ByteBuffer} object, * but does not actually copy the data, it still refers to the same bytes * as the original ByteBuffer. Also useful with nested FlatBuffers, etc. * * @param vector_offset The position of the vector in the byte buffer * @param elem_size The size of each element in the array * @return The {@link ByteBuffer} for the array */ protected ByteBuffer __vector_as_bytebuffer(int vector_offset, int elem_size) { int o = __offset(vector_offset); if (o == 0) return null; ByteBuffer bb = this.bb.duplicate().order(ByteOrder.LITTLE_ENDIAN); int vectorstart = __vector(o); bb.position(vectorstart); bb.limit(vectorstart + __vector_len(o) * elem_size); return bb; }