Example usage for io.netty.buffer ByteBuf readableBytes

List of usage examples for io.netty.buffer ByteBuf readableBytes

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readableBytes.

Prototype

public abstract int readableBytes();

Source Link

Document

Returns the number of readable bytes which is equal to (this.writerIndex - this.readerIndex) .

Usage

From source file:com.antsdb.saltedfish.server.mysql.packet.replication.HandshakeInitPacket.java

License:Open Source License

@Override
public void read(MysqlClientHandler handler, ByteBuf in) {
    // ignore handshake info, assure master is mysql 5.6
    in.readBytes(in.readableBytes());
}

From source file:com.antsdb.saltedfish.server.mysql.util.BufferUtils.java

License:Open Source License

public static String readString(ByteBuf buf) {
    String s;//from  w  ww  . ja v a 2s.c  om
    int bytes = buf.bytesBefore((byte) 0);
    if (bytes == -1) {
        // string might not be terminated by 0
        bytes = buf.readableBytes();
        s = buf.toString(buf.readerIndex(), bytes, Charset.defaultCharset());
        buf.skipBytes(bytes);
    } else {
        s = buf.toString(buf.readerIndex(), bytes, Charset.defaultCharset());
        buf.skipBytes(bytes + 1);
    }
    return s;
}

From source file:com.athena.dolly.websocket.server.test.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;/*from   w w  w.j av  a2s  .  c  o m*/
    }

    // Allow only GET methods.
    if (req.getMethod() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Send the demo page and favicon.ico
    if ("/".equals(req.getUri())) {
        ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
        setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }
    if ("/favicon.ico".equals(req.getUri())) {
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
        sendHttpResponse(ctx, req, res);
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, false);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}

From source file:com.athena.dolly.websocket.server.test.WebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
        try {// w  w w . j a v a  2  s .  c o  m
            fos.flush();
            fos.close();
            fos = null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return;
    }
    if (frame instanceof PingWebSocketFrame) {
        ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
        return;
    }

    if (frame instanceof TextWebSocketFrame) {

        // Send the uppercase string back.
        String fileName = ((TextWebSocketFrame) frame).text();
        logger.debug(String.format("Received file name is [%s]", fileName));

        destFile = new File(fileName + ".received");
        try {
            fos = new FileOutputStream(destFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        ctx.channel().write(new TextWebSocketFrame(fileName.toUpperCase()));
    }

    if (frame instanceof BinaryWebSocketFrame) {
        byte[] buffer = null;
        ByteBuf rawMessage = ((BinaryWebSocketFrame) frame).content();

        //logger.debug(">>>> BinaryWebSocketFrame Found, " + rawMessage);
        // check if this ByteBuf is DIRECT (no backing byte[])
        if (rawMessage.hasArray() == false) {
            int size = rawMessage.readableBytes();
            buffer = new byte[size];
            rawMessage.readBytes(buffer);

            try {
                fos.write(buffer);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            buffer = rawMessage.array();
        }
        logger.debug(">>>> Read Byte Array: " + buffer.length);

        return;
    }
}

From source file:com.athena.dolly.websocket.server.test.WebSocketSslServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//from w ww.  j  a  va  2 s .c  o m
    }

    // Allow only GET methods.
    if (req.getMethod() != GET) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // Send the demo page and favicon.ico
    if ("/".equals(req.getUri())) {
        ByteBuf content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req));
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

        res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
        setContentLength(res, content.readableBytes());

        sendHttpResponse(ctx, req, res);
        return;
    }

    if ("/favicon.ico".equals(req.getUri())) {
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
        sendHttpResponse(ctx, req, res);
        return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, false);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}

From source file:com.baidu.jprotobuf.pbrpc.transport.handler.RpcDataPackageDecoder.java

License:Apache License

