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.jayqqaa12.jbase.tcp.netty.code.DreamJSONDecoder.java

License:Open Source License

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

        if (in.readableBytes() <= 4) {
            break;
        }/*from   ww  w  . ja va 2 s .  co  m*/
        in.markReaderIndex();
        int length = in.readInt();
        if (length <= 0) {
            throw new Exception("a negative length occurd while decode!");
        }
        if (in.readableBytes() < length) {
            in.resetReaderIndex();
            break;
        }
        byte[] msg = new byte[length];
        in.readBytes(msg);
        out.add(new String(msg, "UTF-8"));
    }

}

From source file:com.jin.jlg.netty.websock.WebSocketIndexPageHandler.java

License:Apache License

@Override
protected void channelRead0(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.  java  2s .c o m
    }

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

    // Send the index page
    if ("/".equals(req.getUri()) || "/index.html".equals(req.getUri())) {
        String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath);
        ByteBuf content = WebSocketServerIndexPage.getContent(webSocketLocation);
        FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

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

        sendHttpResponse(ctx, req, res);
    } else {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
    }
}

From source file:com.jjneko.jjnet.networking.http.server.WebSocketHttpServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
    // Handle a bad request.
    if (!req.decoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;// ww  w .j  a va2s.  co m
    }

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

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

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

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

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

    /* TODO disconnect clients that are not valid JJNET clients */
}

From source file:com.just.server.http.websocketx.benchmarkserver.WebSocketServerHandler.java

License:Apache License

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {

    // Handle a bad request.
    if (!req.decoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//from  w w w  .j av a  2s. c o m
    }

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

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

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

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

    // Handshake
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
            null, true, 5 * 1024 * 1024);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}

From source file:com.kael.surf.net.codec.LengthFieldBasedFrameDecoder.java

License:Apache License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 *
 * @param   ctx             the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param   in              the {@link ByteBuf} from which to read data
 * @return  frame           the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 *                          be created./*from  w  w  w . j  av a  2s .  c om*/
 */
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    Integer packetNum = ctx.attr(countKey).get();
    if (packetNum == null || packetNum <= 100) {
        ctx.attr(countKey).set(packetNum == null ? 1 : packetNum + 1);

        int readableBytes = in.readableBytes();
        if (skipPolicy && readableBytes >= lengthFieldEndOffset) {
            if (readableBytes >= POLICY_STR_BYTES.length) {
                byte[] dst = new byte[POLICY_STR_BYTES.length];
                in.getBytes(in.readerIndex(), dst);
                if (isEqual(dst, POLICY_STR_BYTES)) {
                    in.skipBytes(POLICY_STR_BYTES.length);
                    return new String(dst);
                }
            } else {
                byte[] dst = new byte[readableBytes];
                in.getBytes(in.readerIndex(), dst);
                if (isEqual(dst, POLICY_STR_BYTES)) {
                    return null;
                }
            }
        }

        if (skipTencentGTWHead && readableBytes >= lengthFieldEndOffset) {
            if (readableBytes >= GET_BYTES.length) {
                byte[] dst = new byte[readableBytes];
                in.getBytes(in.readerIndex(), dst);
                if (isBeginWith(dst, GET_BYTES)) {
                    int endIndex = findEndIndex(dst, CRLF_BYTES);
                    if (endIndex == -1) {
                        return null;
                    }
                    in.skipBytes(endIndex);
                }
            } else {
                byte[] dst = new byte[readableBytes];
                in.getBytes(in.readerIndex(), dst);
                if (isEqual(dst, GET_BYTES)) {
                    return null;
                }
            }
        }
    }

    if (discardingTooLongFrame) {
        long bytesToDiscard = this.bytesToDiscard;
        int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes());
        in.skipBytes(localBytesToDiscard);
        bytesToDiscard -= localBytesToDiscard;
        this.bytesToDiscard = bytesToDiscard;

        failIfNecessary(false);
    }

    if (in.readableBytes() < lengthFieldEndOffset) {
        return null;
    }

    int actualLengthFieldOffset = in.readerIndex() + lengthFieldOffset;
    long frameLength = getUnadjustedFrameLength(in, actualLengthFieldOffset, lengthFieldLength, byteOrder);

    if (frameLength < 0) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength);
    }

    frameLength += lengthAdjustment + lengthFieldEndOffset;

    if (frameLength < lengthFieldEndOffset) {
        in.skipBytes(lengthFieldEndOffset);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than lengthFieldEndOffset: " + lengthFieldEndOffset);
    }

    if (frameLength > maxFrameLength) {
        long discard = frameLength - in.readableBytes();
        tooLongFrameLength = frameLength;

        if (discard < 0) {
            // buffer contains more bytes then the frameLength so we can discard all now
            in.skipBytes((int) frameLength);
        } else {
            // Enter the discard mode and discard everything received so far.
            discardingTooLongFrame = true;
            bytesToDiscard = discard;
            in.skipBytes(in.readableBytes());
        }
        failIfNecessary(true);
        return null;
    }

    // never overflows because it's less than maxFrameLength
    int frameLengthInt = (int) frameLength;
    if (in.readableBytes() < frameLengthInt) {
        return null;
    }

    if (initialBytesToStrip > frameLengthInt) {
        in.skipBytes(frameLengthInt);
        throw new CorruptedFrameException("Adjusted frame length (" + frameLength + ") is less "
                + "than initialBytesToStrip: " + initialBytesToStrip);
    }
    in.skipBytes(initialBytesToStrip);

    // extract frame
    int readerIndex = in.readerIndex();
    int actualFrameLength = frameLengthInt - initialBytesToStrip;
    ByteBuf frame = extractFrame(ctx, in, readerIndex, actualFrameLength);
    in.readerIndex(readerIndex + actualFrameLength);
    return frame;
}

