Example usage for io.netty.buffer ByteBuf writerIndex

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

Introduction

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

Prototype

public abstract int writerIndex();

Source Link

Document

Returns the writerIndex of this buffer.

Usage

From source file:org.l2junity.loginserver.network.client.crypt.Crypt.java

License:Open Source License

@Override
public void encrypt(ByteBuf buf) {
    // Ensure that byte order is little endian because we set new packet size in first 2 bytes
    if (buf.order() != ByteOrder.LITTLE_ENDIAN) {
        buf = buf.order(ByteOrder.LITTLE_ENDIAN);
    }/* www .  j  a  v a2s .  c  om*/

    // Checksum & XOR Key or Checksum only
    buf.writeZero(_static ? 8 : 4);

    // Padding
    buf.writeZero(8 - (buf.readableBytes() % 8));

    if (_static) {
        _static = false;

        int key = Rnd.nextInt();
        buf.skipBytes(4); // The first 4 bytes are ignored
        while (buf.readerIndex() < (buf.writerIndex() - 8)) {
            int data = buf.readInt();
            key += data;
            data ^= key;
            buf.setInt(buf.readerIndex() - 4, data);
        }
        buf.setInt(buf.readerIndex(), key);

        buf.resetReaderIndex();

        final byte[] block = new byte[8];
        while (buf.isReadable(8)) {
            buf.readBytes(block);
            STATIC_BLOWFISH_ENGINE.encryptBlock(block, 0);
            buf.setBytes(buf.readerIndex() - block.length, block);
        }
    } else {
        int checksum = 0;
        while (buf.isReadable(8)) {
            checksum ^= buf.readInt();
        }
        buf.setInt(buf.readerIndex(), checksum);

        buf.resetReaderIndex();

        final byte[] block = new byte[8];
        while (buf.isReadable(8)) {
            buf.readBytes(block);
            _blowfishEngine.encryptBlock(block, 0);
            buf.setBytes(buf.readerIndex() - block.length, block);
        }
    }
}

From source file:org.l2junity.network.codecs.PacketDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    if ((in == null) || !in.isReadable()) {
        return;//from   w w w .  j  av  a  2s  .  c  om
    }

    if (in.order() != _byteOrder) {
        in = in.order(_byteOrder);
    }

    try {
        final short packetId = in.readUnsignedByte();
        if (packetId >= _incomingPackets.length) {
            LOGGER.debug("Unknown packet: {}", Integer.toHexString(packetId));
            return;
        }

        final IIncomingPackets<T> incomingPacket = _incomingPackets[packetId];
        if (incomingPacket == null) {
            LOGGER.debug("Unknown packet: {}", Integer.toHexString(packetId));
            return;
        }

        final IConnectionState connectionState = ctx.channel().attr(IConnectionState.ATTRIBUTE_KEY).get();
        if ((connectionState == null) || !incomingPacket.getConnectionStates().contains(connectionState)) {
            LOGGER.warn("{}: Connection at invalid state: {} Required States: {}", incomingPacket,
                    connectionState, incomingPacket.getConnectionStates());
            return;
        }

        final IIncomingPacket<T> packet = incomingPacket.newIncomingPacket();
        if ((packet != null) && packet.read(_client, new PacketReader(in))) {
            out.add(packet);
        }
    } finally {
        // We always consider that we read whole packet.
        in.readerIndex(in.writerIndex());
    }
}

From source file:org.l2junity.network.codecs.PacketEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, IOutgoingPacket packet, ByteBuf out) {
    if (out.order() != _byteOrder) {
        out = out.order(_byteOrder);//from   w ww  . j a v  a  2s . c  o m
    }

    try {
        if (packet.write(new PacketWriter(out))) {
            if (out.writerIndex() > _maxPacketSize) {
                throw new IllegalStateException("Packet (" + packet + ") size (" + out.writerIndex()
                        + ") is bigger than the limit (" + _maxPacketSize + ")");
            }
        } else {
            // Avoid sending the packet
            out.clear();
        }
    } catch (Throwable e) {
        LOGGER.warn("Failed sending Packet({})", packet, e);
        // Avoid sending the packet if some exception happened
        out.clear();
    }
}

