Java Code Examples for org.apache.qpid.proton.message.Message#encode()

The following examples show how to use org.apache.qpid.proton.message.Message#encode() . 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: DeferredSettlementTest.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
private Delivery sendMessageToClient(String deliveryTag, int messageBody)
{
    byte[] tag = deliveryTag.getBytes(StandardCharsets.UTF_8);

    Message m = Proton.message();
    m.setBody(new AmqpValue(messageBody));

    byte[] encoded = new byte[BUFFER_SIZE];
    int len = m.encode(encoded, 0, BUFFER_SIZE);

    assertTrue("given array was too small", len < BUFFER_SIZE);

    Sender serverSender = getServer().getSender();
    Delivery serverDelivery = serverSender.delivery(tag);
    int sent = serverSender.send(encoded, 0, len);

    assertEquals("sender unable to send all data at once as assumed for simplicity", len, sent);

    boolean senderAdvanced = serverSender.advance();
    assertTrue("sender has not advanced", senderAdvanced);

    return serverDelivery;
}
 
Example 2
Source File: TransportImplTest.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
private void handleTransfer(TransportImpl transport, int deliveryNumber, String deliveryTag, String messageContent)
{
    byte[] tag = deliveryTag.getBytes(StandardCharsets.UTF_8);

    Message m = Message.Factory.create();
    m.setBody(new AmqpValue(messageContent));

    byte[] encoded = new byte[BUFFER_SIZE];
    int len = m.encode(encoded, 0, BUFFER_SIZE);

    assertTrue("given array was too small", len < BUFFER_SIZE);

    Transfer transfer = new Transfer();
    transfer.setDeliveryId(UnsignedInteger.valueOf(deliveryNumber));
    transfer.setHandle(UnsignedInteger.ZERO);
    transfer.setDeliveryTag(new Binary(tag));
    transfer.setMessageFormat(UnsignedInteger.valueOf(DeliveryImpl.DEFAULT_MESSAGE_FORMAT));

    transport.handleFrame(new TransportFrame(0, transfer, new Binary(encoded, 0, len)));
}
 
Example 3
Source File: TransportImplTest.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
private ArrayList<byte[]> createTransferPayloads(String content, int payloadChunkSize)
{
    ArrayList<byte[]> payloadChunks = new ArrayList<>();

    Message m = Message.Factory.create();
    m.setBody(new AmqpValue(content));

    byte[] encoded = new byte[BUFFER_SIZE];
    int len = m.encode(encoded, 0, BUFFER_SIZE);
    assertTrue("given array was too small", len < BUFFER_SIZE);

    int copied = 0;
    while(copied < len) {
        int chunkSize = Math.min(len - copied, payloadChunkSize);
        byte[] chunk = new byte[chunkSize];

        System.arraycopy(encoded, copied, chunk, 0, chunkSize);

        payloadChunks.add(chunk);
        copied += chunkSize;
    }

    assertFalse("no payload chunks to return", payloadChunks.isEmpty());

    return payloadChunks;
}
 
Example 4
Source File: AmqpTransactionCoordinator.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void sendTxCommand(Message message) throws IOException {
   int encodedSize = 0;
   byte[] buffer = OUTBOUND_BUFFER;
   while (true) {
      try {
         encodedSize = message.encode(buffer, 0, buffer.length);
         break;
      } catch (BufferOverflowException e) {
         buffer = new byte[buffer.length * 2];
      }
   }

   Sender sender = getEndpoint();
   sender.send(buffer, 0, encodedSize);
   sender.advance();
}
 
Example 5
Source File: AmqpSender.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void encodeAndSend(Message message, Delivery delivery) throws IOException {

      int encodedSize;
      while (true) {
         try {
            encodedSize = message.encode(encodeBuffer, 0, encodeBuffer.length);
            break;
         } catch (java.nio.BufferOverflowException e) {
            encodeBuffer = new byte[encodeBuffer.length * 2];
         }
      }

      int sentSoFar = 0;

      while (true) {
         int sent = getEndpoint().send(encodeBuffer, sentSoFar, encodedSize - sentSoFar);
         if (sent > 0) {
            sentSoFar += sent;
            if ((encodedSize - sentSoFar) == 0) {
               break;
            }
         } else {
            LOG.warn("{} failed to send any data from current Message.", this);
         }
      }
   }
 
Example 6
Source File: AmqpMessageSupport.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
/**
 * Given a Message instance, encode the Message to the wire level representation
 * of that Message.
 *
 * @param message
 *      the Message that is to be encoded into the wire level representation.
 *
 * @return a buffer containing the wire level representation of the input Message.
 */
