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:buildcraft.transport.network.PacketFluidUpdate.java

License:Minecraft Mod Public

@Override
public void readData(ByteBuf data) {
    super.readData(data);

    World world = CoreProxy.proxy.getClientWorld();
    if (!world.blockExists(posX, posY, posZ)) {
        return;//  w  w  w. j a v a2s  .c  o m
    }

    TileEntity entity = world.getTileEntity(posX, posY, posZ);
    if (!(entity instanceof TileGenericPipe)) {
        return;
    }

    TileGenericPipe pipe = (TileGenericPipe) entity;
    if (pipe.pipe == null) {
        return;
    }

    if (!(pipe.pipe.transport instanceof PipeTransportFluids)) {
        return;
    }

    PipeTransportFluids transLiq = (PipeTransportFluids) pipe.pipe.transport;

    renderCache = transLiq.renderCache;
    colorRenderCache = transLiq.colorRenderCache;

    byte[] dBytes = new byte[2];
    data.readBytes(dBytes);
    delta = fromByteArray(dBytes);

    // System.out.printf("read %d, %d, %d = %s, %s%n", posX, posY, posZ, Arrays.toString(dBytes), delta);

    for (ForgeDirection dir : ForgeDirection.values()) {
        if (delta.get(dir.ordinal() * FLUID_DATA_NUM + FLUID_ID_BIT)) {
            int amt = renderCache[dir.ordinal()] != null ? renderCache[dir.ordinal()].amount : 0;
            renderCache[dir.ordinal()] = new FluidStack(data.readShort(), amt);
            colorRenderCache[dir.ordinal()] = data.readInt();
        }
        if (delta.get(dir.ordinal() * FLUID_DATA_NUM + FLUID_AMOUNT_BIT)) {
            if (renderCache[dir.ordinal()] == null) {
                renderCache[dir.ordinal()] = new FluidStack(0, 0);
            }
            renderCache[dir.ordinal()].amount = Math.min(transLiq.getCapacity(), data.readInt());
        }
    }
}

From source file:buildcraftAdditions.tileEntities.TileItemSorter.java

License:GNU General Public License

@Override
public void readFromByteBuff(ByteBuf buf) {
    rotation = ForgeDirection.getOrientation(buf.readByte());
    buf.readBytes(colors);
    updateRender();
}

From source file:ccwihr.client.t2.HttpResponseHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    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 a v a2 s. 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:ch.ethz.globis.distindex.middleware.net.MiddlewareMessageDecoder.java

License:Open Source License

/**
 * Checks whether the bytes accumulated in the in Buffer constitute a full message sent
 * from the client. If that is the case, the message is copied to the out list and the
 * next handler is notified.//from   w  ww .java  2s  . c  o  m
 *
 * @param ctx                           The Netty context associated with the channel.
 * @param in                            A Netty managed buffer that holds the accumulated received chunks.
 * @param out                           The list of objects to be passed to the next handler.
 * @throws Exception
 */
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 4) {
        //need to know exactly how many bytes to read
        return;
    }
    if (bytesToRead == -1) {
        bytesToRead = in.readInt();
    }

    if (in.readableBytes() == bytesToRead) {
        out.add(in.readBytes(in.readableBytes()));
        bytesToRead = -1;
    }
}

From source file:cloudeventbus.codec.Decoder.java

License:Open Source License

