org.springframework.amqp.core.MessageProperties Java Examples

The following examples show how to use org.springframework.amqp.core.MessageProperties. 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: 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 #2
Source File: RabbitMqTracingUtils.java    From java-spring-rabbitmq with Apache License 2.0 6 votes vote down vote up
static Scope buildSendSpan(Tracer tracer, MessageProperties messageProperties) {
  Tracer.SpanBuilder spanBuilder =
      tracer
          .buildSpan(RabbitMqTracingTags.SPAN_KIND_PRODUCER)
          .ignoreActiveSpan()
          .withTag(Tags.SPAN_KIND.getKey(), RabbitMqTracingTags.SPAN_KIND_PRODUCER);

  ScopeManager scopeManager = tracer.scopeManager();
  Optional<SpanContext> existingSpanContext = Optional.ofNullable(scopeManager)
      .map(ScopeManager::activeSpan)
      .map(Span::context);

  existingSpanContext.ifPresent(spanBuilder::asChildOf);

  if (messageProperties.getHeaders() != null) {
    Optional<SpanContext> messageParentContext = findParent(messageProperties, tracer);
    messageParentContext.ifPresent(spanBuilder::asChildOf);
  }
  Span span = spanBuilder.start();
  return scopeManager.activate(span);
}
 
Example #3
Source File: RepublishUnitTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 6 votes vote down vote up
@Test
public void testBadRepublishSetting() throws IOException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection conn = mock(Connection.class);
	given(cf.createConnection()).willReturn(conn);
	Channel channel = mock(Channel.class);
	given(channel.isOpen()).willReturn(true);
	given(channel.exchangeDeclarePassive("DLX")).willThrow(new IOException());
	given(conn.createChannel(false)).willReturn(channel);
	RabbitProperties props = new RabbitProperties();
	RabbitMessageChannelBinder binder = new RabbitMessageChannelBinder(cf, props, null);
	RabbitConsumerProperties extension = new RabbitConsumerProperties();
	ExtendedConsumerProperties<RabbitConsumerProperties> bindingProps =
			new ExtendedConsumerProperties<RabbitConsumerProperties>(extension);
	MessageHandler handler = binder.getErrorMessageHandler(mock(ConsumerDestination.class), "foo", bindingProps);
	ErrorMessage message = new ErrorMessage(new RuntimeException("test"),
			Collections.singletonMap(IntegrationMessageHeaderAccessor.SOURCE_DATA,
					new Message("foo".getBytes(), new MessageProperties())));
	handler.handleMessage(message);
	handler.handleMessage(message);
	verify(channel, times(1)).exchangeDeclarePassive("DLX");
	verify(channel, never()).basicPublish(any(), any(), eq(false), any(), any());
}
 
Example #4
Source File: RabbitMqSendTracingAspectTest.java    From java-spring-rabbitmq with Apache License 2.0 6 votes vote down vote up
@Test(expected = RuntimeException.class)
public void testTraceRabbitSend_whenException() throws Throwable {
  // given
  String exchange = "opentracing.event.exchange";

  MessageProperties properties = new MessageProperties();
  Message message = new Message("".getBytes(), properties);
  Object[] args = new Object[] {exchange, ROUTING_KEY, message};
  given(proceedingJoinPoint.getArgs()).willReturn(args);

  given(messageConverter.toMessage(any(Object.class), any(MessageProperties.class)))
      .willReturn(message);

  given(proceedingJoinPoint.proceed(args)).willThrow(new RuntimeException());

  try {
    // when
    aspect.traceRabbitSend(proceedingJoinPoint, exchange, ROUTING_KEY, message);
  } catch (RuntimeException e) {
    // then
    verify(proceedingJoinPoint).getArgs();
    verify(proceedingJoinPoint).proceed(args);

    throw e;
  }
}
 
Example #5
Source File: RabbitMqSendTracingHelper.java    From java-spring-rabbitmq with Apache License 2.0 6 votes vote down vote up
private Message doBefore(String exchange, String routingKey, Object message) {

    Message convertedMessage = convertMessageIfNecessary(message);

    final MessageProperties messageProperties = convertedMessage.getMessageProperties();

    // Add tracing header to outgoing AMQP message
    // so that new spans created on the AMQP message consumer side could be associated with span of current trace
    scope = RabbitMqTracingUtils.buildSendSpan(tracer, messageProperties);
    tracer.inject(
        tracer.scopeManager().activeSpan().context(),
        Format.Builtin.TEXT_MAP,
        new RabbitMqInjectAdapter(messageProperties));

    // Add AMQP related tags to tracing span
    spanDecorator.onSend(messageProperties, exchange, routingKey, tracer.scopeManager().activeSpan());

    return convertedMessage;
  }
 
