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:io.airlift.drift.transport.netty.HeaderMessageEncoding.java

License:Apache License

private static String readString(ByteBuf messageHeader) {
    int length = readVarint(messageHeader);
    return messageHeader.readBytes(length).toString(UTF_8);
}

From source file:io.andromeda.logcollector.LocalFileReader.java

License:Apache License

private Observable.Operator<String, Buffer> extractLines() {
    ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(8192);
    return subscriber -> new Subscriber<Buffer>() {
        @Override/*  w w  w  . j  av a2 s .  com*/
        public void onCompleted() {
            if (!subscriber.isUnsubscribed()) {
                subscriber.onCompleted();
            }
        }

        @Override
        public void onError(Throwable e) {
            if (!subscriber.isUnsubscribed()) {
                subscriber.onError(e);
            }

        }

        @Override
        public void onNext(Buffer buffer) {
            ByteBuf _buf = ((io.vertx.core.buffer.Buffer) buffer.getDelegate()).getByteBuf();
            while (_buf.readableBytes() > 0) {
                byte b = _buf.readByte();
                if ((b == '\n') || (b == '\r')) {
                    byte[] _bArr = new byte[buf.readableBytes()];
                    buf.readBytes(_bArr);
                    subscriber.onNext(new String(_bArr));
                } else {
                    buf.writeByte(b);
                }
            }
            buf.clear();
        }
    };
}

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 {//from w ww .  ja  v  a 2 s . c  o  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.apigee.trireme.container.netty.NettyServer.java

License:Open Source License

/**
 * Copy the Netty byte buffer into a new buffer.
 *//* w w w. j a v  a 2s.com*/
public static ByteBuffer copyBuffer(ByteBuf buf) {
    ByteBuffer ret = ByteBuffer.allocate(buf.readableBytes());
    buf.readBytes(ret);
    ret.flip();
    return ret;
}

From source file:io.apigee.trireme.container.netty.UpgradedSocketHandler.java

License:Open Source License

void deliverRead(ByteBuf bb) {
    if (bb == null) {
        log.debug("Not null read (EOF)");
        readHandler.ioComplete(ErrorCodes.EOF, null);
    } else {/*from w w w. j  a  v  a  2  s .  c  o  m*/
        ByteBuffer readBuf = ByteBuffer.allocate(bb.readableBytes());
        bb.readBytes(readBuf);
        readBuf.flip();

        if (log.isDebugEnabled()) {
            log.debug("Got {} bytes on the upgraded socket", (readBuf.remaining()));
        }
        readHandler.ioComplete(0, readBuf);
    }
}

From source file:io.atomix.cluster.messaging.impl.MessageDecoder.java

License:Apache License

@Override
@SuppressWarnings("squid:S128") // suppress switch fall through warning
protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> out) throws Exception {

    switch (currentState) {
    case READ_SENDER_VERSION:
        if (buffer.readableBytes() < SHORT_SIZE) {
            return;
        }//from w w  w  .  j  a  va  2  s. com
        version = buffer.readShort();
        currentState = DecoderState.READ_SENDER_IP;
    case READ_SENDER_IP:
        if (buffer.readableBytes() < BYTE_SIZE) {
            return;
        }
        buffer.markReaderIndex();
        int octetsLength = buffer.readByte();
        if (buffer.readableBytes() < octetsLength) {
            buffer.resetReaderIndex();
            return;
        }

        byte[] octets = new byte[octetsLength];
        buffer.readBytes(octets);
        senderIp = InetAddress.getByAddress(octets);
        currentState = DecoderState.READ_SENDER_PORT;
    case READ_SENDER_PORT:
        if (buffer.readableBytes() < INT_SIZE) {
            return;
        }
        senderPort = buffer.readInt();
        address = new Address(senderIp.getHostName(), senderPort, senderIp);
        currentState = DecoderState.READ_TYPE;
    case READ_TYPE:
        if (buffer.readableBytes() < BYTE_SIZE) {
            return;
        }
        type = InternalMessage.Type.forId(buffer.readByte());
        currentState = DecoderState.READ_PREAMBLE;
    case READ_PREAMBLE:
        if (buffer.readableBytes() < INT_SIZE) {
            return;
        }
        preamble = buffer.readInt();
        currentState = DecoderState.READ_MESSAGE_ID;
    case READ_MESSAGE_ID:
        if (buffer.readableBytes() < LONG_SIZE) {
            return;
        }
        messageId = buffer.readLong();
        currentState = DecoderState.READ_CONTENT_LENGTH;
    case READ_CONTENT_LENGTH:
        if (buffer.readableBytes() < INT_SIZE) {
            return;
        }
        contentLength = buffer.readInt();
        currentState = DecoderState.READ_CONTENT;
    case READ_CONTENT:
        if (buffer.readableBytes() < contentLength) {
            return;
        }
        if (contentLength > 0) {
            // TODO: Perform a sanity check on the size before allocating
            content = new byte[contentLength];
            buffer.readBytes(content);
        } else {
            content = EMPTY_PAYLOAD;
        }

        switch (type) {
        case REQUEST:
            currentState = DecoderState.READ_SUBJECT_LENGTH;
            break;
        case REPLY:
            currentState = DecoderState.READ_STATUS;
            break;
        default:
            checkState(false, "Must not be here");
        }
        break;
    default:
        break;
    }

    switch (type) {
    case REQUEST:
        switch (currentState) {
        case READ_SUBJECT_LENGTH:
            if (buffer.readableBytes() < SHORT_SIZE) {
                return;
            }
            subjectLength = buffer.readShort();
            currentState = DecoderState.READ_SUBJECT;
        case READ_SUBJECT:
            if (buffer.readableBytes() < subjectLength) {
                return;
            }
            final String subject = readString(buffer, subjectLength, UTF_8);
            InternalRequest message = new InternalRequest(preamble, messageId, address, subject, content);
            out.add(message);
            currentState = DecoderState.READ_TYPE;
            break;
        default:
            break;
        }
        break;
    case REPLY:
        switch (currentState) {
        case READ_STATUS:
            if (buffer.readableBytes() < BYTE_SIZE) {
                return;
            }
            InternalReply.Status status = InternalReply.Status.forId(buffer.readByte());
            InternalReply message = new InternalReply(preamble, messageId, content, status);
            out.add(message);
            currentState = DecoderState.READ_TYPE;
            break;
        default:
            break;
        }
        break;
    default:
        checkState(false, "Must not be here");
    }
}

