Java Code Examples for org.springframework.amqp.core.MessageProperties#setHeader()

The following examples show how to use org.springframework.amqp.core.MessageProperties#setHeader() . 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: ProtobufMessageConverter.java    From common-project with Apache License 2.0 6 votes vote down vote up
@Override
public Message toMessage(Object obj, MessageProperties messageProperties) throws MessageConversionException {
    String messageType = obj.getClass().getSimpleName();
    Codec<Object> codec = codecMap.get(messageType);
    if (codec == null) {
        throw new MessageConversionException("不支持转换的消息类型:" + messageType);
    }
    messageProperties.setHeader("messageType", messageType);
    byte[] body;
    try {
        body = codec.encode(obj);
    } catch (Exception e) {
        throw new MessageConversionException("编码失败:" + messageType, e);
    }
    return new Message(body, messageProperties);
}
 
Example 2
Source File: AmqpMessageHandlerServiceTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Tests a invalid message without event topic")
public void invalidEventTopic() {
    final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
    final Message message = new Message(new byte[0], messageProperties);

    assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class)
            .as(FAIL_MESSAGE_AMQP_REJECT_REASON + "due to unknown message type").isThrownBy(
                    () -> amqpMessageHandlerService.onMessage(message, "unknownMessageType", TENANT, VIRTUAL_HOST));

    messageProperties.setHeader(MessageHeaderKey.TOPIC, "wrongTopic");
    assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class)
            .as(FAIL_MESSAGE_AMQP_REJECT_REASON + "due to unknown topic").isThrownBy(() -> amqpMessageHandlerService
                    .onMessage(message, MessageType.EVENT.name(), TENANT, VIRTUAL_HOST));

    messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.CANCEL_DOWNLOAD.name());
    assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class)
            .as(FAIL_MESSAGE_AMQP_REJECT_REASON + "because there was no event topic")
            .isThrownBy(() -> amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT,
                    VIRTUAL_HOST));
}
 
Example 3
Source File: DeviceEventRabbitEndpointTest.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReceiveOnConfigPub() throws Exception {

    final String apiKey = "jV5bnJWK";
    final String channel = "temp";
    final String payload = "{ 'a' : '52T' }";
    final Long epochMilli = 1490001001000L;
    Instant timestamp = Instant.ofEpochMilli(epochMilli);

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setHeader("apiKey", apiKey);
    messageProperties.setHeader("channel", channel);
    messageProperties.setHeader("ts", epochMilli);

    Message message = new Message(payload.getBytes("UTF-8"), messageProperties);
    deviceEventRabbitEndpoint.onDataPub(message);

    verify(deviceEventProcessor, times(1)).process(apiKey, channel, payload.getBytes("UTF-8"), timestamp);

}
 
Example 4
Source File: AmqpMessageHandlerServiceTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Tests the target attribute update by calling the same method that incoming RabbitMQ messages would access.")
public void updateAttributes() {
    final String knownThingId = "1";
    final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
    messageProperties.setHeader(MessageHeaderKey.THING_ID, knownThingId);
    messageProperties.setHeader(MessageHeaderKey.TOPIC, "UPDATE_ATTRIBUTES");
    final DmfAttributeUpdate attributeUpdate = new DmfAttributeUpdate();
    attributeUpdate.getAttributes().put("testKey1", "testValue1");
    attributeUpdate.getAttributes().put("testKey2", "testValue2");

    final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(attributeUpdate,
            messageProperties);

    when(controllerManagementMock.updateControllerAttributes(targetIdCaptor.capture(), attributesCaptor.capture(),
            modeCaptor.capture())).thenReturn(null);

    amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, VIRTUAL_HOST);

    // verify
    assertThat(targetIdCaptor.getValue()).as("Thing id is wrong").isEqualTo(knownThingId);
    assertThat(attributesCaptor.getValue()).as("Attributes is not right")
            .isEqualTo(attributeUpdate.getAttributes());
}
 
