Example usage for java.nio ByteBuffer remaining

List of usage examples for java.nio ByteBuffer remaining

Introduction

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

Prototype

public final int remaining() 

Source Link

Document

Returns the number of remaining elements in this buffer, that is limit - position .

Usage

From source file:org.wso2.carbon.http2.transport.util.http2Encoder.java

@Override
public int write(ByteBuffer src) throws IOException {
    int l = 0;/*from   ww  w  . ja v  a2  s. c  o m*/
    //channel.newPromise();

    while (src.hasRemaining()) {
        byte[] b;//= new byte[chContext.channel().alloc().buffer().capacity()];
        //  if(src.remaining()<b.length){
        b = new byte[src.remaining()];
        src.get(b);
        // request.replace(Unpooled.wrappedBuffer(b));
        if (src.hasRemaining())
            encoder.writeData(chContext, streamId, Unpooled.wrappedBuffer(b), 0, false, promise);
        else {
            encoder.writeData(chContext, streamId, Unpooled.wrappedBuffer(b), 0, true, promise);
            isComplete = true;
        }
    }

    return src.position();
}

From source file:com.navercorp.pinpoint.common.server.bo.serializer.trace.v1.SpanBoTest.java

@Test
public void serialize_V1() {
    final SpanBo spanBo = new SpanBo();
    spanBo.setAgentId("agentId");
    spanBo.setApplicationId("applicationId");
    spanBo.setEndPoint("end");
    spanBo.setRpc("rpc");

    spanBo.setParentSpanId(5);/*  ww  w .  jav  a2  s .  c  o  m*/
    spanBo.setAgentStartTime(1);

    TransactionId transactionId = new TransactionId("agentId", 2, 3);
    spanBo.setTransactionId(transactionId);
    spanBo.setElapsed(4);
    spanBo.setStartTime(5);

    spanBo.setServiceType(ServiceType.STAND_ALONE.getCode());

    spanBo.setLoggingTransactionInfo(LoggingInfo.INFO.getCode());

    spanBo.setExceptionInfo(1000, "Exception");

    ByteBuffer bytes = spanSerializer.writeColumnValue(spanBo);

    SpanBo newSpanBo = new SpanBo();
    Buffer valueBuffer = new OffsetFixedBuffer(bytes.array(), bytes.arrayOffset(), bytes.remaining());
    int i = spanDecoder.readSpan(newSpanBo, valueBuffer);
    logger.debug("length:{}", i);
    Assert.assertEquals(bytes.limit(), i);
    Assert.assertEquals(newSpanBo.getAgentId(), spanBo.getAgentId());
    Assert.assertEquals(newSpanBo.getApplicationId(), spanBo.getApplicationId());
    Assert.assertEquals(newSpanBo.getAgentStartTime(), spanBo.getAgentStartTime());
    Assert.assertEquals(newSpanBo.getElapsed(), spanBo.getElapsed());
    Assert.assertEquals(newSpanBo.getEndPoint(), spanBo.getEndPoint());
    Assert.assertEquals(newSpanBo.getErrCode(), spanBo.getErrCode());
    Assert.assertEquals(newSpanBo.getFlag(), spanBo.getFlag());

    //        not included for serialization
    //        Assert.assertEquals(newSpanBo.getTraceAgentStartTime(), spanBo.getTraceAgentStartTime());
    //        Assert.assertEquals(newSpanBo.getTraceTransactionSequence(), spanBo.getTraceTransactionSequence());
    Assert.assertEquals(newSpanBo.getParentSpanId(), spanBo.getParentSpanId());

    Assert.assertEquals(newSpanBo.getServiceType(), spanBo.getServiceType());
    Assert.assertEquals(newSpanBo.getApplicationServiceType(), spanBo.getServiceType());

    Assert.assertEquals(newSpanBo.getVersion(), spanBo.getVersion());

    Assert.assertEquals(newSpanBo.getLoggingTransactionInfo(), spanBo.getLoggingTransactionInfo());

    Assert.assertEquals(newSpanBo.getExceptionId(), spanBo.getExceptionId());
    Assert.assertEquals(newSpanBo.getExceptionMessage(), spanBo.getExceptionMessage());

}

From source file:com.taobao.common.tfs.comm.TfsClient.java

