Example usage for io.netty.buffer ByteBuf slice

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

Introduction

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

Prototype

public abstract ByteBuf slice();

Source Link

Document

Returns a slice of this buffer's readable bytes.

Usage

From source file:at.yawk.dbus.protocol.codec.MessageHeaderCodec.java

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf rawBuf, List<Object> out) throws Exception {
    if (toRead != 0) {
        if (rawBuf.readableBytes() < toRead) {
            return;
        }/*  ww  w  .j  a  va  2 s .c om*/
        ByteBuf slice = rawBuf.slice().order(byteOrder);
        slice.writerIndex(slice.readerIndex() + toRead);
        slice.retain();
        AlignableByteBuf decoding = AlignableByteBuf.decoding(slice);
        log.trace("INBOUND {}", decoding);
        out.add(decoding);

        rawBuf.readerIndex(rawBuf.readerIndex() + toRead);
        toRead = 0;
    }

    if (rawBuf.readableBytes() < MIN_HEADER_LENGTH) {
        return;
    }

    rawBuf.markReaderIndex();
    byte endianness = rawBuf.readByte();
    ByteOrder order;
    switch (endianness) {
    case 'l':
        order = ByteOrder.LITTLE_ENDIAN;
        break;
    case 'B':
        order = ByteOrder.BIG_ENDIAN;
        break;
    default:
        throw new DecoderException("Unknown byte order byte " + endianness);
    }

    AlignableByteBuf buf = AlignableByteBuf.decoding(rawBuf.resetReaderIndex().order(order));

    buf.getBuffer().markReaderIndex();
    buf.readByte(); // skip endianness byte we read above

    @Nullable
    MessageType type = MessageType.byId(buf.readByte());
    byte flags = buf.readByte();
    byte majorProtocolVersion = buf.readByte();
    if (majorProtocolVersion != PROTOCOL_VERSION) {
        throw new DecoderException("Unsupported major protocol version " + majorProtocolVersion);
    }
    long bodyLength = buf.readUnsignedInt();
    int serial = buf.readInt();

    MessageHeader header = new MessageHeader();
    header.setByteOrder(order);
    header.setMessageType(type);
    header.setNoReplyExpected((flags & NO_REPLY_EXPECTED) != 0);
    header.setNoAutoStart((flags & NO_AUTO_START) != 0);
    header.setAllowInteractiveAuthorization((flags & ALLOW_INTERACTIVE_AUTHORIZATION) != 0);
    header.setMajorProtocolVersion(majorProtocolVersion);
    header.setMessageBodyLength(bodyLength);
    header.setSerial(serial);
    header.setHeaderFields(new EnumMap<>(HeaderField.class));

    ArrayObject headers = (ArrayObject) tryDecode(HEADER_FIELD_LIST_TYPE, buf);
    if (headers == null) {
        // not enough data
        buf.getBuffer().resetReaderIndex();
        return;
    }
    for (DbusObject struct : headers.getValues()) {
        HeaderField field = HeaderField.byId(struct.get(0).byteValue());
        if (field != null) {
            DbusObject value = struct.get(1).getValue();
            if (!value.getType().equals(field.getType())) {
                throw new DecoderException("Invalid header type on " + field + ": got " + value.getType()
                        + " but expected " + field.getType());
            }
            header.getHeaderFields().put(field, value);
        }
    }

    if (type != null) {
        checkRequiredHeaderFieldsPresent(header);
    }

    if (!buf.canAlignRead(8)) {
        buf.getBuffer().resetReaderIndex();
        return;
    }
    buf.alignRead(8);

    toRead = Math.toIntExact(header.getMessageBodyLength());
    byteOrder = order;
    out.add(header);
}

From source file:buildcraft.core.lib.network.ChannelHandler.java

License:Minecraft Mod Public

@Override
protected void decode(ChannelHandlerContext ctx, FMLProxyPacket msg, List<Object> out) throws Exception {
    testMessageValidity(msg);/*from w w  w  . j ava 2 s .  c o  m*/
    ByteBuf payload = msg.payload();
    byte discriminator = payload.readByte();
    Class<? extends Packet> clazz = discriminators.get(discriminator);
    if (clazz == null) {
        throw new NullPointerException(
                "Undefined message for discriminator " + discriminator + " in channel " + msg.channel());
    }
    Packet newMsg = clazz.newInstance();
    ctx.attr(INBOUNDPACKETTRACKER).get().set(new WeakReference<FMLProxyPacket>(msg));
    newMsg.readData(payload.slice());
    out.add(newMsg);
}

From source file:c5db.control.ByteBufInput.java

License:Apache License