From source file:io.atomix.cluster.messaging.impl.MessageDecoder.java

License:Apache License

static String readString(ByteBuf buffer, int length, Charset charset) {
    if (buffer.isDirect()) {
        final String result = buffer.toString(buffer.readerIndex(), length, charset);
        buffer.skipBytes(length);/*  www.j  ava 2 s. com*/
        return result;
    } else if (buffer.hasArray()) {
        final String result = new String(buffer.array(), buffer.arrayOffset() + buffer.readerIndex(), length,
                charset);
        buffer.skipBytes(length);
        return result;
    } else {
        final byte[] array = new byte[length];
        buffer.readBytes(array);
        return new String(array, charset);
    }
}

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;//from  w  ww .j  ava  2s .c o m
    }

    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.codis.nedis.handler.RedisResponseDecoder.java

License:Apache License

private boolean decode(ByteBuf in, List<Object> out, Object nullValue) throws Exception {
    if (in.readableBytes() < 2) {
        return false;
    }//from  w  ww .  j  av a2 s.  c om
    byte b = in.readByte();
    switch (b) {
    case '+': {
        String reply = decodeString(in);
        if (reply == null) {
            return false;
        }
        out.add(reply);
        return true;
    }
    case '-': {
        String reply = decodeString(in);
        if (reply == null) {
            return false;
        }
        out.add(new RedisResponseException(reply));
        return true;
    }
    case ':': {
        Long reply = decodeLong(in);
        if (reply == null) {
            return false;
        }
        out.add(reply);
        return true;
    }
    case '$': {
        Long numBytes = decodeLong(in);
        if (numBytes == null) {
            return false;
        }
        if (numBytes.intValue() == -1) {
            out.add(nullValue);
            return true;
        }
        if (in.readableBytes() < numBytes.intValue() + 2) {
            return false;
        }
        if (in.getByte(in.readerIndex() + numBytes.intValue()) != '\r'
                || in.getByte(in.readerIndex() + numBytes.intValue() + 1) != '\n') {
            throw new ProtocolException("Response is not ended by CRLF");
        }
        byte[] reply = new byte[numBytes.intValue()];
        in.readBytes(reply);
        // skip CRLF
        in.skipBytes(2);
        out.add(reply);
        return true;
    }
    case '*': {
        Long numReplies = decodeLong(in);
        if (numReplies == null) {
            return false;
        }
        if (numReplies.intValue() == -1) {
            out.add(nullValue);
            return true;
        }
        List<Object> replies = new ArrayList<>();
        for (int i = 0; i < numReplies.intValue(); i++) {
            if (!decode(in, replies, null)) {
                return false;
            }
        }
        out.add(replies);
        return true;
    }
    default:
        throw new ProtocolException("Unknown leading char: " + (char) b);
    }
}

From source file:io.crate.protocols.postgres.MessagesTest.java

License:Apache License

private static void verifyResponse(EmbeddedChannel channel, String response) {
    byte[] responseBytes = response.getBytes(StandardCharsets.UTF_8);
    ByteBuf buffer = (ByteBuf) channel.outboundMessages().poll();
    assertThat(buffer.readByte(), is((byte) 'C'));
    assertThat(buffer.readInt(), is(responseBytes.length + 4 + 1));
    byte[] string = new byte[9];
    buffer.readBytes(string);
    assertThat(string, is(responseBytes));
}