Example 5
Source File: RabbitGateway.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
public void queueEvent(Device device, EventRoute eventRoute, Event event) {
    try {
        MessageProperties properties = new MessageProperties();
        properties.setHeader(RabbitMQDataConfig.MSG_HEADER_APIKEY, device.getApiKey());
        properties.setHeader(RabbitMQDataConfig.MSG_HEADER_EVENT_ROUTE_GUID, eventRoute.getGuid());

        Message message = new Message(toByteArray(event), properties);
        rabbitTemplate.convertAndSend("routed.events", message);

        if (!event.getIncoming().getChannel().equals("_echo")) {
            LOGGER.info(MessageFormat.format("Output tenant: {0} app: {1} channel: {2} device: {3} ts: {4} size: {5}",
                    device.getTenant().getDomainName(),
                    device.getApplication().getName(),
                    eventRoute.getOutgoing().getData().get("channel"),
                    eventRoute.getOutgoing().getDisplayName(),
                    event.getCreationTimestamp(),
                    event.getPayload().getBytes().length));

        }

    } catch (AmqpException ex) {
        LOGGER.error("AmqpException while sending message to RabbitMQ...", ex);
    }
}
 
Example 6
Source File: AmqpMessageHandlerServiceTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Tests the update of an action of a target without a exist action id")
public void updateActionStatusWithoutExistActionId() {
    final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
    messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name());
    when(controllerManagementMock.findActionWithDetails(anyLong())).thenReturn(Optional.empty());

    final DmfActionUpdateStatus actionUpdateStatus = createActionUpdateStatus(DmfActionStatus.DOWNLOAD);
    final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(actionUpdateStatus,
            messageProperties);

    assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class)
            .as(FAIL_MESSAGE_AMQP_REJECT_REASON + "since no action id was set")
            .isThrownBy(() -> amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT,
                    VIRTUAL_HOST));
}
 
Example 7
Source File: EventPublisherDeviceTest.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotSendAnyEventThroughGatewayIfDeviceIsDisabled() throws Exception {
    Tenant tenant = tenantRepository.findByDomainName("konker");
    Application application = applicationRepository.findByTenantAndName(tenant.getId(), "smartffkonker");

    Optional.of(deviceRegisterService.findByTenantDomainNameAndDeviceGuid(REGISTERED_TENANT_DOMAIN,REGISTERED_DEVICE_GUID))
        .filter(device -> !device.isActive())
        .orElseGet(() -> deviceRegisterService.switchEnabledDisabled(tenant, application, THE_DEVICE_GUID).getResult());

    subject.send(event,destinationUri,data,device.getTenant(),device.getApplication());

    MessageProperties properties = new MessageProperties();
    properties.setHeader(RabbitMQDataConfig.MSG_HEADER_APIKEY, device.getApiKey());
    properties.setHeader(RabbitMQDataConfig.MSG_HEADER_CHANNEL, data.get(DEVICE_MQTT_CHANNEL));

    Message message = new Message(event.getPayload().getBytes("UTF-8"), properties);

    verify(rabbitTemplate,never()).convertAndSend("data.sub", message);
    verify(deviceLogEventService,never()).logIncomingEvent(Mockito.any() , Mockito.any());
    verify(deviceLogEventService,never()).logOutgoingEvent(Mockito.any() , Mockito.any());
}
 
Example 8
Source File: TracingRabbitListenerAdviceTest.java    From brave with Apache License 2.0 6 votes vote down vote up
@Test public void continues_parent_trace() throws Throwable {
  MessageProperties props = new MessageProperties();
  props.setHeader("X-B3-TraceId", TRACE_ID);
  props.setHeader("X-B3-SpanId", SPAN_ID);
  props.setHeader("X-B3-ParentSpanId", PARENT_ID);
  props.setHeader("X-B3-Sampled", SAMPLED);

  Message message = MessageBuilder.withBody(new byte[0]).andProperties(props).build();
  onMessageConsumed(message);

  // cleared the headers to later work doesn't try to use the old parent
  assertThat(message.getMessageProperties().getHeaders()).isEmpty();

  assertThat(spans)
    .filteredOn(span -> span.kind() == CONSUMER)
    .extracting(MutableSpan::parentId)
    .contains(SPAN_ID);
}
 
Example 9
Source File: RabbitGateway.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
public void queueEventDataPub(String apiKey, String channel, Long epochMilli, byte[] payload) {
    try {
        MessageProperties properties = new MessageProperties();
        properties.setHeader(RabbitMQConfig.MSG_HEADER_APIKEY, apiKey);
        properties.setHeader(RabbitMQConfig.MSG_HEADER_CHANNEL, channel);
        properties.setHeader(RabbitMQConfig.MSG_HEADER_TIMESTAMP, epochMilli);

        Message message = new Message(payload, properties);

        rabbitTemplate.convertAndSend("data.pub", message);
    } catch (AmqpException ex) {
        LOGGER.error("AmqpException while sending message to RabbitMQ...", ex);
    }
}
 
