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 int limit() 

Source Link

Document

Returns the limit of this buffer.

Usage

From source file:org.redisson.codec.JsonJacksonCodec.java

@Override
public Object decodeMapValue(ByteBuffer bytes) {
    try {/*from  ww w  . j a v  a 2 s  . c om*/
        return mapObjectMapper.readValue(bytes.array(), bytes.arrayOffset() + bytes.position(), bytes.limit(),
                Object.class);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:net.phoenix.thrift.hello.ThreadPoolTest.java

@Test
public void testBinary() throws Exception {
    LOG.info("Client starting....");
    String name = "Hello ";
    // TTransport transport = new TNonblockingSocket("localhost", 9804);
    TTransport transport = new TSocket("localhost", 9804);
    transport.open();/*from w w  w  . j  a va2 s  .c om*/
    // TTransport transport = new TTransport(socket);
    TProtocol protocol = new TBinaryProtocol(transport);
    HelloService.Client client = new HelloService.Client(protocol);
    try {

        ByteBuffer buffer = client.testBinary(ByteBuffer.wrap(name.getBytes("UTF-8")));

        assertEquals(new String(buffer.array(), buffer.position(), buffer.limit() - buffer.position(), "UTF-8"),
                "Hello " + name);
        // System.out.println(message);
    } finally {
        transport.close();
    }
}

From source file:com.linkedin.pinot.core.segment.index.converter.SegmentV1V2ToV3FormatConverter.java

private void readCopyBuffers(SegmentDirectory.Reader reader, SegmentDirectory.Writer writer, String column,
        ColumnIndexType indexType) throws IOException {

    PinotDataBuffer oldBuffer = reader.getIndexFor(column, indexType);
    Preconditions.checkState(oldBuffer.size() >= 0 && oldBuffer.size() < Integer.MAX_VALUE,
            "Buffer sizes of greater than 2GB is not supported. segment: " + reader.toString() + ", column: "
                    + column);/*from w  ww .  j a  v a  2  s.  co  m*/
    PinotDataBuffer newDictBuffer = writer.newIndexFor(column, indexType, (int) oldBuffer.size());
    // this shouldn't copy data
    ByteBuffer bb = oldBuffer.toDirectByteBuffer(0, (int) oldBuffer.size());
    newDictBuffer.readFrom(bb, 0, 0, bb.limit());
}

From source file:jnative.io.AIO.java

public void submit() {
    NativeObject eventArray = new NativeObject(pendingOps.size() * SIZE_IOCB, true);
    long eventArrayAddress = eventArray.address();
    // TODO: more efficient way, pass the command list to native code through only one jni call
    for (int i = 0; i < pendingOps.size(); i++) {
        IOCommand command = pendingOps.get(i);

        final ByteBuffer bb = command.data;
        int pos = bb.position();
        int lim = bb.limit();
        assert (pos <= lim);
        int rem = (pos <= lim ? lim - pos : 0);

        prepare(eventArrayAddress + i * SIZE_IOCB, command.type, command.fd, command.offset,
                ((DirectBuffer) bb).address() + pos, rem, eventFd);
    }//w ww.  j a v a2s.  c om
    submit0(context, pendingOps.size(), eventArrayAddress);
    eventArray.free();
    pendingOps.clear();
}

From source file:org.apache.nifi.processor.util.listen.handler.socket.SSLSocketChannelHandler.java

@Override
public void run() {
    boolean eof = false;
    SSLSocketChannel sslSocketChannel = null;
    try {/* w w  w .ja  va2  s  .  c o m*/
        int bytesRead;
        final SocketChannel socketChannel = (SocketChannel) key.channel();
        final SocketChannelAttachment attachment = (SocketChannelAttachment) key.attachment();

        // get the SSLSocketChannel from the attachment
        sslSocketChannel = attachment.getSslSocketChannel();

        // SSLSocketChannel deals with byte[] so ByteBuffer isn't used here, but we'll use the size to create a new byte[]
        final ByteBuffer socketBuffer = attachment.getByteBuffer();
        byte[] socketBufferArray = new byte[socketBuffer.limit()];

        // read until no more data
        try {
            while ((bytesRead = sslSocketChannel.read(socketBufferArray)) > 0) {
                processBuffer(sslSocketChannel, socketChannel, bytesRead, socketBufferArray);
                logger.debug("bytes read from sslSocketChannel {}", new Object[] { bytesRead });
            }
        } catch (SocketTimeoutException ste) {
            // SSLSocketChannel will throw this exception when 0 bytes are read and the timeout threshold
            // is exceeded, we don't want to close the connection in this case
            bytesRead = 0;
        }

        // Check for closed socket
        if (bytesRead < 0) {
            eof = true;
            logger.debug("Reached EOF, closing connection");
        } else {
            logger.debug("No more data available, returning for selection");
        }
    } catch (ClosedByInterruptException | InterruptedException e) {
        logger.debug("read loop interrupted, closing connection");
        // Treat same as closed socket
        eof = true;
    } catch (ClosedChannelException e) {
        // ClosedChannelException doesn't have a message so handle it separately from IOException
        logger.error("Error reading from channel due to channel being closed", e);
        // Treat same as closed socket
        eof = true;
    } catch (IOException e) {
        logger.error("Error reading from channel due to {}", new Object[] { e.getMessage() }, e);
        // Treat same as closed socket
        eof = true;
    } finally {
        if (eof == true) {
            IOUtils.closeQuietly(sslSocketChannel);
            dispatcher.completeConnection(key);
        } else {
            dispatcher.addBackForSelection(key);
        }
    }
}

From source file:net.phoenix.thrift.hello.ThreadedSelectorTest.java

@Test
public void testBinary() throws Exception {
    LOG.info("Client starting....");
    String name = "Hello";
    // TTransport transport = new TNonblockingSocket("localhost", 9804);
    TTransport transport = new TFramedTransport(new TSocket("localhost", 9804));
    transport.open();//from w  w w  .ja v a  2  s  .c o  m
    // TTransport transport = new TTransport(socket);
    TProtocol protocol = new TBinaryProtocol(transport);
    HelloService.Client client = new HelloService.Client(protocol);
    try {

        ByteBuffer buffer = client.testBinary(ByteBuffer.wrap(name.getBytes("UTF-8")));
        assertEquals(new String(buffer.array(), buffer.position(), buffer.limit() - buffer.position(), "UTF-8"),
                "Hello " + name);
        // System.out.println(message);
    } finally {
        transport.close();
    }
}

From source file:rx.apache.http.consumers.ResponseConsumerEventStream.java

@Override
protected void onByteReceived(ByteBuffer buf, IOControl ioctrl) throws IOException {
    if (parentSubscription.isUnsubscribed()) {
        ioctrl.shutdown();//from   w w w  . j  a  va 2 s  . co m
    }
    while (buf.position() < buf.limit()) {
        byte b = buf.get();
        if (b == 10 || b == 13) {
            if (dataBuffer.hasContent()) {
                contentSubject.onNext(dataBuffer.getBytes());
            }
            dataBuffer.reset();
        } else {
            dataBuffer.addByte(b);
        }
    }
}

From source file:ja.lingo.engine.mergedindex.ChannelMergedIndex.java

public ChannelMergedIndex(String fileName, Map<String, IDictionaryIndex> indexFileNameToReaderMap)
        throws IOException {
    Arguments.assertNotNull("fileName", fileName);
    Arguments.assertNotNull("indexFileNameToReaderMap", indexFileNameToReaderMap);

    this.fileName = fileName;

    fisMappedByteBufferWrapper = new MappedByteBufferWrapper(fileName);

    ISliceReader sliceReader = new ByteBufferSliceReader(fisMappedByteBufferWrapper.getMappedByteBuffer());

    // read position + fill readerIntIdToReaderMap
    {// w  w w  .  j av  a 2  s .c o m
        ByteBuffer buffer = sliceReader.getSlice(SLICE_READER_INT_ID_TO_READER_ID_MAP);
        byte[] bytes = new byte[buffer.limit()];
        buffer.position(0);
        buffer.get(bytes);

        try {
            readerIntIdToReaderMap = _deserializeReaderIdToReaderMap(
                    new DataInputStream(new ByteArrayInputStream(bytes)), indexFileNameToReaderMap);
        } catch (IOException e) {
            Files.close(fisMappedByteBufferWrapper);
            throw e;
        }
    }

    groupsIndexLengthIntReader = new IntBufferIntReader(
            sliceReader.getSlice(SLICE_GROUPS_INDEX_LENGTH_LIST).asIntBuffer());
    groupsIntReader = new IntBufferIntReader(sliceReader.getSlice(SLICE_GROUPS_LIST).asIntBuffer());
}

From source file:com.haulmont.yarg.formatters.impl.DocxFormatter.java

private String toString(ByteBuffer bb) throws UnsupportedEncodingException {
    byte[] bytes = new byte[bb.limit()];
    bb.get(bytes);//from  w  w  w . j av a 2  s. co  m
    return new String(bytes, "UTF-8");
}

From source file:jext2.SymlinkInode.java

@NotThreadSafe(useLock = true)
private String readSlowSymlink() throws JExt2Exception, FileTooLarge {
    ByteBuffer buf = readData((int) getSize(), 0);
    return Ext2fsDataTypes.getString(buf, 0, buf.limit());
}