org.apache.activemq.artemis.api.core.ActiveMQBuffer

Here are the examples of the java api class org.apache.activemq.artemis.api.core.ActiveMQBuffer taken from open source projects.

1. LargeMessageBufferTest#testReadData()

Project: activemq-artemis
File: LargeMessageBufferTest.java
@Test
public void testReadData() throws Exception {
    ActiveMQBuffer dynamic = ActiveMQBuffers.dynamicBuffer(1);
    String str1 = RandomUtil.randomString();
    String str2 = RandomUtil.randomString();
    double d1 = RandomUtil.randomDouble();
    float f1 = RandomUtil.randomFloat();
    dynamic.writeUTF(str1);
    dynamic.writeString(str2);
    dynamic.writeDouble(d1);
    dynamic.writeFloat(f1);
    LargeMessageControllerImpl readBuffer = splitBuffer(3, dynamic.toByteBuffer().array());
    Assert.assertEquals(str1, readBuffer.readUTF());
    Assert.assertEquals(str2, readBuffer.readString());
    Assert.assertEquals(d1, readBuffer.readDouble(), 0.000001);
    Assert.assertEquals(f1, readBuffer.readFloat(), 0.000001);
}

2. BroadcastGroupImpl#broadcastConnectors()

Project: activemq-artemis
File: BroadcastGroupImpl.java
@Override
public synchronized void broadcastConnectors() throws Exception {
    ActiveMQBuffer buff = ActiveMQBuffers.dynamicBuffer(4096);
    buff.writeString(nodeManager.getNodeId().toString());
    buff.writeString(uniqueID);
    buff.writeInt(connectors.size());
    for (TransportConfiguration tcConfig : connectors) {
        tcConfig.encode(buff);
    }
    // Only send as many bytes as we need.
    byte[] data = new byte[buff.readableBytes()];
    buff.getBytes(buff.readerIndex(), data);
    endpoint.broadcast(data);
}

3. PacketImpl#encode()

Project: activemq-artemis
File: PacketImpl.java
@Override
public ActiveMQBuffer encode(final RemotingConnection connection) {
    ActiveMQBuffer buffer = connection.createTransportBuffer(PacketImpl.INITIAL_PACKET_SIZE);
    // The standard header fields
    // The length gets filled in at the end
    buffer.writeInt(0);
    buffer.writeByte(type);
    buffer.writeLong(channelID);
    encodeRest(buffer);
    size = buffer.writerIndex();
    // The length doesn't include the actual length byte
    int len = size - DataConstants.SIZE_INT;
    buffer.setInt(0, len);
    return buffer;
}

4. DiscoveryStayAliveTest#sendBadData()

