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

The following examples show how to use org.apache.qpid.proton.message.Message#setMessageId() . 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: TenantMessageFilterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the filter detects a missing subject.
 */
@Test
public void testVerifyDetectsMissingSubject() {

    // GIVEN a request message without a subject
    final Message msg = ProtonHelper.message();
    msg.setMessageId("msg");
    msg.setReplyTo("reply");
    // WHEN receiving the message via a link with any tenant
    final ResourceIdentifier linkTarget = getResourceIdentifier(DEFAULT_TENANT);

    // THEN message validation fails
    assertFalse(TenantMessageFilter.verify(linkTarget, msg));
}
 
Example 2
Source File: TenantMessageFilterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Message givenAMessageHavingProperties(final TenantConstants.TenantAction action) {
    final Message msg = ProtonHelper.message();
    msg.setMessageId("msg");
    msg.setReplyTo("reply");
    msg.setSubject(action.toString());
    return msg;
}
 
Example 3
Source File: RegistrationMessageFilterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static Message givenAMessageHavingProperties(final String deviceId, final String action) {
    final Message msg = ProtonHelper.message();
    msg.setMessageId("msg-id");
    msg.setReplyTo("reply");
    msg.setSubject(action);
    if (deviceId != null) {
        MessageHelper.addDeviceId(msg, deviceId);
    }
    return msg;
}
 
Example 4
Source File: CredentialsMessageFilterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static Message givenAValidMessageWithoutBody(final CredentialsConstants.CredentialsAction action) {
    final Message msg = ProtonHelper.message();
    msg.setMessageId("msg");
    msg.setReplyTo("reply");
    msg.setSubject(action.toString());
    return msg;
}
 
Example 5
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 6
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 7
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 8
Source File: TelemetrySenderImpl.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Sends an AMQP 1.0 message to the peer this client is configured for.
 *
 * @param message The message to send.
 * @param currentSpan The <em>OpenTracing</em> span used to trace the sending of the message.
 *              The span will be finished by this method and will contain an error log if
 *              the message has not been accepted by the peer.
 * @return A future indicating the outcome of the operation.
 *         <p>
 *         The future will succeed if the message has been sent to the peer.
 *         The delivery contained in the future will represent the delivery
 *         state at the time the future has been succeeded, i.e. it will be
 *         locally <em>unsettled</em> without any outcome yet.
 *         <p>
 *         The future will be failed with a {@link ServiceInvocationException} if the
 *         message could not be sent.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
@Override
protected Future<ProtonDelivery> sendMessage(final Message message, final Span currentSpan) {

    Objects.requireNonNull(message);
    Objects.requireNonNull(currentSpan);

    final String messageId = String.format("%s-%d", getClass().getSimpleName(), MESSAGE_COUNTER.getAndIncrement());
    message.setMessageId(messageId);
    logMessageIdAndSenderInfo(currentSpan, messageId);

    final ClientConfigProperties config = connection.getConfig();
    final AtomicBoolean timeoutReached = new AtomicBoolean(false);
    final Long timerId = config.getSendMessageTimeout() > 0
            ? connection.getVertx().setTimer(config.getSendMessageTimeout(), id -> {
                if (timeoutReached.compareAndSet(false, true)) {
                    final ServerErrorException exception = new ServerErrorException(
                            HttpURLConnection.HTTP_UNAVAILABLE,
                            "waiting for delivery update timed out after " + config.getSendMessageTimeout() + "ms");
                    logMessageSendingError(
                            "waiting for delivery update timed out for message [ID: {}, address: {}] after {}ms",
                            messageId, getMessageAddress(message), connection.getConfig().getSendMessageTimeout());
                    TracingHelper.logError(currentSpan, exception.getMessage());
                    Tags.HTTP_STATUS.set(currentSpan, HttpURLConnection.HTTP_UNAVAILABLE);
                    currentSpan.finish();
                }
            })
            : null;

    final ProtonDelivery result = sender.send(message, deliveryUpdated -> {
        if (timerId != null) {
            connection.getVertx().cancelTimer(timerId);
        }
        final DeliveryState remoteState = deliveryUpdated.getRemoteState();
        if (timeoutReached.get()) {
            log.debug("ignoring received delivery update for message [ID: {}, address: {}]: waiting for the update has already timed out",
                    messageId, getMessageAddress(message));
        } else if (deliveryUpdated.remotelySettled()) {
            logUpdatedDeliveryState(currentSpan, message, deliveryUpdated);
        } else {
            logMessageSendingError("peer did not settle message [ID: {}, address: {}, remote state: {}], failing delivery",
                    messageId, getMessageAddress(message), remoteState.getClass().getSimpleName());
            TracingHelper.logError(currentSpan, new ServerErrorException(
                    HttpURLConnection.HTTP_INTERNAL_ERROR,
                    "peer did not settle message, failing delivery"));
        }
        currentSpan.finish();
    });
    log.trace("sent message [ID: {}, address: {}], remaining credit: {}, queued messages: {}", messageId,
            getMessageAddress(message), sender.getCredit(), sender.getQueued());

    return Future.succeededFuture(result);
}
 
