Java Code Examples for org.apache.qpid.proton.amqp.Binary#getLength()

The following examples show how to use org.apache.qpid.proton.amqp.Binary#getLength() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractMessageSectionMatcher.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
/**
 * @param receivedBinary
 *      The received Binary value that should be validated.
 *
 * @return the number of bytes consumed from the provided Binary
 *
 * @throws RuntimeException if the provided Binary does not match expectation in some way
 */
public int verify(Binary receivedBinary) throws RuntimeException
{
    int length = receivedBinary.getLength();
    Data data = Data.Factory.create();
    long decoded = data.decode(receivedBinary.asByteBuffer());
    if(decoded > Integer.MAX_VALUE)
    {
        throw new IllegalStateException("Decoded more bytes than Binary supports holding");
    }

    if(decoded < length && !_expectTrailingBytes)
    {
        throw new IllegalArgumentException("Expected to consume all bytes, but trailing bytes remain: Got "
                                    + length + ", consumed "+ decoded);
    }

    DescribedType decodedDescribedType = data.getDescribedType();
    verifyReceivedDescribedType(decodedDescribedType);

    //Need to cast to int, but verified earlier that it is < Integer.MAX_VALUE
    return (int) decoded;
}
 
Example 2
Source File: BinaryType.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
public void fastWrite(EncoderImpl encoder, Binary binary)
{
    if (binary.getLength() <= 255)
    {
        // Reserve size of body + type encoding and single byte size
        encoder.getBuffer().ensureRemaining(2 + binary.getLength());
        encoder.writeRaw(EncodingCodes.VBIN8);
        encoder.writeRaw((byte) binary.getLength());
        encoder.writeRaw(binary.getArray(), binary.getArrayOffset(), binary.getLength());
    }
    else
    {
        // Reserve size of body + type encoding and four byte size
        encoder.getBuffer().ensureRemaining(5 + binary.getLength());
        encoder.writeRaw(EncodingCodes.VBIN32);
        encoder.writeRaw(binary.getLength());
        encoder.writeRaw(binary.getArray(), binary.getArrayOffset(), binary.getLength());
    }
}
 
Example 3
Source File: JMSMappingOutboundTransformerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertTextMessageContentNotStoredCreatesBodyUsingOriginalEncodingWithDataSection() throws Exception {
   String contentString = "myTextMessageContent";
   ServerJMSTextMessage outbound = createTextMessage(contentString);
   outbound.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_DATA);
   outbound.encode();

   AMQPMessage amqp = AMQPConverter.getInstance().fromCore(outbound.getInnerMessage(), null);

   assertNotNull(amqp.getBody());
   assertTrue(amqp.getBody() instanceof Data);
   assertTrue(((Data) amqp.getBody()).getValue() instanceof Binary);

   Binary data = ((Data) amqp.getBody()).getValue();
   String contents = new String(data.getArray(), data.getArrayOffset(), data.getLength(), StandardCharsets.UTF_8);
   assertEquals(contentString, contents);
}
 
Example 4
Source File: JMSMappingOutboundTransformerTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testConvertTextMessageCreatesBodyUsingOriginalEncodingWithDataSection() throws Exception {
   String contentString = "myTextMessageContent";
   ServerJMSTextMessage outbound = createTextMessage(contentString);
   outbound.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_DATA);
   outbound.encode();

   AMQPMessage amqp = AMQPConverter.getInstance().fromCore(outbound.getInnerMessage(), null);

   assertNotNull(amqp.getBody());
   assertTrue(amqp.getBody() instanceof Data);
   assertTrue(((Data) amqp.getBody()).getValue() instanceof Binary);

   Binary data = ((Data) amqp.getBody()).getValue();
   String contents = new String(data.getArray(), data.getArrayOffset(), data.getLength(), StandardCharsets.UTF_8);
   assertEquals(contentString, contents);
}
 
Example 5
Source File: MessageImpl.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] getUserId()
{
    if(_properties == null || _properties.getUserId() == null)
    {
        return null;
    }
    else
    {
        final Binary userId = _properties.getUserId();
        byte[] id = new byte[userId.getLength()];
        System.arraycopy(userId.getArray(),userId.getArrayOffset(),id,0,userId.getLength());
        return id;
    }

}
 
Example 6
Source File: AMQPMessage.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Before we added AMQP into Artemis the name getUserID was already taken by JMSMessageID.
 * We cannot simply change the names now as it would break the API for existing clients.
 *
 * This is to return and read the proper AMQP userID.
 *
 * @return the UserID value in the AMQP Properties if one is present.
 */
public final Object getAMQPUserID() {
   if (properties != null && properties.getUserId() != null) {
      Binary binary = properties.getUserId();
      return new String(binary.getArray(), binary.getArrayOffset(), binary.getLength(), StandardCharsets.UTF_8);
   } else {
      return null;
   }
}
 