From source file:com.king.platform.net.http.netty.response.HttpClientResponseHandler.java

License:Apache License

public void handleResponse(ChannelHandlerContext ctx, Object msg) throws Exception {
    HttpRequestContext httpRequestContext = ctx.channel().attr(HttpRequestContext.HTTP_REQUEST_ATTRIBUTE_KEY)
            .get();//  w  w  w.  j  ava 2  s  .  c om

    if (httpRequestContext == null) {
        logger.trace("httpRequestContext is null, msg was {}", msg);
        return;
    }

    NettyHttpClientResponse nettyHttpClientResponse = httpRequestContext.getNettyHttpClientResponse();

    RequestEventBus requestEventBus = nettyHttpClientResponse.getRequestEventBus();

    ResponseBodyConsumer responseBodyConsumer = nettyHttpClientResponse.getResponseBodyConsumer();

    try {

        if (msg instanceof HttpResponse) {
            requestEventBus.triggerEvent(Event.TOUCH);

            logger.trace("read HttpResponse");
            HttpResponse response = (HttpResponse) msg;

            HttpResponseStatus httpResponseStatus = response.getStatus();
            HttpHeaders httpHeaders = response.headers();

            nettyHttpClientResponse.setHttpResponseStatus(httpResponseStatus);
            nettyHttpClientResponse.setHttpHeaders(httpHeaders);

            requestEventBus.triggerEvent(Event.onReceivedStatus, httpResponseStatus);
            requestEventBus.triggerEvent(Event.onReceivedHeaders, httpHeaders);

            httpRequestContext.getTimeRecorder().readResponseHttpHeaders();

            if (httpRequestContext.isFollowRedirects()
                    && httpRedirector.isRedirectResponse(httpResponseStatus)) {
                httpRedirector.redirectRequest(httpRequestContext, httpHeaders);
                return;
            }

            if (response.getStatus().code() == 100) {
                requestEventBus.triggerEvent(Event.WRITE_BODY, ctx);
                return;
            }

            String contentLength = httpHeaders.get(HttpHeaders.Names.CONTENT_LENGTH);

            String contentType = httpHeaders.get(HttpHeaders.Names.CONTENT_TYPE);
            String charset = StringUtil.substringAfter(contentType, '=');
            if (charset == null) {
                charset = StandardCharsets.ISO_8859_1.name();
            }

            contentType = StringUtil.substringBefore(contentType, ';');

            if (contentLength != null) {
                long length = Long.parseLong(contentLength);
                responseBodyConsumer.onBodyStart(contentType, charset, length);
            } else {
                responseBodyConsumer.onBodyStart(contentType, charset, 0);
            }

            httpRequestContext.getTimeRecorder().responseBodyStart();

        } else if (msg instanceof HttpContent) {
            logger.trace("read HttpContent");
            requestEventBus.triggerEvent(Event.TOUCH);

            HttpResponseStatus httpResponseStatus = nettyHttpClientResponse.getHttpResponseStatus();
            HttpHeaders httpHeaders = nettyHttpClientResponse.getHttpHeaders();

            if (httpResponseStatus == null || (httpRequestContext.isFollowRedirects()
                    && httpRedirector.isRedirectResponse(httpResponseStatus))) {
                return;
            }

            if (msg == LastHttpContent.EMPTY_LAST_CONTENT
                    && nettyHttpClientResponse.getHttpResponseStatus().code() == 100) {
                logger.trace("read EMPTY_LAST_CONTENT with status code 100");
                return;
            }

            HttpContent chunk = (HttpContent) msg;

            ByteBuf content = chunk.content();

            content.resetReaderIndex();

            int readableBytes = content.readableBytes();

            if (readableBytes > 0) {
                ByteBuffer byteBuffer = content.nioBuffer();

                responseBodyConsumer.onReceivedContentPart(byteBuffer);
                requestEventBus.triggerEvent(Event.onReceivedContentPart, readableBytes, content);

            }

            content.release();

            requestEventBus.triggerEvent(Event.TOUCH);

            if (chunk instanceof LastHttpContent) {

                responseBodyConsumer.onCompletedBody();

                requestEventBus.triggerEvent(Event.onReceivedCompleted, httpResponseStatus, httpHeaders);
                httpRequestContext.getTimeRecorder().responseBodyCompleted();

                com.king.platform.net.http.HttpResponse httpResponse = new com.king.platform.net.http.HttpResponse(
                        httpResponseStatus.code(), responseBodyConsumer);

                for (Map.Entry<String, String> entry : httpHeaders.entries()) {
                    httpResponse.addHeader(entry.getKey(), entry.getValue());
                }

                requestEventBus.triggerEvent(Event.onHttpResponseDone, httpResponse);

                requestEventBus.triggerEvent(Event.COMPLETED, httpRequestContext);

            }
        }
    } catch (Throwable e) {
        requestEventBus.triggerEvent(Event.ERROR, httpRequestContext, e);
    }
}