Example 9
Source File: CommandClientImpl.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Future<Void> sendOneWayCommand(
        final String deviceId,
        final String command,
        final String contentType,
        final Buffer data,
        final Map<String, Object> properties) {

    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(command);

    final Span currentSpan = newChildSpan(null, command);
    TracingHelper.setDeviceTags(currentSpan, getTenantId(), deviceId);

    if (sender.isOpen()) {
        final Promise<BufferResult> responseTracker = Promise.promise();
        final Message request = ProtonHelper.message();

        AbstractHonoClient.setApplicationProperties(request, properties);

        final String messageId = createMessageId();
        request.setAddress(getTargetAddress(getTenantId(), deviceId));
        request.setMessageId(messageId);
        request.setSubject(command);

        MessageHelper.setPayload(request, contentType, data);
        sendRequest(request, responseTracker, null, currentSpan);

        return responseTracker.future()
                .recover(t -> {
                    Tags.HTTP_STATUS.set(currentSpan, ServiceInvocationException.extractStatusCode(t));
                    TracingHelper.logError(currentSpan, t);
                    currentSpan.finish();
                    return Future.failedFuture(t);
                }).map(ignore -> {
                    Tags.HTTP_STATUS.set(currentSpan, HttpURLConnection.HTTP_ACCEPTED);
                    currentSpan.finish();
                    return null;
                });
    } else {
        Tags.HTTP_STATUS.set(currentSpan, HttpURLConnection.HTTP_UNAVAILABLE);
        TracingHelper.logError(currentSpan, "sender link is not open");
        currentSpan.finish();
        return Future.failedFuture(new ServerErrorException(
                HttpURLConnection.HTTP_UNAVAILABLE, "sender link is not open"));
    }
}
 
Example 10
Source File: CommandAndControlAmqpIT.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that the adapter rejects malformed command messages sent by applications.
 *
 * @param endpointConfig The endpoints to use for sending/receiving commands.
 * @param ctx The vert.x test context.
 * @throws InterruptedException if not all commands and responses are exchanged in time.
 */