@Override
public Frame decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    in.markReaderIndex();//from   ww w.ja  v  a  2  s .  c o m
    final int frameLength = indexOf(in, Codec.DELIMITER);
    // Frame hasn't been fully read yet.
    if (frameLength < 0) {
        if (in.readableBytes() > maxMessageSize) {
            throw new TooLongFrameException("Frame exceeds maximum size");
        }
        in.resetReaderIndex();
        return null;
    }
    // Empty frame, discard and continue decoding
    if (frameLength == 0) {
        in.skipBytes(Codec.DELIMITER.length);
        return decode(ctx, in);
    }
    if (frameLength > maxMessageSize) {
        throw new TooLongFrameException("Frame exceeds maximum size");
    }
    final String command = in.readBytes(frameLength).toString(CharsetUtil.UTF_8);
    in.skipBytes(Codec.DELIMITER.length);
    final String[] parts = command.split("\\s+");
    final char frameTypeChar = parts[0].charAt(0);
    final FrameType frameType = FrameType.getFrameType(frameTypeChar);
    if (frameType == null) {
        throw new DecodingException("Invalid frame type " + frameTypeChar);
    }
    LOGGER.debug("Decoding frame of type {}", frameType);
    final int argumentsLength = parts.length - 1;
    switch (frameType) {
    case AUTH_RESPONSE:
        assertArgumentsLength(3, argumentsLength, "authentication response");
        final CertificateChain certificates = new CertificateChain();
        final byte[] rawCertificates = Base64.decodeBase64(parts[1].getBytes());
        CertificateStoreLoader.load(new ByteArrayInputStream(rawCertificates), certificates);
        final byte[] salt = Base64.decodeBase64(parts[2]);
        final byte[] digitalSignature = Base64.decodeBase64(parts[3]);
        return new AuthenticationResponseFrame(certificates, salt, digitalSignature);
    case AUTHENTICATE:
        assertArgumentsLength(1, argumentsLength, "authentication request");
        final byte[] challenge = Base64.decodeBase64(parts[1]);
        return new AuthenticationRequestFrame(challenge);
    case ERROR:
        if (parts.length == 0) {
            throw new DecodingException("Error is missing error code");
        }
        final Integer errorNumber = Integer.valueOf(parts[1]);
        final ErrorFrame.Code errorCode = ErrorFrame.Code.lookupCode(errorNumber);
        int messageIndex = 1;
        messageIndex = skipWhiteSpace(messageIndex, command);
        while (messageIndex < command.length() && Character.isDigit(command.charAt(messageIndex))) {
            messageIndex++;
        }
        messageIndex = skipWhiteSpace(messageIndex, command);
        final String errorMessage = command.substring(messageIndex).trim();
        if (errorMessage.length() > 0) {
            return new ErrorFrame(errorCode, errorMessage);
        } else {
            return new ErrorFrame(errorCode);
        }
    case GREETING:
        assertArgumentsLength(3, argumentsLength, "greeting");
        final int version = Integer.valueOf(parts[1]);
        final String agent = parts[2];
        final long id = Long.valueOf(parts[3]);
        return new GreetingFrame(version, agent, id);
    case PING:
        return PingFrame.PING;
    case PONG:
        return PongFrame.PONG;
    case PUBLISH:
        if (argumentsLength < 2 || argumentsLength > 3) {
            throw new DecodingException(
                    "Expected message frame to have 2 or 3 arguments. It has " + argumentsLength + ".");
        }
        final String messageSubject = parts[1];
        final String replySubject;
        final Integer messageLength;
        if (parts.length == 3) {
            replySubject = null;
            messageLength = Integer.valueOf(parts[2]);
        } else {
            replySubject = parts[2];
            messageLength = Integer.valueOf(parts[3]);
        }
        if (in.readableBytes() < messageLength + Codec.DELIMITER.length) {
            // If we haven't received the entire message body (plus the CRLF), wait until it arrives.
            in.resetReaderIndex();
            return null;
        }
        final ByteBuf messageBytes = in.readBytes(messageLength);
        final String messageBody = new String(messageBytes.array(), CharsetUtil.UTF_8);
        in.skipBytes(Codec.DELIMITER.length); // Ignore the CRLF after the message body.
        return new PublishFrame(new Subject(messageSubject),
                replySubject == null ? null : new Subject(replySubject), messageBody);
    case SERVER_READY:
        return ServerReadyFrame.SERVER_READY;
    case SUBSCRIBE:
        assertArgumentsLength(1, argumentsLength, "subscribe");
        return new SubscribeFrame(new Subject(parts[1]));
    case UNSUBSCRIBE:
        assertArgumentsLength(1, argumentsLength, "unsubscribe");
        return new UnsubscribeFrame(new Subject(parts[1]));
    default:
        throw new DecodingException("Unknown frame type " + frameType);
    }
}