public Object invoke(final BasePacket packet, final long timeout) throws TfsException {
    if (isDebugEnabled) {
        log.debug("send request [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
    }/*from  w ww. j a  va 2s.  c  o  m*/
    ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1);
    responses.put(packet.getChid(), queue);
    ByteBuffer bb = packet.getByteBuffer();
    bb.flip();
    byte[] data = new byte[bb.remaining()];
    bb.get(data);
    WriteFuture writeFuture = session.write(data);
    writeFuture.addListener(new IoFutureListener() {

        public void operationComplete(IoFuture future) {

            WriteFuture wfuture = (WriteFuture) future;
            if (wfuture.isWritten()) {
                return;
            }
            String error = "send message to tfs server error [" + packet.getChid() + "], tfs server: "
                    + session.getRemoteAddress() + ", maybe because this connection closed: "
                    + !session.isConnected();

            try {
                putResponse(packet.getChid(), new TfsException(error));
            } catch (TfsException e) {
                // should never happen
                log.error("put response fail", e);
            }

            // close this session
            if (session.isConnected()) {
                session.close();
            } else {
                TfsClientFactory.getInstance().removeClient(key);
            }
        }

    });

    Object response = null;
    try {
        response = queue.poll(timeout, TimeUnit.MILLISECONDS);
        if (response == null) { // timeout
            return null;
        } else if (response instanceof TfsException) {
            throw (TfsException) response;
        }
    } catch (InterruptedException e) {
        throw new TfsException("tfs client invoke error", e);
    } finally {
        responses.remove(packet.getChid());
        // For GC
        queue = null;
    }
    if (isDebugEnabled) {
        log.debug("return response [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
    }

    // do decode here
    if (response instanceof BasePacket) {
        ((BasePacket) response).decode();
    }
    return response;
}

From source file:com.taobao.tair.comm.TairClient.java

public Object invoke(final BasePacket packet, final long timeout) throws TairClientException {
    if (isDebugEnabled) {
        LOGGER.debug("send request [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
    }/*  w w w .  j  av  a 2 s  . c om*/
    ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1);
    responses.put(packet.getChid(), queue);
    ByteBuffer bb = packet.getByteBuffer();
    bb.flip();
    byte[] data = new byte[bb.remaining()];
    bb.get(data);
    WriteFuture writeFuture = session.write(data);
    writeFuture.addListener(new IoFutureListener() {

        public void operationComplete(IoFuture future) {
            WriteFuture wfuture = (WriteFuture) future;
            if (wfuture.isWritten()) {
                return;
            }
            String error = "send message to tair server error [" + packet.getChid() + "], tair server: "
                    + session.getRemoteAddress() + ", maybe because this connection closed :"
                    + !session.isConnected();
            LOGGER.warn(error);
            TairResponse response = new TairResponse();
            response.setRequestId(packet.getChid());
            response.setResponse(new TairClientException(error));
            try {
                putResponse(packet.getChid(), response.getResponse());
            } catch (TairClientException e) {
                // IGNORE,should not happen
            }
            // close this session
            if (session.isConnected())
                session.close();
            else
                clientFactory.removeClient(key);
        }

    });
    Object response = null;
    try {
        response = queue.poll(timeout, TimeUnit.MILLISECONDS);
        if (response == null) {
            throw new TairClientException("tair client invoke timeout,timeout is: " + timeout
                    + ",requestId is: " + packet.getChid() + "request type:" + packet.getClass().getName());
        } else if (response instanceof TairClientException) {
            throw (TairClientException) response;
        }
    } catch (InterruptedException e) {
        throw new TairClientException("tair client invoke error", e);
    } finally {
        responses.remove(packet.getChid());
        // For GC
        queue = null;
    }
    if (isDebugEnabled) {
        LOGGER.debug("return response [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
        LOGGER.debug("current responses size: " + responses.size());
    }

    // do decode here
    if (response instanceof BasePacket) {
        ((BasePacket) response).decode();
    }
    return response;
}

From source file:com.github.mrstampy.gameboot.otp.websocket.OtpEncryptedWebSocketHandler.java

private byte[] extractArray(WebSocketSession session, BinaryMessage message) throws IOException {
    ByteBuffer buf = message.getPayload();

    if (buf.hasArray())
        return buf.array();

    int size = buf.remaining();

    if (size == 0) {
        log.error("No message, closing session {}", session);
        session.close();/*w  w  w.j  a va2 s .  co m*/
        return null;
    }

    byte[] b = new byte[size];

    buf.get(b, 0, b.length);

    return b;
}

From source file:org.ojai.beans.jackson.DocumentParser.java

@Override
public byte[] getBinaryValue(Base64Variant bv) throws IOException {
    ByteBuffer buf = r.getBinary();
    byte[] result = new byte[buf.remaining()];
    buf.get(result);//from   w  w  w. j  a  v  a2s  .  c  o  m
    return result;
}

From source file:gridool.communication.transport.tcp.GridNioServer.java

private static void handleRead(final SocketChannel channel, final SelectionKey key,
        final ByteBuffer sharedReadBuf, final GridTransportListener notifier, final ExecutorService exec) {
    sharedReadBuf.clear();/* ww  w  .  j  a v  a  2s .  c  o m*/
    final SocketAddress remoteAddr = channel.socket().getRemoteSocketAddress();
    final int bytesRead;
    try {
        bytesRead = channel.read(sharedReadBuf);
    } catch (IOException e) {
        LOG.warn("Failed to read data from client: " + remoteAddr, e);
        NIOUtils.close(key);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Read " + bytesRead + " bytes from a client socket: " + remoteAddr);
    }
    if (bytesRead == -1) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Remote client closed connection: " + remoteAddr);
        }
        NIOUtils.close(key);
        return;
    } else if (bytesRead == 0) {
        return;
    }

    final GridMessageBuffer msgBuf = (GridMessageBuffer) key.attachment();
    sharedReadBuf.flip();
    while (sharedReadBuf.remaining() > 0) {
        msgBuf.read(sharedReadBuf);
        if (msgBuf.isFilled()) {
            exec.execute(new Runnable() {
                public void run() {
                    final GridCommunicationMessage msg = msgBuf.toMessage();
                    msgBuf.reset();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Recieved a GridCommunicationMessage [" + msg.getMessageId() + "]");
                    }
                    notifier.notifyListener(msg);
                }
            });
            break;
        }
    }
}