@ParameterizedTest(name = IntegrationTestSupport.PARAMETERIZED_TEST_NAME_PATTERN)
@MethodSource("allCombinations")
@Timeout(timeUnit = TimeUnit.SECONDS, value = 10)
public void testSendCommandFailsForMalformedMessage(
        final AmqpCommandEndpointConfiguration endpointConfig,
        final VertxTestContext ctx) throws InterruptedException {

    final String commandTargetDeviceId = endpointConfig.isSubscribeAsGateway()
            ? helper.setupGatewayDeviceBlocking(tenantId, deviceId, 5)
            : deviceId;

    final AtomicReference<MessageSender> sender = new AtomicReference<>();
    final String targetAddress = endpointConfig.getSenderLinkTargetAddress(tenantId);

    final VertxTestContext setup = new VertxTestContext();
    final Checkpoint preconditions = setup.checkpoint(2);

    connectToAdapter(tenantId, tenant, deviceId, password, () -> createEventConsumer(tenantId, msg -> {
        // expect empty notification with TTD -1
        ctx.verify(() -> assertThat(msg.getContentType()).isEqualTo(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION));
        final TimeUntilDisconnectNotification notification = TimeUntilDisconnectNotification.fromMessage(msg).orElse(null);
        log.debug("received notification [{}]", notification);
        ctx.verify(() -> assertThat(notification).isNotNull());
        if (notification.getTtd() == -1) {
            preconditions.flag();
        }
    }))
    .compose(con -> subscribeToCommands(endpointConfig, tenantId, commandTargetDeviceId)
        .map(recv -> {
            recv.handler((delivery, msg) -> ctx
                    .failNow(new IllegalStateException("should not have received command")));
            return null;
        }))
    .compose(ok -> helper.applicationClientFactory.createGenericMessageSender(targetAddress))
    .map(s -> {
        log.debug("created generic sender for sending commands [target address: {}]", targetAddress);
        sender.set(s);
        preconditions.flag();
        return s;
    })
    .onComplete(setup.completing());

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

    final Checkpoint expectedFailures = ctx.checkpoint(2);

    log.debug("sending command message lacking subject");
    final Message messageWithoutSubject = ProtonHelper.message("input data");
    messageWithoutSubject.setAddress(endpointConfig.getCommandMessageAddress(tenantId, commandTargetDeviceId));
    messageWithoutSubject.setMessageId("message-id");
    messageWithoutSubject.setReplyTo("reply/to/address");
    sender.get().sendAndWaitForOutcome(messageWithoutSubject).onComplete(ctx.failing(t -> {
        ctx.verify(() -> assertThat(t).isInstanceOf(ClientErrorException.class));
        expectedFailures.flag();
    }));

    log.debug("sending command message lacking message ID and correlation ID");
    final Message messageWithoutId = ProtonHelper.message("input data");
    messageWithoutId.setAddress(endpointConfig.getCommandMessageAddress(tenantId, commandTargetDeviceId));
    messageWithoutId.setSubject("setValue");
    messageWithoutId.setReplyTo("reply/to/address");
    sender.get().sendAndWaitForOutcome(messageWithoutId).onComplete(ctx.failing(t -> {
        ctx.verify(() -> assertThat(t).isInstanceOf(ClientErrorException.class));
        expectedFailures.flag();
    }));
}
 
Example 11
Source File: CommandAndControlMqttIT.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that the adapter rejects malformed command messages sent by applications.
 *
 * @param endpointConfig The endpoints to use for sending/receiving commands.
 * @param ctx The vert.x test context.
 * @throws InterruptedException if not all commands and responses are exchanged in time.
 */
@ParameterizedTest(name = IntegrationTestSupport.PARAMETERIZED_TEST_NAME_PATTERN)
@MethodSource("allCombinations")
@Timeout(timeUnit = TimeUnit.SECONDS, value = 20)
public void testSendCommandFailsForMalformedMessage(
        final MqttCommandEndpointConfiguration endpointConfig,
        final VertxTestContext ctx) throws InterruptedException {

    final VertxTestContext setup = new VertxTestContext();
    final Checkpoint ready = setup.checkpoint(3);

    final String commandTargetDeviceId = endpointConfig.isSubscribeAsGateway()
            ? helper.setupGatewayDeviceBlocking(tenantId, deviceId, 5)
            : deviceId;

    helper.registry
            .addDeviceForTenant(tenantId, tenant, deviceId, password)
            .compose(ok -> connectToAdapter(IntegrationTestSupport.getUsername(deviceId, tenantId), password))
            .compose(ok -> createConsumer(tenantId, msg -> {
                // expect empty notification with TTD -1
                setup.verify(() -> assertThat(msg.getContentType()).isEqualTo(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION));
                final TimeUntilDisconnectNotification notification = TimeUntilDisconnectNotification
                        .fromMessage(msg).orElse(null);
                LOGGER.info("received notification [{}]", notification);
                if (notification.getTtd() == -1) {
                    ready.flag();
                }
            }))
            .compose(conAck -> subscribeToCommands(commandTargetDeviceId, msg -> {
                setup.failNow(new IllegalStateException("should not have received command"));
            }, endpointConfig, MqttQoS.AT_MOST_ONCE))
            .onComplete(ctx.succeeding(ok -> ready.flag()));

    final AtomicReference<MessageSender> sender = new AtomicReference<>();
    final String linkTargetAddress = endpointConfig.getSenderLinkTargetAddress(tenantId);

    helper.applicationClientFactory.createGenericMessageSender(linkTargetAddress)
    .map(s -> {
        LOGGER.debug("created generic sender for sending commands [target address: {}]", linkTargetAddress);
        sender.set(s);
        ready.flag();
        return s;
    });

    assertThat(setup.awaitCompletion(15, TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        ctx.failNow(setup.causeOfFailure());
    }

    final Checkpoint failedAttempts = ctx.checkpoint(2);
    final String messageAddress = endpointConfig.getCommandMessageAddress(tenantId, commandTargetDeviceId);

    LOGGER.debug("sending command message lacking subject");
    final Message messageWithoutSubject = ProtonHelper.message("input data");
    messageWithoutSubject.setAddress(messageAddress);
    messageWithoutSubject.setMessageId("message-id");
    messageWithoutSubject.setReplyTo("reply/to/address");
    sender.get().sendAndWaitForOutcome(messageWithoutSubject).onComplete(ctx.failing(t -> {
        ctx.verify(() -> assertThat(t).isInstanceOf(ClientErrorException.class));
        failedAttempts.flag();
    }));

    LOGGER.debug("sending command message lacking message ID and correlation ID");
    final Message messageWithoutId = ProtonHelper.message("input data");
    messageWithoutId.setAddress(messageAddress);
    messageWithoutId.setSubject("setValue");
    messageWithoutId.setReplyTo("reply/to/address");
    sender.get().sendAndWaitForOutcome(messageWithoutId).onComplete(ctx.failing(t -> {
        ctx.verify(() -> assertThat(t).isInstanceOf(ClientErrorException.class));
        failedAttempts.flag();
    }));
}
 
Example 12
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;
}
 
