org.apache.qpid.proton.message.Message Java Examples

The following examples show how to use org.apache.qpid.proton.message.Message. 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: DeviceConnectionMessageFilter.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Checks whether a given device connection message contains all required properties.
 *
 * @param linkTarget The resource path to check the message's properties against for consistency.
 * @param msg The AMQP 1.0 message to perform the checks on.
 * @return {@code true} if the message passes all checks.
 */
public static boolean verify(final ResourceIdentifier linkTarget, final Message msg) {

    final Object correlationId = MessageHelper.getCorrelationId(msg);

    if (!hasValidDeviceId(linkTarget, msg)) {
        return false;
    } else if (correlationId == null) {
        LOG.trace("message has neither a message-id nor correlation-id");
        return false;
    } else if (msg.getSubject() == null) {
        LOG.trace("message [correlation ID: {}] does not contain a subject", correlationId);
        return false;
    } else if (msg.getReplyTo() == null) {
        LOG.trace("message [correlation ID: {}] contains no reply-to address", correlationId);
        return false;
    } else {
        return true;
    }
}
 
Example #2
Source File: MessageHelperTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the current system time is set on a downstream message
 * if the message doesn't contain a creation time.
 */
@Test
public void testAddPropertiesSetsCreationTime() {

    final Message message = ProtonHelper.message();
    assertThat(message.getCreationTime()).isEqualTo(0);

    MessageHelper.addProperties(
            message,
            ResourceIdentifier.fromString("telemetry/DEFAULT_TENANT/4711"),
            null,
            null,
            null,
            null,
            null,
            "custom-adapter",
            true,
            true);

    assertThat(message.getCreationTime()).isGreaterThan(0);
}
 
Example #3
Source File: AmqpJmsMessageFacadeTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetCorrelationIdBytesOnReceievedMessageWithBinaryId() throws Exception {
    Binary testCorrelationId = createBinaryId();
    byte[] bytes = testCorrelationId.getArray();

    Data payloadData = Data.Factory.create();
    PropertiesDescribedType props = new PropertiesDescribedType();
    props.setCorrelationId(new Binary(bytes));
    payloadData.putDescribedType(props);
    Binary b = payloadData.encode();

    System.out.println("Using encoded AMQP message payload: " + b);

    Message message = Proton.message();
    int decoded = message.decode(b.getArray(), b.getArrayOffset(), b.getLength());
    assertEquals(decoded, b.getLength());

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

    assertEquals("Unexpected correlationId value on underlying AMQP message", testCorrelationId, amqpMessageFacade.getProperties().getCorrelationId());
    assertArrayEquals("Expected correlationId bytes not returned", bytes, amqpMessageFacade.getCorrelationIdBytes());
}
 
Example #4
Source File: AmqpCodecTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
/**
 * Test that a receiving a data body containing nothing and no content type being set
 * results in a BytesMessage 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 testCreateBytesMessageFromDataWithEmptyBinaryAndNoContentType() throws Exception {
    Message message = Proton.message();
    Binary binary = new Binary(new byte[0]);
    message.setBody(new Data(binary));

    assertNull(message.getContentType());

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

    JmsMessageFacade facade = jmsMessage.getFacade();
    assertNotNull("Facade should not be null", facade);
    assertEquals("Unexpected facade class type", AmqpJmsBytesMessageFacade.class, facade.getClass());
}
 
Example #5
Source File: RegistrationClientImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the client includes the required information in the request
 * message sent to the Device Registration service.
 */
@Test
public void testGetRegistrationInfoIncludesRequiredParamsInRequest() {

    // GIVEN an adapter without a cache

    // WHEN getting registration information
    client.assertRegistration("device", "gateway");

    // THEN the message being sent contains the device ID and the gateway ID
    final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    verify(sender).send(messageCaptor.capture(), VertxMockSupport.anyHandler());
    final Message sentMessage = messageCaptor.getValue();
    assertThat(MessageHelper.getDeviceId(sentMessage)).isEqualTo("device");
    assertThat(
            MessageHelper.getApplicationProperty(
                    sentMessage.getApplicationProperties(),
                    MessageHelper.APP_PROPERTY_GATEWAY_ID,
                    String.class))
            .isEqualTo("gateway");
}
 