public static ReadableBuffer encodeMessage(Message message) {
    final int BUFFER_SIZE = 4096;
    byte[] encodedMessage = new byte[BUFFER_SIZE];
    int encodedSize = 0;
    while (true) {
        try {
            encodedSize = message.encode(encodedMessage, 0, encodedMessage.length);
            break;
        } catch (java.nio.BufferOverflowException e) {
            encodedMessage = new byte[encodedMessage.length * 2];
        }
    }

    return ReadableBuffer.ByteBufferReader.wrap(ByteBuffer.wrap(encodedMessage, 0, encodedSize));
}
 
Example 7
Source File: AmqpTransactionCoordinator.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private void sendTxCommand(Message message) throws ProviderException {
    int encodedSize = 0;
    byte[] buffer = OUTBOUND_BUFFER;
    while (true) {
        try {
            encodedSize = message.encode(buffer, 0, buffer.length);
            break;
        } catch (BufferOverflowException e) {
            buffer = new byte[buffer.length * 2];
        }
    }

    Sender sender = getEndpoint();
    sender.send(buffer, 0, encodedSize);
    sender.advance();
}
 
Example 8
Source File: MessageAnnotationsInjectExtractAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the same entries injected via the {@code MessageAnnotationsInjectAdapter} are extracted via the
 * {@code MessageAnnotationsExtractAdapter}.
 * Also verifies that there are no errors during encoding/decoding of the message with the injected entries.
 */
@Test
public void testInjectAndExtract() {
    final Map<String, String> testEntries = new HashMap<>();
    testEntries.put("key1", "value1");
    testEntries.put("key2", "value2");

    final Message message = ProtonHelper.message();
    // inject the properties
    final MessageAnnotationsInjectAdapter injectAdapter = new MessageAnnotationsInjectAdapter(message, propertiesMapName);
    testEntries.forEach((key, value) -> {
        injectAdapter.put(key, value);
    });

    // encode the message
    final WritableBuffer.ByteBufferWrapper buffer = WritableBuffer.ByteBufferWrapper.allocate(100);
    message.encode(buffer);

    // decode the message
    final Message decodedMessage = ProtonHelper.message();
    decodedMessage.decode(buffer.toReadableBuffer());
    // extract the properties from the decoded message
    final MessageAnnotationsExtractAdapter extractAdapter = new MessageAnnotationsExtractAdapter(decodedMessage, propertiesMapName);
    extractAdapter.iterator().forEachRemaining(extractedEntry -> {
        assertThat(extractedEntry.getValue()).isEqualTo(testEntries.get(extractedEntry.getKey()));
    });
}
 
Example 9
Source File: AmqpRawMessageConverter.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Override
public KafkaProducerRecord<String, byte[]> toKafkaRecord(String kafkaTopic, Integer partition, Message message) {

    Object partitionFromMessage = null, key = null;
    byte[] value;
    byte[] buffer = new byte[AmqpRawMessageConverter.BUFFER_SIZE];

    // get topic and body from AMQP message
    String topic = (message.getAddress() == null) ?
            kafkaTopic :
            message.getAddress().replace('/', '.');

    int encoded = message.encode(buffer, 0, AmqpRawMessageConverter.BUFFER_SIZE);
    value = Arrays.copyOfRange(buffer, 0, encoded);

    // get partition and key from AMQP message annotations
    // NOTE : they are not mandatory
    MessageAnnotations messageAnnotations = message.getMessageAnnotations();

    if (messageAnnotations != null) {

        partitionFromMessage = messageAnnotations.getValue().get(Symbol.getSymbol(AmqpBridge.AMQP_PARTITION_ANNOTATION));
        key = messageAnnotations.getValue().get(Symbol.getSymbol(AmqpBridge.AMQP_KEY_ANNOTATION));

        if (partitionFromMessage != null && !(partitionFromMessage instanceof Integer))
            throw new IllegalArgumentException("The partition annotation must be an Integer");

        if (key != null && !(key instanceof String))
            throw new IllegalArgumentException("The key annotation must be a String");
    }

    // build the record for the KafkaProducer and then send it
    KafkaProducerRecord<String, byte[]> record = KafkaProducerRecord.create(topic, (String) key, value, (Integer) partitionFromMessage);
    return record;
}
 
Example 10
Source File: AmqpMessageCoder.java    From beam with Apache License 2.0 5 votes vote down vote up
private void encode(Message value, OutputStream outStream, int messageSize)
    throws IOException, BufferOverflowException {
  byte[] data = new byte[messageSize];
  int bytesWritten = value.encode(data, 0, data.length);
  VarInt.encode(bytesWritten, outStream);
  outStream.write(data, 0, bytesWritten);
}
 
Example 11
Source File: MessageImplTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
void doMessageEncodingWithDataBodySectionTestImpl(int bytesLength)
{
    byte[] bytes = generateByteArray(bytesLength);

    byte[] expectedBytes = generateExpectedDataSectionBytes(bytes);
    byte[] encodedBytes = new byte[expectedBytes.length];

    Message msg = Message.Factory.create();
    msg.setBody(new Data(new Binary(bytes)));

    int encodedLength = msg.encode(encodedBytes, 0, encodedBytes.length);

    assertArrayEquals("Encoded bytes do not match expectation", expectedBytes, encodedBytes);
    assertEquals("Encoded length different than expected length", encodedLength, encodedBytes.length);
}
 