Example 10
Source File: TracingRabbitListenerAdviceTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void continues_parent_trace_single_header() throws Throwable {
  MessageProperties props = new MessageProperties();
  props.setHeader("b3", TRACE_ID + "-" + SPAN_ID + "-" + SAMPLED);

  Message message = MessageBuilder.withBody(new byte[0]).andProperties(props).build();
  onMessageConsumed(message);

  // cleared the headers to later work doesn't try to use the old parent
  assertThat(message.getMessageProperties().getHeaders()).isEmpty();

  assertThat(spans)
    .filteredOn(span -> span.kind() == CONSUMER)
    .extracting(MutableSpan::parentId)
    .contains(SPAN_ID);
}
 
Example 11
Source File: AmqpMessageHandlerServiceTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Tests the creation of a thing without a 'reply to' header in message.")
public void createThingWithoutReplyTo() {
    final MessageProperties messageProperties = createMessageProperties(MessageType.THING_CREATED, null);
    messageProperties.setHeader(MessageHeaderKey.THING_ID, "1");
    final Message message = messageConverter.toMessage("", messageProperties);

    assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class)
            .as(FAIL_MESSAGE_AMQP_REJECT_REASON + "since no replyTo header was set")
            .isThrownBy(() -> amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT,
                    VIRTUAL_HOST));
}
 
Example 12
Source File: AmqpMessageDispatcherService.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private static MessageProperties createConnectorMessagePropertiesEvent(final String tenant,
        final String controllerId, final EventTopic topic) {
    final MessageProperties messageProperties = createConnectorMessageProperties(tenant, controllerId);
    messageProperties.setHeader(MessageHeaderKey.TOPIC, topic);
    messageProperties.setHeader(MessageHeaderKey.TYPE, MessageType.EVENT);
    return messageProperties;
}
 
Example 13
Source File: DmfSenderService.java    From hawkbit-examples with Eclipse Public License 1.0 5 votes vote down vote up
private MessageProperties createAttributeUpdateMessage(final String tenant, final String targetId) {
    final MessageProperties messagePropertiesForSP = new MessageProperties();
    messagePropertiesForSP.setHeader(MessageHeaderKey.TYPE, MessageType.EVENT.name());
    messagePropertiesForSP.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ATTRIBUTES);
    messagePropertiesForSP.setHeader(MessageHeaderKey.TENANT, tenant);
    messagePropertiesForSP.setHeader(MessageHeaderKey.THING_ID, targetId);
    messagePropertiesForSP.setContentType(MessageProperties.CONTENT_TYPE_JSON);
    messagePropertiesForSP.setReplyTo(amqpProperties.getSenderForSpExchange());
    return messagePropertiesForSP;
}
 
Example 14
Source File: AmqpMessageHandlerServiceTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private MessageProperties createMessageProperties(final MessageType type, final String replyTo) {
    final MessageProperties messageProperties = new MessageProperties();
    if (type != null) {
        messageProperties.setHeader(MessageHeaderKey.TYPE, type.name());
    }
    messageProperties.setHeader(MessageHeaderKey.TENANT, TENANT);
    messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
    messageProperties.setReplyTo(replyTo);
    return messageProperties;
}
 
Example 15
Source File: RabbitGateway.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
public void sendConfig(String apiKey, String config) {

        try {
            MessageProperties properties = new MessageProperties();
            properties.setHeader(RabbitMQConfig.MSG_HEADER_APIKEY, apiKey);

            Message message = new Message(config.getBytes("UTF-8"), properties);

            rabbitTemplate.convertAndSend("mgmt.config.sub", message);
        } catch (AmqpException | UnsupportedEncodingException ex) {
            LOGGER.error("AmqpException while sending message to RabbitMQ...", ex);
        }

    }
 
Example 16
Source File: RabbitGateway.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
public void sendEvent(String apiKey, String channel, byte[] payload) {

        try {
            MessageProperties properties = new MessageProperties();
            properties.setHeader(RabbitMQConfig.MSG_HEADER_APIKEY, apiKey);
            properties.setHeader(RabbitMQConfig.MSG_HEADER_CHANNEL, channel);

            Message message = new Message(payload, properties);

            rabbitTemplate.convertAndSend("data.sub", message);
        } catch (AmqpException ex) {
            LOGGER.error("AmqpException while sending message to RabbitMQ...", ex);
        }
    }
 