From source file:com.kixeye.kixmpp.KixmppCodec.java

License:Apache License

/**
 * @see io.netty.handler.codec.ByteToMessageCodec#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)
 *//*from  w w w .ja v  a 2 s. com*/
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Received: [{}]", in.toString(StandardCharsets.UTF_8));
    }

    int retryCount = 0;
    Exception thrownException = null;

    // feed the data into the async xml input feeded
    byte[] data = new byte[in.readableBytes()];
    in.readBytes(data);

    if (streamReader != null) {
        while (retryCount < 2) {
            try {
                asyncInputFeeder.feedInput(data, 0, data.length);

                int event = -1;

                while (isValidEvent(event = streamReader.next())) {
                    // handle stream start/end
                    if (streamReader.getDepth() == STANZA_ELEMENT_DEPTH - 1) {
                        if (event == XMLStreamConstants.END_ELEMENT) {
                            out.add(new KixmppStreamEnd());

                            asyncInputFeeder.endOfInput();
                            streamReader.close();

                            streamReader = null;
                            asyncInputFeeder = null;

                            break;
                        } else if (event == XMLStreamConstants.START_ELEMENT) {
                            StAXElementBuilder streamElementBuilder = new StAXElementBuilder(true);

                            streamElementBuilder.process(streamReader);

                            out.add(new KixmppStreamStart(null, true));
                        }
                        // only handle events that have element depth of 2 and above (everything under <stream:stream>..)
                    } else if (streamReader.getDepth() >= STANZA_ELEMENT_DEPTH) {
                        // if this is the beginning of the element and this is at stanza depth
                        if (event == XMLStreamConstants.START_ELEMENT
                                && streamReader.getDepth() == STANZA_ELEMENT_DEPTH) {
                            elementBuilder = new StAXElementBuilder(true);
                            elementBuilder.process(streamReader);

                            // get the constructed element
                            Element element = elementBuilder.getElement();

                            if ("stream:stream".equals(element.getQualifiedName())) {
                                throw new RuntimeException("Starting a new stream.");
                            }
                            // if this is the ending of the element and this is at stanza depth
                        } else if (event == XMLStreamConstants.END_ELEMENT
                                && streamReader.getDepth() == STANZA_ELEMENT_DEPTH) {
                            elementBuilder.process(streamReader);

                            // get the constructed element
                            Element element = elementBuilder.getElement();

                            out.add(element);

                            // just process the event
                        } else {
                            elementBuilder.process(streamReader);
                        }
                    }
                }

                break;
            } catch (Exception e) {
                retryCount++;

                logger.info("Attempting to recover from impropper XML: " + e.getMessage());

                thrownException = e;

                try {
                    streamReader.close();
                } finally {
                    streamReader = inputFactory.createAsyncXMLStreamReader();
                    asyncInputFeeder = streamReader.getInputFeeder();
                }
            }
        }

        if (retryCount > 1) {
            throw thrownException;
        }
    }
}