From source file:org.lmdbjava.ByteBufProxy.java

License:Apache License

@Override
protected void in(final ByteBuf buffer, final Pointer ptr, final long ptrAddr) {
    UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_SIZE, buffer.writerIndex() - buffer.readerIndex());
    UNSAFE.putLong(ptrAddr + STRUCT_FIELD_OFFSET_DATA, buffer.memoryAddress() + buffer.readerIndex());
}

From source file:org.onosproject.lisp.msg.types.lcaf.LispLcafAddress.java

License:Apache License

/**
 * Updates the header length field value based on the size of LISP header.
 *
 * @param lcafIndex the index of LCAF address, because LCAF address is
 *                  contained inside LISP control message, so to correctly
 *                  find the right LCAF length index, we need to know the
 *                  absolute lcaf index inside LISP control message byte buf
 * @param byteBuf   netty byte buffer// w  w w . j  av  a 2 s.co m
 */
public static void updateLength(int lcafIndex, ByteBuf byteBuf) {
    byteBuf.setByte(lcafIndex + LENGTH_FIELD_INDEX, byteBuf.writerIndex() - COMMON_HEADER_SIZE - lcafIndex);
}

From source file:org.onosproject.ovsdb.lib.utils.JsonRpcReaderUtil.java

License:Apache License

/**
 * Decode the bytes to Json object./*from   w  ww .  ja  v  a 2  s.  c om*/
 * @param in input of bytes
 * @param out ouput of Json object list
 * @param jrContext context for the last decoding process
 */
public static void readToJsonNode(ByteBuf in, List<Object> out, JsonReadContext jrContext) throws Exception {
    int lastReadBytes = jrContext.getLastReadBytes();
    if (lastReadBytes == 0) {
        if (in.readableBytes() < 4) {
            return;
        }
        checkEncoding(in);
    }

    int i = lastReadBytes + in.readerIndex();
    Stack<Byte> bufStack = jrContext.getBufStack();
    for (; i < in.writerIndex(); i++) {
        byte b = in.getByte(i);
        switch (b) {
        case '{':
            if (!isDoubleQuote(bufStack)) {
                bufStack.push(b);
                jrContext.setStartMatch(true);
            }
            break;
        case '}':
            if (!isDoubleQuote(bufStack)) {
                bufStack.pop();
            }
            break;
        case '"':
            if (in.getByte(i - 1) != '\\') {
                if (!bufStack.isEmpty() && bufStack.peek() != '"') {
                    bufStack.push(b);
                } else {
                    bufStack.pop();
                }
            }
            break;
        default:
            break;
        }

        if (jrContext.isStartMatch() && bufStack.isEmpty()) {
            ByteBuf buf = in.readSlice(i - in.readerIndex() + 1);
            JsonParser jf = new MappingJsonFactory().createParser(new ByteBufInputStream(buf));
            JsonNode jsonNode = jf.readValueAsTree();
            out.add(jsonNode);
            lastReadBytes = 0;
            jrContext.setLastReadBytes(lastReadBytes);
            break;
        }
    }

    if (i >= in.writerIndex()) {
        lastReadBytes = in.readableBytes();
        jrContext.setLastReadBytes(lastReadBytes);
    }
}

From source file:org.onosproject.ovsdb.rfc.utils.JsonRpcReaderUtil.java

License:Apache License

/**
 * Decode the bytes to Json object./*ww  w  .  j  av a2 s.  com*/
 * @param in input of bytes
 * @param out ouput of Json object list
 * @param jrContext context for the last decoding process
 * @throws IOException IOException
 * @throws JsonParseException JsonParseException
 */
