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

The following examples show how to use org.apache.qpid.proton.message.Message#setContentType() . 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: AmqpCodecTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private void doCreateTextMessageFromDataWithContentTypeTestImpl(String contentType, Charset expectedCharset) throws IOException {
    Message message = Proton.message();
    Binary binary = new Binary(new byte[0]);
    message.setBody(new Data(binary));
    message.setContentType(contentType);

    JmsMessage jmsMessage = AmqpCodec.decodeMessage(mockConsumer, encodeMessage(message)).asJmsMessage();
    assertNotNull("Message should not be null", jmsMessage);
    assertEquals("Unexpected message class type", JmsTextMessage.class, jmsMessage.getClass());

    JmsMessageFacade facade = jmsMessage.getFacade();
    assertNotNull("Facade should not be null", facade);
    assertEquals("Unexpected facade class type", AmqpJmsTextMessageFacade.class, facade.getClass());

    AmqpJmsTextMessageFacade textFacade = (AmqpJmsTextMessageFacade) facade;
    assertEquals("Unexpected character set", expectedCharset, textFacade.getCharset());
}
 
Example 2
Source File: AmqpCodecTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
/**
* Test that a message with no body section, but with the content type set to
* {@value AmqpMessageSupport#SERIALIZED_JAVA_OBJECT_CONTENT_TYPE} results in an ObjectMessage
* when not otherwise annotated to indicate the type of JMS message it is.
 *
 * @throws Exception if an error occurs during the test.
*/
@Test
public void testCreateObjectMessageFromNoBodySectionAndContentType() throws Exception {
    Message message = Proton.message();
    message.setContentType(AmqpMessageSupport.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE.toString());

    JmsMessage jmsMessage = AmqpCodec.decodeMessage(mockConsumer, encodeMessage(message)).asJmsMessage();
    assertNotNull("Message should not be null", jmsMessage);
    assertEquals("Unexpected message class type", JmsObjectMessage.class, jmsMessage.getClass());

    JmsMessageFacade facade = jmsMessage.getFacade();
    assertNotNull("Facade should not be null", facade);
    assertEquals("Unexpected facade class type", AmqpJmsObjectMessageFacade.class, facade.getClass());

    AmqpObjectTypeDelegate delegate = ((AmqpJmsObjectMessageFacade) facade).getDelegate();
    assertTrue("Unexpected delegate type: " + delegate, delegate instanceof AmqpSerializedObjectDelegate);
}
 
Example 3
Source File: AbstractSenderTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the sender removes the registration assertion
 * from a message if the peer does not support validation of
 * assertions.
 */
@Test
public void testSendMessageRemovesRegistrationAssertion() {

    // GIVEN a sender that is connected to a peer which does not
    // support validation of registration assertions
    when(protonSender.getRemoteOfferedCapabilities()).thenReturn(null);
    when(protonSender.send(any(Message.class), VertxMockSupport.anyHandler())).thenReturn(mock(ProtonDelivery.class));
    final AbstractSender sender = newSender("tenant", "endpoint");

    // WHEN sending a message
    final Message msg = ProtonHelper.message("some payload");
    msg.setContentType("application/text");
    MessageHelper.addDeviceId(msg, "device");
    sender.send(msg);

    // THEN the message is sent without the registration assertion
    final ArgumentCaptor<Message> sentMessage = ArgumentCaptor.forClass(Message.class);
    verify(protonSender).send(sentMessage.capture());
    assertNull(MessageHelper.getAndRemoveRegistrationAssertion(sentMessage.getValue()));
}
 
Example 4
Source File: AmqpJmsObjectMessageFacadeTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
/**
 * Test that clearing the body on a message results in the underlying body
 * section being set with the null object body, ensuring getObject returns null.
 *
 * @throws Exception if an error occurs during the test.
 */
@Test
public void testClearBodyWithExistingSerializedBodySection() throws Exception {
    Message protonMessage = Message.Factory.create();
    protonMessage.setContentType(AmqpMessageSupport.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE.toString());
    protonMessage.setBody(new Data(new Binary(new byte[0])));

    AmqpJmsObjectMessageFacade amqpObjectMessageFacade = createReceivedObjectMessageFacade(createMockAmqpConsumer(), protonMessage);

    assertNotNull("Expected existing body section to be found", amqpObjectMessageFacade.getBody());
    amqpObjectMessageFacade.clearBody();
    assertSame("Expected existing body section to be replaced", AmqpSerializedObjectDelegate.NULL_OBJECT_BODY, amqpObjectMessageFacade.getBody());
    assertNull("Expected null object", amqpObjectMessageFacade.getObject());
}
 
