Example usage for io.netty.buffer ByteBuf resetWriterIndex

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

Introduction

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

Prototype

public abstract ByteBuf resetWriterIndex();

Source Link

Document

Repositions the current writerIndex to the marked writerIndex in this buffer.

Usage

From source file:com.heliosapm.webrpc.jsonservice.JSONResponse.java

License:Apache License

/**
 * Discards written content from the output stream, discarding the content and creating a new output stream
 *///from  w ww.  j  av  a  2 s.  c  o  m
public void resetChannelOutputStream() {
    if (content != null) {
        throw new RuntimeException("Cannot reset OutputStream. Content already set");
    }
    if (channelOutputStream != null) {
        ByteBuf buff = channelOutputStream.buffer();
        try {
            channelOutputStream.flush();
        } catch (Exception ex) {
        }
        buff.resetWriterIndex();
        channelOutputStream = new ByteBufOutputStream(BufferManager.getInstance().buffer(8096)) {
            final ByteBuf buf = this.buffer();
            boolean closed = false;

            @Override
            public void close() throws IOException {
                if (!closed) {
                    closed = true;
                    super.flush();
                    super.close();
                    channel.write(buf);
                }
            }

            public void flush() throws IOException {
                super.flush();
                super.close();
            }
        };
        jsonGen = null;
        //         try {
        //            jsonGen = JSON.getFactory().createGenerator(channelOutputStream);
        //         } catch (IOException e) {
        //            throw new RuntimeException("Failed to create a new JsonGenerator after reset", e);
        //         }
    }
}

From source file:com.lambdaworks.redis.protocol.CommandEncoder.java

License:Apache License

private void encode(ChannelHandlerContext ctx, ByteBuf out, RedisCommand<?, ?, ?> command) {

    try {//from ww w. j ava 2 s . c  om
        out.markWriterIndex();
        command.encode(out);
    } catch (RuntimeException e) {
        out.resetWriterIndex();
        command.completeExceptionally(new EncoderException(
                "Cannot encode command. Please close the connection as the connection state may be out of sync.",
                e));
    }

    if (debugEnabled) {
        logger.debug("{} writing command {}", logPrefix(ctx.channel()), command);
        if (traceEnabled) {
            logger.trace("{} Sent: {}", logPrefix(ctx.channel()),
                    out.toString(Charset.defaultCharset()).trim());
        }
    }
}

From source file:com.ogarproject.ogar.server.net.packet.outbound.PacketOutUpdateNodes.java

License:Open Source License

@Override
public void writeData(ByteBuf buf) {
    // Removals by eating
    int lengthIndex = buf.writerIndex();
    int eaten = 0;
    buf.writerIndex(lengthIndex + 2);/* ww  w.  java 2s  .c  o m*/
    for (EntityImpl entity : removals) {
        if (entity.getConsumer() > 0) {
            eaten++;
            buf.writeInt(entity.getConsumer());
            buf.writeInt(entity.getID());
        }
    }
    buf.markWriterIndex();
    buf.writerIndex(lengthIndex);
    buf.writeShort(eaten);
    buf.resetWriterIndex();

    // Updates
    for (int id : updates) {
        EntityImpl entity = world.getEntity(id);
        if (entity == null) {
            // TODO - Theoretically this could be ignored, but it might cause other issues,
            // like having nonexistent entities on the player's screen. Re-evaluate this later?
            throw new MalformedPacketException("Attempted to update nonexistent entity");
        }

        buf.writeInt(entity.getID());
        buf.writeInt((int) entity.getPosition().getX());
        buf.writeInt((int) entity.getPosition().getY());
        buf.writeShort(entity.getPhysicalSize());
        buf.writeByte(entity.getColor().getRed());
        buf.writeByte(entity.getColor().getGreen());
        buf.writeByte(entity.getColor().getBlue());
        buf.writeBoolean(entity.isSpiked());
        // buf.skipBytes(18);
        if (entity instanceof CellImpl) {
            CellImpl cell = (CellImpl) entity;
            if (cell.getName() == null) {
                writeUTF16(buf, "");
            } else {
                writeUTF16(buf, cell.getName());
            }
        } else {
            writeUTF16(buf, "");
        }
    }
    buf.writeInt(0);

    // General removals
    buf.writeInt(removals.size());
    for (EntityImpl entity : removals) {
        buf.writeInt(entity.getID());
    }
}

From source file:eu.jangos.realm.network.encoder.RealmPacketEncoder.java

License:Open Source License