Project: activemq-artemis
File: DiscoveryStayAliveTest.java
private static void sendBadData(BroadcastEndpointFactory factoryEndpoint) throws Exception {
    BroadcastEndpoint endpoint = factoryEndpoint.createBroadcastEndpoint();
    ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(500);
    buffer.writeString("This is a test1!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    buffer.writeString("This is a test2!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    byte[] bytes = new byte[buffer.writerIndex()];
    buffer.readBytes(bytes);
    // messing up with the string!!!
    for (int i = bytes.length - 10; i < bytes.length; i++) {
        bytes[i] = 0;
    }
    endpoint.openBroadcaster();
    endpoint.broadcast(bytes);
    endpoint.close(true);
}

5. LargeMessageBufferTest#testGetBytesILChannelBufferII()

Project: activemq-artemis
File: LargeMessageBufferTest.java
// testing void getBytes(int index, ChannelBuffer dst, int dstIndex, int length)
@Test
public void testGetBytesILChannelBufferII() throws Exception {
    LargeMessageControllerImpl buffer = create15BytesSample();
    ActiveMQBuffer dstBuffer = ActiveMQBuffers.fixedBuffer(20);
    dstBuffer.setIndex(0, 5);
    buffer.getBytes(0, dstBuffer);
    byte[] compareBytes = new byte[15];
    dstBuffer.getBytes(5, compareBytes);
    validateAgainstSample(compareBytes);
}

6. JMSQueueControlImpl#sendTextMessage()

Project: activemq-artemis
File: JMSQueueControlImpl.java
@Override
public String sendTextMessage(Map<String, String> headers, String body, String user, String password) throws Exception {
    boolean durable = false;
    if (headers.containsKey("JMSDeliveryMode")) {
        String jmsDeliveryMode = headers.remove("JMSDeliveryMode");
        if (jmsDeliveryMode != null && (jmsDeliveryMode.equals("2") || jmsDeliveryMode.equalsIgnoreCase("PERSISTENT"))) {
            durable = true;
        }
    }
    String userID = UUIDGenerator.getInstance().generateStringUUID();
    ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(56);
    buffer.writeNullableSimpleString(new SimpleString(body));
    byte[] bytes = new byte[buffer.readableBytes()];
    buffer.readBytes(bytes);
    coreQueueControl.sendMessage(headers, Message.TEXT_TYPE, Base64.encodeBytes(bytes), userID, durable, user, password);
    return userID;
}

7. NettyConnectionTest#testCreateBuffer()

Project: activemq-artemis
File: NettyConnectionTest.java
@Test
public void testCreateBuffer() throws Exception {
    EmbeddedChannel channel = createChannel();
    NettyConnection conn = new NettyConnection(emptyMap, channel, new MyListener(), false, false);
    final int size = 1234;
    ActiveMQBuffer buff = conn.createTransportBuffer(size);
    // Netty buffer does lazy initialization.
    buff.writeByte((byte) 0x00);
    Assert.assertEquals(size, buff.capacity());
}

8. UTF8Test#testReadUTF()

Project: activemq-artemis
File: UTF8Test.java
@Test
public void testReadUTF() throws Exception {
    ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(10 * 1024);
    buffer.writeUTF(str);
    long start = System.currentTimeMillis();
    for (int c = 0; c < TIMES; c++) {
        for (long i = 0; i < numberOfIteractions; i++) {
            if (i == 10000) {
                start = System.currentTimeMillis();
            }
            buffer.resetReaderIndex();
            String newstr = buffer.readUTF();
            Assert.assertEquals(str, newstr);
        }
        long spentTime = System.currentTimeMillis() - start;
        System.out.println("Time readUTF = " + spentTime);
    }
}

9. TransportConfigurationEncodingSupportTest#testTransportConfiguration()

Project: activemq-artemis
File: TransportConfigurationEncodingSupportTest.java
// Constants -----------------------------------------------------
// Attributes ----------------------------------------------------
// Static --------------------------------------------------------
// Constructors --------------------------------------------------
// Public --------------------------------------------------------
@Test
public void testTransportConfiguration() throws Exception {
    Map<String, Object> params = new HashMap<>();
    params.put(TransportConstants.PORT_PROP_NAME, 5665);
    params.put(TransportConstants.HOST_PROP_NAME, RandomUtil.randomString());
    TransportConfiguration config = new TransportConfiguration(NettyConnectorFactory.class.getName(), params);
    ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(TransportConfigurationEncodingSupport.getEncodeSize(config));
    TransportConfigurationEncodingSupport.encode(buffer, config);
    assertEquals(buffer.capacity(), buffer.writerIndex());
    buffer.readerIndex(0);
    TransportConfiguration decoded = TransportConfigurationEncodingSupport.decode(buffer);
    assertNotNull(decoded);
    assertEquals(config.getName(), decoded.getName());
    assertEquals(config.getFactoryClassName(), decoded.getFactoryClassName());
    assertEquals(config.getParams().size(), decoded.getParams().size());
    for (String key : config.getParams().keySet()) {
        assertEquals(config.getParams().get(key).toString(), decoded.getParams().get(key).toString());
    }
}

10. UTF8Test#testValidateUTFOnDataInputStream()

Project: activemq-artemis
File: UTF8Test.java
private void testValidateUTFOnDataInputStream(final String str, final ActiveMQBuffer wrap) throws Exception {
    UTF8Util.saveUTF(wrap, str);
    DataInputStream data = new DataInputStream(new ByteArrayInputStream(wrap.toByteBuffer().array()));
    String newStr = data.readUTF();
    Assert.assertEquals(str, newStr);
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DataOutputStream outData = new DataOutputStream(byteOut);
    outData.writeUTF(str);
    ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(byteOut.toByteArray());
    newStr = UTF8Util.readUTF(buffer);
    Assert.assertEquals(str, newStr);
}

11. UTF8Test#testValidateUTF()

Project: activemq-artemis
File: UTF8Test.java
@Test
public void testValidateUTF() throws Exception {
    ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(60 * 1024);
    byte[] bytes = new byte[20000];
    Random random = new Random();
    random.getRandom().nextBytes(bytes);
    String str = new String(bytes);
    UTF8Util.saveUTF(buffer, str);
    String newStr = UTF8Util.readUTF(buffer);
    Assert.assertEquals(str, newStr);
}

12. NettyConnectionTest#testWrite()

Project: activemq-artemis
File: NettyConnectionTest.java
@Test
public void testWrite() throws Exception {
    ActiveMQBuffer buff = ActiveMQBuffers.wrappedBuffer(ByteBuffer.allocate(128));
    EmbeddedChannel channel = createChannel();
    Assert.assertEquals(0, channel.outboundMessages().size());
    NettyConnection conn = new NettyConnection(emptyMap, channel, new MyListener(), false, false);
    conn.write(buff);
    channel.runPendingTasks();
    Assert.assertEquals(1, channel.outboundMessages().size());
}

13. UTF8Test#testWriteUTF()

Project: activemq-artemis
File: UTF8Test.java
@Test
public void testWriteUTF() throws Exception {
    ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(10 * 1024);
    long start = System.currentTimeMillis();
    for (int c = 0; c < TIMES; c++) {
        for (long i = 0; i < numberOfIteractions; i++) {
            if (i == 10000) {
                start = System.currentTimeMillis();
            }
            buffer.clear();
            buffer.writeUTF(str);
        }
        long spentTime = System.currentTimeMillis() - start;
        System.out.println("Time WriteUTF = " + spentTime);
    }
}

14. JDBCSequentialFileFactoryTest#testCloneFile()

Project: activemq-artemis
File: JDBCSequentialFileFactoryTest.java
@Test
public void testCloneFile() throws Exception {
    JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
    file.open();
    // Create buffer and fill with test data
    int bufferSize = 1024;
    ActiveMQBuffer src = ActiveMQBuffers.fixedBuffer(bufferSize);
    for (int i = 0; i < bufferSize; i++) {
        src.writeByte((byte) 5);
    }
    IOCallbackCountdown callback = new IOCallbackCountdown(1);
    file.internalWrite(src, callback);
    assertEquals(bufferSize, file.size());
    JDBCSequentialFile copy = (JDBCSequentialFile) file.cloneFile();
    copy.open();
    assertEquals(bufferSize, copy.size());
    assertEquals(bufferSize, file.size());
}

15. JDBCSequentialFileFactoryTest#testCopyFile()

Project: activemq-artemis
File: JDBCSequentialFileFactoryTest.java
@Test
public void testCopyFile() throws Exception {
    JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
    file.open();
    // Create buffer and fill with test data
    int bufferSize = 1024;
    ActiveMQBuffer src = ActiveMQBuffers.fixedBuffer(bufferSize);
    for (int i = 0; i < bufferSize; i++) {
        src.writeByte((byte) 5);
    }
    IOCallbackCountdown callback = new IOCallbackCountdown(1);
    file.internalWrite(src, callback);
    JDBCSequentialFile copy = (JDBCSequentialFile) factory.createSequentialFile("copy.txt");
    file.copyTo(copy);
    checkData(file, src);
    checkData(copy, src);
}

16. JDBCSequentialFileFactoryTest#testAsyncAppendToFile()

Project: activemq-artemis
File: JDBCSequentialFileFactoryTest.java
@Test
public void testAsyncAppendToFile() throws Exception {
    JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
    file.open();
    // Create buffer and fill with test data
    int bufferSize = 1024;
    ActiveMQBuffer src = ActiveMQBuffers.fixedBuffer(bufferSize);
    for (int i = 0; i < bufferSize; i++) {
        src.writeByte((byte) 1);
    }
    IOCallbackCountdown callback = new IOCallbackCountdown(1);
    file.internalWrite(src, callback);
    callback.assertEmpty(5);
    checkData(file, src);
}

17. TypedPropertiesTest#testEncodeDecodeEmpty()

Project: activemq-artemis
File: TypedPropertiesTest.java
@Test
public void testEncodeDecodeEmpty() throws Exception {
    TypedProperties emptyProps = new TypedProperties();
    ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(1024);
    emptyProps.encode(buffer);
    Assert.assertEquals(props.getEncodeSize(), buffer.writerIndex());
    TypedProperties decodedProps = new TypedProperties();
    decodedProps.decode(buffer);
    TypedPropertiesTest.assertEqualsTypeProperties(emptyProps, decodedProps);
}

18. RandomUtil#randomBuffer()

Project: activemq-artemis
File: RandomUtil.java
public static ActiveMQBuffer randomBuffer(final int size, final long... data) {
    ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(size + 8 * data.length);
    for (long d : data) {
        buffer.writeLong(d);
    }
    for (int i = 0; i < size; i++) {
        buffer.writeByte(randomByte());
    }
    return buffer;
}

19. SessionReceiveMessage#encode()

Project: activemq-artemis
File: SessionReceiveMessage.java
@Override
public ActiveMQBuffer encode(final RemotingConnection connection) {
    ActiveMQBuffer buffer = message.getEncodedBuffer();
    ActiveMQBuffer bufferWrite = connection.createTransportBuffer(buffer.writerIndex());
    bufferWrite.writeBytes(buffer, 0, bufferWrite.capacity());
    bufferWrite.setIndex(buffer.readerIndex(), buffer.writerIndex());
    // Sanity check
    if (bufferWrite.writerIndex() != message.getEndOfMessagePosition()) {
        throw new IllegalStateException("Wrong encode position");
    }
    bufferWrite.writeLong(consumerID);
    bufferWrite.writeInt(deliveryCount);
    size = bufferWrite.writerIndex();
    // Write standard headers
    int len = size - DataConstants.SIZE_INT;
    bufferWrite.setInt(0, len);
    bufferWrite.setByte(DataConstants.SIZE_INT, getType());
    bufferWrite.setLong(DataConstants.SIZE_INT + DataConstants.SIZE_BYTE, channelID);
    // Position reader for reading by Netty
    bufferWrite.setIndex(0, size);
    return bufferWrite;
}

20. SessionSendMessage#encode()

Project: activemq-artemis
File: SessionSendMessage.java
@Override
public ActiveMQBuffer encode(final RemotingConnection connection) {
    ActiveMQBuffer buffer = message.getEncodedBuffer();
    ActiveMQBuffer bufferWrite;
    if (connection == null) {
        // this is for unit tests only
        bufferWrite = buffer.copy(0, buffer.capacity());
    } else {
        // 1 for the requireResponse
        bufferWrite = connection.createTransportBuffer(buffer.writerIndex() + 1);
    }
    bufferWrite.writeBytes(buffer, 0, buffer.writerIndex());
    bufferWrite.setIndex(buffer.readerIndex(), buffer.writerIndex());
    // Sanity check
    if (bufferWrite.writerIndex() != message.getEndOfMessagePosition()) {
        throw new IllegalStateException("Wrong encode position");
    }
    bufferWrite.writeBoolean(requiresResponse);
    size = bufferWrite.writerIndex();
    // Write standard headers
    int len = size - DataConstants.SIZE_INT;
    bufferWrite.setInt(0, len);
    bufferWrite.setByte(DataConstants.SIZE_INT, getType());
    bufferWrite.setLong(DataConstants.SIZE_INT + DataConstants.SIZE_BYTE, channelID);
    // Position reader for reading by Netty
    bufferWrite.readerIndex(0);
    return bufferWrite;
}

21. Page#write()

Project: activemq-artemis
File: Page.java
public synchronized void write(final PagedMessage message) throws Exception {
    if (!file.isOpen()) {
        return;
    }
    ByteBuffer buffer = fileFactory.newBuffer(message.getEncodeSize() + Page.SIZE_RECORD);
    ActiveMQBuffer wrap = ActiveMQBuffers.wrappedBuffer(buffer);
    wrap.clear();
    wrap.writeByte(Page.START_BYTE);
    wrap.writeInt(0);
    int startIndex = wrap.writerIndex();
    message.encode(wrap);
    int endIndex = wrap.writerIndex();
    // The encoded length
    wrap.setInt(1, endIndex - startIndex);
    wrap.writeByte(Page.END_BYTE);
    buffer.rewind();
    file.writeDirect(buffer, false);
    if (pageCache != null) {
        pageCache.addLiveMessage(message);
    }
    numberOfMessages.incrementAndGet();
    size.addAndGet(buffer.limit());
    storageManager.pageWrite(message, pageId);
}

22. LargeMessageBufferTest#testReadDataOverCached()

Project: activemq-artemis
File: LargeMessageBufferTest.java
@Test
public void testReadDataOverCached() throws Exception {
    clearDataRecreateServerDirs();
    ActiveMQBuffer dynamic = ActiveMQBuffers.dynamicBuffer(1);
    String str1 = RandomUtil.randomString();
    String str2 = RandomUtil.randomString();
    double d1 = RandomUtil.randomDouble();
    float f1 = RandomUtil.randomFloat();
    dynamic.writeUTF(str1);
    dynamic.writeString(str2);
    dynamic.writeDouble(d1);
    dynamic.writeFloat(f1);
    LargeMessageControllerImpl readBuffer = splitBuffer(3, dynamic.toByteBuffer().array(), getTestFile());
    Assert.assertEquals(str1, readBuffer.readUTF());
    Assert.assertEquals(str2, readBuffer.readString());
    Assert.assertEquals(d1, readBuffer.readDouble(), 0.00000001);
    Assert.assertEquals(f1, readBuffer.readFloat(), 0.000001);
    readBuffer.readerIndex(0);
    Assert.assertEquals(str1, readBuffer.readUTF());
    Assert.assertEquals(str2, readBuffer.readString());
    Assert.assertEquals(d1, readBuffer.readDouble(), 0.00000001);
    Assert.assertEquals(f1, readBuffer.readFloat(), 0.000001);
    readBuffer.close();
}

23. SimpleTransformer#transform()

Project: activemq-artemis
File: SimpleTransformer.java
@Override
public ServerMessage transform(final ServerMessage message) {
    SimpleString oldProp = (SimpleString) message.getObjectProperty(new SimpleString("wibble"));
    if (!oldProp.equals(new SimpleString("bing"))) {
        throw new IllegalStateException("Wrong property value!!");
    }
    // Change a property
    message.putStringProperty(new SimpleString("wibble"), new SimpleString("bong"));
    // Change the body
    ActiveMQBuffer buffer = message.getBodyBuffer();
    buffer.readerIndex(0);
    String str = buffer.readString();
    if (!str.equals("doo be doo be doo be doo")) {
        throw new IllegalStateException("Wrong body!!");
    }
    buffer.clear();
    buffer.writeString("dee be dee be dee be dee");
    return message;
}

24. SequentialFileFactoryTestBase#testWriteandRead()

Project: activemq-artemis
File: SequentialFileFactoryTestBase.java
@Test
public void testWriteandRead() throws Exception {
    SequentialFile sf = factory.createSequentialFile("write.amq");
    sf.open();
    String s1 = "aardvark";
    byte[] bytes1 = s1.getBytes(StandardCharsets.UTF_8);
    ActiveMQBuffer bb1 = wrapBuffer(bytes1);
    String s2 = "hippopotamus";
    byte[] bytes2 = s2.getBytes(StandardCharsets.UTF_8);
    ActiveMQBuffer bb2 = wrapBuffer(bytes2);
    String s3 = "echidna";
    byte[] bytes3 = s3.getBytes(StandardCharsets.UTF_8);
    ActiveMQBuffer bb3 = wrapBuffer(bytes3);
    long initialPos = sf.position();
    sf.write(bb1, true);
    long bytesWritten = sf.position() - initialPos;
    Assert.assertEquals(calculateRecordSize(bytes1.length, sf.getAlignment()), bytesWritten);
    initialPos = sf.position();
    sf.write(bb2, true);
    bytesWritten = sf.position() - initialPos;
    Assert.assertEquals(calculateRecordSize(bytes2.length, sf.getAlignment()), bytesWritten);
    initialPos = sf.position();
    sf.write(bb3, true);
    bytesWritten = sf.position() - initialPos;
    Assert.assertEquals(calculateRecordSize(bytes3.length, sf.getAlignment()), bytesWritten);
    sf.position(0);
    ByteBuffer rb1 = factory.newBuffer(bytes1.length);
    ByteBuffer rb2 = factory.newBuffer(bytes2.length);
    ByteBuffer rb3 = factory.newBuffer(bytes3.length);
    int bytesRead = sf.read(rb1);
    Assert.assertEquals(calculateRecordSize(bytes1.length, sf.getAlignment()), bytesRead);
    for (int i = 0; i < bytes1.length; i++) {
        Assert.assertEquals(bytes1[i], rb1.get(i));
    }
    bytesRead = sf.read(rb2);
    Assert.assertEquals(calculateRecordSize(bytes2.length, sf.getAlignment()), bytesRead);
    for (int i = 0; i < bytes2.length; i++) {
        Assert.assertEquals(bytes2[i], rb2.get(i));
    }
    bytesRead = sf.read(rb3);
    Assert.assertEquals(calculateRecordSize(bytes3.length, sf.getAlignment()), bytesRead);
    for (int i = 0; i < bytes3.length; i++) {
        Assert.assertEquals(bytes3[i], rb3.get(i));
    }
    sf.close();
}

25. TransportConfigurationEncodingSupportTest#testTransportConfigurations()

Project: activemq-artemis
File: TransportConfigurationEncodingSupportTest.java
@Test
public void testTransportConfigurations() throws Exception {
    List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs = new ArrayList<>();
    Map<String, Object> liveParams = new HashMap<>();
    liveParams.put(TransportConstants.PORT_PROP_NAME, 5665);
    TransportConfiguration live1 = new TransportConfiguration(NettyConnectorFactory.class.getName(), liveParams);
    Map<String, Object> backupParams = new HashMap<>();
    backupParams.put(TransportConstants.PORT_PROP_NAME, 5775);
    TransportConfiguration backup1 = new TransportConfiguration(NettyConnectorFactory.class.getName(), backupParams);
    Map<String, Object> liveParams2 = new HashMap<>();
    liveParams2.put(TransportConstants.PORT_PROP_NAME, 6665);
    TransportConfiguration live2 = new TransportConfiguration(NettyConnectorFactory.class.getName(), liveParams2);
    connectorConfigs.add(new Pair<>(live1, backup1));
    connectorConfigs.add(new Pair<TransportConfiguration, TransportConfiguration>(live2, null));
    ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(TransportConfigurationEncodingSupport.getEncodeSize(connectorConfigs));
    TransportConfigurationEncodingSupport.encodeConfigs(buffer, connectorConfigs);
    assertEquals(buffer.capacity(), buffer.writerIndex());
    buffer.readerIndex(0);
    List<Pair<TransportConfiguration, TransportConfiguration>> decodedConfigs = TransportConfigurationEncodingSupport.decodeConfigs(buffer);
    assertNotNull(decodedConfigs);
    assertEquals(2, decodedConfigs.size());
    assertEquivalent(connectorConfigs.get(0).getA(), decodedConfigs.get(0).getA());
    assertEquivalent(connectorConfigs.get(0).getB(), decodedConfigs.get(0).getB());
    assertEquivalent(connectorConfigs.get(1).getA(), decodedConfigs.get(1).getA());
    assertNull(decodedConfigs.get(1).getB());
}

26. InVMConnection#write()

Project: activemq-artemis
File: InVMConnection.java
@Override
public void write(final ActiveMQBuffer buffer, final boolean flush, final boolean batch, final ChannelFutureListener futureListener) {
    final ActiveMQBuffer copied = buffer.copy(0, buffer.capacity());
    copied.setIndex(buffer.readerIndex(), buffer.writerIndex());
    try {
        executor.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    if (!closed) {
                        // read and discard
                        copied.readInt();
                        if (logger.isTraceEnabled()) {
                            logger.trace(InVMConnection.this + "::Sending inVM packet");
                        }
                        handler.bufferReceived(id, copied);
                        if (futureListener != null) {
                            // TODO BEFORE MERGE: (is null a good option here?)
                            futureListener.operationComplete(null);
                        }
                    }
                } catch (Exception e) {
                    final String msg = "Failed to write to handler on connector " + this;
                    ActiveMQServerLogger.LOGGER.errorWritingToInvmConnector(e, this);
                    throw new IllegalStateException(msg, e);
                } finally {
                    if (logger.isTraceEnabled()) {
                        logger.trace(InVMConnection.this + "::packet sent done");
                    }
                }
            }
        });
        if (flush && flushEnabled) {
            final CountDownLatch latch = new CountDownLatch(1);
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    latch.countDown();
                }
            });
            try {
                if (!latch.await(10, TimeUnit.SECONDS)) {
                    ActiveMQServerLogger.LOGGER.timedOutFlushingInvmChannel();
                }
            } catch (InterruptedException e) {
                throw new ActiveMQInterruptedException(e);
            }
        }
    } catch (RejectedExecutionException e) {
    }
}

