Example usage for java.nio ByteBuffer limit

List of usage examples for java.nio ByteBuffer limit

Introduction

In this page you can find the example usage for java.nio ByteBuffer limit.

Prototype

public final Buffer limit(int newLimit) 

Source Link

Document

Sets the limit of this buffer.

Usage

From source file:com.koda.integ.hbase.util.CacheableSerializer.java

@Override
public void write(ByteBuffer buf, Cacheable obj) throws IOException {
    if (deserializer.get() == null) {
        CacheableDeserializer<Cacheable> des = obj.getDeserializer();
        deserializer.compareAndSet(null, des);
    }/*from   w w w .  jav  a  2  s .  co  m*/
    // Serializer does not honor current buffer position
    int len = obj.getSerializedLength();
    int pos = buf.position();
    obj.serialize(buf);
    buf.limit(len + pos);
    buf.position(len + pos);
}

From source file:com.slytechs.capture.file.editor.FileEditorImpl.java

/**
 * @param headerReader//  www.ja v  a  2s  .  c  om
 * @param l
 * @param length
 * @throws IOException
 */
private PartialBuffer fetchPartialBuffer(final HeaderReader lengthGetter, final long global,
        final int minLength) throws IOException {

    final RegionSegment<PartialLoader> segment = this.edits.getSegment(global);
    final PartialLoader loader = segment.getData();
    final long regional = segment.mapGlobalToRegional(global);

    final PartialBuffer blockBuffer = loader.fetchBlock(regional, minLength);

    final int p = (int) (regional - blockBuffer.getStartRegional());

    /*
     * Make sure the next record we want to fetch resides in the existing shared
     * buffer, otherwise we have to prefetch another buffer.
     */
    if ((p < 0) || (blockBuffer.checkBoundsRegional(regional, minLength) == false)) {

        throw new IllegalStateException("Unable to prefetch buffer [" + regional + "/" + minLength + "]");
    }

    final ByteBuffer buffer = blockBuffer.getByteBuffer();

    buffer.limit(p + lengthGetter.getMinLength());
    buffer.position(p);

    return blockBuffer;
}

From source file:com.google.flatbuffers.Table.java

/**
 * Create a Java `String` from UTF-8 data stored inside the FlatBuffer.
 *
 * This allocates a new string and converts to wide chars upon each access,
 * which is not very efficient. Instead, each FlatBuffer string also comes with an
 * accessor based on __vector_as_bytebuffer below, which is much more efficient,
 * assuming your Java program can handle UTF-8 data directly.
 *
 * @param offset An `int` index into the Table's ByteBuffer.
 * @return Returns a `String` from the data stored inside the FlatBuffer at `offset`.
 *//*from w  w  w. j  ava 2 s  .c  o  m*/
protected String __string(int offset) {
    CharsetDecoder decoder = UTF8_DECODER.get();
    decoder.reset();

    offset += bb.getInt(offset);
    ByteBuffer src = bb.duplicate().order(ByteOrder.LITTLE_ENDIAN);
    int length = src.getInt(offset);
    src.position(offset + SIZEOF_INT);
    src.limit(offset + SIZEOF_INT + length);

    int required = (int) ((float) length * decoder.maxCharsPerByte());
    CharBuffer dst = CHAR_BUFFER.get();
    if (dst == null || dst.capacity() < required) {
        dst = CharBuffer.allocate(required);
        CHAR_BUFFER.set(dst);
    }

    dst.clear();

    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new Error(x);
    }

    return dst.flip().toString();
}

From source file:de.csdev.ebus.command.EBusCommandUtils.java

/**
 * @param commandChannel/*from ww w.ja  v  a2s. c  o  m*/
 * @return
 */
public static ByteBuffer getMasterTelegramMask(IEBusCommandMethod commandChannel) {

    // byte len = 0;
    ByteBuffer buf = ByteBuffer.allocate(50);
    buf.put(commandChannel.getSourceAddress() == null ? (byte) 0x00 : (byte) 0xFF); // QQ - Source
    buf.put(commandChannel.getDestinationAddress() == null ? (byte) 0x00 : (byte) 0xFF); // ZZ - Target
    buf.put(new byte[] { (byte) 0xFF, (byte) 0xFF }); // PB SB - Command
    buf.put((byte) 0xFF); // NN - Length

    if (commandChannel.getMasterTypes() != null) {
        for (IEBusValue entry : commandChannel.getMasterTypes()) {
            IEBusType<?> type = entry.getType();

            if (entry.getName() == null && type instanceof EBusTypeBytes && entry.getDefaultValue() != null) {
                for (int i = 0; i < type.getTypeLength(); i++) {
                    buf.put((byte) 0xFF);
                }
            } else {
                for (int i = 0; i < type.getTypeLength(); i++) {
                    buf.put((byte) 0x00);

                }
            }
        }
    }

    buf.put((byte) 0x00); // Master CRC

    // set limit and reset position
    buf.limit(buf.position());
    buf.position(0);

    return buf;
}

From source file:net.jradius.freeradius.FreeRadiusListener.java