Example 17
Source File: AmqpMessageHandlerServiceTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Tests the deletion of a target/thing, requested by the target itself.")
public void deleteThing() {
    // prepare valid message
    final String knownThingId = "1";
    final MessageProperties messageProperties = createMessageProperties(MessageType.THING_REMOVED);
    messageProperties.setHeader(MessageHeaderKey.THING_ID, knownThingId);
    final Message message = messageConverter.toMessage(new byte[0], messageProperties);

    // test
    amqpMessageHandlerService.onMessage(message, MessageType.THING_REMOVED.name(), TENANT, VIRTUAL_HOST);

    // verify
    verify(controllerManagementMock).deleteExistingTarget(knownThingId);
}
 
Example 18
Source File: MessageHeaders.java    From brave with Apache License 2.0 4 votes vote down vote up
/**
 * If {@link MessageProperties} exist, this invokes {@link MessageProperties#setHeader(String,
 * Object)}.
 */
static void setHeader(Message message, String name, String value) {
  MessageProperties properties = message.getMessageProperties();
  if (properties == null) return;
  properties.setHeader(name, value);
}
 
Example 19
Source File: RabbitMQHeadSend.java    From springbootexamples with Apache License 2.0 4 votes vote down vote up
public void send(String message) {
	MessageProperties properties = new MessageProperties();
	properties.setHeader("token", "abc123");
	Message amqpMessage = new Message(message.getBytes(), properties);
	amqpTemplate.convertAndSend(RabbitMQHeaderConfig.HEAD_EXCHAGE, "", amqpMessage);
}
 
Example 20
Source File: AmqpMessageHandlerServiceTest.java    From hawkbit with Eclipse Public License 1.0 4 votes vote down vote up
@Test
@Description("Verifies that the update mode is retrieved from the UPDATE_ATTRIBUTES message and passed to the controller management.")
public void attributeUpdateModes() {
    final String knownThingId = "1";
    final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
    messageProperties.setHeader(MessageHeaderKey.THING_ID, knownThingId);
    messageProperties.setHeader(MessageHeaderKey.TOPIC, "UPDATE_ATTRIBUTES");
    final DmfAttributeUpdate attributeUpdate = new DmfAttributeUpdate();
    attributeUpdate.getAttributes().put("testKey1", "testValue1");
    attributeUpdate.getAttributes().put("testKey2", "testValue2");

    when(controllerManagementMock.updateControllerAttributes(targetIdCaptor.capture(), attributesCaptor.capture(),
            modeCaptor.capture())).thenReturn(null);

    // send a message which does not specify a update mode
    Message message = amqpMessageHandlerService.getMessageConverter().toMessage(attributeUpdate, messageProperties);
    amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, VIRTUAL_HOST);
    // verify that NO fallback is made on the way to the controller
    // management layer
    assertThat(modeCaptor.getValue()).isNull();

    // send a message which specifies update mode MERGE
    attributeUpdate.setMode(DmfUpdateMode.MERGE);
    message = amqpMessageHandlerService.getMessageConverter().toMessage(attributeUpdate, messageProperties);
    amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, VIRTUAL_HOST);
    // verify that the update mode is converted and forwarded as expected
    assertThat(modeCaptor.getValue()).isEqualTo(UpdateMode.MERGE);

    // send a message which specifies update mode REPLACE
    attributeUpdate.setMode(DmfUpdateMode.REPLACE);
    message = amqpMessageHandlerService.getMessageConverter().toMessage(attributeUpdate, messageProperties);
    amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, VIRTUAL_HOST);
    // verify that the update mode is converted and forwarded as expected
    assertThat(modeCaptor.getValue()).isEqualTo(UpdateMode.REPLACE);

    // send a message which specifies update mode REMOVE
    attributeUpdate.setMode(DmfUpdateMode.REMOVE);
    message = amqpMessageHandlerService.getMessageConverter().toMessage(attributeUpdate, messageProperties);
    amqpMessageHandlerService.onMessage(message, MessageType.EVENT.name(), TENANT, VIRTUAL_HOST);
    // verify that the update mode is converted and forwarded as expected
    assertThat(modeCaptor.getValue()).isEqualTo(UpdateMode.REMOVE);
}