27. VersionedStompFrameHandler#createMessageFrame()

Project: activemq-artemis
File: VersionedStompFrameHandler.java
public StompFrame createMessageFrame(ServerMessage serverMessage, StompSubscription subscription, int deliveryCount) throws Exception {
    StompFrame frame = createStompFrame(Stomp.Responses.MESSAGE);
    if (subscription.getID() != null) {
        frame.addHeader(Stomp.Headers.Message.SUBSCRIPTION, subscription.getID());
    }
    ActiveMQBuffer buffer = serverMessage.getBodyBufferDuplicate();
    int bodyPos = serverMessage.getEndOfBodyPosition() == -1 ? buffer.writerIndex() : serverMessage.getEndOfBodyPosition();
    buffer.readerIndex(MessageImpl.BUFFER_HEADER_SPACE + DataConstants.SIZE_INT);
    int size = bodyPos - buffer.readerIndex();
    byte[] data = new byte[size];
    if (serverMessage.containsProperty(Stomp.Headers.CONTENT_LENGTH) || serverMessage.getType() == Message.BYTES_TYPE) {
        frame.addHeader(Headers.CONTENT_LENGTH, String.valueOf(data.length));
        buffer.readBytes(data);
    } else {
        SimpleString text = buffer.readNullableSimpleString();
        if (text != null) {
            data = text.toString().getBytes(StandardCharsets.UTF_8);
        } else {
            data = new byte[0];
        }
    }
    frame.setByteBody(data);
    StompUtils.copyStandardHeadersFromMessageToFrame(serverMessage, frame, deliveryCount);
    return frame;
}

