Example usage for io.netty.buffer ByteBuf resetReaderIndex

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

Introduction

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

Prototype

public abstract ByteBuf resetReaderIndex();

Source Link

Document

Repositions the current readerIndex to the marked readerIndex in this buffer.

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 w  ww .j a  va2s.  c om*/
        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.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.  ja v  a 2 s .c  o m*/

    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.kradac.karview.netty.MyDecoder.java

@Override
protected void decode(ChannelHandlerContext chc, ByteBuf bb, List<Object> list) throws Exception {
    if (bb.readableBytes() < 2) {
        return;/*  www .java2  s  . com*/
    }
    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.CryptCodec.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) {
    // Check if there are any data to encrypt.
    if (!msg.isReadable()) {
        return;/*  w ww .  ja v a2s.c om*/
    }

    msg.resetReaderIndex();
    _crypt.encrypt(msg);
    msg.resetReaderIndex();
    out.writeBytes(msg);
}

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

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    in.resetReaderIndex();
    _crypt.decrypt(in);/*from  w  ww  . j ava  2  s.  c o  m*/
    in.readerIndex(in.writerIndex());
    out.add(in.copy(0, in.writerIndex()));
}

From source file:com.lambdaworks.redis.protocol.CommandArgs.java

License:Apache License

@Override
public String toString() {

    final StringBuilder sb = new StringBuilder();
    sb.append(getClass().getSimpleName());

    ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.buffer(singularArguments.size() * 10);
    encode(buffer);//from   w ww. j a  v a2  s .  c o m
    buffer.resetReaderIndex();

    byte[] bytes = new byte[buffer.readableBytes()];
    buffer.readBytes(bytes);
    sb.append(" [buffer=").append(new String(bytes));
    sb.append(']');
    buffer.release();

    return sb.toString();
}

From source file:com.linecorp.armeria.client.endpoint.dns.DnsServiceEndpointGroup.java

License:Apache License

@Override
ImmutableSortedSet<Endpoint> onDnsRecords(List<DnsRecord> records, int ttl) throws Exception {
    final ImmutableSortedSet.Builder<Endpoint> builder = ImmutableSortedSet.naturalOrder();
    for (DnsRecord r : records) {
        if (!(r instanceof DnsRawRecord) || r.type() != DnsRecordType.SRV) {
            continue;
        }//from w  ww  . j  av  a2s. c  o  m

        final ByteBuf content = ((ByteBufHolder) r).content();
        if (content.readableBytes() <= 6) { // Too few bytes
            warnInvalidRecord(DnsRecordType.SRV, content);
            continue;
        }

        content.markReaderIndex();
        content.skipBytes(2); // priority unused
        final int weight = content.readUnsignedShort();
        final int port = content.readUnsignedShort();

        final Endpoint endpoint;
        try {
            final String target = stripTrailingDot(DefaultDnsRecordDecoder.decodeName(content));
            endpoint = port > 0 ? Endpoint.of(target, port) : Endpoint.of(target);
        } catch (Exception e) {
            content.resetReaderIndex();
            warnInvalidRecord(DnsRecordType.SRV, content);
            continue;
        }

        builder.add(endpoint.withWeight(weight));
    }

    final ImmutableSortedSet<Endpoint> endpoints = builder.build();
    if (logger().isDebugEnabled()) {
        logger().debug("{} Resolved: {} (TTL: {})", logPrefix(),
                endpoints.stream().map(e -> e.authority() + '/' + e.weight()).collect(Collectors.joining(", ")),
                ttl);
    }

    return endpoints;
}

From source file:com.linecorp.armeria.client.endpoint.dns.DnsTextEndpointGroup.java

License:Apache License

@Override
ImmutableSortedSet<Endpoint> onDnsRecords(List<DnsRecord> records, int ttl) throws Exception {
    final ImmutableSortedSet.Builder<Endpoint> builder = ImmutableSortedSet.naturalOrder();
    for (DnsRecord r : records) {
        if (!(r instanceof DnsRawRecord) || r.type() != DnsRecordType.TXT) {
            continue;
        }//from   www . j a v  a  2s  .  co m

        final ByteBuf content = ((ByteBufHolder) r).content();
        if (!content.isReadable()) { // Missing length octet
            warnInvalidRecord(DnsRecordType.TXT, content);
            continue;
        }

        content.markReaderIndex();
        final int txtLen = content.readUnsignedByte();
        if (txtLen == 0) { // Empty content
            continue;
        }

        if (content.readableBytes() != txtLen) { // Mismatching number of octets
            content.resetReaderIndex();
            warnInvalidRecord(DnsRecordType.TXT, content);
            continue;
        }

        final byte[] txt = new byte[txtLen];
        content.readBytes(txt);

        final Endpoint endpoint;
        try {
            endpoint = mapping.apply(txt);
        } catch (Exception e) {
            content.resetReaderIndex();
            warnInvalidRecord(DnsRecordType.TXT, content);
            continue;
        }

        if (endpoint != null) {
            if (endpoint.isGroup()) {
                logger().warn("{} Ignoring group endpoint: {}", logPrefix(), endpoint);
            } else {
                builder.add(endpoint);
            }
        }
    }

    final ImmutableSortedSet<Endpoint> endpoints = builder.build();
    if (logger().isDebugEnabled()) {
        logger().debug("{} Resolved: {} (TTL: {})", logPrefix(),
                endpoints.stream().map(Object::toString).collect(Collectors.joining(", ")), ttl);
    }

    return endpoints;
}

From source file:com.mastfrog.acteur.ContentConverter.java

License:Open Source License

public String toString(ByteBuf content, Charset encoding) throws IOException {
    String result;/*from w w w . j av  a2 s. com*/
    try (ByteBufInputStream in = new ByteBufInputStream(content)) {
        result = Streams.readString(in, encoding.toString());
    } finally {
        content.resetReaderIndex();
    }
    if (result.length() > 0 && result.charAt(0) == '"') {
        result = result.substring(1);
    }
    if (result.length() > 1 && result.charAt(result.length() - 1) == '"') {
        result = result.substring(0, result.length() - 2);
    }
    return result;
}

From source file:com.mastfrog.acteur.ContentConverter.java

License:Open Source License

protected <T> T readObject(ByteBuf buf, MediaType mimeType, Class<T> type)
        throws IOException, InvalidInputException {
    if (type == String.class || type == CharSequence.class) {
        return type.cast(toString(buf, findCharset(mimeType)));
    }/*from w  ww .j  av  a 2  s.  c o m*/
    Origin origin = type.getAnnotation(Origin.class);
    if (origin != null) {
        Map map;
        try (InputStream in = new ByteBufInputStream(buf)) {
            map = codec.readValue(in, Map.class);
            validate(origin, map).throwIfFatalPresent();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            throw ioe;
        } finally {
            buf.resetReaderIndex();
        }
    }
    buf.resetReaderIndex();
    try (InputStream in = new ByteBufInputStream(buf)) {
        T result = codec.readValue(in, type);
        return result;
    } catch (IOException ioe) {
        ioe.printStackTrace();
        throw ioe;
    } finally {
        buf.resetReaderIndex();
    }
}