Example 5
Source File: AmqpCodecTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateTextMessageFromNoBodySectionAndContentType() throws Exception {
    Message message = Proton.message();
    message.setContentType("text/plain");

    JmsMessage jmsMessage = AmqpCodec.decodeMessage(mockConsumer, encodeMessage(message)).asJmsMessage();
    assertNotNull("Message should not be null", jmsMessage);
    assertEquals("Unexpected message class type", JmsTextMessage.class, jmsMessage.getClass());

    JmsMessageFacade facade = jmsMessage.getFacade();
    assertNotNull("Facade should not be null", facade);
    assertEquals("Unexpected facade class type", AmqpJmsTextMessageFacade.class, facade.getClass());
}
 
Example 6
Source File: AmqpCodecTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
private void createObjectMessageFromMessageTypeAnnotationTestImpl(boolean setJavaSerializedContentType) throws Exception {
    Message message = Proton.message();

    Map<Symbol, Object> map = new HashMap<Symbol, Object>();
    map.put(AmqpMessageSupport.JMS_MSG_TYPE, AmqpMessageSupport.JMS_OBJECT_MESSAGE);

    MessageAnnotations messageAnnotations = new MessageAnnotations(map);
    message.setMessageAnnotations(messageAnnotations);

    if (setJavaSerializedContentType) {
        message.setContentType(AmqpMessageSupport.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE.toString());
    }

    JmsMessage jmsMessage = AmqpCodec.decodeMessage(mockConsumer, encodeMessage(message)).asJmsMessage();
    assertNotNull("Message should not be null", jmsMessage);
    assertEquals("Unexpected message class type", JmsObjectMessage.class, jmsMessage.getClass());

    JmsMessageFacade facade = jmsMessage.getFacade();
    assertNotNull("Facade should not be null", facade);
    assertEquals("Unexpected facade class type", AmqpJmsObjectMessageFacade.class, facade.getClass());

    AmqpObjectTypeDelegate delegate = ((AmqpJmsObjectMessageFacade) facade).getDelegate();
    if (setJavaSerializedContentType) {
        assertTrue("Unexpected delegate type: " + delegate, delegate instanceof AmqpSerializedObjectDelegate);
    } else {
        assertTrue("Unexpected delegate type: " + delegate, delegate instanceof AmqpTypedObjectDelegate);
    }
}
 
Example 7
Source File: MessageTapTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Message createTestMessage(final String contentType, final String payload) {
    final Message msg = createTestMessageWithoutBody(payload);
    if (payload != null) {
        msg.setBody(new Data(new Binary(payload.getBytes(StandardCharsets.UTF_8))));
    }
    msg.setContentType(contentType);
    MessageHelper.setJsonPayload(msg, payload);
    return msg;
}
 
Example 8
Source File: MessageHelperTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the registered default content type is not set on a downstream message
 * that already contains a content type.
 */
@Test
public void testAddDefaultsDoesNotAddDefaultContentType() {

    final Message message = ProtonHelper.message();
    message.setContentType("application/existing");
    final ResourceIdentifier target = ResourceIdentifier.from(TelemetryConstants.TELEMETRY_ENDPOINT, Constants.DEFAULT_TENANT, "4711");
    final JsonObject defaults = new JsonObject()
            .put(MessageHelper.SYS_PROPERTY_CONTENT_TYPE, "application/hono");

    MessageHelper.addDefaults(message, target, defaults, TenantConstants.UNLIMITED_TTL);

    assertThat(message.getContentType()).isEqualTo("application/existing");
}
 
Example 9
Source File: MessageHelperTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the helper does not add JMS vendor properties for
 * empty content type.
 */
@Test
public void testAddJmsVendorPropertiesRejectsEmptyContentType() {

    final Message msg = ProtonHelper.message();
    msg.setContentType("");
    MessageHelper.addJmsVendorProperties(msg);
    assertThat(msg.getApplicationProperties()).isNull();;
}
 
Example 10
Source File: MessageHelperTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the helper adds JMS vendor properties for
 * non-empty content type.
 */
@Test
public void testAddJmsVendorPropertiesAddsContentType() {

    final Message msg = ProtonHelper.message();
    msg.setContentType("application/json");
    MessageHelper.addJmsVendorProperties(msg);
    assertThat(msg.getApplicationProperties().getValue().get(MessageHelper.JMS_VENDOR_PROPERTY_CONTENT_TYPE)).isEqualTo("application/json");
}
 
