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:com.jamierf.jsonrpc.util.JsonObjectDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (state == ST_CORRUPTED) {
        in.skipBytes(in.readableBytes());
        return;/* w w  w.j a  va  2s .  com*/
    }

    // index of next byte to process.
    int idx = this.idx;
    int wrtIdx = in.writerIndex();

    if (wrtIdx > maxObjectLength) {
        // buffer size exceeded maxObjectLength; discarding the complete buffer.
        in.skipBytes(in.readableBytes());
        reset();
        throw new TooLongFrameException(
                "object length exceeds " + maxObjectLength + ": " + wrtIdx + " bytes discarded");
    }

    for (/* use current idx */; idx < wrtIdx; idx++) {
        byte c = in.getByte(idx);
        if (state == ST_DECODING_NORMAL) {
            decodeByte(c, in, idx);

            // All opening braces/brackets have been closed. That's enough to conclude
            // that the JSON object/array is complete.
            if (openBraces == 0) {
                ByteBuf json = extractObject(ctx, in, in.readerIndex(), idx + 1 - in.readerIndex());
                if (json != null) {
                    out.add(json);
                }

                // The JSON object/array was extracted => discard the bytes from
                // the input buffer.
                in.readerIndex(idx + 1);
                // Reset the object state to get ready for the next JSON object/text
                // coming along the byte stream.
                reset();
            }
        } else if (state == ST_DECODING_ARRAY_STREAM) {
            decodeByte(c, in, idx);

            if (!insideString && (openBraces == 1 && c == ',' || openBraces == 0 && c == ']')) {
                // skip leading spaces. No range check is needed and the loop will terminate
                // because the byte at position idx is not a whitespace.
                for (int i = in.readerIndex(); Character.isWhitespace(in.getByte(i)); i++) {
                    in.skipBytes(1);
                }

                // skip trailing spaces.
                int idxNoSpaces = idx - 1;
                while (idxNoSpaces >= in.readerIndex() && Character.isWhitespace(in.getByte(idxNoSpaces))) {
                    idxNoSpaces--;
                }

                ByteBuf json = extractObject(ctx, in, in.readerIndex(), idxNoSpaces + 1 - in.readerIndex());
                if (json != null) {
                    out.add(json);
                }

                in.readerIndex(idx + 1);

                if (c == ']') {
                    reset();
                }
            }
            // JSON object/array detected. Accumulate bytes until all braces/brackets are closed.
        } else if (c == '{' || c == '[') {
            initDecoding(c);

            if (state == ST_DECODING_ARRAY_STREAM) {
                // Discard the array bracket
                in.skipBytes(1);
            }
            // Discard leading spaces in front of a JSON object/array.
        } else if (Character.isWhitespace(c)) {
            in.skipBytes(1);
        } else {
            state = ST_CORRUPTED;
            throw new CorruptedFrameException(
                    "invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in));
        }
    }

    if (in.readableBytes() == 0) {
        this.idx = 0;
    } else {
        this.idx = idx;
    }
}

From source file:com.jfastnet.peers.netty.FutureGenericFutureListener.java

License:Apache License

@Override
public void operationComplete(final Future<? super Void> future) throws Exception {
    if (!future.isSuccess()) {
        if (callerObj != null) {
            log.error("Operation failed for '{}'. Caller: {}, Message: {}, toString: {}",
                    new Object[] { action, callerObj.getClass().getSimpleName(),
                            messageObj.getClass().getSimpleName(), messageObj.toString(), future.cause() });
            if (messageObj instanceof Message) {
                Message message = (Message) messageObj;
                if (message.payload instanceof ByteBuf) {
                    ByteBuf payload = (ByteBuf) message.payload;
                    int writerIndex = payload.writerIndex();
                    log.error("Size of failed message: {}", writerIndex);
                }/* w  w  w.ja va2  s .com*/
            }
        } else if (msgType == null) {
            log.error("Operation failed", future.cause());
        } else {
            log.error("Operation failed for {}", msgType, future.cause());
        }
    }
}