public JRadiusEvent parseRequest(ListenerRequest listenerRequest, ByteBuffer notUsed, InputStream in)
        throws Exception {
    FreeRadiusRequest request = (FreeRadiusRequest) requestObjectPool.borrowObject();
    request.setBorrowedFromPool(requestObjectPool);

    int totalLength = (int) (RadiusFormat.readUnsignedInt(in) - 4);
    int readOffset = 0;

    ByteBuffer buffer = request.buffer_in;

    if (totalLength < 0 || totalLength > buffer.capacity()) {
        return null;
    }/*from www.  j a v  a2  s .co m*/

    buffer.clear();
    byte[] payload = buffer.array();

    while (readOffset < totalLength) {
        int result = in.read(payload, readOffset, totalLength - readOffset);
        if (result < 0)
            return null;
        readOffset += result;
    }

    buffer.limit(totalLength);

    long nameLength = RadiusFormat.getUnsignedInt(buffer);

    if (nameLength < 0 || nameLength > 1024) {
        throw new RadiusException("KeepAlive rlm_jradius connection has been closed");
    }

    byte[] nameBytes = new byte[(int) nameLength];
    buffer.get(nameBytes);

    int messageType = RadiusFormat.getUnsignedByte(buffer);
    int packetCount = RadiusFormat.getUnsignedByte(buffer);

    RadiusPacket rp[] = PacketFactory.parse(buffer, packetCount);

    long length = RadiusFormat.getUnsignedInt(buffer);

    if (length > buffer.remaining()) {
        throw new RadiusException("bad length");
    }

    AttributeList configItems = new AttributeList();
    format.unpackAttributes(configItems, buffer, (int) length, true);

    request.setConfigItems(configItems);
    request.setSender(new String(nameBytes));
    request.setType(messageType);
    request.setPackets(rp);

    return request;
}

From source file:org.apache.hadoop.hive.ql.io.orc.RecordReaderUtils.java

public static void readDirect(FSDataInputStream file, int len, ByteBuffer directBuf) throws IOException {
    // TODO: HDFS API is a mess, so handle all kinds of cases.
    // Before 2.7, read() also doesn't adjust position correctly, so track it separately.
    int pos = directBuf.position(), startPos = pos, endPos = pos + len;
    try {/* w  w  w .  j av a 2s.  co m*/
        while (pos < endPos) {
            int count = SHIMS.readByteBuffer(file, directBuf);
            if (count < 0)
                throw new EOFException();
            assert count != 0 : "0-length read: " + (endPos - pos) + "@" + (pos - startPos);
            pos += count;
            assert pos <= endPos : "Position " + pos + " > " + endPos + " after reading " + count;
            directBuf.position(pos);
        }
    } catch (UnsupportedOperationException ex) {
        assert pos == startPos;
        // Happens in q files and such.
        RecordReaderImpl.LOG.error("Stream does not support direct read; we will copy.");
        byte[] buffer = new byte[len];
        file.readFully(buffer, 0, buffer.length);
        directBuf.put(buffer);
    }
    directBuf.position(startPos);
    directBuf.limit(startPos + len);
}

From source file:com.linkedin.pinot.core.common.datatable.DataTableImplV2.java

@Nonnull
@Override//  w w  w .j  a va  2 s.  c  om
public <T> T getObject(int rowId, int colId) {
    int size = positionCursorInVariableBuffer(rowId, colId);
    ObjectType objectType = ObjectType.getObjectType(_variableSizeData.getInt());
    ByteBuffer byteBuffer = _variableSizeData.slice();
    byteBuffer.limit(size);
    try {
        return ObjectCustomSerDe.deserialize(byteBuffer, objectType);
    } catch (IOException e) {
        throw new RuntimeException("Caught exception while de-serializing object.", e);
    }
}

From source file:com.spidertracks.datanucleus.convert.ByteConverterContext.java

/**
 * Get the row key for the given id/*from  www.j a v  a2 s .  co  m*/
 * 
 * @param ec
 * @param id
 * @return
 */
public Bytes getRowKeyForId(Object id) {
    ByteBuffer buffer = getRowKeyForId(id, null);
    buffer.limit(buffer.position());
    buffer.reset();
    return Bytes.fromByteBuffer(buffer);
}

From source file:io.pcp.parfait.dxm.PcpMmvWriter.java

private void preparePerMetricBufferSlices() {
    for (PcpValueInfo info : metricData.values()) {
        TypeHandler<?> rawHandler = info.getTypeHandler();
        int bufferPosition = rawHandler.requiresLargeStorage() ? info.getLargeValue().getOffset()
                : info.getOffset();/*  w w w  . j a v  a  2s . c om*/
        // need to position the original buffer first, as the sliced buffer starts from there
        dataFileBuffer.position(bufferPosition);
        ByteBuffer metricByteBufferSlice = dataFileBuffer.slice();
        metricByteBufferSlice.limit(rawHandler.getDataLength());
        perMetricByteBuffers.put(info, metricByteBufferSlice);
        metricByteBufferSlice.order(dataFileBuffer.order());
    }
}