Example #6
Source File: AMQPMessageTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetScheduledDeliveryTimeMessageSentWithFixedTime() {
   final long scheduledTime = System.currentTimeMillis();
   final long newScheduledTime = System.currentTimeMillis() + 1000;

   MessageImpl protonMessage = (MessageImpl) Message.Factory.create();
   MessageAnnotations annotations = new MessageAnnotations(new HashMap<>());
   annotations.getValue().put(AMQPMessageSupport.SCHEDULED_DELIVERY_TIME, scheduledTime);
   protonMessage.setMessageAnnotations(annotations);
   AMQPStandardMessage decoded = encodeAndDecodeMessage(protonMessage);

   assertEquals(scheduledTime, decoded.getScheduledDeliveryTime().longValue());

   decoded.setScheduledDeliveryTime(newScheduledTime);
   assertEquals(newScheduledTime, decoded.getScheduledDeliveryTime().longValue());
   decoded.reencode();
   assertEquals(newScheduledTime, decoded.getMessageAnnotations().getValue().get(AMQPMessageSupport.SCHEDULED_DELIVERY_TIME));
}
 
Example #7
Source File: DeviceConnectionClientImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the client handles the response of the <em>set-cmd-handling-adapter-instance</em> operation from the
 * Device Connection service.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testSetCommandHandlingAdapterInstance(final VertxTestContext ctx) {

    // WHEN setting the command handling adapter instance
    client.setCommandHandlingAdapterInstance("deviceId", "adapterInstanceId", null, span.context())
            .onComplete(ctx.succeeding(r -> {
                ctx.verify(() -> {
                    // THEN the response has been handled and the span is finished
                    verify(span).finish();
                });
                ctx.completeNow();
            }));

    final Message sentMessage = verifySenderSend();
    final Message response = createNoContentResponseMessage(sentMessage.getMessageId());
    client.handleResponse(mock(ProtonDelivery.class), response);
}
 
Example #8
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 that has an empty reply-to property.
 * Verifies that the replyToId is {@code null} and the command reports that it is a one-way command.
 */
@Test
public void testFromMessageSucceedsWithoutReplyTo() {
    final String correlationId = "the-correlation-id";
    final Message message = mock(Message.class);
    when(message.getAddress()).thenReturn(String.format("%s/%s/%s",
            CommandConstants.COMMAND_ENDPOINT, Constants.DEFAULT_TENANT, "4711"));
    when(message.getSubject()).thenReturn("doThis");
    when(message.getCorrelationId()).thenReturn(correlationId);
    final Command cmd = Command.from(message, Constants.DEFAULT_TENANT, "4711");
    assertTrue(cmd.isValid());
    assertThat(cmd.getName()).isEqualTo("doThis");
    assertThat(cmd.getCorrelationId()).isEqualTo(correlationId);
    assertThat(cmd.getReplyToId()).isNull();;
    assertTrue(cmd.isOneWay());
}
 
Example #9
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 having no device-id as part of the reply-to address.
 * Verifies that the reply-to address contains the device-id and the reply-id is prefixed with flag 1.
 */
@Test
public void testForReplyToWithoutDeviceId() {
    final String replyToId = "the-reply-to-id";
    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, "4711"));
    message.setSubject("doThis");
    message.setCorrelationId(correlationId);
    message.setReplyTo(String.format("%s/%s/%s",
            CommandConstants.NORTHBOUND_COMMAND_RESPONSE_ENDPOINT, Constants.DEFAULT_TENANT, replyToId));
    final boolean replyToContainedDeviceId = false;
    final String replyToOptionsBitFlag = Command.encodeReplyToOptions(replyToContainedDeviceId);
    final Command cmd = Command.from(message, Constants.DEFAULT_TENANT, "4711");
    assertTrue(cmd.isValid());
    assertThat(cmd.getReplyToId()).isEqualTo(replyToId);
    assertThat(cmd.getCommandMessage()).isNotNull();
    assertThat(cmd.getCommandMessage().getReplyTo()).isNotNull();
    assertThat(cmd.getCommandMessage().getReplyTo()).isEqualTo(String.format("%s/%s/%s/%s%s",
            CommandConstants.COMMAND_RESPONSE_ENDPOINT, Constants.DEFAULT_TENANT, "4711", replyToOptionsBitFlag, replyToId));
}
 