From source file:net.socket.nio.TimeClientHandle.java

private void handleInput(SelectionKey key) throws IOException {

    if (key.isValid()) {
        // ??//w w w. jav  a 2  s  .  c  om
        SocketChannel sc = (SocketChannel) key.channel();
        if (key.isConnectable()) {
            if (sc.finishConnect()) {
                sc.register(selector, SelectionKey.OP_READ);
                doWrite(sc);
            } else {
                System.exit(1);// 
            }
        }
        if (key.isReadable()) {
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            int readBytes = sc.read(readBuffer);
            if (readBytes > 0) {
                readBuffer.flip();
                byte[] bytes = new byte[readBuffer.remaining()];
                readBuffer.get(bytes);
                String body = new String(bytes, "UTF-8");
                System.out.println("Now is : " + body);
                this.stop = true;
            } else if (readBytes < 0) {
                // 
                key.cancel();
                sc.close();
            } else {
                ; // 0
            }
        }
    }

}

From source file:com.tera.common.network.nio.MMOConnection.java

final void createWriteBuffer(ByteBuffer buf) {
    if (primaryWriteBuffer == null) {
        // APPENDING FOR NULL

        primaryWriteBuffer = getReadWriteThread().getPooledBuffer();
        primaryWriteBuffer.put(buf);//from   www .j a v  a 2 s.c o  m
    } else {
        // PREPENDING ON EXISTING

        ByteBuffer temp = getReadWriteThread().getPooledBuffer();
        temp.put(buf);

        int remaining = temp.remaining();
        primaryWriteBuffer.flip();
        int limit = primaryWriteBuffer.limit();

        if (remaining >= primaryWriteBuffer.remaining()) {
            temp.put(primaryWriteBuffer);
            getReadWriteThread().recycleBuffer(primaryWriteBuffer);
            primaryWriteBuffer = temp;
        } else {
            primaryWriteBuffer.limit(remaining);
            temp.put(primaryWriteBuffer);
            primaryWriteBuffer.limit(limit);
            primaryWriteBuffer.compact();
            secondaryWriteBuffer = primaryWriteBuffer;
            primaryWriteBuffer = temp;
        }
    }
}

From source file:org.apache.cassandra.db.index.sasi.plan.Expression.java

public boolean contains(ByteBuffer value) {
    if (!TypeUtil.isValid(value, validator)) {
        int size = value.remaining();
        if ((value = TypeUtil.tryUpcast(value, validator)) == null) {
            logger.error("Can't cast value for {} to size accepted by {}, value size is {} bytes.",
                    index.getColumnName(), validator, size);
            return false;
        }//from   ww w .ja  va2s.co  m
    }

    if (lower != null) {
        // suffix check
        if (isLiteral) {
            if (!validateStringValue(value, lower.value))
                return false;
        } else {
            // range or (not-)equals - (mainly) for numeric values
            int cmp = validator.compare(lower.value, value);

            // in case of (NOT_)EQ lower == upper
            if (operation == Op.EQ || operation == Op.NOT_EQ)
                return cmp == 0;

            if (cmp > 0 || (cmp == 0 && !lower.inclusive))
                return false;
        }
    }

    if (upper != null && lower != upper) {
        // string (prefix or suffix) check
        if (isLiteral) {
            if (!validateStringValue(value, upper.value))
                return false;
        } else {
            // range - mainly for numeric values
            int cmp = validator.compare(upper.value, value);
            if (cmp < 0 || (cmp == 0 && !upper.inclusive))
                return false;
        }
    }

    // as a last step let's check exclusions for the given field,
    // this covers EQ/RANGE with exclusions.
    for (ByteBuffer term : exclusions) {
        if (isLiteral && validateStringValue(value, term))
            return false;
        else if (validator.compare(term, value) == 0)
            return false;
    }

    return true;
}