28. OpenWireUtil#toActiveMQBuffer()

Project: activemq-artemis
File: OpenWireUtil.java
public static ActiveMQBuffer toActiveMQBuffer(ByteSequence bytes) {
    ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(bytes.length);
    buffer.writeBytes(bytes.data, bytes.offset, bytes.length);
    return buffer;
}

29. MessageImpl#getEncodedBuffer()

Project: activemq-artemis
File: MessageImpl.java
@Override
public synchronized ActiveMQBuffer getEncodedBuffer() {
    ActiveMQBuffer buff = encodeToBuffer();
    return buff.duplicate();
}

30. TypedPropertiesTest#testEncodeDecode()

Project: activemq-artemis
File: TypedPropertiesTest.java
@Test
public void testEncodeDecode() throws Exception {
    props.putByteProperty(RandomUtil.randomSimpleString(), RandomUtil.randomByte());
    props.putBytesProperty(RandomUtil.randomSimpleString(), RandomUtil.randomBytes());
    props.putBytesProperty(RandomUtil.randomSimpleString(), null);
    props.putBooleanProperty(RandomUtil.randomSimpleString(), RandomUtil.randomBoolean());
    props.putShortProperty(RandomUtil.randomSimpleString(), RandomUtil.randomShort());
    props.putIntProperty(RandomUtil.randomSimpleString(), RandomUtil.randomInt());
    props.putLongProperty(RandomUtil.randomSimpleString(), RandomUtil.randomLong());
    props.putFloatProperty(RandomUtil.randomSimpleString(), RandomUtil.randomFloat());
    props.putDoubleProperty(RandomUtil.randomSimpleString(), RandomUtil.randomDouble());
    props.putCharProperty(RandomUtil.randomSimpleString(), RandomUtil.randomChar());
    props.putSimpleStringProperty(RandomUtil.randomSimpleString(), RandomUtil.randomSimpleString());
    props.putSimpleStringProperty(RandomUtil.randomSimpleString(), null);
    SimpleString keyToRemove = RandomUtil.randomSimpleString();
    props.putSimpleStringProperty(keyToRemove, RandomUtil.randomSimpleString());
    ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(1024);
    props.encode(buffer);
    Assert.assertEquals(props.getEncodeSize(), buffer.writerIndex());
    TypedProperties decodedProps = new TypedProperties();
    decodedProps.decode(buffer);
    TypedPropertiesTest.assertEqualsTypeProperties(props, decodedProps);
    buffer.clear();
    // After removing a property, you should still be able to encode the Property
    props.removeProperty(keyToRemove);
    props.encode(buffer);
    Assert.assertEquals(props.getEncodeSize(), buffer.writerIndex());
}