Example 11
Source File: AmqpJmsObjectMessageFacadeTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetObjectUsingReceivedMessageWithNonDataNonAmqvValueBinarySectionThrowsISE() throws Exception {
    Message message = Message.Factory.create();
    message.setContentType(AmqpMessageSupport.SERIALIZED_JAVA_OBJECT_CONTENT_TYPE.toString());
    message.setBody(new AmqpValue("nonBinarySectionContent"));

    AmqpJmsObjectMessageFacade amqpObjectMessageFacade = createReceivedObjectMessageFacade(createMockAmqpConsumer(), message);

    try {
        amqpObjectMessageFacade.getObject();
        fail("Expected exception to be thrown");
    } catch (IllegalStateException ise) {
        // expected
    }
}
 
Example 12
Source File: MessageHelper.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets the payload of an AMQP message using a <em>Data</em> section.
 *
 * @param message The message.
 * @param contentType The type of the payload. The message's <em>content-type</em> property
 *                    will only be set if both this and the payload parameter are not {@code null}.
 * @param payload The payload or {@code null} if there is no payload to convey in the message body.
 *
 * @throws NullPointerException If message is {@code null}.
 */
public static void setPayload(final Message message, final String contentType, final byte[] payload) {
    Objects.requireNonNull(message);

    if (payload != null) {
        message.setBody(new Data(new Binary(payload)));
        if (contentType != null) {
            message.setContentType(contentType);
        }
    }
}
 
Example 13
Source File: CommandAndControlAmqpIT.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private ProtonMessageHandler createCommandConsumer(final VertxTestContext ctx, final ProtonReceiver cmdReceiver,
        final ProtonSender cmdResponseSender) {

    return (delivery, msg) -> {
        ctx.verify(() -> {
            assertThat(msg.getReplyTo()).isNotNull();
            assertThat(msg.getSubject()).isNotNull();
            assertThat(msg.getCorrelationId()).isNotNull();
        });
        final String command = msg.getSubject();
        final Object correlationId = msg.getCorrelationId();
        log.debug("received command [name: {}, reply-to: {}, correlation-id: {}]", command, msg.getReplyTo(), correlationId);
        ProtonHelper.accepted(delivery, true);
        cmdReceiver.flow(1);
        // send response
        final Message commandResponse = ProtonHelper.message(command + " ok");
        commandResponse.setAddress(msg.getReplyTo());
        commandResponse.setCorrelationId(correlationId);
        commandResponse.setContentType("text/plain");
        MessageHelper.addProperty(commandResponse, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
        log.debug("sending response [to: {}, correlation-id: {}]", commandResponse.getAddress(), commandResponse.getCorrelationId());
        cmdResponseSender.send(commandResponse, updatedDelivery -> {
            if (!Accepted.class.isInstance(updatedDelivery.getRemoteState())) {
                log.error("AMQP adapter did not accept command response [remote state: {}]",
                        updatedDelivery.getRemoteState().getClass().getSimpleName());
            }
        });
    };
}
 
Example 14
Source File: AmqpUploadTestBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a message containing a payload which has the <em>emtpy notification</em>
 * content type is rejected by the adapter.
 *
 * @param context The Vert.x context for running asynchronous tests.
 * @throws InterruptedException if test is interrupted while running.
 */
@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 10)
public void testAdapterRejectsBadInboundMessage(final VertxTestContext context) throws InterruptedException {

    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);

    final VertxTestContext setup = new VertxTestContext();

    setupProtocolAdapter(tenantId, deviceId, false)
    .map(s -> {
        sender = s;
        return s;
    })
    .onComplete(setup.completing());

    assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        context.failNow(setup.causeOfFailure());
        return;
    }

    final Message msg = ProtonHelper.message("some payload");
    msg.setContentType(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION);
    msg.setAddress(getEndpointName());
    sender.send(msg, delivery -> {

        context.verify(() -> {
            assertThat(delivery.getRemoteState()).isInstanceOf(Rejected.class);
            final Rejected rejected = (Rejected) delivery.getRemoteState();
            final ErrorCondition error = rejected.getError();
            assertThat((Object) error.getCondition()).isEqualTo(Constants.AMQP_BAD_REQUEST);
        });
        context.completeNow();
    });

}
 
