List of usage examples for io.netty.buffer ByteBuf writerIndex
public abstract int writerIndex();
From source file:org.graylog2.inputs.transports.netty.LenientLineBasedFrameDecoder.java
License:Open Source License
/** * Create a frame out of the {@link ByteBuf} and return it. * * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to * @param buffer the {@link ByteBuf} from which to read data * @return frame the {@link ByteBuf} which represent the frame or {@code null} if no frame could * be created.//from ww w. j a v a 2 s .c o m */ protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { final int eol = findEndOfLine(buffer); if (!discarding) { if (eol < 0 && emitLastLineWithoutDelimiter && !ctx.channel().isActive()) { final ByteBuf frame; final int length = buffer.readableBytes(); if (length > maxLength) { buffer.readerIndex(length); fail(ctx, length); return null; } frame = buffer.readRetainedSlice(length); return frame; } else if (eol >= 0) { final ByteBuf frame; final int length = eol - buffer.readerIndex(); final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1; if (length > maxLength) { buffer.readerIndex(eol + delimLength); fail(ctx, length); return null; } if (stripDelimiter) { frame = buffer.readRetainedSlice(length); buffer.skipBytes(delimLength); } else { frame = buffer.readRetainedSlice(length + delimLength); } return frame; } else { final int length = buffer.readableBytes(); if (length > maxLength) { discardedBytes = length; buffer.readerIndex(buffer.writerIndex()); discarding = true; offset = 0; if (failFast) { fail(ctx, "over " + discardedBytes); } } return null; } } else { if (eol >= 0) { final int length = discardedBytes + eol - buffer.readerIndex(); final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1; buffer.readerIndex(eol + delimLength); discardedBytes = 0; discarding = false; if (!failFast) { fail(ctx, length); } } else { discardedBytes += buffer.readableBytes(); buffer.readerIndex(buffer.writerIndex()); } return null; } }
From source file:org.hawkular.metrics.clients.ptrans.collectd.packet.PacketDecodingTest.java
License:Apache License
static ByteBuf createValuesPartBuffer(Values values) { List<Number> data = values.getData(); ListIterator<Number> dataIterator = data.listIterator(); List<DataType> dataTypes = values.getDataTypes(); ListIterator<DataType> dataTypeIterator = dataTypes.listIterator(); ByteBuf payloadBuffer = Unpooled.buffer(); while (dataTypeIterator.hasNext()) { payloadBuffer.writeByte(dataTypeIterator.next().getId()); }/*from w w w. j a v a 2 s. c o m*/ dataTypeIterator = dataTypes.listIterator(); while (dataIterator.hasNext()) { DataType dataType = dataTypeIterator.next(); Number number = dataIterator.next(); switch (dataType) { case COUNTER: case ABSOLUTE: BigInteger bigInteger = (BigInteger) number; payloadBuffer.writeBytes(bigInteger.toByteArray()); break; case DERIVE: payloadBuffer.writeLong((Long) number); break; case GAUGE: payloadBuffer.writeLong(ByteBufUtil.swapLong(Double.doubleToLongBits((Double) number))); break; default: fail("Unknown data type: " + dataType); } } ByteBuf headerBuffer = Unpooled.buffer(); headerBuffer.writeShort(VALUES.getId()); headerBuffer.writeShort(6 + payloadBuffer.writerIndex()); headerBuffer.writeShort(data.size()); ByteBuf buffer = Unpooled.buffer(); buffer.writeBytes(headerBuffer.duplicate()).writeBytes(payloadBuffer.duplicate()); return buffer; }
From source file:org.helios.octo.util.NettyUtil.java
License:Open Source License
public static String formatBuffer(ByteBuf buf) { int length = buf.readableBytes(); int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4; StringBuilder dump = new StringBuilder(rows * 80); dump.append(NEWLINE + " +-------------------------------------------------+" + NEWLINE + " | 0 1 2 3 4 5 6 7 8 9 a b c d e f |" + NEWLINE + "+--------+-------------------------------------------------+----------------+"); final int startIndex = buf.readerIndex(); final int endIndex = buf.writerIndex(); int i;// www . ja va2 s . com for (i = startIndex; i < endIndex; i++) { int relIdx = i - startIndex; int relIdxMod16 = relIdx & 15; if (relIdxMod16 == 0) { dump.append(NEWLINE); dump.append(Long.toHexString(relIdx & 0xFFFFFFFFL | 0x100000000L)); dump.setCharAt(dump.length() - 9, '|'); dump.append('|'); } dump.append(BYTE2HEX[buf.getUnsignedByte(i)]); if (relIdxMod16 == 15) { dump.append(" |"); for (int j = i - 15; j <= i; j++) { dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]); } dump.append('|'); } } if ((i - startIndex & 15) != 0) { int remainder = length & 15; dump.append(HEXPADDING[remainder]); dump.append(" |"); for (int j = i - remainder; j < i; j++) { dump.append(BYTE2CHAR[buf.getUnsignedByte(j)]); } dump.append(BYTEPADDING[remainder]); dump.append('|'); } dump.append(NEWLINE + "+--------+-------------------------------------------------+----------------+"); return dump.toString(); }
From source file:org.hornetq.amqp.dealer.protonimpl.AbstractProtonSender.java
License:Apache License
protected int performSend(ProtonJMessage serverMessage, Object context) { if (!creditsSemaphore.tryAcquire()) { try {/*from www . j a v a 2 s. co m*/ creditsSemaphore.acquire(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // nothing to be done here.. we just keep going throw new IllegalStateException(e.getMessage(), e); } } //presettle means we can ack the message on the dealer side before we send it, i.e. for browsers boolean preSettle = sender.getRemoteSenderSettleMode() == SenderSettleMode.SETTLED; //we only need a tag if we are going to ack later byte[] tag = preSettle ? new byte[0] : protonSession.getTag(); ByteBuf nettyBuffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024); try { serverMessage.encode(new NettyWritable(nettyBuffer)); int size = nettyBuffer.writerIndex(); synchronized (connection.getTrio().getLock()) { final Delivery delivery; delivery = sender.delivery(tag, 0, tag.length); delivery.setContext(context); // this will avoid a copy.. patch provided by Norman using buffer.array() sender.send(nettyBuffer.array(), nettyBuffer.arrayOffset() + nettyBuffer.readerIndex(), nettyBuffer.readableBytes()); if (preSettle) { delivery.settle(); } else { sender.advance(); } } connection.flush(); return size; } finally { nettyBuffer.release(); } }
From source file:org.hornetq.amqp.dealer.util.ByteUtil.java
License:Apache License
public static void debugFrame(String message, ByteBuf byteIn) { int location = byteIn.readerIndex(); // debugging// www . j ava 2 s . c o m byte[] frame = new byte[byteIn.writerIndex()]; byteIn.readBytes(frame); try { System.err.println(message + "\n" + ByteUtil.formatGroup(ByteUtil.bytesToHex(frame), 4, 16)); } catch (Exception e) { e.printStackTrace(); } byteIn.readerIndex(location); }
From source file:org.hornetq.amqp.dealer.util.DeliveryUtil.java
License:Apache License
public static int readDelivery(Receiver receiver, ByteBuf buffer) { int initial = buffer.writerIndex(); // optimization by norman int count;/* w w w . j a v a 2 s . co m*/ while ((count = receiver.recv(buffer.array(), buffer.arrayOffset() + buffer.writerIndex(), buffer.writableBytes())) > 0) { // Increment the writer index by the number of bytes written into it while calling recv. buffer.writerIndex(buffer.writerIndex() + count); } return buffer.writerIndex() - initial; }
From source file:org.hornetq.amqp.test.minimalserver.MinimalConnectionSPI.java
License:Apache License
@Override public void output(final ByteBuf bytes, final ChannelFutureListener futureCompletion) { if (DebugInfo.debug) { // some debug byte[] frame = new byte[bytes.writerIndex()]; int readerOriginalPos = bytes.readerIndex(); bytes.getBytes(0, frame);//from ww w .ja v a 2 s. c o m try { System.err.println( "Buffer Outgoing: " + "\n" + ByteUtil.formatGroup(ByteUtil.bytesToHex(frame), 4, 16)); } catch (Exception e) { e.printStackTrace(); } bytes.readerIndex(readerOriginalPos); } // ^^ debug channel.writeAndFlush(bytes).addListener(futureCompletion); }
From source file:org.hornetq.tests.integration.transports.netty.HornetQFrameDecoder2Test.java
License:Apache License
@Test public void testOrdinaryFragmentation() throws Exception { final EmbeddedChannel decoder = new EmbeddedChannel(new HornetQFrameDecoder2()); final byte[] data = new byte[HornetQFrameDecoder2Test.MSG_LEN]; HornetQFrameDecoder2Test.rand.nextBytes(data); ByteBuf src = Unpooled.buffer(HornetQFrameDecoder2Test.MSG_CNT * (HornetQFrameDecoder2Test.MSG_LEN + 4)); while (src.writerIndex() < src.capacity()) { src.writeInt(HornetQFrameDecoder2Test.MSG_LEN); src.writeBytes(data);// ww w. ja v a 2 s . co m } List<ByteBuf> packets = new ArrayList<ByteBuf>(); while (src.isReadable()) { int length = Math.min(HornetQFrameDecoder2Test.rand.nextInt(HornetQFrameDecoder2Test.FRAGMENT_MAX_LEN), src.readableBytes()); packets.add(src.readBytes(length)); } int cnt = 0; for (ByteBuf p : packets) { decoder.writeInbound(p); for (;;) { ByteBuf frame = (ByteBuf) decoder.readInbound(); if (frame == null) { break; } Assert.assertEquals(4, frame.readerIndex()); Assert.assertEquals(HornetQFrameDecoder2Test.MSG_LEN, frame.readableBytes()); Assert.assertEquals(Unpooled.wrappedBuffer(data), frame); cnt++; frame.release(); } } Assert.assertEquals(HornetQFrameDecoder2Test.MSG_CNT, cnt); }
From source file:org.l2junity.gameserver.network.client.Crypt.java
License:Open Source License
private void onPacketSent(ByteBuf buf) { byte[] data = new byte[buf.writerIndex()]; buf.getBytes(0, data);//from w ww .ja v a 2 s . c om EventDispatcher.getInstance().notifyEvent(new OnPacketSent(_client, data)); }
From source file:org.l2junity.gameserver.network.client.Crypt.java
License:Open Source License
private void onPacketReceive(ByteBuf buf) { byte[] data = new byte[buf.writerIndex()]; buf.getBytes(0, data);// w w w.j av a2 s . com EventDispatcher.getInstance().notifyEvent(new OnPacketReceived(_client, data)); }