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

The following examples show how to use org.apache.qpid.proton.message.Message#setApplicationProperties() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
Source File: AbstractRequestResponseClientTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the client succeeds the result handler if the peer accepts
 * the request message for a one-way request.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testSendOneWayRequestSucceedsOnAcceptedMessage(final VertxTestContext ctx) {

    // GIVEN a request-response client that times out requests after 200 ms
    client.setRequestTimeout(200);

    // WHEN sending a one-way request message with some headers and payload
    final JsonObject payload = new JsonObject().put("key", "value");
    final Map<String, Object> applicationProps = new HashMap<>();

    final Message request = ProtonHelper.message();
    request.setMessageId("12345");
    request.setCorrelationId("23456");
    request.setSubject("aRequest");
    request.setApplicationProperties(new ApplicationProperties(applicationProps));
    MessageHelper.setPayload(request, "application/json", payload.toBuffer());

    final SpanContext spanContext = mock(SpanContext.class);
    final Span span = mock(Span.class);
    when(span.context()).thenReturn(spanContext);

    client.sendRequest(request, ctx.succeeding(t -> {
        // THEN the result handler is succeeded
        ctx.completeNow();
    }), null, span);
    // and the peer accepts the message
    final Accepted accepted = new Accepted();
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    when(delivery.getRemoteState()).thenReturn(accepted);
    @SuppressWarnings("unchecked")
    final ArgumentCaptor<Handler<ProtonDelivery>> dispositionHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
    verify(sender).send(any(Message.class), dispositionHandlerCaptor.capture());
    dispositionHandlerCaptor.getValue().handle(delivery);
}
 
Example 8
Source File: RequestResponseApiConstants.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates an AMQP message from a result to a service invocation.
 *
 * @param endpoint The service endpoint that the operation has been invoked on.
 * @param tenantId The id of the tenant (may be {@code null}).
 * @param request The request message.
 * @param result The result message.
 * @return The AMQP message.
 * @throws NullPointerException if endpoint, request or result is {@code null}.
 * @throws IllegalArgumentException if the result does not contain a correlation ID.
 */
public static final Message getAmqpReply(final String endpoint, final String tenantId, final Message request, final RequestResponseResult<JsonObject> result) {

    Objects.requireNonNull(endpoint);
    Objects.requireNonNull(request);
    Objects.requireNonNull(result);

    final Object correlationId = MessageHelper.getCorrelationId(request);

    if (correlationId == null) {
        throw new IllegalArgumentException("request must contain correlation ID");
    }

    final String deviceId = MessageHelper.getDeviceId(request);

    final ResourceIdentifier address = ResourceIdentifier.from(endpoint, tenantId, deviceId);

    final Message message = ProtonHelper.message();
    message.setMessageId(UUID.randomUUID().toString());
    message.setCorrelationId(correlationId.toString());
    message.setAddress(address.toString());

    final Map<String, Object> map = new HashMap<>();
    map.put(MessageHelper.APP_PROPERTY_STATUS, result.getStatus());
    if (tenantId != null) {
        map.put(MessageHelper.APP_PROPERTY_TENANT_ID, tenantId);
    }
    if (deviceId != null) {
        map.put(MessageHelper.APP_PROPERTY_DEVICE_ID, deviceId);
    }
    if (result.getCacheDirective() != null) {
        map.put(MessageHelper.APP_PROPERTY_CACHE_CONTROL, result.getCacheDirective().toString());
    }
    message.setApplicationProperties(new ApplicationProperties(map));

    MessageHelper.setJsonPayload(message, result.getPayload());

    return message;
}
 
Example 9
Source File: MessageHelper.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns a copy of the given message.
 * <p>
 * This is a shallow copy of the <em>Message</em> object, except for the copied <em>Properties</em>.
 *
 * @param message The message to copy.
 * @return The message copy.
 */
public static Message getShallowCopy(final Message message) {
    final Message copy = ProtonHelper.message();
    copy.setDeliveryAnnotations(message.getDeliveryAnnotations());
    copy.setMessageAnnotations(message.getMessageAnnotations());
    if (message.getProperties() != null) {
        copy.setProperties(new Properties(message.getProperties()));
    }
    copy.setApplicationProperties(message.getApplicationProperties());
    copy.setBody(message.getBody());
    copy.setFooter(message.getFooter());
    return copy;
}
 
Example 10
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 11
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 12
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 13
Source File: AmqpJmsMessageFacadeTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertyExists() 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);

    assertTrue(amqpMessageFacade.propertyExists(TEST_PROP_A));
    assertFalse(amqpMessageFacade.propertyExists(TEST_PROP_B));
}
 
