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:com.corundumstudio.socketio.SocketIOEncoder.java

License:Apache License

private void handle(WebSocketPacketMessage webSocketPacketMessage, Channel channel, ByteBuf out)
        throws IOException {
    encoder.encodePacket(webSocketPacketMessage.getPacket(), out);
    WebSocketFrame res = new TextWebSocketFrame(out);
    log.trace("Out message: {} sessionId: {}", out.toString(CharsetUtil.UTF_8),
            webSocketPacketMessage.getSessionId());
    channel.writeAndFlush(res);/*from   w  w  w.  j  a  va2 s.c  om*/
    if (!out.isReadable()) {
        out.release();
    }
}

From source file:com.crm.provisioning.thread.osa.CallbackServerHandler.java

License:Apache License

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

        if (is100ContinueExpected(request)) {
            send100Continue(ctx);/*from w ww . j av a  2 s .  c om*/
        }

        buffer.setLength(0);
        requestDate = new Date();
        appendDecoderResult(buffer, request);
    }

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

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            buffer.append(content.toString(CharsetUtil.UTF_8));

            appendDecoderResult(buffer, request);
        }

        if (msg instanceof LastHttpContent) {
            String actionType = parserContent();

            writeResponse((LastHttpContent) msg, ctx, actionType);
        }
    }
}