31. UTF8Test#testBigSize()

Project: activemq-artemis
File: UTF8Test.java
@Test
public void testBigSize() throws Exception {
    char[] chars = new char[0xffff + 1];
    for (int i = 0; i < chars.length; i++) {
        chars[i] = ' ';
    }
    String str = new String(chars);
    ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(0xffff + 4);
    try {
        UTF8Util.saveUTF(buffer, str);
        Assert.fail("String is too big, supposed to throw an exception");
    } catch (Exception ignored) {
    }
    Assert.assertEquals("A buffer was supposed to be untouched since the string was too big", 0, buffer.writerIndex());
    chars = new char[25000];
    for (int i = 0; i < chars.length; i++) {
        chars[i] = 0x810;
    }
    str = new String(chars);
    try {
        UTF8Util.saveUTF(buffer, str);
        Assert.fail("Encoded String is too big, supposed to throw an exception");
    } catch (Exception ignored) {
    }
    Assert.assertEquals("A buffer was supposed to be untouched since the string was too big", 0, buffer.writerIndex());
    // Testing a string right on the limit
    chars = new char[0xffff];
    for (int i = 0; i < chars.length; i++) {
        chars[i] = (char) (i % 100 + 1);
    }
    str = new String(chars);
    UTF8Util.saveUTF(buffer, str);
    Assert.assertEquals(0xffff + DataConstants.SIZE_SHORT, buffer.writerIndex());
    String newStr = UTF8Util.readUTF(buffer);
    Assert.assertEquals(str, newStr);
}

32. ActiveMQBufferInputStreamTest#testReadBytes()

Project: activemq-artemis
File: ActiveMQBufferInputStreamTest.java
@Test
public void testReadBytes() throws Exception {
    byte[] bytes = new byte[10 * 1024];
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = getSamplebyte(i);
    }
    ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(bytes);
    ActiveMQBufferInputStream is = new ActiveMQBufferInputStream(buffer);
    // First read byte per byte
    for (int i = 0; i < 1024; i++) {
        assertEquals(getSamplebyte(i), is.read());
    }
    // Second, read in chunks
    for (int i = 1; i < 10; i++) {
        bytes = new byte[1024];
        is.read(bytes);
        for (int j = 0; j < bytes.length; j++) {
            assertEquals(getSamplebyte(i * 1024 + j), bytes[j]);
        }
    }
    assertEquals(-1, is.read());
    bytes = new byte[1024];
    int sizeRead = is.read(bytes);
    assertEquals(-1, sizeRead);
    is.close();
}

33. PagingStoreImplTest#testStore()

Project: activemq-artemis
File: PagingStoreImplTest.java
@Test
public void testStore() throws Exception {
    SequentialFileFactory factory = new FakeSequentialFileFactory();
    PagingStoreFactory storeFactory = new FakeStoreFactory(factory);
    AddressSettings addressSettings = new AddressSettings().setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE);
    PagingStore storeImpl = new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), createStorageManagerMock(), factory, storeFactory, PagingStoreImplTest.destinationTestName, addressSettings, getExecutorFactory().getExecutor(), true);
    storeImpl.start();
    Assert.assertEquals(0, storeImpl.getNumberOfPages());
    storeImpl.startPaging();
    Assert.assertEquals(1, storeImpl.getNumberOfPages());
    List<ActiveMQBuffer> buffers = new ArrayList<>();
    ActiveMQBuffer buffer = createRandomBuffer(0, 10);
    buffers.add(buffer);
    SimpleString destination = new SimpleString("test");
    ServerMessage msg = createMessage(1, storeImpl, destination, buffer);
    Assert.assertTrue(storeImpl.isPaging());
    final RoutingContextImpl ctx = new RoutingContextImpl(null);
    Assert.assertTrue(storeImpl.page(msg, ctx.getTransaction(), ctx.getContextListing(storeImpl.getStoreName()), lock));
    Assert.assertEquals(1, storeImpl.getNumberOfPages());
    storeImpl.sync();
    storeImpl = new PagingStoreImpl(PagingStoreImplTest.destinationTestName, null, 100, createMockManager(), createStorageManagerMock(), factory, storeFactory, PagingStoreImplTest.destinationTestName, addressSettings, getExecutorFactory().getExecutor(), true);
    storeImpl.start();
    Assert.assertEquals(1, storeImpl.getNumberOfPages());
}

34. PagingStoreImplTest#testAddAndRemoveMessages()

Project: activemq-artemis
File: PagingStoreImplTest.java
@Test
public void testAddAndRemoveMessages() {
    long id1 = RandomUtil.randomLong();
    long id2 = RandomUtil.randomLong();
    PageTransactionInfo trans = new PageTransactionInfoImpl(id2);
    trans.setRecordID(id1);
    // anything between 2 and 100
    int nr1 = RandomUtil.randomPositiveInt() % 98 + 2;
    for (int i = 0; i < nr1; i++) {
        trans.increment(1, 0);
    }
    Assert.assertEquals(nr1, trans.getNumberOfMessages());
    ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(trans.getEncodeSize());
    trans.encode(buffer);
    PageTransactionInfo trans2 = new PageTransactionInfoImpl(id1);
    trans2.decode(buffer);
    Assert.assertEquals(id2, trans2.getTransactionID());
    Assert.assertEquals(nr1, trans2.getNumberOfMessages());
}

35. LargeMessageBufferTest#testReadBytesOnStreaming()

Project: activemq-artemis
File: LargeMessageBufferTest.java
@Test
public void testReadBytesOnStreaming() throws Exception {
    byte[] byteArray = new byte[1024];
    for (int i = 0; i < byteArray.length; i++) {
        byteArray[i] = getSamplebyte(i);
    }
    ActiveMQBuffer splitbuffer = splitBuffer(3, byteArray);
    ActiveMQBufferInputStream is = new ActiveMQBufferInputStream(splitbuffer);
    for (int i = 0; i < 100; i++) {
        assertEquals(getSamplebyte(i), (byte) is.read());
    }
    for (int i = 100; i < byteArray.length; i += 10) {
        byte[] readBytes = new byte[10];
        int size = is.read(readBytes);
        for (int j = 0; j < size; j++) {
            assertEquals(getSamplebyte(i + j), readBytes[j]);
        }
    }
    is.close();
}

36. ReplicationTest#testSendPackets()