Example #6
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 #7
Source File: MQServer.java    From zxl with Apache License 2.0 6 votes vote down vote up
private void replyIfNecessary(Message message, Object result, RabbitTemplate mqTemplate) {
	MessageProperties messageProperties = message.getMessageProperties();
	String correlationId = null;
	try {
		correlationId = new String(messageProperties.getCorrelationId(), DEFAULT_CHARSET);
	} catch (Exception ignored) {
		try {
			correlationId = (String) SerializationUtils.deserialize(messageProperties.getCorrelationId());
		} catch (Exception warnException) {
			LogUtil.warn(logger, "#####获取correlationId失败,可能导致客户端挂起", warnException);
		}
	}
	boolean isNecessary = result != null && messageProperties.getReplyTo() != null;
	if (isNecessary) {
		mqTemplate.send(messageProperties.getReplyTo(), correlationId == null ? mqMessageConverter.toSendMessage(result) : mqMessageConverter.toReplyMessage(result, correlationId));
	}
}
 
Example #8
Source File: AmqpMessageHandlerServiceTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description("Tests the creation of a target/thing by calling the same method that incoming RabbitMQ messages would access.")
public void createThing() {
    final String knownThingId = "1";
    final MessageProperties messageProperties = createMessageProperties(MessageType.THING_CREATED);
    messageProperties.setHeader(MessageHeaderKey.THING_ID, "1");
    final Message message = messageConverter.toMessage(new byte[0], messageProperties);

    final Target targetMock = mock(Target.class);

    final ArgumentCaptor<String> targetIdCaptor = ArgumentCaptor.forClass(String.class);
    final ArgumentCaptor<URI> uriCaptor = ArgumentCaptor.forClass(URI.class);
    when(controllerManagementMock.findOrRegisterTargetIfItDoesNotExist(targetIdCaptor.capture(),
            uriCaptor.capture())).thenReturn(targetMock);
    when(controllerManagementMock.findActiveActionWithHighestWeight(any())).thenReturn(Optional.empty());

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

    // verify
    assertThat(targetIdCaptor.getValue()).as("Thing id is wrong").isEqualTo(knownThingId);
    assertThat(uriCaptor.getValue().toString()).as("Uri is not right")
            .isEqualTo("amqp://" + VIRTUAL_HOST + "/MyTest");
}
 
Example #9
Source File: RabbitWithoutRabbitTemplateConfig.java    From java-spring-rabbitmq with Apache License 2.0 6 votes vote down vote up
private void sendReplyIfRequested(Message message) {
  MessageProperties messageProperties = message.getMessageProperties();
  String replyToProperty = messageProperties.getReplyTo();

  if (replyToProperty != null) {
    RabbitTemplate rabbitTemplate = rabbitTemplateProvider.getRabbitTemplate();
    Address replyTo = new Address(replyToProperty);
    String replyMsg = REPLY_MSG_PREFIX + new String(message.getBody(), UTF_8);
    Message replyMessage = rabbitTemplate.getMessageConverter().toMessage(replyMsg, null);

    Object addCustomResponseErrorMarkerHeader = messageProperties.getHeaders()
        .get(HEADER_ADD_CUSTOM_ERROR_HEADER_TO_RESPONSE);

    if (addCustomResponseErrorMarkerHeader != null) {
      replyMessage.getMessageProperties().setHeader(HEADER_CUSTOM_RESPONSE_ERROR_MARKER_HEADER, "dummy error message");
    }
    replyMessage.getMessageProperties().setCorrelationId(messageProperties.getCorrelationId());

    rabbitTemplate.convertAndSend(replyTo.getExchangeName(), replyTo.getRoutingKey(), replyMessage);
  }
}
 
Example #10
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 #11
Source File: TraceeMessagePropertiesConverter.java    From tracee with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Incoming messages
 */