Example 7
Source File: EncodedAmqpTypeMatcher.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matchesSafely(Binary receivedBinary)
{
    int length = receivedBinary.getLength();
    Data data = Data.Factory.create();
    long decoded = data.decode(receivedBinary.asByteBuffer());
    _decodedDescribedType = data.getDescribedType();
    Object descriptor = _decodedDescribedType.getDescriptor();

    if(!(_descriptorCode.equals(descriptor) || _descriptorSymbol.equals(descriptor)))
    {
        return false;
    }

    if(_expectedValue == null && _decodedDescribedType.getDescribed() != null)
    {
        return false;
    }
    else if(_expectedValue != null && !_expectedValue.equals(_decodedDescribedType.getDescribed()))
    {
        return false;
    }

    if(decoded < length && !_permitTrailingBytes)
    {
        _unexpectedTrailingBytes = true;
        return false;
    }

    return true;
}
 
Example 8
Source File: ProducerIntegrationTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 20000)
public void testAsyncCompletionResetsBytesMessage() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        Connection connection = testFixture.establishConnecton(testPeer);
        testPeer.expectBegin();
        testPeer.expectSenderAttach();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue("myQueue");

        MessageProducer producer = session.createProducer(queue);

        // Create and transfer a new message
        testPeer.expectTransfer(new TransferPayloadCompositeMatcher());
        testPeer.expectClose();

        Binary payload = new Binary(new byte[] {1, 2, 3, 4});
        BytesMessage message = session.createBytesMessage();
        message.writeBytes(payload.getArray());

        TestJmsCompletionListener listener = new TestJmsCompletionListener();

        producer.send(message, listener);

        assertTrue("Did not get async callback", listener.awaitCompletion(5, TimeUnit.SECONDS));
        assertNull(listener.exception);
        assertNotNull(listener.message);
        assertTrue(listener.message instanceof BytesMessage);

        BytesMessage completed = (BytesMessage) listener.message;
        assertEquals(payload.getLength(), completed.getBodyLength());
        byte[] data = new byte[payload.getLength()];
        completed.readBytes(data);

        connection.close();

        testPeer.waitForAllHandlersToComplete(1000);
    }
}
 
Example 9
Source File: AmqpJmsBytesMessageFacade.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] copyBody() {
    Binary content = getBinaryFromBody();
    byte[] result = new byte[content.getLength()];

    System.arraycopy(content.getArray(), content.getArrayOffset(), result, 0, content.getLength());

    return result;
}
 
Example 10
Source File: FrameWithNoPayloadMatchingHandler.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
protected final void verifyPayload(Binary payload)
{
    _logger.debug("About to check that there is no payload");
    if(payload != null && payload.getLength() > 0)
    {
        throw new AssertionError("Expected no payload but received payload of length: " + payload.getLength());
    }
}
 
Example 11
Source File: AmqpJmsMessageFacade.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
public String getUserId() {
    String userId = null;

    if (properties != null && properties.getUserId() != null) {
        Binary userIdBytes = properties.getUserId();
        if (userIdBytes.getLength() != 0) {
            userId = new String(userIdBytes.getArray(), userIdBytes.getArrayOffset(), userIdBytes.getLength(), StandardCharsets.UTF_8);
        }
    }

    return userId;
}
 
Example 12
Source File: BinaryElement.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
BinaryElement(Element parent, Element prev, Binary b)
{
    super(parent, prev);
    byte[] data = new byte[b.getLength()];
    System.arraycopy(b.getArray(),b.getArrayOffset(),data,0,b.getLength());
    _value = new Binary(data);
}
 
Example 13
Source File: DeliveryImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
void append(Binary payload)
{
    byte[] data = payload.getArray();

    // The Composite buffer cannot handle composites where the array
    // is a view of a larger array so we must copy the payload into
    // an array of the exact size
    if (payload.getArrayOffset() > 0 || payload.getLength() < data.length)
    {
        data = new byte[payload.getLength()];
        System.arraycopy(payload.getArray(), payload.getArrayOffset(), data, 0, payload.getLength());
    }

    getOrCreateDataBuffer().append(data);
}
 