Example #10
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 #11
Source File: AmqpDefaultMessageConverter.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
@Override
public Message toMessage(String address, KafkaConsumerRecord<String, byte[]> record) {

    Message message = Proton.message();
    message.setAddress(address);

    // put message annotations about partition, offset and key (if not null)
    Map<Symbol, Object> map = new HashMap<>();
    map.put(Symbol.valueOf(AmqpBridge.AMQP_PARTITION_ANNOTATION), record.partition());
    map.put(Symbol.valueOf(AmqpBridge.AMQP_OFFSET_ANNOTATION), record.offset());
    map.put(Symbol.valueOf(AmqpBridge.AMQP_KEY_ANNOTATION), record.key());
    map.put(Symbol.valueOf(AmqpBridge.AMQP_TOPIC_ANNOTATION), record.topic());

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

    message.setBody(new Data(new Binary(record.value())));

    return message;
}
 
Example #12
Source File: AMQPMessageTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonDurableMessageReencodedToDurable() {
   MessageImpl protonMessage = (MessageImpl) Message.Factory.create();
   protonMessage.setHeader(new Header());
   AMQPStandardMessage decoded = encodeAndDecodeMessage(protonMessage);
   assertFalse(decoded.isDurable());

   // Underlying message data not updated yet
   assertNull(decoded.getHeader().getDurable());

   decoded.setDurable(true);
   decoded.reencode();
   assertTrue(decoded.isDurable());

   // Underlying message data now updated
   assertTrue(decoded.getHeader().getDurable());
}
 
Example #13
Source File: AmqpReceiver.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void processDelivery(Delivery incoming) throws Exception {
   doDeliveryInspection(incoming);

   Message message = null;
   try {
      message = decodeIncomingMessage(incoming);
   } catch (Exception e) {
      LOG.warn("Error on transform: {}", e.getMessage());
      deliveryFailed(incoming, true);
      return;
   }

   AmqpMessage amqpMessage = new AmqpMessage(this, message, incoming);
   // Store reference to envelope in delivery context for recovery
   incoming.setContext(amqpMessage);
   prefetch.add(amqpMessage);

   // We processed a message, signal completion
   // of a message pull request if there is one.
   if (pullRequest != null) {
      pullRequest.onSuccess();
      pullRequest = null;
   }
}
 
Example #14
Source File: MessageHelperTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the fall back content type is set on a downstream message
 * if no default has been configured for the device.
 */
@Test
public void testAddPropertiesAddsFallbackContentType() {

    final Message message = ProtonHelper.message();
    message.setAddress("telemetry/DEFAULT_TENANT/4711");
    MessageHelper.addProperties(
            message,
            null,
            null,
            null,
            null,
            null,
            null,
            "custom",
            true,
            false);

    assertThat(message.getContentType()).isEqualTo(MessageHelper.CONTENT_TYPE_OCTET_STREAM);
}
 
Example #15
Source File: AbstractRequestResponseClientTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the adapter puts the response from the service to the cache
 * using the default cache timeout if the response does not contain a
 * <em>no-cache</em> cache directive.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateAndSendRequestAddsResponseToCache(final VertxTestContext ctx) {

    // GIVEN an adapter with an empty cache
    client.setResponseCache(cache);

    // WHEN sending a request
    client.createAndSendRequest("get", (Buffer) null, ctx.succeeding(result -> {
        assertEquals(200, result.getStatus());
        // THEN the response has been put to the cache
        verify(cache).put(eq("cacheKey"), any(SimpleRequestResponseResult.class),
                eq(Duration.ofSeconds(RequestResponseClientConfigProperties.DEFAULT_RESPONSE_CACHE_TIMEOUT)));
        ctx.completeNow();
    }), "cacheKey");
    final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    verify(sender).send(messageCaptor.capture(), VertxMockSupport.anyHandler());
    final Message response = ProtonHelper.message("result");
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
    response.setCorrelationId(messageCaptor.getValue().getMessageId());
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    client.handleResponse(delivery, response);
}
 