Example 13
Source File: AmqpSendReceiveTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
private void doTestBrokerRestartAndDurability(boolean durable, boolean enforceHeader, boolean explicitSetNonDurable) throws Exception {
   AmqpClient client = createAmqpClient();
   AmqpConnection connection = addConnection(client.connect());
   AmqpSession session = connection.createSession();

   AmqpSender sender = session.createSender(getQueueName());

   final Queue queueView1 = getProxyToQueue(getQueueName());

   Message protonMessage = Message.Factory.create();
   protonMessage.setMessageId("ID:Message:1");
   protonMessage.setBody(new AmqpValue("Test-Message -> " + (durable ? "durable" : "non-durable")));
   if (durable || enforceHeader) {
      Header header = new Header();
      if (durable) {
         header.setDurable(true);
      } else {
         if (explicitSetNonDurable) {
            header.setDurable(false);
         } else {
            // Set priority so the durable field gets defaulted
            header.setPriority(UnsignedByte.valueOf((byte) 5));
            assertNull(header.getDurable());
         }
      }

      protonMessage.setHeader(header);
   } else {
      assertNull("Should not have a header", protonMessage.getHeader());
   }

   AmqpMessage message = new AmqpMessage(protonMessage);

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

   Wait.assertEquals(1, queueView1::getMessageCount);

   // Restart the server and the Queue should be empty
   // if the message was non-durable
   server.stop();
   server.start();

   // Reconnect now
   connection = addConnection(client.connect());
   session = connection.createSession();
   AmqpReceiver receiver = session.createReceiver(getQueueName());

   final Queue queueView2 = getProxyToQueue(getQueueName());
   if (durable) {
      Wait.assertTrue("Message should not have returned", () -> queueView2.getMessageCount() == 1);
   } else {
      Wait.assertTrue("Message should have been restored", () -> queueView2.getMessageCount() == 0);
   }

   receiver.flow(1);
   message = receiver.receive(1, TimeUnit.SECONDS);

   if (durable) {
      assertNotNull("Should have read a message", message);
   } else {
      assertNull("Should not have read a message", message);
   }

   connection.close();
}
 
Example 14
Source File: AbstractRequestResponseClient.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates an AMQP message for a subject and address.
 * <p>
 * The message can be extended by arbitrary application properties passed in.
 *
 * @param subject The subject system property of the message.
 * @param address The address of the message, put in the <em>to</em> property.
 * @param appProperties The map containing arbitrary application properties.
 *                      Maybe null if no application properties are needed.
 * @return The Proton message constructed from the provided parameters.
 * @throws NullPointerException if the subject is {@code null}.
 * @throws IllegalArgumentException if the application properties contain not AMQP 1.0 compatible values
 *                  (see {@link AbstractHonoClient#setApplicationProperties(Message, Map)}
 */
private Message createMessage(final String subject, final String address,
        final Map<String, Object> appProperties) {

    Objects.requireNonNull(subject);
    final Message msg = ProtonHelper.message();
    final String messageId = createMessageId();
    AbstractHonoClient.setApplicationProperties(msg, appProperties);
    msg.setAddress(address);
    msg.setReplyTo(replyToAddress);
    msg.setMessageId(messageId);
    msg.setSubject(subject);
    return msg;
}