Example 12
Source File: MessageImplTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
void doMessageEncodingWithDataBodySectionTestImplUsingWritableBuffer(int bytesLength)
{
    byte[] bytes = generateByteArray(bytesLength);

    byte[] expectedBytes = generateExpectedDataSectionBytes(bytes);
    ByteBufferWrapper encodedBytes = WritableBuffer.ByteBufferWrapper.allocate(expectedBytes.length);

    Message msg = Message.Factory.create();
    msg.setBody(new Data(new Binary(bytes)));

    int encodedLength = msg.encode(encodedBytes);

    assertArrayEquals("Encoded bytes do not match expectation", expectedBytes, encodedBytes.byteBuffer().array());
    assertEquals("Encoded length different than expected length", encodedLength, encodedBytes.position());
}
 
Example 13
Source File: DeliveryTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private Delivery sendMessageToClient(String deliveryTag, String messageContent, Integer messageFormat)
{
    byte[] tag = deliveryTag.getBytes(StandardCharsets.UTF_8);

    Message m = Proton.message();
    m.setBody(new AmqpValue(messageContent));

    final int BUFFER_SIZE = messageContent.length() * 4;
    byte[] encoded = new byte[BUFFER_SIZE];
    int len = m.encode(encoded, 0, BUFFER_SIZE);

    assertTrue("given array was too small", len <= BUFFER_SIZE);

    Delivery serverDelivery = getServer().sender.delivery(tag);

    // Verify the default format of 0 is in place
    assertEquals("Unexpected message format", 0, serverDelivery.getMessageFormat());

    // Set the message format explicitly if given, or leave it at the default
    if(messageFormat != null) {
        serverDelivery.setMessageFormat(messageFormat);
    }

    int sent = getServer().sender.send(encoded, 0, len);

    assertEquals("sender unable to send all data at once as assumed for simplicity", len, sent);

    boolean senderAdvanced = getServer().sender.advance();
    assertTrue("sender has not advanced", senderAdvanced);

    return serverDelivery;
}
 
Example 14
Source File: TransportImplTest.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
private Delivery sendMessage(Sender sender, String deliveryTag, String messageContent)
{
    byte[] tag = deliveryTag.getBytes(StandardCharsets.UTF_8);

    Message m = Message.Factory.create();
    m.setBody(new AmqpValue(messageContent));

    byte[] encoded = new byte[BUFFER_SIZE];
    int len = m.encode(encoded, 0, BUFFER_SIZE);

    assertTrue("given array was too small", len < BUFFER_SIZE);

    Delivery delivery = sender.delivery(tag);

    int sent = sender.send(encoded, 0, len);

    assertEquals("sender unable to send all data at once as assumed for simplicity", len, sent);

    boolean senderAdvanced = sender.advance();
    assertTrue("sender has not advanced", senderAdvanced);

    return delivery;
}
 
Example 15
Source File: LinkTest.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
private Delivery sendMessageToClient(String deliveryTag, String messageContent)
{
    byte[] tag = deliveryTag.getBytes(StandardCharsets.UTF_8);

    Message m = Proton.message();
    m.setBody(new AmqpValue(messageContent));

    byte[] encoded = new byte[BUFFER_SIZE];
    int len = m.encode(encoded, 0, BUFFER_SIZE);

    assertTrue("given array was too small", len < BUFFER_SIZE);

    Delivery serverDelivery = getServer().sender.delivery(tag);

    int sent = getServer().sender.send(encoded, 0, len);

    assertEquals("sender unable to send all data at once as assumed for simplicity", len, sent);

    boolean senderAdvanced = getServer().sender.advance();
    assertTrue("sender has not advanced", senderAdvanced);

    return serverDelivery;
}
 
Example 16
Source File: DefaultDeliveryStateTest.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
private Delivery sendMessageToClient(String deliveryTag, String messageBody)
{
    byte[] tag = deliveryTag.getBytes(StandardCharsets.UTF_8);

    Message m = Proton.message();
    m.setBody(new AmqpValue(messageBody));

    byte[] encoded = new byte[BUFFER_SIZE];
    int len = m.encode(encoded, 0, BUFFER_SIZE);

    assertTrue("given array was too small", len < BUFFER_SIZE);

    Delivery serverDelivery = getServer().sender.delivery(tag);
    int sent = getServer().sender.send(encoded, 0, len);

    assertEquals("sender unable to send all data at once as assumed for simplicity", len, sent);

    boolean senderAdvanced = getServer().sender.advance();
    assertTrue("sender has not advanced", senderAdvanced);

    return serverDelivery;
}