Example #16
Source File: AmqpJmsMessageFacadeTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetRedeliveredWhenAlreadyRedeliveredDoesNotChangeDeliveryCount() {
    Message message = Proton.message();
    Header header = new Header();
    header.setDeliveryCount(new UnsignedInteger(1));
    message.setHeader(header);

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

    // Redelivered state inferred from delivery count
    assertTrue(amqpMessageFacade.isRedelivered());
    assertEquals(1, amqpMessageFacade.getRedeliveryCount());;

    amqpMessageFacade.setRedelivered(true);
    assertTrue(amqpMessageFacade.isRedelivered());
    assertEquals(1, amqpMessageFacade.getRedeliveryCount());;
}
 
Example #17
Source File: VertxProtonExamples.java    From vertx-proton with Apache License 2.0 6 votes vote down vote up
public void example2(ProtonConnection connection) {
  connection.createSender("myQueue").openHandler(openResult -> {
    if (openResult.succeeded()) {
      ProtonSender sender = openResult.result();

      Message message = message();
      message.setBody(new AmqpValue("Hello World"));

      // Send message, providing an onUpdated delivery handler that prints updates
      sender.send(message, delivery -> {
        System.out.println(String.format("Message received by server: remote state=%s, remotely settled=%s",
                                         delivery.getRemoteState(), delivery.remotelySettled()));
      });
    }
  }).open();
}
 
Example #18
Source File: AmqpIOTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testRead() throws Exception {
  PCollection<Message> output =
      pipeline.apply(
          AmqpIO.read()
              .withMaxNumRecords(100)
              .withAddresses(Collections.singletonList(broker.getQueueUri("testRead"))));
  PAssert.thatSingleton(output.apply(Count.globally())).isEqualTo(100L);

  Messenger sender = Messenger.Factory.create();
  sender.start();
  for (int i = 0; i < 100; i++) {
    Message message = Message.Factory.create();
    message.setAddress(broker.getQueueUri("testRead"));
    message.setBody(new AmqpValue("Test " + i));
    sender.put(message);
    sender.send();
  }
  sender.stop();

  pipeline.run();
}
 
Example #19
Source File: AmqpJmsMessageFacadeTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
private void correlationIdOnReceivedMessageTestImpl(final Object testCorrelationId, final String expected, boolean appSpecificCorrelationId) {
    Message message = Proton.message();

    Properties props = new Properties();
    props.setCorrelationId(testCorrelationId);
    message.setProperties(props);

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

    String result = amqpMessageFacade.getCorrelationId();
    assertNotNull("Expected a correlationId on received message", result);
    assertEquals("Incorrect correlationId value received", expected, result);
    if(!appSpecificCorrelationId) {
        assertTrue("Should have have 'ID:' prefix", result.startsWith(AmqpMessageIdHelper.JMS_ID_PREFIX));
    }
}
 
Example #20
Source File: AbstractRequestResponseClient.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private R getRequestResponseResult(final Message message) {

        final Integer status = MessageHelper.getStatus(message);
        if (status == null) {
            LOG.debug("response message has no status code application property [reply-to: {}, correlation ID: {}]",
                    replyToAddress, message.getCorrelationId());
            return null;
        } else {
            final CacheDirective cacheDirective = CacheDirective.from(MessageHelper.getCacheDirective(message));
            return getResult(
                    status,
                    message.getContentType(),
                    MessageHelper.getPayload(message),
                    cacheDirective,
                    message.getApplicationProperties());
        }
    }
 
Example #21
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 #22
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 #23
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 #24
Source File: TransportImplTest.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
private void handleTransfer(TransportImpl transport, int deliveryNumber, String deliveryTag, String messageContent)
{
    byte[] tag = deliveryTag.getBytes(StandardCharsets.UTF_8);

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

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

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

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

    transport.handleFrame(new TransportFrame(0, transfer, new Binary(encoded, 0, len)));
}
 
Example #25
Source File: AmqpJmsMessageFacadeTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetPropertiesWithoutAnyApplicationPropertiesSection() throws Exception {
    Message message = Proton.message();
    JmsMessageFacade amqpMessageFacade = createReceivedMessageFacade(createMockAmqpConsumer(), message);

    Set<String> applicationProperties = amqpMessageFacade.getPropertyNames();
    assertNotNull(applicationProperties);
    assertTrue(applicationProperties.isEmpty());
}
 