From source file:com.kixeye.kixmpp.KixmppCodec.java

License:Apache License

/**
 * @see io.netty.handler.codec.ByteToMessageCodec#encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, io.netty.buffer.ByteBuf)
 *///  w w w  .j av a  2 s.  co m
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
    if (msg instanceof Element) {
        new XMLOutputter().output((Element) msg, new ByteBufOutputStream(out));
    } else if (msg instanceof KixmppStreamStart) {
        KixmppStreamStart streamStart = (KixmppStreamStart) msg;
        if (streamStart.doesIncludeXmlHeader()) {
            out.writeBytes("<?xml version='1.0' encoding='UTF-8'?>".getBytes(StandardCharsets.UTF_8));
        }
        out.writeBytes("<stream:stream ".getBytes(StandardCharsets.UTF_8));
        if (streamStart.getId() != null) {
            out.writeBytes(String.format("id=\"%s\" ", streamStart.getId()).getBytes(StandardCharsets.UTF_8));
        }
        if (streamStart.getFrom() != null) {
            out.writeBytes(String.format("from=\"%s\" ", streamStart.getFrom().getFullJid())
                    .getBytes(StandardCharsets.UTF_8));
        }
        if (streamStart.getTo() != null) {
            out.writeBytes(String.format("to=\"%s\" ", streamStart.getTo().getFullJid())
                    .getBytes(StandardCharsets.UTF_8));
        }
        out.writeBytes(
                "version=\"1.0\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\">"
                        .getBytes(StandardCharsets.UTF_8));
    } else if (msg instanceof KixmppStreamEnd) {
        out.writeBytes("</stream:stream>".getBytes(StandardCharsets.UTF_8));
    } else if (msg instanceof String) {
        out.writeBytes(((String) msg).getBytes(StandardCharsets.UTF_8));
    } else if (msg instanceof ByteBuf) {
        ByteBuf buf = (ByteBuf) msg;

        out.writeBytes(buf, 0, buf.readableBytes());
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Sending: [{}]", out.toString(StandardCharsets.UTF_8));
    }
}

From source file:com.kradac.karview.netty.MyDecoder.java

@Override
protected void decode(ChannelHandlerContext chc, ByteBuf bb, List<Object> list) throws Exception {
    if (bb.readableBytes() < 2) {
        return;// w  w w  . j  av a 2 s  .co m
    }
    bb.markReaderIndex();
    int length = bb.readChar();
    if (length > 150) {
        String data = "";
        while (bb.isReadable()) {
            data += (char) bb.readByte();
        }
        bb.clear();
        if (data.contains("OK") || data.contains("handshake")) {
            if (data.contains("handshake")) {
                chc.channel().write("0%%at");
            }
            if (data.contains("OK")) {
                System.out.println("Respuesta de Comando AT [" + data + "]");
            }
        } else {
            System.err.println("Datos incorrectos enviados al Servidor [" + data + "]");
            chc.channel().disconnect();
        }
    }
    if (bb.readableBytes() < length - 2) {
        bb.resetReaderIndex();
        return;
    }
    in.writeBytes(bb);//Escribimos los bytes
    in.discardReadBytes();//
    in.retain();
    list.add(in);
    bb.clear();//vaciamos el byteBuf
}

From source file:com.l2jmobius.commons.network.codecs.LengthFieldBasedFrameEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) {
    final ByteBuf buf = ctx.alloc().buffer(2);
    final short length = (short) (msg.readableBytes() + 2);
    buf.writeShort(buf.order() != ByteOrder.LITTLE_ENDIAN ? Short.reverseBytes(length) : length);
    out.add(buf);//from w w  w . java 2 s.c  om
    out.add(msg.retain());
}