@Override
public MessageProperties toMessageProperties(AMQP.BasicProperties source, Envelope envelope, String charset) {
	final MessageProperties messageProperties = super.toMessageProperties(source, envelope, charset);

	final TraceeFilterConfiguration filterConfiguration = backend.getConfiguration(profile);
	if (filterConfiguration.shouldProcessContext(AsyncProcess)) {
		// Values are stored as type of LongStringHelper.ByteArrayLongString - but it's private
		final Map<String, String> traceeContextMap = transformToTraceeContextMap(
			(Map<String, ?>) messageProperties.getHeaders().get(TPIC_HEADER));
		if (traceeContextMap != null && !traceeContextMap.isEmpty()) {
			backend.putAll(filterConfiguration.filterDeniedParams(traceeContextMap, AsyncProcess));
		}
	}

	Utilities.generateInvocationIdIfNecessary(backend);
	return messageProperties;
}
 
Example #12
Source File: RabbitTemplateMessageQueue.java    From elasticactors with Apache License 2.0 6 votes vote down vote up
private MessageProperties createProps(InternalMessage message) {
    MessageBuilderSupport<MessageProperties> messageBuilderSupport =
            MessagePropertiesBuilder.newInstance()
                    .setContentType(MessageProperties.CONTENT_TYPE_BYTES)
                    .setDeliveryMode(message.isDurable()
                            ? MessageDeliveryMode.PERSISTENT
                            : MessageDeliveryMode.NON_PERSISTENT);
    if (message.getTimeout() < 0) {
        return messageBuilderSupport.build();
    } else {
        return messageBuilderSupport
                .setPriority(MessageProperties.DEFAULT_PRIORITY)
                .setExpiration(String.valueOf(message.getTimeout()))
                .build();
    }
}
 
Example #13
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 #14
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 #15
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 #16
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 #17
Source File: ExceptionMessageExchangerTest.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
@Test
public void AbstractAmqpExceptionを継承した例外の場合は例外IDがヘッダに設定される() {
    class AmqpException extends AmqpApplicationRecoverableException {
        private static final long serialVersionUID = 1L;
        public AmqpException(String code, String routingKey) {
            super(code, routingKey);
        }
    }
    AmqpException e = new AmqpException("code", "dummy");
    exchanger.recover(message, e);
    ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    ArgumentCaptor<String> routingKeyCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<String> exchangeCaptor = ArgumentCaptor.forClass(String.class);
    verify(mock).send(exchangeCaptor.capture(), routingKeyCaptor.capture(), messageCaptor.capture());
    MessageProperties prop = messageCaptor.getValue().getMessageProperties();
    assertThat(prop.getHeaders().get("x-exception-stacktrace").toString(), is(ExceptionUtils.getStackTrace(e)));
    assertThat(prop.getHeaders().get("x-exception-message").toString(), is(e.getMessage()));
    assertThat(prop.getHeaders().get("x-original-exchange").toString(), is("the.original.exchange"));
    assertThat(prop.getHeaders().get("x-original-routing-key").toString(), is("the.original.routing-key"));
    assertThat(prop.getHeaders().get("x-exception-id").toString(), is(e.getId()));
    assertThat(exchangeCaptor.getValue(), is("error.exchange"));
    assertThat(routingKeyCaptor.getValue(), is(e.getRoutingKey()));
}
 
Example #18
Source File: BaseAmqpService.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
protected static void checkContentTypeJson(final Message message) {
    final MessageProperties messageProperties = message.getMessageProperties();
    if (messageProperties.getContentType() != null && messageProperties.getContentType().contains("json")) {
        return;
    }
    throw new AmqpRejectAndDontRequeueException("Content-Type is not JSON compatible");
}
 
Example #19
Source File: AmqpAuthenticationMessageHandlerIntegrationTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Tests wrong content type. This message is invalid and should not be requeued. Additional the receive message is null")
public void wrongContentType() {
    final Message createAndSendMessage = getDmfClient()
            .sendAndReceive(new Message("".getBytes(), new MessageProperties()));
    assertThat(createAndSendMessage).isNull();
    assertEmptyAuthenticationMessageCount();
}
 