From source file:com.dwarf.netty.guide.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   w  w  w  .  j  a  v a2s  . com*/
        }

        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<CharSequence, CharSequence> h : headers) {
                CharSequence key = h.getKey();
                CharSequence 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 (CharSequence name : trailer.trailingHeaders().names()) {
                    for (CharSequence 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:com.example.discard.DiscardServerHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    log.info("message coming.");
    final ByteBuf byteBuf = (ByteBuf) msg;
    final EmitterProcessor<Byte> emitter = EmitterProcessor.create();

    // ??? ByteBuf.toString(StandardCharset.UTF_8) ????
    final Mono<String> messageMono = emitter.collectList().map(DiscardServerHandler::unBoxing)
            .map(bs -> new String(bs, StandardCharsets.UTF_8));
    messageMono.subscribe(message -> log.info("received message: {}", message));
    messageMono.doOnTerminate(() -> ReferenceCountUtil.release(byteBuf));

    while (byteBuf.isReadable()) {
        emitter.onNext(byteBuf.readByte());
    }//w ww. j a va2 s .  c  o  m
    emitter.onComplete();
}

From source file:com.facebook.nifty.core.NiftyDispatcher.java

License:Apache License

private void writeResponse(ChannelHandlerContext ctx, TNiftyTransport messageTransport,
        int responseSequenceId) {
    // Ensure responses to requests are written in the same order the requests
    // were received.
    synchronized (responseMap) {
        ByteBuf response = messageTransport.getOutputBuffer();
        ThriftTransportType transportType = messageTransport.getTransportType();
        int currentResponseId = lastResponseWrittenId.get() + 1;
        if (responseSequenceId != currentResponseId) {
            // This response is NOT next in line of ordered responses, save it to
            // be sent later, after responses to all earlier requests have been
            // sent.
            responseMap.put(responseSequenceId, response);
        } else {// w  ww  . j  ava 2 s. c o  m
            // This response was next in line, write this response now, and see if
            // there are others next in line that should be sent now as well.
            do {
                if (response.isReadable()) {
                    response = addFraming(ctx, response, transportType);
                    //ctx.nextOutboundByteBuffer().writeBytes(response);
                    ctx.channel().write(response);
                    //response.release();
                }
                lastResponseWrittenId.incrementAndGet();
                ++currentResponseId;
                response = responseMap.remove(currentResponseId);
            } while (null != response);

            ctx.channel().flush();

            // Now that we've written some responses, check if reads should be unblocked
            if (isChannelReadBlocked(ctx)) {
                int lastRequestSequenceId = dispatcherSequenceId.get();
                if (lastRequestSequenceId <= lastResponseWrittenId.get() + queuedResponseLimit) {
                    unblockChannelReads(ctx);
                }
            }
        }
    }
}

From source file:com.facebook.nifty.core.NiftyDispatcher.java

License:Apache License

private ByteBuf addFraming(ChannelHandlerContext ctx, ByteBuf response, ThriftTransportType transportType) {
    if (!response.isReadable()) {
        // Empty response from one-way message, don't frame it
        return response;
    }//from  w  w w. j  av  a 2s  .c  o  m

    if (transportType == ThriftTransportType.UNFRAMED) {
        return response;
    } else if (transportType == ThriftTransportType.FRAMED) {
        ByteBuf frameSizeBuffer = ctx.alloc().buffer(4);
        frameSizeBuffer.writeInt(response.readableBytes());
        return Unpooled.wrappedBuffer(frameSizeBuffer, response);
    } else {
        throw new UnsupportedOperationException("Header protocol is not supported");
    }
}

From source file:com.facebook.nifty.core.ThriftFrameDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {

    if (!buffer.isReadable()) {
        return;//from  www  .  j  a  v  a  2  s.c  o m
    }
    TTransport ttransport = null;
    short firstByte = buffer.getUnsignedByte(0);
    if (firstByte >= 0x80) {
        // A non-zero MSB for the first byte of the message implies the message starts with a
        // protocol id (and thus it is unframed).
        ttransport = tryDecodeUnframedMessage(ctx, buffer);
    } else if (buffer.readableBytes() < MESSAGE_FRAME_SIZE) {
        // Expecting a framed message, but not enough bytes available to read the frame size
        ttransport = null;
        log.error("Expecting a framed message, but not enough bytes available to read the frame size {}",
                MESSAGE_FRAME_SIZE);
    } else {
        // Messages with a zero MSB in the first byte are framed messages
        ttransport = tryDecodeFramedMessage(ctx, buffer);
    }
    if (ttransport != null) {
        out.add(ttransport);
    } else {
        log.error("ttransport is null , firstByte is {}", firstByte);
    }
}

From source file:com.fjn.helper.frameworkex.netty.v4.discardserver.DiscardServerHandler.java

License:Apache License

/**
 * ??//from w  w w .ja  v a 2  s .c o  m
 */
public void channelRead2(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    try {
        while (in.isReadable()) {
            System.out.print((char) in.readByte());
            System.out.flush();
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.fjn.helper.frameworkex.netty.v4.discardserver.DiscardServerHandler.java

License:Apache License

/**
 * ???/*from  www  .  java2  s. co m*/
 * @param ctx
 * @param msg
 * @throws Exception
 */
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    try {
        while (in.isReadable()) {
            char c = (char) in.readByte();
            content += c;
            if (c == '\n' || c == '\r') {
                if (!line.isEmpty()) {
                    System.out.println(line);
                }
                if ("quit".equals(line)) {
                    ByteBuf bf = ctx.alloc().buffer(content.getBytes().length);
                    bf.setBytes(0, content.getBytes());
                    final ChannelFuture f = ctx.writeAndFlush(bf); // (3)
                    f.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws InterruptedException {
                            assert f == future;
                            ctx.close();
                        }
                    }); // (4)
                }
                line = "";
                continue;
            } else {
                line += c;
            }
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.flysoloing.learning.network.netty.http.snoop.HttpSnoopServerHandler.java

License:Apache License

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

        if (HttpUtil.is100ContinueExpected(request)) {
            send100Continue(ctx);/*from   ww  w  .  ja v a2s  .  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(HttpHeaderNames.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 (Entry<String, String> h : headers) {
                CharSequence key = h.getKey();
                CharSequence 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 (CharSequence name : trailer.trailingHeaders().names()) {
                    for (CharSequence 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);
            }
        }
    }
}