Project: activemq-artemis
File: ReplicationTest.java
@Test
public void testSendPackets() throws Exception {
    setupServer(true);
    StorageManager storage = getStorage();
    manager = liveServer.getReplicationManager();
    waitForComponent(manager);
    Journal replicatedJournal = new ReplicatedJournal((byte) 1, new FakeJournal(), manager);
    replicatedJournal.appendPrepareRecord(1, new FakeData(), false);
    replicatedJournal.appendAddRecord(1, (byte) 1, new FakeData(), false);
    replicatedJournal.appendUpdateRecord(1, (byte) 2, new FakeData(), false);
    replicatedJournal.appendDeleteRecord(1, false);
    replicatedJournal.appendAddRecordTransactional(2, 2, (byte) 1, new FakeData());
    replicatedJournal.appendUpdateRecordTransactional(2, 2, (byte) 2, new FakeData());
    replicatedJournal.appendCommitRecord(2, false);
    replicatedJournal.appendDeleteRecordTransactional(3, 4, new FakeData());
    replicatedJournal.appendPrepareRecord(3, new FakeData(), false);
    replicatedJournal.appendRollbackRecord(3, false);
    blockOnReplication(storage, manager);
    Assert.assertTrue("Expecting no active tokens:" + manager.getActiveTokens(), manager.getActiveTokens().isEmpty());
    ServerMessage msg = new ServerMessageImpl(1, 1024);
    SimpleString dummy = new SimpleString("dummy");
    msg.setAddress(dummy);
    replicatedJournal.appendAddRecordTransactional(23, 24, (byte) 1, new FakeData());
    PagedMessage pgmsg = new PagedMessageImpl(msg, new long[0]);
    manager.pageWrite(pgmsg, 1);
    manager.pageWrite(pgmsg, 2);
    manager.pageWrite(pgmsg, 3);
    manager.pageWrite(pgmsg, 4);
    blockOnReplication(storage, manager);
    PagingManager pagingManager = createPageManager(backupServer.getStorageManager(), backupServer.getConfiguration(), backupServer.getExecutorFactory(), backupServer.getAddressSettingsRepository());
    PagingStore store = pagingManager.getPageStore(dummy);
    store.start();
    Assert.assertEquals(4, store.getNumberOfPages());
    store.stop();
    manager.pageDeleted(dummy, 1);
    manager.pageDeleted(dummy, 2);
    manager.pageDeleted(dummy, 3);
    manager.pageDeleted(dummy, 4);
    manager.pageDeleted(dummy, 5);
    manager.pageDeleted(dummy, 6);
    blockOnReplication(storage, manager);
    ServerMessageImpl serverMsg = new ServerMessageImpl();
    serverMsg.setMessageID(500);
    serverMsg.setAddress(new SimpleString("tttt"));
    ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(100);
    serverMsg.encodeHeadersAndProperties(buffer);
    manager.largeMessageBegin(500);
    manager.largeMessageWrite(500, new byte[1024]);
    manager.largeMessageDelete(Long.valueOf(500));
    blockOnReplication(storage, manager);
    store.start();
    Assert.assertEquals(0, store.getNumberOfPages());
}

37. JMSConnectionFactoryConfigurationStorageTest#testSizeOfCF()

Project: activemq-artemis
File: JMSConnectionFactoryConfigurationStorageTest.java
@Test
public void testSizeOfCF() throws Exception {
    String[] str = new String[5];
    for (int i = 0; i < 5; i++) {
        str[i] = "str" + i;
    }
    ConnectionFactoryConfiguration config = new ConnectionFactoryConfigurationImpl().setName("some-name").setConnectorNames(new ArrayList<String>()).setBindings("");
    int size = config.getEncodeSize();
    ActiveMQBuffer buffer = ActiveMQBuffers.fixedBuffer(size);
    config.encode(buffer);
    assertEquals(size, buffer.writerIndex());
    PersistedConnectionFactory persistedCF = new PersistedConnectionFactory(config);
    size = persistedCF.getEncodeSize();
    buffer = ActiveMQBuffers.fixedBuffer(size);
    persistedCF.encode(buffer);
    assertEquals(size, buffer.writerIndex());
}

38. LargeMessageTestBase#createLargeBuffer()

Project: activemq-artemis
File: LargeMessageTestBase.java
protected ActiveMQBuffer createLargeBuffer(final int numberOfIntegers) {
    ActiveMQBuffer body = ActiveMQBuffers.fixedBuffer(DataConstants.SIZE_INT * numberOfIntegers);
    for (int i = 0; i < numberOfIntegers; i++) {
        body.writeInt(i);
    }
    return body;
}

39. FailoverTestBase#assertLargeMessageBody()

Project: activemq-artemis
File: FailoverTestBase.java
/**
    * Large message version of {@link #assertMessageBody(int, ClientMessage)}.
    *
    * @param i
    * @param message
    */
protected static void assertLargeMessageBody(final int i, final ClientMessage message) {
    ActiveMQBuffer buffer = message.getBodyBuffer();
    for (int j = 0; j < LARGE_MESSAGE_SIZE; j++) {
        Assert.assertTrue("msg " + i + ", expecting " + LARGE_MESSAGE_SIZE + " bytes, got " + j, buffer.readable());
        Assert.assertEquals("equal at " + j, ActiveMQTestBase.getSamplebyte(j), buffer.readByte());
    }
}

40. BackupSyncLargeMessageTest#testBackupStartsWhenLiveIsReceivingLargeMessage()

Project: activemq-artemis
File: BackupSyncLargeMessageTest.java
/**
    * LargeMessages are passed from the client to the server in chunks. Here we test the backup
    * starting the data synchronization with the live in the middle of a multiple chunks large
    * message upload from the client to the live server.
    *
    * @throws Exception
    */
@Test
public void testBackupStartsWhenLiveIsReceivingLargeMessage() throws Exception {
    final ClientSession session = addClientSession(sessionFactory.createSession(true, true));
    session.createQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null, true);
    final ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS);
    final ClientMessage message = session.createMessage(true);
    final int largeMessageSize = 1000 * MIN_LARGE_MESSAGE;
    message.setBodyInputStream(ActiveMQTestBase.createFakeLargeStream(largeMessageSize));
    final AtomicBoolean caughtException = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    Runnable r = new Runnable() {

        @Override
        public void run() {
            try {
                latch.countDown();
                producer.send(message);
                sendMessages(session, producer, 20);
                session.commit();
            } catch (ActiveMQException e) {
                e.printStackTrace();
                caughtException.set(true);
            } finally {
                latch2.countDown();
            }
        }
    };
    Executors.defaultThreadFactory().newThread(r).start();
    waitForLatch(latch);
    startBackupFinishSyncing();
    ActiveMQTestBase.waitForLatch(latch2);
    crash(session);
    assertFalse("no exceptions while sending message", caughtException.get());
    session.start();
    ClientConsumer consumer = session.createConsumer(FailoverTestBase.ADDRESS);
    ClientMessage msg = consumer.receive(2000);
    ActiveMQBuffer buffer = msg.getBodyBuffer();
    for (int j = 0; j < largeMessageSize; j++) {
        Assert.assertTrue("large msg , expecting " + largeMessageSize + " bytes, got " + j, buffer.readable());
        Assert.assertEquals("equal at " + j, ActiveMQTestBase.getSamplebyte(j), buffer.readByte());
    }
    receiveMessages(consumer, 0, 20, true);
    assertNull("there should be no more messages!", consumer.receiveImmediate());
    consumer.close();
    session.commit();
}

41. OutgoingVertxEventHandler#extractMessageBody()