Example #20
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 #21
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 #22
Source File: AmqpMessageDispatcherService.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
protected void sendPingReponseToDmfReceiver(final Message ping, final String tenant, final String virtualHost) {
    final Message message = MessageBuilder.withBody(String.valueOf(System.currentTimeMillis()).getBytes())
            .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
            .setCorrelationId(ping.getMessageProperties().getCorrelationId())
            .setHeader(MessageHeaderKey.TYPE, MessageType.PING_RESPONSE).setHeader(MessageHeaderKey.TENANT, tenant)
            .build();

    amqpSenderService.sendMessage(message,
            IpUtil.createAmqpUri(virtualHost, ping.getMessageProperties().getReplyTo()));
}
 
Example #23
Source File: AmqpMessageHandlerServiceTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Tests the update of an action of a target without a exist action id")
public void updateActionStatusWithoutActionId() {
    when(controllerManagementMock.findActionWithDetails(anyLong())).thenReturn(Optional.empty());
    final MessageProperties messageProperties = createMessageProperties(MessageType.EVENT);
    messageProperties.setHeader(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name());
    final DmfActionUpdateStatus actionUpdateStatus = new DmfActionUpdateStatus(1L, 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 #24
Source File: AmqpMessageHandlerServiceTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Tests not allowed content-type in message")
public void wrongContentType() {
    final MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType("xml");
    final Message message = new Message(new byte[0], messageProperties);
    assertThatExceptionOfType(AmqpRejectAndDontRequeueException.class)
            .as(FAIL_MESSAGE_AMQP_REJECT_REASON + "due to wrong content type")
            .isThrownBy(() -> amqpMessageHandlerService.onMessage(message, MessageType.THING_CREATED.name(), TENANT,
                    VIRTUAL_HOST));
}
 
Example #25
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
private MessageBatch doReleaseBatch() {
	if (this.messages.size() < 1) {
		return null;
	}
	else {
		ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[this.currentSize]);
		for (org.springframework.amqp.core.Message message: messages) {
			byteBuffer.put(message.getBody()).putChar('\n');
		}
		MessageBatch messageBatch = new MessageBatch(this.exchange, this.routingKey,
				new org.springframework.amqp.core.Message(byteBuffer.array(), new MessageProperties()));
		this.messages.clear();
		return messageBatch;
	}
}
 
Example #26
Source File: AbstractAmqpIntegrationTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
protected Message createMessage(final Object payload, final MessageProperties messageProperties) {
    if (payload == null) {
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        return new Message(null, messageProperties);
    }
    return getDmfClient().getMessageConverter().toMessage(payload, messageProperties);
}
 
Example #27
Source File: RabbitMessageChannelBinder.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@Override
public MessageProperties toMessageProperties(AMQP.BasicProperties source,
		Envelope envelope, String charset) {
	MessageProperties properties = super.toMessageProperties(source, envelope,
			charset);
	properties.setDeliveryMode(null);
	return properties;
}
 
Example #28
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 #29
Source File: ExceptionMessageExchangerTest.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
@Test
public void メッセージヘッダに例外情報が付与されてメッセージが転送される() {
    exchanger.recover(message, t);
    ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    ArgumentCaptor<String> routingKeyCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<String> exchangeCaptor = ArgumentCaptor.forClass(String.class);
    verify(mock).send(exchangeCaptor.capture(), routingKeyCaptor.capture(), messageCaptor.capture());
    MessageProperties prop = messageCaptor.getValue().getMessageProperties();
    assertThat(prop.getHeaders().get("x-exception-stacktrace").toString(), is(ExceptionUtils.getStackTrace(t)));
    assertThat(prop.getHeaders().get("x-exception-message").toString(), is(t.getMessage()));
    assertThat(prop.getHeaders().get("x-original-exchange").toString(), is("the.original.exchange"));
    assertThat(prop.getHeaders().get("x-original-routing-key").toString(), is("the.original.routing-key"));
    assertThat(prop.getHeaders().get("x-exception-id"), is(nullValue()));
}
 
Example #30
Source File: TraceeMessagePropertiesConverter.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Outgoing messages
 */
@Override
public AMQP.BasicProperties fromMessageProperties(MessageProperties source, String charset) {

	final TraceeFilterConfiguration filterConfiguration = backend.getConfiguration(profile);
	if (!backend.isEmpty() && filterConfiguration.shouldProcessContext(AsyncDispatch)) {
		final Map<String, String> filteredParams = filterConfiguration.filterDeniedParams(backend.copyToMap(), AsyncDispatch);
		source.getHeaders().put(TPIC_HEADER, filteredParams);
	}

	return super.fromMessageProperties(source, charset);
}