From source file:cn.ifengkou.hestia.serialize.MessageDecoder.java

License:Apache License

protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    if (in.readableBytes() < MessageDecoder.MESSAGE_LENGTH) {
        return;/*  w  w w  .  j  a  v  a2 s .c  om*/
    }

    in.markReaderIndex();
    int messageLength = in.readInt();

    if (messageLength < 0) {
        ctx.close();
    }

    if (in.readableBytes() < messageLength) {
        in.resetReaderIndex();
        return;
    } else {
        byte[] messageBody = new byte[messageLength];
        in.readBytes(messageBody);

        try {
            Object obj = messageCodecUtil.decode(messageBody);
            out.add(obj);
        } catch (IOException ex) {
            LOGGER.error("messageCodeUtil decode failed!", ex);
        }
    }
}

From source file:cn.jpush.api.common.connection.HttpResponseHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;/*from w  w  w  .j a va2s . co m*/
    } else {
        LOG.debug("HttpResponseHandler response message received: " + msg);
    }

    Entry<ChannelFuture, ChannelPromise> entry = streamidPromiseMap.get(streamId);
    List<String> list = new ArrayList<String>();
    list.add(msg.status().code() + "");
    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 byteBuf = msg.content();
        if (byteBuf.isReadable()) {
            int contentLength = byteBuf.readableBytes();
            byte[] arr = new byte[contentLength];
            byteBuf.readBytes(arr);
            String content = new String(arr, 0, contentLength, CharsetUtil.UTF_8);
            list.add(content);
            System.out.println("Protocol version: " + msg.protocolVersion());
            System.out.println("status: " + list.get(0) + " response content: " + list.get(1));
            LOG.debug("Protocol version: " + msg.protocolVersion());
            LOG.debug("status: " + list.get(0) + " response content: " + list.get(1));
        }

        mNettyHttp2Client.setResponse(streamId + ctx.channel().id().asShortText(), list);
        if (null != mCallback) {
            ResponseWrapper wrapper = new ResponseWrapper();
            wrapper.responseCode = Integer.valueOf(list.get(0));
            if (list.size() > 1) {
                wrapper.responseContent = list.get(1);
            }
            mCallback.onSucceed(wrapper);
        }

        entry.getValue().setSuccess();
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            System.err.println("content: " + content.content().toString(CharsetUtil.UTF_8));
            System.err.flush();

            if (content instanceof LastHttpContent) {
                System.err.println(" end of content");
                //                    ctx.close();
            }
        }

    }
}

From source file:cn.pengj.udpdemo.EchoSeverHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    // ??//ww  w  .j  av  a 2s.  co m
    ByteBuf buf = (ByteBuf) packet.copy().content();
    byte[] req = new byte[buf.readableBytes()];
    buf.readBytes(req);
    String body = new String(req, CharsetUtil.UTF_8);
    System.out.println("?NOTE>>>>>> ?" + body);

    // ???
    ctx.writeAndFlush(new DatagramPacket(
            Unpooled.copiedBuffer("HelloServer" + System.currentTimeMillis(),
                    CharsetUtil.UTF_8),
            packet.sender())).sync();
}

From source file:co.rsk.net.discovery.PacketDecoder.java

License:Open Source License

@Override
public void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object> out) throws Exception {
    ByteBuf buf = packet.content();
    byte[] encoded = new byte[buf.readableBytes()];
    buf.readBytes(encoded);
    out.add(this.decodeMessage(ctx, encoded, packet.sender()));
}

From source file:code.google.nfs.rpc.netty.serialize.NettyProtocolDecoder.java

License:Apache License

@Override
public final void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    ByteBuf buf = internalBuffer();
    int readable = buf.readableBytes();
    if (buf.isReadable()) {
        ByteBuf bytes = buf.readBytes(readable);
        buf.release();//from  ww w.j av a  2  s. co m
        ctx.fireChannelRead(bytes);
    }
    cumulation = null;
    ctx.fireChannelReadComplete();
    handlerRemoved0(ctx);
}