private void reverseHeader(ChannelHandlerContext ctx, ByteBuf out) {
    // Retaining the actual index.
    int index = out.writerIndex();
    out.resetReaderIndex();//w w  w.j a va2  s  .c om

    // Reading the header.
    byte[] header = out.readBytes(4).array();

    // Resetting the reader index to send it.
    out.resetReaderIndex();

    // Swapping the header.
    byte temp = header[2];
    header[2] = header[3];
    header[3] = temp;

    // Encrypting the header (if applicable).
    header = ctx.channel().attr(CRYPT).get().encrypt(header);

    // Reset the writer index.
    out.resetWriterIndex();

    // Write the header.
    out.writeBytes(header);

    // Reset the writer index to the default one.
    out.writerIndex(index);
}

From source file:org.apache.activemq.artemis.tests.util.SimpleStringTest.java

License:Apache License

@Test
public void testByteBufSimpleStringPool() {
    final int capacity = 8;
    final int chars = Integer.toString(capacity).length();
    final SimpleString.ByteBufSimpleStringPool pool = new SimpleString.ByteBufSimpleStringPool(capacity, chars);
    final int bytes = new SimpleString(Integer.toString(capacity)).sizeof();
    final ByteBuf bb = Unpooled.buffer(bytes, bytes);
    for (int i = 0; i < capacity; i++) {
        final SimpleString s = new SimpleString(Integer.toString(i));
        bb.resetWriterIndex();
        SimpleString.writeSimpleString(bb, s);
        bb.resetReaderIndex();//  ww w .j  av a2 s.  c  o m
        final SimpleString expectedPooled = pool.getOrCreate(bb);
        bb.resetReaderIndex();
        Assert.assertSame(expectedPooled, pool.getOrCreate(bb));
        bb.resetReaderIndex();
    }
}

From source file:org.apache.activemq.artemis.utils.TypedPropertiesTest.java

License:Apache License

@Test
public void testByteBufStringValuePool() {
    final int capacity = 8;
    final int chars = Integer.toString(capacity).length();
    final TypedProperties.StringValue.ByteBufStringValuePool pool = new TypedProperties.StringValue.ByteBufStringValuePool(
            capacity, chars);/*from ww w . jav a 2  s .  c o m*/
    final int bytes = new SimpleString(Integer.toString(capacity)).sizeof();
    final ByteBuf bb = Unpooled.buffer(bytes, bytes);
    for (int i = 0; i < capacity; i++) {
        final SimpleString s = new SimpleString(Integer.toString(i));
        bb.resetWriterIndex();
        SimpleString.writeSimpleString(bb, s);
        bb.resetReaderIndex();
        final TypedProperties.StringValue expectedPooled = pool.getOrCreate(bb);
        bb.resetReaderIndex();
        Assert.assertSame(expectedPooled, pool.getOrCreate(bb));
        bb.resetReaderIndex();
    }
}

From source file:org.apache.bookkeeper.benchmark.BenchBookie.java

License:Apache License

/**
 * @param args/*from   w  w  w.ja v  a 2 s  . c om*/
 * @throws InterruptedException
 */
