Example usage for io.netty.buffer ByteBuf readBytes

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

Introduction

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

Prototype

public abstract ByteBuf readBytes(ByteBuffer dst);

Source Link

Document

Transfers this buffer's data to the specified destination starting at the current readerIndex until the destination's position reaches its limit, and increases the readerIndex by the number of the transferred bytes.

Usage

From source file:com.intuit.karate.netty.WebSocketClientHandler.java

License:Open Source License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();// ww  w . jav  a  2  s  .  c o m
    if (!handshaker.isHandshakeComplete()) {
        try {
            handshaker.finishHandshake(ch, (FullHttpResponse) msg);
            logger.debug("websocket client connected");
            handshakeFuture.setSuccess();
        } catch (WebSocketHandshakeException e) {
            logger.debug("websocket client connect failed: {}", e.getMessage());
            handshakeFuture.setFailure(e);
        }
        return;
    }
    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("unexpected FullHttpResponse (getStatus=" + response.status()
                + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }
    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        if (logger.isTraceEnabled()) {
            logger.trace("websocket received text");
        }
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        listener.onMessage(textFrame.text());
    } else if (frame instanceof PongWebSocketFrame) {
        if (logger.isTraceEnabled()) {
            logger.trace("websocket received pong");
        }
    } else if (frame instanceof CloseWebSocketFrame) {
        logger.debug("websocket closing");
        ch.close();
    } else if (frame instanceof BinaryWebSocketFrame) {
        logger.debug("websocket received binary");
        BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
        ByteBuf buf = binaryFrame.content();
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        listener.onMessage(bytes);
    }
}

From source file:com.jadarstudios.rankcapes.forge.network.packet.C1PacketCapePack.java

License:MIT License

@Override
public void read(ByteBuf data) throws IndexOutOfBoundsException {
    this.packSize = data.readInt();
    int length = data.readInt();
    this.packBytes = data.readBytes(length).array();
}

From source file:com.jadarstudios.rankcapes.forge.network.packet.PacketBase.java

License:MIT License

/**
 * Reads a string from a {@link ByteBuf}.
 *
 * @param data the buffer to read from//from ww w . java 2 s . c  o m
 *
 * @throws IndexOutOfBoundsException thrown if the buffer does not have enough bytes from which to read
 */
public String readString(ByteBuf data) throws IndexOutOfBoundsException {
    int length = data.readInt();
    byte[] stringBytes = new byte[length];
    data.readBytes(stringBytes);

    return new String(stringBytes);
}

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;
        }// w  ww  .  j a v a2  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.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 www . j  a va2 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.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);// w ww  .  j a  v  a 2 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.lampard.netty4.frame.fault.TimeServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buf = (ByteBuf) msg;

    byte[] req = new byte[buf.readableBytes()];
    buf.readBytes(req);
    String body = new String(req, "UTF-8").substring(0,
            req.length - System.getProperty("line.separator").length());

    System.out.println("The time server receive order : " + body + " ; the counter is : " + ++counter);

    String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body)
            ? new java.util.Date(System.currentTimeMillis()).toString()
            : "BAD ORDER";
    currentTime = currentTime + System.getProperty("line.separator");

    ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
    ctx.writeAndFlush(resp);//from   ww  w. j  a  v a  2 s  .c o  m
}

From source file:com.ldp.nettydemo.netty.codec.NettyMessageDecoder.java

License:Apache License

@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    ByteBuf frame = (ByteBuf) super.decode(ctx, in);
    if (frame == null) {
        return null;
    }//from   w  w w .jav  a2  s .  com

    NettyMessage message = new NettyMessage();
    Header header = new Header();
    header.setCrcCode(frame.readInt());
    header.setLength(frame.readInt());
    header.setSessionID(frame.readLong());
    header.setType(frame.readByte());
    header.setPriority(frame.readByte());

    int size = frame.readInt();
    if (size > 0) {
        Map<String, Object> attch = new HashMap<String, Object>(size);
        int keySize = 0;
        byte[] keyArray = null;
        String key = null;
        for (int i = 0; i < size; i++) {
            keySize = frame.readInt();
            keyArray = new byte[keySize];
            frame.readBytes(keyArray);
            key = new String(keyArray, "UTF-8");
            attch.put(key, ByteObjConverter.ByteToObject(new ByteBufToBytes().read(frame)));
            //      attch.put(key, marshallingDecoder.decode(frame));
        }
        keyArray = null;
        key = null;
        header.setAttachment(attch);
    }
    if (frame.readableBytes() > 4) {
        message.setBody(ByteObjConverter.ByteToObject(new ByteBufToBytes().read(frame)));
        //       message.setBody(marshallingDecoder.decode(frame));
    }
    message.setHeader(header);
    return message;
}

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  w w w .  j  av a  2 s.  c  o  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.linecorp.armeria.server.thrift.THttp2Client.java

License:Apache License

@Override
public void flush() throws TTransportException {
    THttp2ClientInitializer initHandler = new THttp2ClientInitializer();

    Bootstrap b = new Bootstrap();
    b.group(group);/*ww w .j a v  a 2  s.  c om*/
    b.channel(NioSocketChannel.class);
    b.handler(initHandler);

    Channel ch = null;
    try {
        ch = b.connect(host, port).syncUninterruptibly().channel();
        THttp2ClientHandler handler = initHandler.THttp2ClientHandler;

        // Wait until HTTP/2 upgrade is finished.
        assertTrue(handler.settingsPromise.await(5, TimeUnit.SECONDS));
        handler.settingsPromise.get();

        // Send a Thrift request.
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, path,
                Unpooled.wrappedBuffer(out.getArray(), 0, out.length()));
        request.headers().add(HttpHeaderNames.HOST, host);
        request.headers().set(ExtensionHeaderNames.SCHEME.text(), uri.getScheme());
        ch.writeAndFlush(request).sync();

        // Wait until the Thrift response is received.
        assertTrue(handler.responsePromise.await(5, TimeUnit.SECONDS));
        ByteBuf response = handler.responsePromise.get();

        // Pass the received Thrift response to the Thrift client.
        final byte[] array = new byte[response.readableBytes()];
        response.readBytes(array);
        in = new TMemoryInputTransport(array);
        response.release();
    } catch (Exception e) {
        throw new TTransportException(TTransportException.UNKNOWN, e);
    } finally {
        if (ch != null) {
            ch.close();
        }
    }
}