Example usage for io.netty.buffer ByteBuf isReadable

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

Introduction

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

Prototype

public abstract boolean isReadable();

Source Link

Document

Returns true if and only if (this.writerIndex - this.readerIndex) is greater than 0 .

Usage

From source file:io.aos.netty5.http.snoop.HttpSnoopServerHandler.java

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaderUtil.is100ContinueExpected(request)) {
            send100Continue(ctx);//from   ww  w  .  jav  a  2  s .c  o m
        }

        buf.setLength(0);
        buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        buf.append("===================================\r\n");

        buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(request.headers().get(HOST, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.uri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, String> h : headers) {
                String key = h.getKey();
                String value = h.getValue();
                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            buf.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            buf.append("\r\n");
        }

        appendDecoderResult(buf, request);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
            appendDecoderResult(buf, request);
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (String name : trailer.trailingHeaders().names()) {
                    for (String value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}

From source file:io.aos.netty5.http2.client.HttpResponseHandler.java

License:Apache License

@Override
protected void messageReceived(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    int streamId = Integer.parseInt(msg.headers().get(Http2HttpHeaders.Names.STREAM_ID));
    ChannelPromise promise = streamidPromiseMap.get(streamId);
    if (promise == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {//  w w w  . ja va  2 s.  co m
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
        }

        promise.setSuccess();
    }
}

From source file:io.bsoa.rpc.grpc.client12.HttpResponseHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    System.out.println("=======4======>" + ctx.pipeline().names() + "<=========" + ctx.pipeline().toMap());
    Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;//w  w  w  . j a  v  a 2  s  . c om
    }

    Entry<ChannelFuture, ChannelPromise> entry = streamidPromiseMap.get(streamId);
    if (entry == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
        }

        entry.getValue().setSuccess();
    }
}

From source file:io.cettia.asity.bridge.netty4.NettyServerHttpExchange.java

License:Apache License

void handleChunk(HttpContent chunk) {
    // To obtain chunkAction
    read();/* w ww .  jav a 2s  . c  o  m*/
    ByteBuf buf = chunk.content();
    if (buf.isReadable() && this.chunkAction != null) {
        this.chunkAction.on(buf.nioBuffer());
    }
    if (chunk instanceof LastHttpContent) {
        endActions.fire();
    }
}

From source file:io.codis.nedis.handler.RedisResponseDecoder.java

License:Apache License

private Long decodeLong(ByteBuf in) throws ProtocolException {
    byte sign = in.readByte();
    final MutableLong l;
    boolean negative;
    if (sign == '-') {
        negative = true;//from w ww. ja  v a 2  s.  c om
        l = new MutableLong(0);
    } else {
        negative = false;
        l = new MutableLong(toDigit(sign));
    }
    final MutableBoolean reachCR = new MutableBoolean(false);
    setReaderIndex(in, in.forEachByte(new ByteBufProcessor() {

        @Override
        public boolean process(byte value) throws Exception {
            if (value == '\r') {
                reachCR.setTrue();
                return false;
            } else {
                if (value >= '0' && value <= '9') {
                    l.setValue(l.longValue() * 10 + toDigit(value));
                } else {
                    throw new ProtocolException("Response is not ended by CRLF");
                }
                return true;
            }
        }
    }));
    if (!reachCR.booleanValue()) {
        return null;
    }
    if (!in.isReadable()) {
        return null;
    }
    if (in.readByte() != '\n') {
        throw new ProtocolException("Response is not ended by CRLF");
    }
    return negative ? -l.longValue() : l.longValue();
}

From source file:io.gatling.http.client.body.multipart.impl.PartImpl.java

License:Apache License

long transferTo(ByteBuf source, WritableByteChannel target, PartImplState sourceFullyWrittenState)
        throws IOException {

    int transferred = 0;
    if (target instanceof GatheringByteChannel) {
        transferred = source.readBytes((GatheringByteChannel) target, source.readableBytes());
    } else {//from w w w  .j av a  2s. co  m
        for (ByteBuffer byteBuffer : source.nioBuffers()) {
            int len = byteBuffer.remaining();
            int written = target.write(byteBuffer);
            transferred += written;
            if (written != len) {
                // couldn't write full buffer, exit loop
                break;
            }
        }
        // assume this is a basic single ByteBuf
        source.readerIndex(source.readerIndex() + transferred);
    }

    if (source.isReadable()) {
        slowTarget = true;
    } else {
        state = sourceFullyWrittenState;
    }
    return transferred;
}

From source file:io.gatling.http.client.test.listener.CompleteResponseListener.java

License:Apache License

@Override
public void onHttpResponseBodyChunk(ByteBuf chunk, boolean last) {

    if (chunk.isReadable()) {
        if (chunks == null) {
            chunks = new ArrayList<>(1);
        }//  w ww.j av a  2s.  co  m
        chunks.add(chunk.retain());
    }

    if (last) {
        onComplete();
    }
}

From source file:io.gatling.netty.util.ahc.ByteBufUtils.java

License:Apache License

static String decodeString(Charset charset, ByteBuf src) {
    if (!src.isReadable()) {
        return "";
    }//www .  ja v  a  2 s  . c  om
    return decode(src, charset).toString();
}

From source file:io.gatling.netty.util.ahc.ByteBufUtils.java

License:Apache License

static char[] decodeChars(Charset charset, ByteBuf src) {
    if (!src.isReadable()) {
        return EMPTY_CHARS;
    }/*from  w  w  w.  j av  a 2 s.  c  o  m*/
    return toCharArray(decode(src, charset));
}

From source file:io.grpc.alts.internal.ByteBufTestUtils.java

License:Apache License

/** Fragment byte buffer into multiple pieces. */
public static List<ByteBuf> fragmentByteBuf(ByteBuf in, int num, RegisterRef ref) {
    ByteBuf buf = in.slice();
    Preconditions.checkArgument(num > 0);
    List<ByteBuf> fragmentedBufs = new ArrayList<>(num);
    int fragmentSize = buf.readableBytes() / num;
    while (buf.isReadable()) {
        int readBytes = num == 0 ? buf.readableBytes() : fragmentSize;
        ByteBuf tmpBuf = getDirectBuffer(readBytes, ref);
        tmpBuf.writeBytes(buf, readBytes);
        fragmentedBufs.add(tmpBuf);//from  w w  w . j  a va 2  s  .co  m
        num--;
    }
    return fragmentedBufs;
}