Example 14
Source File: AmqpLargeMessageTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 60000)
public void testMessageWithDataAndContentTypeOfTextPreservesBodyType() throws Exception {
   server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setDefaultAddressRoutingType(RoutingType.ANYCAST));

   AmqpClient client = createAmqpClient();
   AmqpConnection connection = addConnection(client.connect());
   try {
      AmqpSession session = connection.createSession();
      AmqpSender sender = session.createSender(getTestName());

      AmqpMessage message = createAmqpLargeMessageWithNoBody();

      String messageText = "This text will be in a Data Section";

      message.getWrappedMessage().setContentType("text/plain");
      message.getWrappedMessage().setBody(new Data(new Binary(messageText.getBytes(StandardCharsets.UTF_8))));
      //message.setApplicationProperty("_AMQ_DUPL_ID", "11");

      sender.send(message);
      sender.close();

      AmqpReceiver receiver = session.createReceiver(getTestName());
      receiver.flow(1);

      AmqpMessage received = receiver.receive(10, TimeUnit.SECONDS);
      assertNotNull("failed to read large AMQP message", received);
      MessageImpl wrapped = (MessageImpl) received.getWrappedMessage();

      assertTrue(wrapped.getBody() instanceof Data);
      Data body = (Data) wrapped.getBody();
      assertTrue(body.getValue() instanceof Binary);
      Binary payload = (Binary) body.getValue();
      String reconstitutedString = new String(
         payload.getArray(), payload.getArrayOffset(), payload.getLength(), StandardCharsets.UTF_8);

      assertEquals(messageText, reconstitutedString);

      received.accept();
      session.close();
   } finally {
      connection.close();
   }
}
 
Example 15
Source File: AmqpProtocolTracer.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private String formatPayload(TransportFrame frame) {
    Binary payload = frame.getPayload();

    if (payload == null || payload.getLength() == 0 || payloadStringLimit <= 0) {
        return "";
    }

    final byte[] binData = payload.getArray();
    final int binLength = payload.getLength();
    final int offset = payload.getArrayOffset();

    StringBuilder builder = new StringBuilder();

    // Prefix the payload with total bytes which gives insight regardless of truncation.
    builder.append(" (").append(payload.getLength()).append(") ").append("\"");

    int size = 0;
    boolean truncated = false;
    for (int i = 0; i < binLength; i++) {
        byte c = binData[offset + i];

        if (c > 31 && c < 127 && c != '\\') {
            if (size + 1 <= payloadStringLimit) {
                size += 1;
                builder.append((char) c);
            } else {
                truncated = true;
                break;
            }
        } else {
            if (size + 4 <= payloadStringLimit) {
                size += 4;
                builder.append(String.format("\\x%02x", c));
            } else {
                truncated = true;
                break;
            }
        }
    }

    builder.append("\"");

    if (truncated) {
        builder.append("...(truncated)");
    }

    return builder.toString();
}
 
Example 16
Source File: BinaryType.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
@Override
protected int getEncodedValueSize(final Binary val)
{
    return val.getLength();
}
 
Example 17
Source File: BinaryType.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
@Override
protected int getEncodedValueSize(final Binary val)
{
    return val.getLength();
}
 
Example 18
Source File: BinaryType.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
@Override
public BinaryEncoding getEncoding(final Binary val)
{
    return val.getLength() <= 255 ? _shortBinaryEncoding : _binaryEncoding;
}
 
Example 19
Source File: StringUtils.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
/**
 * Converts the Binary to a quoted string.
 *
 * @param bin the Binary to convert
 * @param stringLength the maximum length of stringified content (excluding the quotes, and truncated indicator)
 * @param appendIfTruncated appends "...(truncated)" if not all of the payload is present in the string
 * @return the converted string
 */
public static String toQuotedString(final Binary bin,final int stringLength,final boolean appendIfTruncated)
{
    if(bin == null)
    {
         return "\"\"";
    }

    final byte[] binData = bin.getArray();
    final int binLength = bin.getLength();
    final int offset = bin.getArrayOffset();

    StringBuilder str = new StringBuilder();
    str.append("\"");

    int size = 0;
    boolean truncated = false;
    for (int i = 0; i < binLength; i++)
    {
        byte c = binData[offset + i];

        if (c > 31 && c < 127 && c != '\\')
        {
            if (size + 1 <= stringLength)
            {
                size += 1;
                str.append((char) c);
            }
            else
            {
                truncated = true;
                break;
            }
        }
        else
        {
            if (size + 4 <= stringLength)
            {
                size += 4;
                str.append(String.format("\\x%02x", c));
            }
            else
            {
                truncated = true;
                break;
            }
        }
    }

    str.append("\"");

    if (truncated && appendIfTruncated)
    {
        str.append("...(truncated)");
    }

    return str.toString();
}
 
Example 20
Source File: AmqpSupport.java    From activemq-artemis with Apache License 2.0 2 votes vote down vote up
/**
 * Converts a Binary value to a long assuming that the contained value is
 * stored in Big Endian encoding.
 *
 * @param value the Binary object whose payload is converted to a long.
 * @return a long value constructed from the bytes of the Binary instance.
 */
public static long toLong(Binary value) {
   Buffer buffer = new Buffer(value.getArray(), value.getArrayOffset(), value.getLength());
   return buffer.bigEndianEditor().readLong();
}