protected Object decode(ChannelHandlerContext ctx, ByteBuf buf) throws Exception {

    // Make sure if the length field was received.
    if (buf.readableBytes() < RpcHeadMeta.SIZE) {
        // The length field was not received yet - return null.
        // This method will be invoked again when more packets are
        // received and appended to the buffer.
        return null;
    }/*from  www .j  av  a  2s  .  c  om*/

    // The length field is in the buffer.

    // Mark the current buffer position before reading the length field
    // because the whole frame might not be in the buffer yet.
    // We will reset the buffer position to the marked position if
    // there's not enough bytes in the buffer.
    buf.markReaderIndex();

    // Read the RPC head
    long rpcMessageDecoderStart = System.nanoTime();
    ByteBuffer buffer = buf.nioBuffer(buf.readerIndex(), RpcHeadMeta.SIZE);

    buffer.order(ByteOrder.LITTLE_ENDIAN);
    byte[] bytes = new byte[RpcHeadMeta.SIZE];
    buffer.get(bytes);

    RpcHeadMeta headMeta = new RpcHeadMeta();
    headMeta.read(bytes);

    // get total message size
    int messageSize = headMeta.getMessageSize() + RpcHeadMeta.SIZE;

    // Make sure if there's enough bytes in the buffer.
    if (buf.readableBytes() < messageSize) {
        // The whole bytes were not received yet - return null.
        // This method will be invoked again when more packets are
        // received and appended to the buffer.

        // Reset to the marked position to read the length field again
        // next time.
        buf.resetReaderIndex();

        return null;
    }

    // check magic code
    String magicCode = headMeta.getMagicCodeAsString();
    if (!ProtocolConstant.MAGIC_CODE.equals(magicCode)) {
        throw new Exception("Error magic code:" + magicCode);
    }
    // There's enough bytes in the buffer. Read it.
    byte[] totalBytes = new byte[messageSize];
    buf.readBytes(totalBytes, 0, messageSize);

    RpcDataPackage rpcDataPackage = new RpcDataPackage();
    rpcDataPackage.setTimeStamp(System.currentTimeMillis());
    rpcDataPackage.read(totalBytes);

    // check if a chunk package
    if (rpcDataPackage.isChunkPackage()) {

        Long chunkStreamId = rpcDataPackage.getChunkStreamId();

        RpcDataPackage chunkDataPackage = tempTrunkPackages.get(chunkStreamId);
        if (chunkDataPackage == null) {
            chunkDataPackage = rpcDataPackage;
            tempTrunkPackages.put(chunkStreamId, rpcDataPackage);
        } else {
            chunkDataPackage.mergeData(rpcDataPackage.getData());
        }

        if (rpcDataPackage.isFinalPackage()) {
            chunkDataPackage.chunkInfo(chunkStreamId, -1);
            tempTrunkPackages.remove(chunkStreamId);

            return chunkDataPackage;
        }

        return null;
    }

    long rpcMessageDecoderEnd = System.nanoTime();
    LOG.log(Level.FINE,
            "[profiling] nshead decode cost : " + (rpcMessageDecoderEnd - rpcMessageDecoderStart) / 1000);

    return rpcDataPackage;
}

From source file:com.barchart.http.server.HttpRequestChannelHandler.java

License:BSD License

private void sendServerError(final ChannelHandlerContext ctx, final ServerException cause) throws Exception {

    if (ctx.channel().isActive()) {

        final ByteBuf content = Unpooled.buffer();

        content.writeBytes(/*from  w  ww.j a v  a  2s .co m*/
                (cause.getStatus().code() + " " + cause.getStatus().reasonPhrase() + " - " + cause.getMessage())
                        .getBytes());

        final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, cause.getStatus());

        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());

        response.content().writeBytes(content);

        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

    }

}

From source file:com.basho.riak.client.core.netty.HealthCheckDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext chc, ByteBuf in, List<Object> list) throws Exception {
    // Make sure we have 4 bytes
    if (in.readableBytes() >= 4) {
        in.markReaderIndex();//from  w w w  . ja  v  a 2s.c  o  m
        int length = in.readInt();

        // See if we have the full frame.
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
        } else {
            byte code = in.readByte();
            byte[] protobuf = new byte[length - 1];
            in.readBytes(protobuf);

            chc.channel().pipeline().remove(this);
            if (code == RiakMessageCodes.MSG_ErrorResp) {
                logger.debug("Received MSG_ErrorResp reply to healthcheck");
                future.setException((riakErrorToException(protobuf)));
            } else {
                logger.debug("Healthcheck op successful; returned code {}", code);
                future.setMessage(new RiakMessage(code, protobuf));
            }
        }
    }
}

From source file:com.basho.riak.client.core.netty.RiakHttpMessageHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HttpResponse) {
        message = new RiakHttpMessage((HttpResponse) msg);
    }// w w  w  .  j a v  a 2 s . c  o m

    if (msg instanceof HttpContent) {
        /** TODO: commented for compilation
         * chunks.add(((HttpContent)msg).data().retain());
         * totalContentLength += ((HttpContent)msg).data().readableBytes();
         */

        if (msg instanceof LastHttpContent) {
            byte[] bytes = new byte[totalContentLength];
            int index = 0;
            for (ByteBuf buffer : chunks) {
                int readable = buffer.readableBytes();
                buffer.readBytes(bytes, index, readable);
                index += readable;
                buffer.release();
            }

            int responseCode = message.getResponse().getStatus().code();
            message.setContent(bytes);

            /**  TODO: commented for compilation
            if ( responseCode < 200 || 
            (responseCode >= 400 && responseCode != 404 && responseCode != 412 ) )
            {
            listener.onException(chc.channel(), new RiakResponseException(responseCode, new String(bytes)));
            }
            else
            { 
            message.setContent(bytes);
            listener.onSuccess(chc.channel(), message);
            }
            chc.channel().pipeline().remove(this);
             */
        }
    }
}

From source file:com.basho.riak.client.core.netty.RiakMessageCodec.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // Make sure we have 4 bytes
    if (in.readableBytes() >= 4) {
        in.markReaderIndex();// w ww.java2s . c  om
        int length = in.readInt();

        // See if we have the full frame.
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
            return;
        } else {
            byte code = in.readByte();
            byte[] array = new byte[length - 1];
            in.readBytes(array);
            out.add(new RiakMessage(code, array));
        }

    }
}