Example usage for io.netty.buffer ByteBuf arrayOffset

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

Introduction

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

Prototype

public abstract int arrayOffset();

Source Link

Document

Returns the offset of the first byte within the backing byte array of this buffer.

Usage

From source file:org.apache.activemq.artemis.protocol.amqp.converter.ProtonMessageConverter.java

License:Apache License

@Override
public Object outbound(ServerMessage messageOutbound, int deliveryCount) throws Exception {
    // Useful for testing but not recommended for real life use.
    ByteBuf nettyBuffer = Unpooled.buffer(1024);
    NettyWritable buffer = new NettyWritable(nettyBuffer);
    long messageFormat = (long) outbound(messageOutbound, deliveryCount, buffer);

    EncodedMessage encoded = new EncodedMessage(messageFormat, nettyBuffer.array(),
            nettyBuffer.arrayOffset() + nettyBuffer.readerIndex(), nettyBuffer.readableBytes());

    return encoded;
}

From source file:org.apache.activemq.artemis.protocol.amqp.proton.ProtonServerSenderContext.java

License:Apache License

/**
 * handle an out going message from ActiveMQ Artemis, send via the Proton Sender
 *///  w w w  .  ja  v a  2  s  .c o  m
public int deliverMessage(MessageReference messageReference, int deliveryCount, Connection transportConnection)
        throws Exception {

    if (closed) {
        return 0;
    }

    AMQPMessage message = CoreAmqpConverter.checkAMQP(messageReference.getMessage());
    sessionSPI.invokeOutgoing(message,
            (ActiveMQProtonRemotingConnection) transportConnection.getProtocolConnection());

    // presettle means we can settle 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 settle later
    byte[] tag = preSettle ? new byte[0] : protonSession.getTag();

    ByteBuf nettyBuffer = PooledByteBufAllocator.DEFAULT.heapBuffer(message.getEncodeSize());
    try {
        message.sendBuffer(nettyBuffer, deliveryCount);

        int size = nettyBuffer.writerIndex();

        while (!connection.tryLock(1, TimeUnit.SECONDS)) {
            if (closed || sender.getLocalState() == EndpointState.CLOSED) {
                // If we're waiting on the connection lock, the link might be in the process of closing.  If this happens
                // we return.
                return 0;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Couldn't get lock on deliverMessage " + this);
                }
            }
        }

        try {
            final Delivery delivery;
            delivery = sender.delivery(tag, 0, tag.length);
            delivery.setMessageFormat((int) message.getMessageFormat());
            delivery.setContext(messageReference);

            // this will avoid a copy.. patch provided by Norman using buffer.array()
            sender.send(nettyBuffer.array(), nettyBuffer.arrayOffset() + nettyBuffer.readerIndex(),
                    nettyBuffer.readableBytes());

            if (preSettle) {
                // Presettled means the client implicitly accepts any delivery we send it.
                sessionSPI.ack(null, brokerConsumer, messageReference.getMessage());
                delivery.settle();
            } else {
                sender.advance();
            }
            connection.flush();
        } finally {
            connection.unlock();
        }

        return size;
    } finally {
        nettyBuffer.release();
    }
}

From source file:org.apache.activemq.artemis.protocol.amqp.util.DeliveryUtil.java

License:Apache License

public static int readDelivery(Receiver receiver, ByteBuf buffer) {
    int initial = buffer.writerIndex();
    // optimization by norman
    int count;/*from w  ww .j  a  v a  2s.  c  om*/
    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);
        buffer.ensureWritable(count);
    }
    return buffer.writerIndex() - initial;
}

From source file:org.apache.activemq.artemis.protocol.amqp.util.DeliveryUtil.java

License:Apache License

public static MessageImpl decodeMessageImpl(ByteBuf buffer) {
    MessageImpl message = (MessageImpl) Message.Factory.create();
    message.decode(buffer.array(), buffer.arrayOffset() + buffer.readerIndex(), buffer.readableBytes());
    return message;
}

From source file:org.apache.activemq.artemis.protocol.amqp.util.NettyReadableTest.java

License:Apache License

@Test
public void testArrayAccess() {
    ByteBuf byteBuffer = Unpooled.buffer(100, 100);
    NettyReadable buffer = new NettyReadable(byteBuffer);

    assertTrue(buffer.hasArray());/*from  w  w  w.  j  a va  2 s .  c o m*/
    assertSame(buffer.array(), byteBuffer.array());
    assertEquals(buffer.arrayOffset(), byteBuffer.arrayOffset());
}

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

License:Apache License

/**
 * Batch hash code implementation that works at its best if {@code bytes}
 * contains a {@link org.apache.activemq.artemis.api.core.SimpleString} encoded.
 *///from   w ww. j  a va  2s  .  com
private static int hashCode(final ByteBuf bytes, final int offset, final int length) {
    if (PlatformDependent.isUnaligned() && PlatformDependent.hasUnsafe()) {
        //if the platform allows it, the hash code could be computed without bounds checking
        if (bytes.hasArray()) {
            return onHeapHashCode(bytes.array(), bytes.arrayOffset() + offset, length);
        } else if (bytes.hasMemoryAddress()) {
            return offHeapHashCode(bytes.memoryAddress(), offset, length);
        }
    }
    return byteBufHashCode(bytes, offset, length);
}

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