public static void main(String[] args)
        throws InterruptedException, ParseException, IOException, BKException, KeeperException {
    Options options = new Options();
    options.addOption("host", true, "Hostname or IP of bookie to benchmark");
    options.addOption("port", true, "Port of bookie to benchmark (default 3181)");
    options.addOption("zookeeper", true, "Zookeeper ensemble, (default \"localhost:2181\")");
    options.addOption("size", true, "Size of message to send, in bytes (default 1024)");
    options.addOption("warmupCount", true, "Number of messages in warmup phase (default 999)");
    options.addOption("latencyCount", true, "Number of messages in latency phase (default 5000)");
    options.addOption("throughputCount", true, "Number of messages in throughput phase (default 50000)");
    options.addOption("help", false, "This message");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help") || !cmd.hasOption("host")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("BenchBookie <options>", options);
        System.exit(-1);
    }

    String addr = cmd.getOptionValue("host");
    int port = Integer.parseInt(cmd.getOptionValue("port", "3181"));
    int size = Integer.parseInt(cmd.getOptionValue("size", "1024"));
    String servers = cmd.getOptionValue("zookeeper", "localhost:2181");
    int warmUpCount = Integer.parseInt(cmd.getOptionValue("warmupCount", "999"));
    int latencyCount = Integer.parseInt(cmd.getOptionValue("latencyCount", "5000"));
    int throughputCount = Integer.parseInt(cmd.getOptionValue("throughputCount", "50000"));

    EventLoopGroup eventLoop;
    if (SystemUtils.IS_OS_LINUX) {
        try {
            eventLoop = new EpollEventLoopGroup();
        } catch (Throwable t) {
            LOG.warn("Could not use Netty Epoll event loop for benchmark {}", t.getMessage());
            eventLoop = new NioEventLoopGroup();
        }
    } else {
        eventLoop = new NioEventLoopGroup();
    }

    OrderedExecutor executor = OrderedExecutor.newBuilder().name("BenchBookieClientScheduler").numThreads(1)
            .build();
    ScheduledExecutorService scheduler = Executors
            .newSingleThreadScheduledExecutor(new DefaultThreadFactory("BookKeeperClientScheduler"));

    ClientConfiguration conf = new ClientConfiguration();
    BookieClient bc = new BookieClientImpl(conf, eventLoop, PooledByteBufAllocator.DEFAULT, executor, scheduler,
            NullStatsLogger.INSTANCE);
    LatencyCallback lc = new LatencyCallback();

    ThroughputCallback tc = new ThroughputCallback();

    long ledger = getValidLedgerId(servers);
    for (long entry = 0; entry < warmUpCount; entry++) {
        ByteBuf toSend = Unpooled.buffer(size);
        toSend.resetReaderIndex();
        toSend.resetWriterIndex();
        toSend.writeLong(ledger);
        toSend.writeLong(entry);
        toSend.writerIndex(toSend.capacity());
        bc.addEntry(new BookieSocketAddress(addr, port), ledger, new byte[20], entry, ByteBufList.get(toSend),
                tc, null, BookieProtocol.FLAG_NONE, false, WriteFlag.NONE);
    }
    LOG.info("Waiting for warmup");
    tc.waitFor(warmUpCount);

    ledger = getValidLedgerId(servers);
    LOG.info("Benchmarking latency");
    long startTime = System.nanoTime();
    for (long entry = 0; entry < latencyCount; entry++) {
        ByteBuf toSend = Unpooled.buffer(size);
        toSend.resetReaderIndex();
        toSend.resetWriterIndex();
        toSend.writeLong(ledger);
        toSend.writeLong(entry);
        toSend.writerIndex(toSend.capacity());
        lc.resetComplete();
        bc.addEntry(new BookieSocketAddress(addr, port), ledger, new byte[20], entry, ByteBufList.get(toSend),
                lc, null, BookieProtocol.FLAG_NONE, false, WriteFlag.NONE);
        lc.waitForComplete();
    }
    long endTime = System.nanoTime();
    LOG.info("Latency: " + (((double) (endTime - startTime)) / ((double) latencyCount)) / 1000000.0);

    ledger = getValidLedgerId(servers);
    LOG.info("Benchmarking throughput");
    startTime = System.currentTimeMillis();
    tc = new ThroughputCallback();
    for (long entry = 0; entry < throughputCount; entry++) {
        ByteBuf toSend = Unpooled.buffer(size);
        toSend.resetReaderIndex();
        toSend.resetWriterIndex();
        toSend.writeLong(ledger);
        toSend.writeLong(entry);
        toSend.writerIndex(toSend.capacity());
        bc.addEntry(new BookieSocketAddress(addr, port), ledger, new byte[20], entry, ByteBufList.get(toSend),
                tc, null, BookieProtocol.FLAG_NONE, false, WriteFlag.NONE);
    }
    tc.waitFor(throughputCount);
    endTime = System.currentTimeMillis();
    LOG.info("Throughput: " + ((long) throughputCount) * 1000 / (endTime - startTime));

    bc.close();
    scheduler.shutdown();
    eventLoop.shutdownGracefully();
    executor.shutdown();
}

From source file:org.apache.bookkeeper.bookie.BufferedChannelTest.java

License:Apache License