From source file:com.jfastnet.peers.netty.KryoNettyPeer.java

License:Apache License

public ByteBuf getByteBuf(Message message) {
    ByteBuf data = Unpooled.buffer();
    config.serialiser.serialiseWithStream(message, new ByteBufOutputStream(data));

    int length = data.writerIndex();
    log.trace("Message size of {} is {}", message, length);
    //      if (length > config.maximumUdpPacketSize) {
    //         log.error("Message {} exceeds maximum size of {}! Size is {} byte", new Object[]{message, config.maximumUdpPacketSize, length});
    //         return null;
    //      }//w  w  w .j a v a  2 s  .co  m
    return data.retain();
}

From source file:com.l2jmobius.commons.network.codecs.CryptCodec.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    in.resetReaderIndex();//ww w  .  j  a v a 2  s. c  o m
    _crypt.decrypt(in);
    in.readerIndex(in.writerIndex());
    out.add(in.copy(0, in.writerIndex()));
}

From source file:com.l2jmobius.commons.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.  ja  va 2s. c o m*/
    }

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

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

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

        final IConnectionState connectionState = ctx.channel().attr(IConnectionState.ATTRIBUTE_KEY).get();
        if ((connectionState == null) || !incomingPacket.getConnectionStates().contains(connectionState)) {
            // LOGGER.warning(incomingPacket + ": Connection at invalid state: " + connectionState + " Required States: " + 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:com.l2jmobius.commons.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 w  w  .  j  a v  a2 s.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.log(Level.WARNING, "Failed sending Packet(" + packet + ")", e);
        // Avoid sending the packet if some exception happened
        out.clear();
    }
}

From source file:com.l2jmobius.gameserver.network.client.Crypt.java

License:Open Source License

@Override
public void encrypt(ByteBuf buf) {
    if (!_isEnabled) {
        _isEnabled = true;//from   w  ww.  j  a  va2 s .  c o  m
        onPacketSent(buf);
        return;
    }

    onPacketSent(buf);

    int a = 0;
    while (buf.isReadable()) {
        final int b = buf.readByte() & 0xFF;
        a = b ^ _outKey[(buf.readerIndex() - 1) & 15] ^ a;
        buf.setByte(buf.readerIndex() - 1, a);
    }

    shiftKey(_outKey, buf.writerIndex());
}

From source file:com.l2jmobius.gameserver.network.client.Crypt.java

License:Open Source License

@Override
public void decrypt(ByteBuf buf) {
    if (!_isEnabled) {
        onPacketReceive(buf);/*ww w .  j  a v a 2  s .  co  m*/
        return;
    }

    int a = 0;
    while (buf.isReadable()) {
        final int b = buf.readByte() & 0xFF;
        buf.setByte(buf.readerIndex() - 1, b ^ _inKey[(buf.readerIndex() - 1) & 15] ^ a);
        a = b;
    }

    shiftKey(_inKey, buf.writerIndex());

    onPacketReceive(buf);
}

From source file:com.l2jmobius.gameserver.network.client.Crypt.java

License:Open Source License

private void onPacketSent(ByteBuf buf) {
    final byte[] data = new byte[buf.writerIndex()];
    buf.getBytes(0, data);//from  w ww  .j av  a 2s.c om
    EventDispatcher.getInstance().notifyEvent(new OnPacketSent(_client, data));
}

From source file:com.l2jmobius.gameserver.network.client.Crypt.java

License:Open Source License

private void onPacketReceive(ByteBuf buf) {
    final byte[] data = new byte[buf.writerIndex()];
    buf.getBytes(0, data);//from   w  w  w.  j a  v  a 2  s .c  om
    EventDispatcher.getInstance().notifyEvent(new OnPacketReceived(_client, data));
}