Example 15
Source File: CredentialsMessageFilterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a valid message passes the filter.
 */
@Test
public void testVerifySucceedsForValidGetAction() {

    // GIVEN a credentials message for user billie
    final Message msg = givenAValidMessageWithoutBody(CredentialsConstants.CredentialsAction.get);
    msg.setBody(new Data(new Binary(BILLIE_HASHED_PASSWORD.toBuffer().getBytes())));
    msg.setContentType("application/json");

    // WHEN receiving the message via a link with any tenant
    final boolean filterResult = CredentialsMessageFilter.verify(target, msg);

    // THEN message validation succeeds
    assertTrue(filterResult);
}
 
Example 16
Source File: CredentialsMessageFilterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a message containing a subject that does not represent
 * a Credentials API operation does not pass the filter.
 */
@Test
public void testVerifyFailsForUnknownAction() {

    // GIVEN a message with an unsupported subject
    final Message msg = givenAValidMessageWithoutBody(CredentialsConstants.CredentialsAction.unknown);
    msg.setBody(new AmqpValue(BILLIE_HASHED_PASSWORD));
    msg.setContentType("application/json");

    // WHEN receiving the message via a link with any tenant
    final boolean filterResult = CredentialsMessageFilter.verify(target, msg);

    // THEN message validation fails
    assertFalse(filterResult);
}
 
Example 17
Source File: MessageHelper.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private static Message addProperties(
        final Message message,
        final ResourceIdentifier target,
        final TenantObject tenant,
        final JsonObject deviceDefaultProperties,
        final boolean useDefaults,
        final boolean useJmsVendorProps) {

    final long maxTtl = Optional.ofNullable(tenant)
            .map(t -> Optional.ofNullable(t.getResourceLimits())
                .map(limits -> limits.getMaxTtl())
                .orElse(TenantConstants.UNLIMITED_TTL))
            .orElse(TenantConstants.UNLIMITED_TTL);

    if (useDefaults) {
        final JsonObject defaults = Optional.ofNullable(tenant)
                .map(t -> t.getDefaults().copy())
                .orElseGet(() -> new JsonObject());
        if (deviceDefaultProperties != null) {
            defaults.mergeIn(deviceDefaultProperties);
        }

        if (!defaults.isEmpty()) {
            addDefaults(message, target, defaults, maxTtl);
        }
    }
    if (Strings.isNullOrEmpty(message.getContentType())) {
        // set default content type if none has been specified when creating the
        // message nor a default content type is available
        message.setContentType(CONTENT_TYPE_OCTET_STREAM);
    }
    if (useJmsVendorProps) {
        addJmsVendorProperties(message);
    }

    // make sure that device provided TTL is capped at max TTL (if set)
    // AMQP spec defines TTL as milliseconds
    final long maxTtlMillis = maxTtl * 1000L;
    if (target.hasEventEndpoint() && maxTtl != TenantConstants.UNLIMITED_TTL) {
        if (message.getTtl() == 0) {
            LOG.debug("setting event's TTL to tenant's max TTL [{}ms]", maxTtlMillis);
            setTimeToLive(message, Duration.ofSeconds(maxTtl));
        } else if (message.getTtl() > maxTtlMillis) {
            LOG.debug("limiting device provided TTL [{}ms] to max TTL [{}ms]", message.getTtl(), maxTtlMillis);
            setTimeToLive(message, Duration.ofSeconds(maxTtl));
        } else {
            LOG.trace("keeping event's TTL [0 < {}ms <= max TTL ({}ms)]", message.getTtl(), maxTtlMillis);
        }
    }
    return message;
}
 
Example 18
Source File: AMQPMessageSupportTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testIsContentTypeWithNonNullStringValueAndNonNullMessageContentTypeNotEqual() {
   Message message = Proton.message();
   message.setContentType("fails");
   assertFalse(AMQPMessageSupport.isContentType("test", message));
}
 
Example 19
Source File: AMQPMessageSupportTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testIsContentTypeWithNonNullStringValueAndNonNullMessageContentTypeEqual() {
   Message message = Proton.message();
   message.setContentType("test");
   assertTrue(AMQPMessageSupport.isContentType("test", message));
}
 
Example 20
Source File: AMQPMessageSupportTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testIsContentTypeWithNullStringValueAndNonNullMessageContentType() {
   Message message = Proton.message();
   message.setContentType("test");
   assertFalse(AMQPMessageSupport.isContentType(null, message));
}