public void testBufferedChannel(int byteBufLength, int numOfWrites, int unpersistedBytesBound, boolean flush,
        boolean shouldForceWrite) throws Exception {
    File newLogFile = File.createTempFile("test", "log");
    newLogFile.deleteOnExit();/*from w w  w . jav a2  s  .co  m*/
    FileChannel fileChannel = new RandomAccessFile(newLogFile, "rw").getChannel();

    BufferedChannel logChannel = new BufferedChannel(UnpooledByteBufAllocator.DEFAULT, fileChannel,
            INTERNAL_BUFFER_WRITE_CAPACITY, INTERNAL_BUFFER_READ_CAPACITY, unpersistedBytesBound);

    ByteBuf dataBuf = generateEntry(byteBufLength);
    dataBuf.markReaderIndex();
    dataBuf.markWriterIndex();

    for (int i = 0; i < numOfWrites; i++) {
        logChannel.write(dataBuf);
        dataBuf.resetReaderIndex();
        dataBuf.resetWriterIndex();
    }

    if (flush && shouldForceWrite) {
        logChannel.flushAndForceWrite(false);
    } else if (flush) {
        logChannel.flush();
    } else if (shouldForceWrite) {
        logChannel.forceWrite(false);
    }

    int expectedNumOfUnpersistedBytes = 0;

    if (flush && shouldForceWrite) {
        /*
         * if flush call is made with shouldForceWrite,
         * then expectedNumOfUnpersistedBytes should be zero.
         */
        expectedNumOfUnpersistedBytes = 0;
    } else if (!flush && shouldForceWrite) {
        /*
         * if flush is not called then internal write buffer is not flushed,
         * but while adding entries to BufferedChannel if writeBuffer has
         * reached its capacity then it will call flush method, and the data
         * gets added to the file buffer. So though explicitly we are not
         * calling flush method, implicitly flush gets called when
         * writeBuffer reaches its capacity.
         */
        expectedNumOfUnpersistedBytes = (byteBufLength * numOfWrites) % INTERNAL_BUFFER_WRITE_CAPACITY;
    } else {
        expectedNumOfUnpersistedBytes = (byteBufLength * numOfWrites) - unpersistedBytesBound;
    }

    Assert.assertEquals("Unpersisted bytes", expectedNumOfUnpersistedBytes, logChannel.getUnpersistedBytes());
    logChannel.close();
    fileChannel.close();
}

From source file:org.mobicents.protocols.ss7.m3ua.impl.message.MessageFactoryImpl.java

License:Open Source License

public M3UAMessageImpl createMessage(ByteBuf message) {
    int dataLen;/*  w w w.ja  va 2  s . com*/
    if (message.readableBytes() < 8) {
        return null;
    }

    // obtain message class and type from header
    message.markReaderIndex();
    message.skipBytes(2);
    int messageClass = message.readUnsignedByte();
    int messageType = message.readUnsignedByte();

    // obtain remaining length of the message and prepare buffer
    dataLen = message.readInt() - 8;
    if (message.readableBytes() < dataLen) {
        message.resetReaderIndex();
        return null;
    }

    // construct new message instance
    M3UAMessageImpl messageTemp = this.createMessage(messageClass, messageType);

    // parsing params of this message
    message.markWriterIndex();
    message.writerIndex(message.readerIndex() + dataLen);
    messageTemp.decode(message);
    message.resetWriterIndex();

    return messageTemp;
}

From source file:org.opendaylight.capwap.ODLCapwapHeader.java

License:Open Source License

/**Method converts Capwap header encoder into byte array.
 * @return true: success, false: failure
 *//*from w w w  .j  a  v a 2 s . c om*/
public boolean encodeHeader(ByteBuf bbuf) {
    if (bbuf.writableBytes() < ODLCapwapConsts.ODL_CAPWAP_MIN_HDRLEN) {
        System.out.println("Byte Buffer do not have capacity to write " + ODLCapwapConsts.ODL_CAPWAP_MIN_HDRLEN
                + " bytes");
        return false;
    }

    byte[] hdrbytes = new byte[ODLCapwapConsts.ODL_CAPWAP_MIN_HDRLEN];
    hdrbytes[0] = preamble;
    /* Converting the header len value */
    hdrbytes[1] = (byte) ((hlen >> 2) & ODLCapwapConsts.ODL_CAPWAP_HLEN_MASK);
    /* Filling higher 3bits of RID */
    hdrbytes[1] |= (byte) (rid & 0x1C);
    /* Filling lower 2bits of RID (higher 2 bits of byte2) */
    hdrbytes[2] = (byte) ((rid & 0x03) << 6);
    /* WBID - 5 bits - bits 3-7 */
    hdrbytes[2] |= (byte) (wbid & 0x3E);
    /* Copying the T flag */
    hdrbytes[2] |= (byte) ((flagBits & 0x20) >> 5);
    /* Copying other flag bits */
    hdrbytes[3] = (byte) ((flagBits & 0x1F) << 3);
    /* Filling first byte of fragment ID */
    hdrbytes[4] = (byte) ((fragId & 0xFF00) >> 8);
    /* Filling the second byte of fragment ID */
    hdrbytes[5] = (byte) (fragId & 0x00FF);
    /* Most significant 8 bits of 13 bits */
    hdrbytes[6] = (byte) (((fragOffset) & 0x1FE0) >> 5);
    /* Least significant 5 bits (higher 5 bits of byte 8) */
    hdrbytes[7] = (byte) ((fragOffset & 0x1F) << 3);

    bbuf.resetWriterIndex();
    bbuf.writeBytes(hdrbytes);

    return true;
}