Project: activemq-artemis
File: OutgoingVertxEventHandler.java
private Object extractMessageBody(ServerMessage message, Integer type) throws Exception {
    Object vertxMsgBody = null;
    ActiveMQBuffer bodyBuffer = message.getBodyBuffer();
    switch(type) {
        case VertxConstants.TYPE_PING:
        case VertxConstants.TYPE_STRING:
            bodyBuffer.resetReaderIndex();
            vertxMsgBody = bodyBuffer.readString();
            break;
        case VertxConstants.TYPE_BUFFER:
            int len = bodyBuffer.readInt();
            byte[] bytes = new byte[len];
            bodyBuffer.readBytes(bytes);
            vertxMsgBody = new Buffer(bytes);
            break;
        case VertxConstants.TYPE_BOOLEAN:
            vertxMsgBody = bodyBuffer.readBoolean();
            break;
        case VertxConstants.TYPE_BYTEARRAY:
            int length = bodyBuffer.readInt();
            byte[] byteArray = new byte[length];
            bodyBuffer.readBytes(byteArray);
            vertxMsgBody = byteArray;
            break;
        case VertxConstants.TYPE_BYTE:
            vertxMsgBody = bodyBuffer.readByte();
            break;
        case VertxConstants.TYPE_CHARACTER:
            vertxMsgBody = bodyBuffer.readChar();
            break;
        case VertxConstants.TYPE_DOUBLE:
            vertxMsgBody = bodyBuffer.readDouble();
            break;
        case VertxConstants.TYPE_FLOAT:
            vertxMsgBody = bodyBuffer.readFloat();
            break;
        case VertxConstants.TYPE_INT:
            vertxMsgBody = bodyBuffer.readInt();
            break;
        case VertxConstants.TYPE_LONG:
            vertxMsgBody = bodyBuffer.readLong();
            break;
        case VertxConstants.TYPE_SHORT:
            vertxMsgBody = bodyBuffer.readShort();
            break;
        case VertxConstants.TYPE_JSON_OBJECT:
            vertxMsgBody = new JsonObject(bodyBuffer.readString());
            break;
        case VertxConstants.TYPE_JSON_ARRAY:
            vertxMsgBody = new JsonArray(bodyBuffer.readString());
            break;
        case VertxConstants.TYPE_REPLY_FAILURE:
            int failureType = bodyBuffer.readInt();
            int failureCode = bodyBuffer.readInt();
            String errMsg = bodyBuffer.readString();
            vertxMsgBody = new ReplyException(ReplyFailure.fromInt(failureType), failureCode, errMsg);
            break;
        case VertxConstants.TYPE_RAWBYTES:
            int size = bodyBuffer.readableBytes();
            byte[] rawBytes = new byte[size];
            bodyBuffer.readBytes(rawBytes);
            vertxMsgBody = rawBytes;
            break;
        default:
            ActiveMQVertxLogger.LOGGER.invalidVertxType(type);
            break;
    }
    return vertxMsgBody;
}

42. DescribeJournal#newObjectEncoding()

Project: activemq-artemis
File: DescribeJournal.java
public static Object newObjectEncoding(RecordInfo info, JournalStorageManager storageManager) {
    ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(info.data);
    long id = info.id;
    int rec = info.getUserRecordType();
    switch(rec) {
        case ADD_LARGE_MESSAGE_PENDING:
            {
                PendingLargeMessageEncoding lmEncoding = new PendingLargeMessageEncoding();
                lmEncoding.decode(buffer);
                return lmEncoding;
            }
        case ADD_LARGE_MESSAGE:
            {
                LargeServerMessage largeMessage = new LargeServerMessageImpl(storageManager);
                LargeMessageEncoding messageEncoding = new LargeMessageEncoding(largeMessage);
                messageEncoding.decode(buffer);
                return new MessageDescribe(largeMessage);
            }
        case ADD_MESSAGE:
            {
                ServerMessage message = new ServerMessageImpl(rec, 50);
                message.decode(buffer);
                return new MessageDescribe(message);
            }
        case ADD_REF:
            {
                final RefEncoding encoding = new RefEncoding();
                encoding.decode(buffer);
                return new ReferenceDescribe(encoding);
            }
        case ACKNOWLEDGE_REF:
            {
                final RefEncoding encoding = new RefEncoding();
                encoding.decode(buffer);
                return new AckDescribe(encoding);
            }
        case UPDATE_DELIVERY_COUNT:
            {
                DeliveryCountUpdateEncoding updateDeliveryCount = new DeliveryCountUpdateEncoding();
                updateDeliveryCount.decode(buffer);
                return updateDeliveryCount;
            }
        case PAGE_TRANSACTION:
            {
                if (info.isUpdate) {
                    PageUpdateTXEncoding pageUpdate = new PageUpdateTXEncoding();
                    pageUpdate.decode(buffer);
                    return pageUpdate;
                } else {
                    PageTransactionInfoImpl pageTransactionInfo = new PageTransactionInfoImpl();
                    pageTransactionInfo.decode(buffer);
                    pageTransactionInfo.setRecordID(info.id);
                    return pageTransactionInfo;
                }
            }
        case SET_SCHEDULED_DELIVERY_TIME:
            {
                ScheduledDeliveryEncoding encoding = new ScheduledDeliveryEncoding();
                encoding.decode(buffer);
                return encoding;
            }
        case DUPLICATE_ID:
            {
                DuplicateIDEncoding encoding = new DuplicateIDEncoding();
                encoding.decode(buffer);
                return encoding;
            }
        case HEURISTIC_COMPLETION:
            {
                HeuristicCompletionEncoding encoding = new HeuristicCompletionEncoding();
                encoding.decode(buffer);
                return encoding;
            }
        case ACKNOWLEDGE_CURSOR:
            {
                CursorAckRecordEncoding encoding = new CursorAckRecordEncoding();
                encoding.decode(buffer);
                return encoding;
            }
        case PAGE_CURSOR_COUNTER_VALUE:
            {
                PageCountRecord encoding = new PageCountRecord();
                encoding.decode(buffer);
                return encoding;
            }
        case PAGE_CURSOR_COMPLETE:
            {
                CursorAckRecordEncoding encoding = new PageCompleteCursorAckRecordEncoding();
                encoding.decode(buffer);
                return encoding;
            }
        case PAGE_CURSOR_COUNTER_INC:
            {
                PageCountRecordInc encoding = new PageCountRecordInc();
                encoding.decode(buffer);
                return encoding;
            }
        case PAGE_CURSOR_PENDING_COUNTER:
            {
                PageCountPendingImpl encoding = new PageCountPendingImpl();
                encoding.decode(buffer);
                encoding.setID(info.id);
                return encoding;
            }
        case QUEUE_BINDING_RECORD:
            return AbstractJournalStorageManager.newBindingEncoding(id, buffer);
        case ID_COUNTER_RECORD:
            EncodingSupport idReturn = new IDCounterEncoding();
            idReturn.decode(buffer);
            return idReturn;
        case JournalRecordIds.GROUP_RECORD:
            return AbstractJournalStorageManager.newGroupEncoding(id, buffer);
        case ADDRESS_SETTING_RECORD:
            return AbstractJournalStorageManager.newAddressEncoding(id, buffer);
        case SECURITY_RECORD:
            return AbstractJournalStorageManager.newSecurityRecord(id, buffer);
        default:
            return null;
    }
}

43. Page#read()