Example 14
Source File: AmqpJmsMessageFacadeTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetProperty() 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);

    assertEquals(TEST_VALUE_STRING_A, amqpMessageFacade.getProperty(TEST_PROP_A));
    assertNull(amqpMessageFacade.getProperty(TEST_PROP_B));
}
 
Example 15
Source File: AmqpMessageTest.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Test
public void testMessageAttributes() {
    Map<String, Object> props = new LinkedHashMap<>();
    props.put("hello", "world");
    props.put("some", "content");
    Message message = message();
    message.setTtl(1);
    message.setDurable(true);
    message.setReplyTo("reply");
    ApplicationProperties apps = new ApplicationProperties(props);
    message.setApplicationProperties(apps);
    message.setContentType("text/plain");
    message.setCorrelationId("1234");
    message.setDeliveryCount(2);
    message.setExpiryTime(10000);
    message.setFooter(new Footer(props));
    message.setGroupId("some-group");
    message.setAddress("address");
    message.setCreationTime(System.currentTimeMillis());
    message.setSubject("subject");
    message.setUserId("username".getBytes());
    message.setPriority((short) 2);
    message.setBody(new AmqpValue("hello"));
    message.setMessageId("4321");

    AmqpMessage<?> msg = new AmqpMessage<>(new AmqpMessageImpl(message), null, null);
    assertThat(msg.getAddress()).isEqualTo("address");
    assertThat(msg.getApplicationProperties()).contains(entry("hello", "world"), entry("some", "content"));
    assertThat(msg.getContentType()).isEqualTo("text/plain");
    assertThat(msg.getCreationTime()).isNotZero();
    assertThat(msg.getDeliveryCount()).isEqualTo(2);
    assertThat(msg.getExpiryTime()).isEqualTo(10000);
    assertThat(msg.getGroupId()).isEqualTo("some-group");
    assertThat(msg.getTtl()).isEqualTo(1);
    assertThat(msg.getSubject()).isEqualTo("subject");
    assertThat(msg.getPriority()).isEqualTo((short) 2);
    assertThat(((AmqpValue) msg.getBody()).getValue()).isEqualTo("hello");
    assertThat(msg.getCorrelationId()).isEqualTo("1234");
    assertThat(msg.getMessageId()).isEqualTo("4321");
    assertThat(msg.getHeader()).isNotNull();
    assertThat(msg.isDurable()).isTrue();
    assertThat(msg.getError().name()).isEqualTo("OK");
    assertThat(msg.getGroupSequence()).isZero();

}
 
Example 16
Source File: RequestResponseApiConstants.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Creates an AMQP message from a response to a service invocation.
 *
 * @param endpoint The service endpoint that the operation has been invoked on.
 * @param response The response message.
 * @return The AMQP message.
 * @throws NullPointerException if endpoint is {@code null}.
 * @throws IllegalArgumentException if the response does not contain a correlation ID.
 */
public static final Message getAmqpReply(final String endpoint, final EventBusMessage response) {

    Objects.requireNonNull(endpoint);
    Objects.requireNonNull(response);

    final Object correlationId = response.getCorrelationId();

    if (correlationId == null) {
        throw new IllegalArgumentException("response must contain correlation ID");
    }

    final String tenantId = response.getTenant();
    final String deviceId = response.getDeviceId();
    final Integer status = response.getStatus();
    final String cacheDirective = response.getCacheDirective();
    final JsonObject payload = response.getJsonPayload();
    final ResourceIdentifier address = ResourceIdentifier.from(endpoint, tenantId, deviceId);

    final Message message = ProtonHelper.message();
    message.setMessageId(UUID.randomUUID().toString());
    message.setCorrelationId(correlationId);
    message.setAddress(address.toString());

    final Map<String, Object> map = new HashMap<>();
    map.put(MessageHelper.APP_PROPERTY_STATUS, status);
    if (tenantId != null) {
        map.put(MessageHelper.APP_PROPERTY_TENANT_ID, tenantId);
    }
    if (deviceId != null) {
        map.put(MessageHelper.APP_PROPERTY_DEVICE_ID, deviceId);
    }
    if (cacheDirective != null) {
        map.put(MessageHelper.APP_PROPERTY_CACHE_CONTROL, cacheDirective);
    }
    message.setApplicationProperties(new ApplicationProperties(map));

    MessageHelper.setJsonPayload(message, payload);

    return message;
}