org.apache.qpid.proton.amqp.messaging.ApplicationProperties Java Examples

The following examples show how to use org.apache.qpid.proton.amqp.messaging.ApplicationProperties. 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: ProtonRequestClient.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public Message request(Message message, long timeout, TimeUnit timeUnit) {
    Map<String, Object> properties = new HashMap<>();
    if (message.getApplicationProperties() != null) {
        properties.putAll(message.getApplicationProperties().getValue());
    }
    message.setApplicationProperties(new ApplicationProperties(properties));

    if (message.getReplyTo() == null) {
        message.setReplyTo(replyTo);
    }
    context.runOnContext(h -> sender.send(message));
    try {
        return replies.poll(timeout, timeUnit);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: TenantClientImpl.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected final TenantResult<TenantObject> getResult(
        final int status,
        final String contentType,
        final Buffer payload,
        final CacheDirective cacheDirective,
        final ApplicationProperties applicationProperties) {

    if (isSuccessResponse(status, contentType, payload)) {
        try {
            return TenantResult.from(
                    status,
                    OBJECT_MAPPER.readValue(payload.getBytes(), TenantObject.class),
                    cacheDirective,
                    applicationProperties);
        } catch (final IOException e) {
            LOG.warn("received malformed payload from Tenant service", e);
            return TenantResult.from(HttpURLConnection.HTTP_INTERNAL_ERROR, null, null, applicationProperties);
        }
    } else {
        return TenantResult.from(status, null, null, applicationProperties);
    }
}
 
Example #3
Source File: RegistrationClientImpl.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected final RegistrationResult getResult(
        final int status,
        final String contentType,
        final Buffer payload,
        final CacheDirective cacheDirective,
        final ApplicationProperties applicationProperties) {

    if (isSuccessResponse(status, contentType, payload)) {
        try {
            return RegistrationResult.from(status, new JsonObject(payload), cacheDirective, applicationProperties);
        } catch (final DecodeException e) {
            LOG.warn("received malformed payload from Device Registration service", e);
            return RegistrationResult.from(HttpURLConnection.HTTP_INTERNAL_ERROR, null, null, applicationProperties);
        }
    } else {
        return RegistrationResult.from(status, null, null, applicationProperties);
    }
}
 
Example #4
Source File: AmqpJmsMessageFacadeTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetPropertyNames() throws Exception {
    Map<String, Object> applicationPropertiesMap = new HashMap<>();
    applicationPropertiesMap.put(TEST_PROP_A, TEST_VALUE_STRING_A);
    applicationPropertiesMap.put(TEST_PROP_B, TEST_VALUE_STRING_B);

    Message message2 = Proton.message();
    message2.setApplicationProperties(new ApplicationProperties(applicationPropertiesMap));

    AmqpJmsMessageFacade amqpMessageFacade = createReceivedMessageFacade(createMockAmqpConsumer(), message2);

    Set<String> applicationPropertyNames = amqpMessageFacade.getPropertyNames();
    assertEquals(2, applicationPropertyNames.size());
    assertTrue(applicationPropertyNames.contains(TEST_PROP_A));
    assertTrue(applicationPropertyNames.contains(TEST_PROP_B));
}
 
Example #5
Source File: DeviceConnectionClientImpl.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected final DeviceConnectionResult getResult(
        final int status,
        final String contentType,
        final Buffer payload,
        final CacheDirective cacheDirective,
        final ApplicationProperties applicationProperties) {

    if (payload == null) {
        return DeviceConnectionResult.from(status, null, null, applicationProperties);
    } else {
        try {
            // ignoring given cacheDirective param here - device connection results shall not be cached
            return DeviceConnectionResult.from(status, new JsonObject(payload), CacheDirective.noCacheDirective(), applicationProperties);
        } catch (final DecodeException e) {
            LOG.warn("received malformed payload from Device Connection service", e);
            return DeviceConnectionResult.from(HttpURLConnection.HTTP_INTERNAL_ERROR, null, null, applicationProperties);
        }
    }
}
 
Example #6
Source File: AMQPPersisterTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private MessageImpl createProtonMessage(String address, byte[] content) {
   MessageImpl message = (MessageImpl) Proton.message();

   Header header = new Header();
   header.setDurable(true);
   header.setPriority(UnsignedByte.valueOf((byte) 9));

   Properties properties = new Properties();
   properties.setCreationTime(new Date(System.currentTimeMillis()));
   properties.setTo(address);
   properties.setMessageId(UUID.randomUUID());

   MessageAnnotations annotations = new MessageAnnotations(new LinkedHashMap<>());
   ApplicationProperties applicationProperties = new ApplicationProperties(new LinkedHashMap<>());

   AmqpValue body = new AmqpValue(Arrays.copyOf(content, content.length));

   message.setHeader(header);
   message.setMessageAnnotations(annotations);
   message.setProperties(properties);
   message.setApplicationProperties(applicationProperties);
   message.setBody(body);

   return message;
}
 
Example #7
Source File: CredentialsClientImpl.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected final CredentialsResult<CredentialsObject> getResult(
        final int status,
        final String contentType,
        final Buffer payload,
        final CacheDirective cacheDirective,
        final ApplicationProperties applicationProperties) {

    if (isSuccessResponse(status, contentType, payload)) {
        try {
            return CredentialsResult.from(
                    status,
                    OBJECT_MAPPER.readValue(payload.getBytes(), CredentialsObject.class),
                    cacheDirective,
                    applicationProperties);
        } catch (final IOException e) {
            LOG.warn("received malformed payload from Credentials service", e);
            return CredentialsResult.from(HttpURLConnection.HTTP_INTERNAL_ERROR, null, null, applicationProperties);
        }
    } else {
        return CredentialsResult.from(status, null, null, applicationProperties);
    }
}
 
Example #8
Source File: TestConversions.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleConversionStream() throws Exception {
   Map<String, Object> mapprop = createPropertiesMap();
   ApplicationProperties properties = new ApplicationProperties(mapprop);
   MessageImpl message = (MessageImpl) Message.Factory.create();
   message.setApplicationProperties(properties);

   List<Object> objects = new LinkedList<>();
   objects.add(new Integer(10));
   objects.add("10");

   message.setBody(new AmqpSequence(objects));

   AMQPMessage encodedMessage = encodeAndCreateAMQPMessage(message);

   ICoreMessage serverMessage = encodedMessage.toCore();

   ServerJMSStreamMessage streamMessage = (ServerJMSStreamMessage) ServerJMSMessage.wrapCoreMessage(serverMessage);

   verifyProperties(streamMessage);

   streamMessage.reset();

   assertEquals(10, streamMessage.readInt());
   assertEquals("10", streamMessage.readString());
}
 
Example #9
Source File: TestConversions.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleConversionText() throws Exception {
   Map<String, Object> mapprop = createPropertiesMap();
   ApplicationProperties properties = new ApplicationProperties(mapprop);
   MessageImpl message = (MessageImpl) Message.Factory.create();
   message.setApplicationProperties(properties);

   String text = "someText";
   message.setBody(new AmqpValue(text));

   AMQPMessage encodedMessage = encodeAndCreateAMQPMessage(message);

   ICoreMessage serverMessage = encodedMessage.toCore();

   ServerJMSTextMessage textMessage = (ServerJMSTextMessage) ServerJMSMessage.wrapCoreMessage(serverMessage);
   textMessage.decode();

   verifyProperties(textMessage);

   assertEquals(text, textMessage.getText());
}
 
Example #10
Source File: CommandTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a command can be created from a valid message with application properties.
 * Verifies that the application properties are able to be retrieved from the message.
 */
@Test
public void testFromMessageSucceedsWithApplicationProperties() {
    final String replyToId = "the-reply-to-id";
    final String correlationId = "the-correlation-id";
    final Map<String, Object> applicationProperties = new HashMap<>();
    applicationProperties.put("deviceId", "4711");
    applicationProperties.put("tenantId", "DEFAULT_TENANT");
    final Message message = mock(Message.class);
    when(message.getAddress()).thenReturn(String.format("%s/%s/%s",
            CommandConstants.COMMAND_ENDPOINT, Constants.DEFAULT_TENANT, "4711"));
    when(message.getApplicationProperties()).thenReturn(new ApplicationProperties(applicationProperties));
    when(message.getSubject()).thenReturn("doThis");
    when(message.getCorrelationId()).thenReturn(correlationId);
    when(message.getReplyTo()).thenReturn(String.format("%s/%s/%s/%s",
            CommandConstants.NORTHBOUND_COMMAND_RESPONSE_ENDPOINT, Constants.DEFAULT_TENANT, "4711", replyToId));
    final Command cmd = Command.from(message, Constants.DEFAULT_TENANT, "4711");
    assertTrue(cmd.isValid());
    assertThat(cmd.getApplicationProperties()).isNotNull();
    assertThat(cmd.getApplicationProperties()).hasSize(2);
    assertThat(cmd.getApplicationProperties().get("deviceId")).isEqualTo("4711");
    assertThat(cmd.getApplicationProperties().get("tenantId")).isEqualTo("DEFAULT_TENANT");
}
 
Example #11
Source File: AbstractHonoClientTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the given application properties are propagated to
 * the message.
 */
@Test
public void testApplicationPropertiesAreSetAtTheMessage() {

    final Message msg = mock(Message.class);
    final Map<String, Object> applicationProps = new HashMap<>();
    applicationProps.put("string-key", "value");
    applicationProps.put("int-key", 15);
    applicationProps.put("long-key", 1000L);

    final ArgumentCaptor<ApplicationProperties> applicationPropsCaptor = ArgumentCaptor.forClass(ApplicationProperties.class);

    AbstractHonoClient.setApplicationProperties(msg, applicationProps);

    verify(msg).setApplicationProperties(applicationPropsCaptor.capture());
    assertThat(applicationPropsCaptor.getValue().getValue()).isEqualTo(applicationProps);
}
 
Example #12
Source File: AbstractHonoClient.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Set the application properties for a Proton Message but do a check for all properties first if they only contain
 * values that the AMQP 1.0 spec allows.
 *
 * @param msg The Proton message. Must not be null.
 * @param properties The map containing application properties.
 * @throws NullPointerException if the message passed in is null.
 * @throws IllegalArgumentException if the properties contain any value that AMQP 1.0 disallows.
 */
protected static final void setApplicationProperties(final Message msg, final Map<String, ?> properties) {
    if (properties != null) {
        final Map<String, Object> propsToAdd = new HashMap<>();
        // check the three types not allowed by AMQP 1.0 spec for application properties (list, map and array)
        for (final Map.Entry<String, ?> entry: properties.entrySet()) {
            if (entry.getValue() != null) {
                if (entry.getValue() instanceof List) {
                    throw new IllegalArgumentException(String.format("Application property %s can't be a List", entry.getKey()));
                } else if (entry.getValue() instanceof Map) {
                    throw new IllegalArgumentException(String.format("Application property %s can't be a Map", entry.getKey()));
                } else if (entry.getValue().getClass().isArray()) {
                    throw new IllegalArgumentException(String.format("Application property %s can't be an Array", entry.getKey()));
                }
            }
            propsToAdd.put(entry.getKey(), entry.getValue());
        }

        final ApplicationProperties applicationProperties = new ApplicationProperties(propsToAdd);
        msg.setApplicationProperties(applicationProperties);
    }
}
 
Example #13
Source File: AdapterInstanceCommandHandlerTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Test
void testHandleCommandMessageWithHandlerForGateway() {
    final String deviceId = "4711";
    final String gatewayId = "gw-1";
    final String correlationId = "the-correlation-id";
    final Message message = ProtonHelper.message("input data");
    message.setAddress(String.format("%s/%s/%s",
            CommandConstants.COMMAND_ENDPOINT, Constants.DEFAULT_TENANT, deviceId));
    message.setSubject("doThis");
    message.setCorrelationId(correlationId);
    message.setApplicationProperties(
            new ApplicationProperties(Collections.singletonMap(MessageHelper.APP_PROPERTY_CMD_VIA, gatewayId)));

    final Handler<CommandContext> commandHandler = VertxMockSupport.mockHandler();
    adapterInstanceCommandHandler.putDeviceSpecificCommandHandler(Constants.DEFAULT_TENANT, gatewayId, null, commandHandler);

    adapterInstanceCommandHandler.handleCommandMessage(message, mock(ProtonDelivery.class));

    final ArgumentCaptor<CommandContext> commandContextCaptor = ArgumentCaptor.forClass(CommandContext.class);
    verify(commandHandler).handle(commandContextCaptor.capture());
    assertThat(commandContextCaptor.getValue()).isNotNull();
    // assert that command is directed at the gateway
    assertThat(commandContextCaptor.getValue().getCommand().getDeviceId()).isEqualTo(gatewayId);
    assertThat(commandContextCaptor.getValue().getCommand().getOriginalDeviceId()).isEqualTo(deviceId);
}
 
Example #14
Source File: JMSTransformationSpeedComparisonTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private MessageImpl createTypicalQpidJMSMessage() {
   Map<String, Object> applicationProperties = new HashMap<>();
   Map<Symbol, Object> messageAnnotations = new HashMap<>();

   applicationProperties.put("property-1", "string");
   applicationProperties.put("property-2", 512);
   applicationProperties.put("property-3", true);

   messageAnnotations.put(Symbol.valueOf("x-opt-jms-msg-type"), 0);
   messageAnnotations.put(Symbol.valueOf("x-opt-jms-dest"), 0);

   MessageImpl message = (MessageImpl) Proton.message();

   message.setAddress("queue://test-queue");
   message.setDeliveryCount(1);
   message.setApplicationProperties(new ApplicationProperties(applicationProperties));
   message.setMessageAnnotations(new MessageAnnotations(messageAnnotations));
   message.setCreationTime(System.currentTimeMillis());
   message.setContentType("text/plain");
   message.setBody(new AmqpValue("String payload for AMQP message conversion performance testing."));

   return message;
}
 
Example #15
Source File: AMQPMessage.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected Map<String, Object> getApplicationPropertiesMap(boolean createIfAbsent) {
   ApplicationProperties appMap = lazyDecodeApplicationProperties();
   Map<String, Object> map = null;

   if (appMap != null) {
      map = appMap.getValue();
   }

   if (map == null) {
      if (createIfAbsent) {
         map = new HashMap<>();
         this.applicationProperties = new ApplicationProperties(map);
      } else {
         map = Collections.EMPTY_MAP;
      }
   }

   return map;
}
 
Example #16
Source File: MessageHelper.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private static String getRegistrationAssertion(final Message msg, final boolean removeAssertion) {
    Objects.requireNonNull(msg);
    String assertion = null;
    final ApplicationProperties properties = msg.getApplicationProperties();
    if (properties != null) {
        final Object obj;
        if (removeAssertion) {
            obj = properties.getValue().remove(APP_PROPERTY_REGISTRATION_ASSERTION);
        } else {
            obj = properties.getValue().get(APP_PROPERTY_REGISTRATION_ASSERTION);
        }
        if (obj instanceof String) {
            assertion = (String) obj;
        }
    }
    return assertion;
}
 
Example #17
Source File: ApplicationPropertiesTypeTest.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeApplicationPropertiesReservesSpaceForPayload() throws IOException {
    final int ENTRIES = 8;

    Map<String, Object> propertiesMap = new LinkedHashMap<>();
    ApplicationProperties properties = new ApplicationProperties(propertiesMap);

    for (int i = 0; i < ENTRIES; ++i) {
        properties.getValue().put(String.valueOf(i), i);
    }

    WritableBuffer writable = new WritableBuffer.ByteBufferWrapper(this.buffer);
    WritableBuffer spy = Mockito.spy(writable);

    encoder.setByteBuffer(spy);
    encoder.writeObject(properties);

    // Check that the Type tries to reserve space, actual encoding size not computed here.
    // Each key should also try and reserve space for the String data
    Mockito.verify(spy, Mockito.times(ENTRIES + 1)).ensureRemaining(Mockito.anyInt());
}
 
Example #18
Source File: TestConversions.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testAmqpValueOfBooleanIsPassedThrough() throws Exception {
   Map<String, Object> mapprop = createPropertiesMap();
   ApplicationProperties properties = new ApplicationProperties(mapprop);
   MessageImpl message = (MessageImpl) Message.Factory.create();
   message.setApplicationProperties(properties);

   byte[] bodyBytes = new byte[4];

   for (int i = 0; i < bodyBytes.length; i++) {
      bodyBytes[i] = (byte) 0xff;
   }

   message.setBody(new AmqpValue(new Boolean(true)));

   AMQPMessage encodedMessage = encodeAndCreateAMQPMessage(message);

   ICoreMessage serverMessage = encodedMessage.toCore();

   verifyProperties(ServerJMSMessage.wrapCoreMessage(serverMessage));
}
 
Example #19
Source File: RequestResponseResult.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a new result for a status code and payload.
 *
 * @param status The code indicating the outcome of processing the request.
 * @param payload The payload to convey to the sender of the request (may be {@code null}).
 * @param directive Restrictions regarding the caching of the payload by
 *                       the receiver of the result (may be {@code null}).
 * @param applicationProperties Arbitrary properties conveyed in the response message's
 *                              <em>application-properties</em>.
 */
public RequestResponseResult(
        final int status,
        final T payload,
        final CacheDirective directive,
        final ApplicationProperties applicationProperties) {

    this.status = status;
    this.payload = payload;
    this.cacheDirective = directive;
    if (applicationProperties == null || applicationProperties.getValue().isEmpty()) {
        this.applicationProperties = Collections.emptyMap();
    } else {
        this.applicationProperties = Collections.unmodifiableMap(applicationProperties.getValue());
    }
}
 
Example #20
Source File: AmqpJmsMessageFacadeTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetProperties() throws Exception {
    Map<String, Object> applicationPropertiesMap = new HashMap<>();
    applicationPropertiesMap.put(TEST_PROP_A, TEST_VALUE_STRING_A);
    applicationPropertiesMap.put(TEST_PROP_B, TEST_VALUE_STRING_B);

    Message message2 = Proton.message();
    message2.setApplicationProperties(new ApplicationProperties(applicationPropertiesMap));

    JmsMessageFacade amqpMessageFacade = createReceivedMessageFacade(createMockAmqpConsumer(), message2);

    Set<String> props = amqpMessageFacade.getPropertyNames();
    assertEquals(2, props.size());
    assertTrue(props.contains(TEST_PROP_A));
    assertEquals(TEST_VALUE_STRING_A, amqpMessageFacade.getProperty(TEST_PROP_A));
    assertTrue(props.contains(TEST_PROP_B));
    assertEquals(TEST_VALUE_STRING_B, amqpMessageFacade.getProperty(TEST_PROP_B));
}
 
Example #21
Source File: FastPathApplicationPropertiesType.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void write(ApplicationProperties val) {
    WritableBuffer buffer = getEncoder().getBuffer();

    buffer.put(EncodingCodes.DESCRIBED_TYPE_INDICATOR);
    buffer.put(EncodingCodes.SMALLULONG);
    buffer.put(DESCRIPTOR_CODE);

    MapType mapType = (MapType) getEncoder().getType(val.getValue());

    mapType.setKeyEncoding(stringType);
    try {
        mapType.write(val.getValue());
    } finally {
        mapType.setKeyEncoding(null);
    }
}
 
Example #22
Source File: AmqpJmsMessageFacadeTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testClearProperties() throws Exception {
    Map<String, Object> applicationPropertiesMap = new HashMap<>();
    applicationPropertiesMap.put(TEST_PROP_A, TEST_VALUE_STRING_A);

    Message message = Proton.message();
    message.setApplicationProperties(new ApplicationProperties(applicationPropertiesMap));

    JmsMessageFacade amqpMessageFacade = createReceivedMessageFacade(createMockAmqpConsumer(), message);

    Set<String> props1 = amqpMessageFacade.getPropertyNames();
    assertEquals(1, props1.size());

    amqpMessageFacade.clearProperties();

    Set<String> props2 = amqpMessageFacade.getPropertyNames();
    assertTrue(props2.isEmpty());
}
 
Example #23
Source File: Artemis.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private Message createAttributeMessage(String resource, String attribute) {
    Message message = Message.Factory.create();
    Map<String, Object> properties = new LinkedHashMap<>();
    properties.put("_AMQ_ResourceName", resource);
    properties.put("_AMQ_Attribute", attribute);
    message.setApplicationProperties(new ApplicationProperties(properties));
    return message;
}
 
Example #24
Source File: AMQPMessageTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetApplicationProperties() {
   MessageImpl protonMessage = createProtonMessage();
   AMQPStandardMessage message = new AMQPStandardMessage(0, encodeMessage(protonMessage), null, null);

   ApplicationProperties decoded = message.getApplicationProperties();
   assertNotSame(decoded, protonMessage.getApplicationProperties());
   assertApplicationPropertiesEquals(protonMessage.getApplicationProperties(), decoded);

   // Update the values
   decoded.getValue().put(UUID.randomUUID().toString(), "test");

   // Check that the message is unaffected.
   assertApplicationPropertiesNotEquals(protonMessage.getApplicationProperties(), decoded);
}
 
Example #25
Source File: Proton.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
public static Message message(Header header,
                  DeliveryAnnotations deliveryAnnotations, MessageAnnotations messageAnnotations,
                  Properties properties, ApplicationProperties applicationProperties,
                  Section body, Footer footer)
{
    return Message.Factory.create(header, deliveryAnnotations,
                                  messageAnnotations, properties,
                                  applicationProperties, body, footer);
}
 
Example #26
Source File: Message.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
public static Message create(Header header,
                             DeliveryAnnotations deliveryAnnotations,
                             MessageAnnotations messageAnnotations,
                             Properties properties,
                             ApplicationProperties applicationProperties,
                             Section body,
                             Footer footer) {
    return new MessageImpl(header, deliveryAnnotations,
                           messageAnnotations, properties,
                           applicationProperties, body, footer);
}
 
Example #27
Source File: Artemis.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private Message createOperationMessage(String resource, String operation) {
    Message message = Message.Factory.create();
    Map<String, Object> properties = new LinkedHashMap<>();
    properties.put("_AMQ_ResourceName", resource);
    properties.put("_AMQ_OperationName", operation);
    message.setApplicationProperties(new ApplicationProperties(properties));
    return message;
}
 
Example #28
Source File: TestConversions.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testEditAndConvert() throws Exception {

   Map<String, Object> mapprop = createPropertiesMap();
   ApplicationProperties properties = new ApplicationProperties(mapprop);
   properties.getValue().put("hello", "hello");
   MessageImpl message = (MessageImpl) Message.Factory.create();
   MessageAnnotations annotations = new MessageAnnotations(new HashMap<>());
   message.setMessageAnnotations(annotations);
   message.setApplicationProperties(properties);

   String text = "someText";
   message.setBody(new AmqpValue(text));

   AMQPMessage encodedMessage = encodeAndCreateAMQPMessage(message);
   TypedProperties extraProperties = new TypedProperties();
   encodedMessage.setAddress(SimpleString.toSimpleString("xxxx.v1.queue"));

   for (int i = 0; i < 10; i++) {
      if (logger.isDebugEnabled()) {
         logger.debug("Message encoded :: " + encodedMessage.toDebugString());
      }

      encodedMessage.messageChanged();
      AmqpValue value = (AmqpValue) encodedMessage.getProtonMessage().getBody();
      Assert.assertEquals(text, (String) value.getValue());

      // this line is needed to force a failure
      ICoreMessage coreMessage = encodedMessage.toCore();

      if (logger.isDebugEnabled()) {
         logger.debug("Converted message: " + coreMessage);
      }
   }
}
 
Example #29
Source File: RouterManagement.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private List<List<?>> collectRouter(SyncRequestClient client, RouterEntity routerEntity) {
    Map<String, Object> properties = new LinkedHashMap<>();
    properties.put("operation", "QUERY");
    properties.put("entityType", routerEntity.getName());
    Map<String, Object> body = new LinkedHashMap<>();

    if (routerEntity.getAttributes() != null) {
        body.put("attributeNames", Arrays.asList(routerEntity.getAttributes()));
    }

    Message message = Proton.message();
    message.setApplicationProperties(new ApplicationProperties(properties));
    message.setBody(new AmqpValue(body));

    long timeoutSeconds = this.queryTimeout.getSeconds();
    Message response = client.request(message, timeoutSeconds, TimeUnit.SECONDS);
    if (response == null) {
        throw new IllegalArgumentException(String.format("No response received within timeout : %s(s)", timeoutSeconds));
    }
    AmqpValue value = (AmqpValue) response.getBody();
    if (value == null) {
        throw new IllegalArgumentException("Unexpected null body");
    }
    Map<?,?> values = (Map<?,?>) value.getValue();
    if (values == null) {
        throw new IllegalArgumentException("Unexpected null body value");
    }

    @SuppressWarnings("unchecked")
    List<List<?>> results = (List<List<?>>) values.get("results");
    if (results == null) {
        throw new IllegalArgumentException("Unexpected null results list");
    }
    return results;
}
 
Example #30
Source File: ApplicationPropertiesCodecTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private void doTestDecodeHeaderSeries(int size) throws IOException {

        Map<String, Object> propertiesMap = new LinkedHashMap<>();
        ApplicationProperties properties = new ApplicationProperties(propertiesMap);

        propertiesMap.put("key-1", "1");
        propertiesMap.put("key-2", "2");
        propertiesMap.put("key-3", "3");
        propertiesMap.put("key-4", "4");
        propertiesMap.put("key-5", "5");
        propertiesMap.put("key-6", "6");
        propertiesMap.put("key-7", "7");
        propertiesMap.put("key-8", "8");

        for (int i = 0; i < size; ++i) {
            encoder.writeObject(properties);
        }

        buffer.clear();

        for (int i = 0; i < size; ++i) {
            final Object result = decoder.readObject();

            assertNotNull(result);
            assertTrue(result instanceof ApplicationProperties);

            ApplicationProperties decoded = (ApplicationProperties) result;

            assertEquals(8, decoded.getValue().size());
            assertTrue(decoded.getValue().equals(propertiesMap));
        }
    }