Project: activemq-artemis
File: Page.java
public synchronized List<PagedMessage> read(StorageManager storage) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("reading page " + this.pageId + " on address = " + storeName);
    }
    if (!file.isOpen()) {
        throw ActiveMQMessageBundle.BUNDLE.invalidPageIO();
    }
    ArrayList<PagedMessage> messages = new ArrayList<>();
    size.set((int) file.size());
    // Using direct buffer, as described on https://jira.jboss.org/browse/HORNETQ-467
    ByteBuffer directBuffer = storage.allocateDirectBuffer((int) file.size());
    ActiveMQBuffer fileBuffer = null;
    try {
        file.position(0);
        file.read(directBuffer);
        directBuffer.rewind();
        fileBuffer = ActiveMQBuffers.wrappedBuffer(directBuffer);
        fileBuffer.writerIndex(fileBuffer.capacity());
        while (fileBuffer.readable()) {
            final int position = fileBuffer.readerIndex();
            byte byteRead = fileBuffer.readByte();
            if (byteRead == Page.START_BYTE) {
                if (fileBuffer.readerIndex() + DataConstants.SIZE_INT < fileBuffer.capacity()) {
                    int messageSize = fileBuffer.readInt();
                    int oldPos = fileBuffer.readerIndex();
                    if (fileBuffer.readerIndex() + messageSize < fileBuffer.capacity() && fileBuffer.getByte(oldPos + messageSize) == Page.END_BYTE) {
                        PagedMessage msg = new PagedMessageImpl();
                        msg.decode(fileBuffer);
                        byte b = fileBuffer.readByte();
                        if (b != Page.END_BYTE) {
                            // constraint was already checked
                            throw new IllegalStateException("Internal error, it wasn't possible to locate END_BYTE " + b);
                        }
                        msg.initMessage(storage);
                        if (logger.isTraceEnabled()) {
                            logger.trace("Reading message " + msg + " on pageId=" + this.pageId + " for address=" + storeName);
                        }
                        messages.add(msg);
                    } else {
                        markFileAsSuspect(file.getFileName(), position, messages.size());
                        break;
                    }
                }
            } else {
                markFileAsSuspect(file.getFileName(), position, messages.size());
                break;
            }
        }
    } finally {
        if (fileBuffer != null) {
            fileBuffer.byteBuf().unwrap().release();
        }
        storage.freeDirectBuffer(directBuffer);
    }
    numberOfMessages.set(messages.size());
    return messages;
}

44. StompConnection#physicalSend()

Project: activemq-artemis
File: StompConnection.java
public void physicalSend(StompFrame frame) throws Exception {
    ActiveMQBuffer buffer = frame.toActiveMQBuffer();
    synchronized (sendLock) {
        getTransportConnection().write(buffer, false, false);
    }
    if (stompListener != null) {
        stompListener.replySent(frame);
    }
}

45. JournalImpl#initFileHeader()

Project: activemq-artemis
File: JournalImpl.java
/**
    * @param fileID
    * @param sequentialFile
    * @throws Exception
    */
public static int initFileHeader(final SequentialFileFactory fileFactory, final SequentialFile sequentialFile, final int userVersion, final long fileID) throws Exception {
    // We don't need to release buffers while writing.
    ByteBuffer bb = fileFactory.newBuffer(JournalImpl.SIZE_HEADER);
    ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(bb);
    try {
        JournalImpl.writeHeader(buffer, userVersion, fileID);
        bb.rewind();
        int bufferSize = bb.limit();
        sequentialFile.position(0);
        sequentialFile.writeDirect(bb, true);
        return bufferSize;
    } finally {
        // release it by first unwrap the unreleasable buffer and then release it.
        buffer.byteBuf().unwrap().release();
    }
}

46. ActiveMQMessage#doBeforeReceive()

Project: activemq-artemis
File: ActiveMQMessage.java
public void doBeforeReceive() throws ActiveMQException {
    message.checkCompletion();
    ActiveMQBuffer body = message.getBodyBuffer();
    if (body != null) {
        body.resetReaderIndex();
    }
}

47. JDBCJournalRecord#setTxData()

Project: activemq-artemis
File: JDBCJournalRecord.java
public void setTxData(EncodingSupport txData) {
    this.txDataSize = txData.getEncodeSize();
    ActiveMQBuffer encodedBuffer = ActiveMQBuffers.fixedBuffer(txDataSize);
    txData.encode(encodedBuffer);
    this.txData = new ActiveMQBufferInputStream(encodedBuffer);
}

48. JDBCJournalRecord#setRecord()

Project: activemq-artemis
File: JDBCJournalRecord.java
public void setRecord(EncodingSupport record) {
    this.variableSize = record.getEncodeSize();
    ActiveMQBuffer encodedBuffer = ActiveMQBuffers.fixedBuffer(variableSize);
    record.encode(encodedBuffer);
    this.record = new ActiveMQBufferInputStream(encodedBuffer);
}

49. JDBCSequentialFile#write()

Project: activemq-artemis
File: JDBCSequentialFile.java
@Override
public void write(EncodingSupport bytes, boolean sync, IOCallback callback) throws Exception {
    ActiveMQBuffer data = ActiveMQBuffers.fixedBuffer(bytes.getEncodeSize());
    bytes.encode(data);
    scheduleWrite(data, callback);
}

50. ChannelImpl#doWrite()

Project: activemq-artemis
File: ChannelImpl.java
private void doWrite(final Packet packet) {
    final ActiveMQBuffer buffer = packet.encode(connection);
    connection.getTransportConnection().write(buffer, false, false);
}

51. ActiveMQSessionContext#sendPacketWithoutLock()

Project: activemq-artemis
File: ActiveMQSessionContext.java
private void sendPacketWithoutLock(final Channel parameterChannel, final Packet packet) {
    packet.setChannelID(parameterChannel.getID());
    Connection conn = parameterChannel.getConnection().getTransportConnection();
    ActiveMQBuffer buffer = packet.encode(this.getCoreConnection());
    conn.write(buffer, false, false);
}

52. ClientSessionImpl#convert()

Project: activemq-artemis
File: ClientSessionImpl.java
/**
    * If you ever tried to debug XIDs you will know what this is about.
    * This will serialize and deserialize the XID to the same way it's going to be printed on server logs
    * or print-data.
    * <p>
    * This will convert to the same XID deserialized on the Server, hence we will be able to debug eventual stuff
    *
    * @param xid
    * @return
    */
public static Object convert(Xid xid) {
    ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(200);
    XidCodecSupport.encodeXid(xid, buffer);
    Object obj = XidCodecSupport.decodeXid(buffer);
    return "xid=" + obj + ",clientXID=" + xid;
}

53. ClientConsumerImpl#handleCompressedMessage()

Project: activemq-artemis
File: ClientConsumerImpl.java
/**
    * This method deals with messages arrived as regular message but its contents are compressed.
    * Such messages come from message senders who are configured to compress large messages, and
    * if some of the messages are compressed below the min-large-message-size limit, they are sent
    * as regular messages.
    * <br>
    * However when decompressing the message, we are not sure how large the message could be..
    * for that reason we fake a large message controller that will deal with the message as it was a large message
    * <br>
    * Say that you sent a 1G message full of spaces. That could be just bellow 100K compressed but you wouldn't have
    * enough memory to decompress it
    */
private void handleCompressedMessage(final ClientMessageInternal clMessage) throws Exception {
    ClientLargeMessageImpl largeMessage = new ClientLargeMessageImpl();
    largeMessage.retrieveExistingData(clMessage);
    File largeMessageCache = null;
    if (session.isCacheLargeMessageClient()) {
        largeMessageCache = File.createTempFile("tmp-large-message-" + largeMessage.getMessageID() + "-", ".tmp");
        largeMessageCache.deleteOnExit();
    }
    ClientSessionFactory sf = session.getSessionFactory();
    ServerLocator locator = sf.getServerLocator();
    long callTimeout = locator.getCallTimeout();
    currentLargeMessageController = new LargeMessageControllerImpl(this, largeMessage.getLargeMessageSize(), callTimeout, largeMessageCache);
    currentLargeMessageController.setLocal(true);
    //sets the packet
    ActiveMQBuffer qbuff = clMessage.getBodyBuffer();
    int bytesToRead = qbuff.writerIndex() - qbuff.readerIndex();
    final byte[] body = qbuff.readBytes(bytesToRead).toByteBuffer().array();
    largeMessage.setLargeMessageController(new CompressedLargeMessageControllerImpl(currentLargeMessageController));
    currentLargeMessageController.addPacket(body, body.length, false);
    handleRegularMessage(largeMessage);
}