License:Apache License

public static void saveUTF(final ByteBuf out, final String str) {

    if (str.length() > 0xffff) {
        throw ActiveMQUtilBundle.BUNDLE.stringTooLong(str.length());
    }/*from   ww w.  ja va  2s.  c o m*/

    final int len = UTF8Util.calculateUTFSize(str);

    if (len > 0xffff) {
        throw ActiveMQUtilBundle.BUNDLE.stringTooLong(len);
    }

    out.writeShort((short) len);

    final int stringLength = str.length();

    if (UTF8Util.isTrace) {
        // This message is too verbose for debug, that's why we are using trace here
        ActiveMQUtilLogger.LOGGER.trace("Saving string with utfSize=" + len + " stringSize=" + stringLength);
    }

    if (out.hasArray()) {
        out.ensureWritable(len);
        final byte[] bytes = out.array();
        final int writerIndex = out.writerIndex();
        final int index = out.arrayOffset() + writerIndex;
        if (PlatformDependent.hasUnsafe()) {
            unsafeOnHeapWriteUTF(str, bytes, index, stringLength);
        } else {
            writeUTF(str, bytes, index, stringLength);
        }
        out.writerIndex(writerIndex + len);
    } else {
        if (PlatformDependent.hasUnsafe() && out.hasMemoryAddress()) {
            out.ensureWritable(len);
            final long addressBytes = out.memoryAddress();
            final int writerIndex = out.writerIndex();
            unsafeOffHeapWriteUTF(str, addressBytes, writerIndex, stringLength);
            out.writerIndex(writerIndex + len);
        } else {
            final StringUtilBuffer buffer = UTF8Util.getThreadLocalBuffer();
            final byte[] bytes = buffer.borrowByteBuffer(len);
            writeUTF(str, bytes, 0, stringLength);
            out.writeBytes(bytes, 0, len);
        }
    }
}

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

License:Apache License

public static String readUTF(final ActiveMQBuffer input) {
    StringUtilBuffer buffer = UTF8Util.getThreadLocalBuffer();

    final int size = input.readUnsignedShort();

    if (UTF8Util.isTrace) {
        // This message is too verbose for debug, that's why we are using trace here
        ActiveMQUtilLogger.LOGGER.trace("Reading string with utfSize=" + size);
    }/*from   www  .j  av  a 2s.  c  o  m*/
    if (PlatformDependent.hasUnsafe() && input.byteBuf() != null && input.byteBuf().hasMemoryAddress()) {
        final ByteBuf byteBuf = input.byteBuf();
        final long addressBytes = byteBuf.memoryAddress();
        final int index = byteBuf.readerIndex();
        byteBuf.skipBytes(size);
        final char[] chars = buffer.borrowCharBuffer(size);
        return unsafeOffHeapReadUTF(addressBytes, index, chars, size);
    }
    final byte[] bytes;
    final int index;
    if (input.byteBuf() != null && input.byteBuf().hasArray()) {
        final ByteBuf byteBuf = input.byteBuf();
        bytes = byteBuf.array();
        index = byteBuf.arrayOffset() + byteBuf.readerIndex();
        byteBuf.skipBytes(size);
    } else {
        bytes = buffer.borrowByteBuffer(size);
        index = 0;
        input.readBytes(bytes, 0, size);
    }
    final char[] chars = buffer.borrowCharBuffer(size);
    if (PlatformDependent.hasUnsafe()) {
        return unsafeOnHeapReadUTF(bytes, index, chars, size);
    } else {
        return readUTF(bytes, index, chars, size);
    }
}

From source file:org.apache.bookkeeper.proto.BookieProtoEncoding.java

License:Apache License

private static ByteBuf serializeProtobuf(MessageLite msg, ByteBufAllocator allocator) {
    int size = msg.getSerializedSize();
    ByteBuf buf = allocator.heapBuffer(size, size);

    try {/*from  w  ww.j a va2  s.  c om*/
        msg.writeTo(CodedOutputStream.newInstance(buf.array(), buf.arrayOffset() + buf.writerIndex(), size));
    } catch (IOException e) {
        // This is in-memory serialization, should not fail
        throw new RuntimeException(e);
    }

    // Advance writer idx
    buf.writerIndex(buf.capacity());
    return buf;
}

From source file:org.apache.bookkeeper.proto.checksum.DirectMemoryCRC32Digest.java

License:Apache License

@Override
public void update(ByteBuf buf) {
    int index = buf.readerIndex();
    int length = buf.readableBytes();

    try {/*  w  ww  .j av a 2 s. c  o m*/
        if (buf.hasMemoryAddress()) {
            // Calculate CRC directly from the direct memory pointer
            crcValue = (int) updateByteBuffer.invoke(null, crcValue, buf.memoryAddress(), index, length);
        } else if (buf.hasArray()) {
            // Use the internal method to update from array based
            crcValue = (int) updateBytes.invoke(null, crcValue, buf.array(), buf.arrayOffset() + index, length);
        } else {
            // Fallback to data copy if buffer is not contiguous
            byte[] b = new byte[length];
            buf.getBytes(index, b, 0, length);
            crcValue = (int) updateBytes.invoke(null, crcValue, b, 0, b.length);
        }
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}