/**
 * An input for a ByteBuffer/*from   w  w w .ja v a2  s.c o  m*/
 *
 * @param buffer            the buffer to read from, it will be sliced
 * @param protostuffMessage if we are parsing a protostuff (true) or protobuf (false) message
 */
public ByteBufInput(ByteBuf buffer, boolean protostuffMessage) {
    this.buffer = buffer.slice();
    this.buffer.markReaderIndex();
    this.decodeNestedMessageAsGroup = protostuffMessage;
}

From source file:com.builtbroken.atomic.network.packet.PacketBase.java

@Override
public void decodeInto(ChannelHandlerContext ctx, ByteBuf buffer) {
    dataToRead = buffer.slice().copy();
}

From source file:com.eightkdata.mongowp.bson.netty.ByteBufByteSource.java

License:Open Source License

public ByteBufByteSource(@Tight @ConservesIndexes ByteBuf byteBuf) {
    this.byteBuf = byteBuf.slice();
}

From source file:com.mastfrog.scamper.compression.CompressingCodec.java

License:Open Source License

private MessageTypeAndBuffer decodeImpl(ByteBuf buf, ChannelHandlerContext ctx, int sctpChannel)
        throws Exception {
    MessageType messageType = reg.forByteBuf(buf);
    if (messageType.isUnknown()) {
        return new MessageTypeAndBuffer(messageType, buf.slice(), sctpChannel);
    }//from   w ww .j a va  2s  .  c o  m
    ByteBuf bb = ctx.alloc().buffer();
    uncompress(buf.slice(), bb);
    return new MessageTypeAndBuffer(messageType, bb, sctpChannel);
}

From source file:com.savageboy74.savagetech.handler.packets.PacketPipeline.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, FMLProxyPacket msg, List<Object> out) throws Exception {
    ByteBuf payload = msg.payload();
    byte discriminator = payload.readByte();

    Class<? extends AbstractPacket> apClass = this.packets.get(discriminator);

    if (apClass == null) {
        throw new NullPointerException(Strings.Packets.NOT_REGISTERED + apClass.getCanonicalName());
    }//from   w  ww .  j  a v  a  2 s  .c o  m

    AbstractPacket abstractPacket = apClass.newInstance();
    abstractPacket.decodeInto(ctx, payload.slice());

    EntityPlayer player;
    switch (FMLCommonHandler.instance().getEffectiveSide()) {
    case CLIENT:
        player = Minecraft.getMinecraft().thePlayer;
        abstractPacket.handleClientSide(player);
        break;
    case SERVER:
        INetHandler handler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();
        player = ((NetHandlerPlayServer) handler).playerEntity;
        abstractPacket.handleServerSide(player);
        break;
    default:
    }

    out.add(abstractPacket);
}

From source file:com.tesora.dve.db.mysql.common.MysqlAPIUtils.java

License:Open Source License

public static ArrayList<Integer> locateLengthCodedStrings(ByteBuf cb, int skipAmount) {
    ArrayList<Integer> offsets = new ArrayList<>();
    ByteBuf slice = cb.slice().order(ByteOrder.LITTLE_ENDIAN);
    slice.skipBytes(skipAmount);/*from ww  w . j a v  a2 s.  co m*/
    while (slice.isReadable()) {
        offsets.add(slice.readerIndex());
        skipLengthCodedString(slice);
    }
    return offsets;
}

From source file:com.tesora.dve.db.mysql.common.MysqlAPIUtils.java

License:Open Source License

/**
 * Returns a byte[] that matches the readable content of the provided ByteBuf.  If possible, this method will
 * return a direct reference to the backing array, rather than copy into a new array.  If the readable content
 * is smaller than the backing array, or there is no backing array because the buffer is direct, the contents
 * are copied into a new byte[].  The readIndex and writeIndex of the provided ByteBuf are not modified by this call.
 * @param cb source of bytes//from  w ww . j a  va 2  s  . co m
 * @return direct reference to backing byte[] data, or a copy if needed,
 */
public static byte[] unwrapOrCopyReadableBytes(ByteBuf cb) {
    if (cb.hasArray() && cb.readableBytes() == cb.array().length) {
        //already a heap array, and readable length is entire array
        return cb.array();
    } else {
        byte[] copy = new byte[cb.readableBytes()];
        cb.slice().readBytes(copy);
        return copy;
    }
}

From source file:com.tesora.dve.db.mysql.libmy.MyBinaryResultRow.java

License:Open Source License

public void marshallRawValues(ByteBuf cb) {
    for (int i = 0; i < fieldSlices.size(); i++) {
        ByteBuf fieldSlice = fieldSlices.get(i);
        if (fieldSlice != null)
            cb.writeBytes(fieldSlice.slice());
    }/*from  w w  w  . ja v  a 2s  .co m*/
}