Example #26
Source File: DeviceConnectionClientImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a client invocation of the <em>set-last-known-gateway</em> operation fails
 * if the device connection service cannot be reached.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testSetLastKnownGatewayForDeviceFailsWithRejectedRequest(final VertxTestContext ctx) {

    // GIVEN a client with no credit left
    final ProtonDelivery update = mock(ProtonDelivery.class);
    when(update.getRemoteState()).thenReturn(new Rejected());
    when(update.remotelySettled()).thenReturn(true);
    when(sender.send(any(Message.class), VertxMockSupport.anyHandler())).thenAnswer(invocation -> {
        final Handler<ProtonDelivery> dispositionHandler = invocation.getArgument(1);
        dispositionHandler.handle(update);
        return mock(ProtonDelivery.class);
    });

    // WHEN setting last known gateway information
    client.setLastKnownGatewayForDevice("deviceId", "gatewayId", span.context())
            .onComplete(ctx.failing(t -> {
                ctx.verify(() -> {
                    assertThat(((ServiceInvocationException) t).getErrorCode()).isEqualTo(HttpURLConnection.HTTP_BAD_REQUEST);
                    // THEN the invocation fails and the span is marked as erroneous
                    verify(span).setTag(eq(Tags.ERROR.getKey()), eq(Boolean.TRUE));
                    // and the span is finished
                    verify(span).finish();
                });
                ctx.completeNow();
            }));
}
 
Example #27
Source File: AMQPMessage.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public final org.apache.activemq.artemis.api.core.Message setRoutingType(RoutingType routingType) {
   if (routingType == null) {
      removeMessageAnnotation(AMQPMessageSupport.ROUTING_TYPE);
   } else {
      setMessageAnnotation(AMQPMessageSupport.ROUTING_TYPE, routingType.getType());
   }
   return this;
}
 
Example #28
Source File: CredentialsMessageFilterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a message containing a non Data section body
 * does not pass the filter.
 */
@Test
public void testVerifyFailsForNonDataSectionBody() {

    // GIVEN a message with an unsupported subject
    final Message msg = givenAValidMessageWithoutBody(CredentialsConstants.CredentialsAction.get);
    msg.setBody(new AmqpValue(BILLIE_HASHED_PASSWORD.encode()));
    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 #29
Source File: PubSubBroker.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public synchronized void sendMessages(String address, List<String> messages) {
    Queue<Message> queue = queues.computeIfAbsent(address, a -> new ArrayDeque<>());
    for (String data : messages) {
        Message message = Proton.message();
        message.setBody(new AmqpValue(data));
        queue.add(message);
    }
}
 
Example #30
Source File: ClientUtils.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private boolean canConnectWithAmqpAddress(ResourceManager resourceManager, AddressSpace addressSpace, UserCredentials credentials, AddressType addressType, String address, boolean defaultValue) throws Exception {
    Set<AddressType> brokeredAddressTypes = new HashSet<>(Arrays.asList(AddressType.QUEUE, AddressType.TOPIC));
    if (AddressSpaceUtils.isBrokered(addressSpace) && !brokeredAddressTypes.contains(addressType)) {
        return defaultValue;
    }
    try (AmqpClient client = resourceManager.getAmqpClientFactory().createAddressClient(addressSpace, addressType)) {
        client.getConnectOptions().setCredentials(credentials);
        ProtonClientOptions protonClientOptions = client.getConnectOptions().getProtonClientOptions();
        protonClientOptions.setLogActivity(true);
        client.getConnectOptions().setProtonClientOptions(protonClientOptions);

        try {
            Future<List<Message>> received = client.recvMessages(address, 1);
            Future<Integer> sent = client.sendMessages(address, Collections.singletonList("msg1"));

            int numReceived = received.get(1, TimeUnit.MINUTES).size();
            int numSent = sent.get(1, TimeUnit.MINUTES);
            return (numSent == numReceived);
        } catch (ExecutionException | SecurityException | UnauthorizedAccessException ex) {
            Throwable cause = ex;
            if (ex instanceof ExecutionException) {
                cause = ex.getCause();
            }

            if (cause instanceof AuthenticationException || cause instanceof SaslSystemException || cause instanceof SecurityException || cause instanceof UnauthorizedAccessException || cause instanceof MechanismMismatchException) {
                LOGGER.info("canConnectWithAmqpAddress {} ({}): {}", address, addressType, ex.getMessage());
                return false;
            } else {
                LOGGER.warn("canConnectWithAmqpAddress {} ({}) exception", address, addressType, ex);
                throw ex;
            }
        }
    }
}