public static void readToJsonNode(ByteBuf in, List<Object> out, JsonReadContext jrContext) throws IOException {
    int lastReadBytes = jrContext.getLastReadBytes();
    if (lastReadBytes == 0) {
        if (in.readableBytes() < 4) {
            return;
        }
        checkEncoding(in);
    }

    int i = lastReadBytes + in.readerIndex();
    Stack<Byte> bufStack = jrContext.getBufStack();
    for (; i < in.writerIndex(); i++) {
        byte b = in.getByte(i);
        switch (b) {
        case '{':
            if (!isDoubleQuote(bufStack)) {
                bufStack.push(b);
                jrContext.setStartMatch(true);
            }
            break;
        case '}':
            if (!isDoubleQuote(bufStack)) {
                bufStack.pop();
            }
            break;
        case '"':
            if (in.getByte(i - 1) != '\\') {
                if (!bufStack.isEmpty() && bufStack.peek() != '"') {
                    bufStack.push(b);
                } else {
                    bufStack.pop();
                }
            }
            break;
        default:
            break;
        }

        if (jrContext.isStartMatch() && bufStack.isEmpty()) {
            ByteBuf buf = in.readSlice(i - in.readerIndex() + 1);
            JsonParser jf = new MappingJsonFactory().createParser(new ByteBufInputStream(buf));
            JsonNode jsonNode = jf.readValueAsTree();
            out.add(jsonNode);
            lastReadBytes = 0;
            jrContext.setLastReadBytes(lastReadBytes);
            break;
        }
    }

    if (i >= in.writerIndex()) {
        lastReadBytes = in.readableBytes();
        jrContext.setLastReadBytes(lastReadBytes);
    }
}

From source file:org.opendaylight.bgp.concepts.NextHopUtil.java

License:Open Source License

/**
 * Parses CNextHop IP address from given ByteBuf.
 *
 * @param buffer contains byte array representation of CNextHop
 * @return CNexthop object/*from   w  ww  .  j  a  v a 2s  . c  om*/
 */
public static CNextHop parseNextHop(final ByteBuf buffer) {
    switch (buffer.writerIndex()) {
    case Ipv4Util.IP4_LENGTH:
        return new Ipv4NextHopCaseBuilder()
                .setIpv4NextHop(new Ipv4NextHopBuilder().setGlobal(Ipv4Util.addressForByteBuf(buffer)).build())
                .build();
    case Ipv6Util.IPV6_LENGTH:
        return new Ipv6NextHopCaseBuilder()
                .setIpv6NextHop(new Ipv6NextHopBuilder().setGlobal(Ipv6Util.addressForByteBuf(buffer)).build())
                .build();
    case Ipv6Util.IPV6_LENGTH * 2:
        return new Ipv6NextHopCaseBuilder()
                .setIpv6NextHop(new Ipv6NextHopBuilder().setGlobal(Ipv6Util.addressForByteBuf(buffer))
                        .setLinkLocal(Ipv6Util.addressForByteBuf(buffer)).build())
                .build();
    default:
        throw new IllegalArgumentException(
                "Cannot parse NEXT_HOP attribute. Wrong bytes length: " + buffer.writerIndex());
    }
}

From source file:org.opendaylight.capwap.binding_802_11.AddWlan.java

License:Open Source License

@Override
public int encode(ByteBuf buf) {
    int start = buf.writerIndex();
    buf.writeByte(this.radioId);
    buf.writeByte(this.wlanId);
    buf.writeBytes(ByteManager.unsignedShortToArray(this.capability));
    buf.writeByte(this.keyIndex);
    buf.writeByte(this.keyStatus);
    buf.writeBytes(ByteManager.unsignedShortToArray(this.keyLength));
    buf.writeBytes(this.key);
    buf.writeBytes(this.groupTsc);
    buf.writeByte(this.qos);
    buf.writeByte(this.authType);
    buf.writeByte(this.macMode);
    buf.writeByte(this.tunnelMode);
    buf.writeByte(this.suppressSSID);
    buf.writeBytes(this.ssId);

    return buf.writerIndex() - start;
}

From source file:org.opendaylight.capwap.binding_802_11.WTP_Radio_Information.java

License:Open Source License

public int encode(ByteBuf buf) {

    int start = buf.writerIndex();
    //encode Radio ID
    buf.writeByte(this.radioId); //radio id is  less than 32 , hence direct byte is fine
    buf.writeBytes(new byte[] { 0, 0, 0 }); //3 bytes are  reserved
    buf.writeByte(this.radioType); //again a byte enumeration
    //encode stations
    return buf.writerIndex() - start;
}