@Override
 public MessageProperties toMessageProperties(
     AMQP.BasicProperties source, Envelope envelope, String charset) {
   MessageProperties properties = super.toMessageProperties(source, envelope, charset);
   properties.setDeliveryMode(null);
   return properties;
 }
 @Override
 public Object invoke(MethodInvocation invocation) throws Throwable {
   String id = null;
   Message message = null;
   boolean redelivered = false;
   try {
     message = (Message) invocation.getArguments()[1];
     MessageProperties messageProperties = message.getMessageProperties();
     if (messageProperties.getMessageId() == null) {
       id = UUID.randomUUID().toString();
       messageProperties.setMessageId(id);
     }
     redelivered = messageProperties.isRedelivered();
     return invocation.proceed();
   } catch (Exception e) {
     if (id != null && redelivered) {
       if (logger.isDebugEnabled()) {
         logger.debug("Canceling delivery of retried message that has no ID");
       }
       throw new ListenerExecutionFailedException(
           "Cannot retry message without an ID",
           new AmqpRejectAndDontRequeueException(e),
           message);
     } else {
       throw e;
     }
   } finally {
     if (id != null) {
       retryContextCache.remove(id);
     }
   }
 }
 @Override
 protected void populateUserDefinedHeader(
     String headerName, Object headerValue, MessageProperties amqpMessageProperties) {
   // do not overwrite an existing header with the same key
   // TODO: do we need to expose a boolean 'overwrite' flag?
   if (!amqpMessageProperties.getHeaders().containsKey(headerName)) {
     amqpMessageProperties.setHeader(headerName, headerValue);
   }
 }
 private static MessageProperties createConnectorMessageProperties(
     final String tenant, final String controllerId, final EventTopic topic) {
   final MessageProperties messageProperties = createMessageProperties();
   messageProperties.setHeader(MessageHeaderKey.TOPIC, topic);
   messageProperties.setHeader(MessageHeaderKey.THING_ID, controllerId);
   messageProperties.setHeader(MessageHeaderKey.TENANT, tenant);
   messageProperties.setHeader(MessageHeaderKey.TYPE, MessageType.EVENT);
   return messageProperties;
 }
  @Test
  public void testReplyToOneDeepCustomCorrelationKey() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    final RabbitTemplate template =
        new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory));
    template.setCorrelationKey(CORRELATION_HEADER);
    Queue replyQueue = new Queue("new.replyTo");
    template.setReplyQueue(replyQueue);

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setReplyTo("replyTo1");
    messageProperties.setCorrelationId("saveThis".getBytes());
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    final AtomicReference<String> replyTo = new AtomicReference<String>();
    final AtomicReference<String> correlationId = new AtomicReference<String>();
    doAnswer(
            new Answer<Object>() {
              public Object answer(InvocationOnMock invocation) throws Throwable {
                BasicProperties basicProps = (BasicProperties) invocation.getArguments()[4];
                replyTo.set(basicProps.getReplyTo());
                correlationId.set((String) basicProps.getHeaders().get(CORRELATION_HEADER));

                MessageProperties springProps =
                    new DefaultMessagePropertiesConverter()
                        .toMessageProperties(basicProps, null, "UTF-8");
                Message replyMessage = new Message("!dlrow olleH".getBytes(), springProps);
                template.onMessage(replyMessage);
                return null;
              }
            })
        .when(mockChannel)
        .basicPublish(
            Mockito.any(String.class),
            Mockito.any(String.class),
            Mockito.anyBoolean(),
            Mockito.anyBoolean(),
            Mockito.any(BasicProperties.class),
            Mockito.any(byte[].class));
    Message reply = template.sendAndReceive(message);
    assertNotNull(reply);

    assertNotNull(replyTo.get());
    assertEquals("new.replyTo", replyTo.get());
    assertNotNull(correlationId.get());
    assertEquals("replyTo1", reply.getMessageProperties().getReplyTo());
    assertTrue(!"saveThis".equals(correlationId.get()));
    assertEquals("replyTo1", reply.getMessageProperties().getReplyTo());
  }
 @Override
 protected Object extractPayload(org.springframework.amqp.core.Message message) {
   MessageProperties messageProperties = message.getMessageProperties();
   if (this.bean != null) {
     messageProperties.setTargetBean(this.bean);
   }
   if (this.method != null) {
     messageProperties.setTargetMethod(this.method);
     if (this.inferredArgumentType != null) {
       messageProperties.setInferredArgumentType(this.inferredArgumentType);
     }
   }
   return extractMessage(message);
 }
 @Override
 protected Message createMessage(Object object, MessageProperties messageProperties) {
   byte[] bytes = null;
   try {
     bytes = converter.serialize(object);
   } catch (Exception e) {
     throw new MessageConversionException("Failed to convert Message content", e);
   }
   messageProperties.setContentType("appication/protobuf");
   if (bytes != null) {
     messageProperties.setContentLength(bytes.length);
   }
   messageProperties.getHeaders().put("__TypeId__", object.getClass().getName());
   return new Message(bytes, messageProperties);
 }
Пример #8
0
 @Override
 public Object fromMessage(Message message) throws MessageConversionException {
   Object content = null;
   try {
     MessageProperties properties = message.getMessageProperties();
     String encoding = properties.getContentEncoding();
     if (encoding == null) {
       encoding = this.defaultCharset;
     }
     content = new String(message.getBody(), encoding);
     content = JSONObject.parse((String) content);
   } catch (UnsupportedEncodingException e) {
     throw new MessageConversionException("failed to convert text-based Message content", e);
   }
   return content;
 }
 protected Message createMessage(Object objectToConvert, MessageProperties messageProperties)
     throws MessageConversionException {
   byte[] bytes;
   try {
     String jsonString = JSON.toJSONString(objectToConvert);
     bytes = jsonString.getBytes(this.defaultCharset);
   } catch (Exception e) {
     throw new MessageConversionException("Failed to convert Message content", e);
   }
   messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
   messageProperties.setContentEncoding(this.defaultCharset);
   if (bytes != null) {
     messageProperties.setContentLength(bytes.length);
   }
   return new Message(bytes, messageProperties);
 }
 /** Extract user-defined headers from an AMQP MessageProperties instance. */
 @Override
 protected Map<String, Object> extractUserDefinedHeaders(MessageProperties amqpMessageProperties) {
   Map<String, Object> headers = amqpMessageProperties.getHeaders();
   headers.remove(AmqpHeaders.STACKED_CORRELATION_HEADER);
   headers.remove(AmqpHeaders.STACKED_REPLY_TO_HEADER);
   return headers;
 }
Пример #11
0
 @Override
 protected Message createMessage(Object objectToConvert, MessageProperties messageProperties) {
   byte[] bytes = null;
   try {
     String jsonString = JSONObject.toJSONString(objectToConvert);
     bytes = jsonString.getBytes(getDefaultCharset());
   } catch (IOException e) {
     throw new MessageConversionException("Failed to convert Message content", e);
   }
   messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
   messageProperties.setContentEncoding(getDefaultCharset());
   if (bytes != null) {
     messageProperties.setContentLength(bytes.length);
   }
   // 不要使用,会丢掉对象属性,缺少实现
   return new Message(bytes, messageProperties);
 }
  @Test
  public void withHeaderMapperStandardAndCustomHeaders() {
    AmqpInboundChannelAdapter adapter =
        context.getBean(
            "withHeaderMapperStandardAndCustomHeaders", AmqpInboundChannelAdapter.class);

    AbstractMessageListenerContainer mlc =
        TestUtils.getPropertyValue(
            adapter, "messageListenerContainer", AbstractMessageListenerContainer.class);
    MessageListener listener =
        TestUtils.getPropertyValue(mlc, "messageListener", MessageListener.class);
    MessageProperties amqpProperties = new MessageProperties();
    amqpProperties.setAppId("test.appId");
    amqpProperties.setClusterId("test.clusterId");
    amqpProperties.setContentEncoding("test.contentEncoding");
    amqpProperties.setContentLength(99L);
    amqpProperties.setContentType("test.contentType");
    amqpProperties.setHeader("foo", "foo");
    amqpProperties.setHeader("bar", "bar");
    Message amqpMessage = new Message("hello".getBytes(), amqpProperties);
    listener.onMessage(amqpMessage);
    QueueChannel requestChannel = context.getBean("requestChannel", QueueChannel.class);
    org.springframework.integration.Message<?> siMessage = requestChannel.receive(0);
    assertEquals("foo", siMessage.getHeaders().get("foo"));
    assertNull(siMessage.getHeaders().get("bar"));
    assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_ENCODING));
    assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CLUSTER_ID));
    assertNotNull(siMessage.getHeaders().get(AmqpHeaders.APP_ID));
    assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE));
  }
Пример #13
0
 public Object invoke(MethodInvocation invocation) throws Throwable {
   String id = null;
   try {
     Message message = (Message) invocation.getArguments()[1];
     MessageProperties messageProperties = message.getMessageProperties();
     if (messageProperties.getMessageId() == null) {
       id = UUID.randomUUID().toString();
       messageProperties.setMessageId(id);
     }
     return invocation.proceed();
   } catch (Throwable t) {
     throw new AmqpRejectAndDontRequeueException("Cannot retry message without an ID", t);
   } finally {
     if (id != null) {
       retryContextCache.remove(id);
     }
   }
 }
  @Override
  protected Message createMessage(Object object, MessageProperties messageProperties) {
    try {
      byte[] body = null;
      if (object != null) {
        body = object.toString().getBytes(this.encoding);
      }

      String msgContentType = this.contentType == null ? DEFAULT_CONTENT_TYPE : this.contentType;
      messageProperties.setContentType(msgContentType);
      messageProperties.setContentEncoding(this.encoding);
      messageProperties.setContentLength(body != null ? body.length : 0);
      return new Message(body, messageProperties);
    } catch (UnsupportedEncodingException ex) {
      LOG.error("Cannot encode strings as {}", this.encoding, ex);
      throw new MessageConversionException("Cannot encode strings as " + this.encoding, ex);
    }
  }
 @Override
 public Object fromMessage(Message message) throws MessageConversionException {
   Object content = null;
   MessageProperties properties = message.getMessageProperties();
   if (properties != null) {
     String contentType = properties.getContentType();
     if (contentType != null && contentType.contains("protobuf")) {
       try {
         String classId = (String) message.getMessageProperties().getHeaders().get("__TypeId__");
         if (classId == null) throw new Exception("no classId found");
         Class<?> targetClass = Class.forName(classId);
         content = converter.deserialize(message.getBody(), targetClass);
       } catch (Exception e) {
         throw new MessageConversionException("Failed to convert json-based Message content", e);
       }
     }
   }
   if (content == null) {
     content = message.getBody();
   }
   return content;
 }
  @Override
  public Object fromMessage(Message message) throws MessageConversionException {
    MessageProperties messageProperties = message.getMessageProperties();
    if (messageProperties == null)
      throw new MessageConversionException("Cannot decode a message with no properties!");

    byte[] body = message.getBody();
    if (body == null) return null;

    String messageEncoding = messageProperties.getContentEncoding();
    if (messageEncoding == null) messageEncoding = this.encoding;

    String messageContentType = messageProperties.getContentType();
    if (this.contentType != null && !this.contentType.equalsIgnoreCase(messageContentType))
      throw new MessageConversionException(
          "Cannot understand a message of type " + messageContentType);

    try {
      return new String(body, messageEncoding);
    } catch (UnsupportedEncodingException ex) {
      LOG.error("Cannot dencode strings as {}", this.encoding, ex);
      throw new MessageConversionException("Cannot dencode strings as " + this.encoding, ex);
    }
  }
  @Override
  public void run() {
    logger.info("Running...");
    while (!stopped) {
      if (generating) {
        Order order = generateOrder();
        logger.info("Sending order: " + order.toString());

        // Create Message
        MessageProperties mp = new MessageProperties();
        mp.setMessageId(order.getTransactionId());
        Message message = new Message(order.toBytes(), mp);

        // Send order
        ApplicationContext ctx = CcDemoAppApplication.getApplicationContext();
        RabbitTemplate rabbitTemplate = ctx.getBean(RabbitTemplate.class);
        rabbitTemplate.convertAndSend(message);

        OrderRepository orderRepository = ctx.getBean(OrderRepository.class);
        orderRepository.save(order);
        logger.info("Sent order: " + order.toString());
      } else {
        logger.info("Not generating...");
        try {
          Thread.sleep(500);
        } catch (Exception e) {
          return;
        }
      }
      try {
        Thread.sleep(100);
      } catch (Exception e) {
        return;
      }
    }
  }
 private static MessageProperties createMessageProperties() {
   final MessageProperties messageProperties = new MessageProperties();
   messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
   messageProperties.setHeader(MessageHeaderKey.CONTENT_TYPE, MessageProperties.CONTENT_TYPE_JSON);
   return messageProperties;
 }
 public MessageProperties toMessageProperties(
     final BasicProperties source, final Envelope envelope, final String charset) {
   MessageProperties target = new MessageProperties();
   Map<String, Object> headers = source.getHeaders();
   if (!CollectionUtils.isEmpty(headers)) {
     for (Map.Entry<String, Object> entry : headers.entrySet()) {
       String key = entry.getKey();
       if (MessageProperties.X_DELAY.equals(key)) {
         Object value = entry.getValue();
         if (value instanceof Integer) {
           target.setReceivedDelay((Integer) value);
         }
       } else {
         target.setHeader(key, convertLongStringIfNecessary(entry.getValue(), charset));
       }
     }
   }
   target.setTimestamp(source.getTimestamp());
   target.setMessageId(source.getMessageId());
   target.setReceivedUserId(source.getUserId());
   target.setAppId(source.getAppId());
   target.setClusterId(source.getClusterId());
   target.setType(source.getType());
   Integer deliveryMode = source.getDeliveryMode();
   if (deliveryMode != null) {
     target.setReceivedDeliveryMode(MessageDeliveryMode.fromInt(deliveryMode));
   }
   target.setDeliveryMode(null);
   target.setExpiration(source.getExpiration());
   target.setPriority(source.getPriority());
   target.setContentType(source.getContentType());
   target.setContentEncoding(source.getContentEncoding());
   String correlationId = source.getCorrelationId();
   if (StringUtils.hasText(correlationId)) {
     target.setCorrelationId(source.getCorrelationId());
   }
   String replyTo = source.getReplyTo();
   if (replyTo != null) {
     target.setReplyTo(replyTo);
   }
   if (envelope != null) {
     target.setReceivedExchange(envelope.getExchange());
     target.setReceivedRoutingKey(envelope.getRoutingKey());
     target.setRedelivered(envelope.isRedeliver());
     target.setDeliveryTag(envelope.getDeliveryTag());
   }
   return target;
 }
 public BasicProperties fromMessageProperties(
     final MessageProperties source, final String charset) {
   BasicProperties.Builder target = new BasicProperties.Builder();
   target
       .headers(this.convertHeadersIfNecessary(source.getHeaders()))
       .timestamp(source.getTimestamp())
       .messageId(source.getMessageId())
       .userId(source.getUserId())
       .appId(source.getAppId())
       .clusterId(source.getClusterId())
       .type(source.getType());
   MessageDeliveryMode deliveryMode = source.getDeliveryMode();
   if (deliveryMode != null) {
     target.deliveryMode(MessageDeliveryMode.toInt(deliveryMode));
   }
   target
       .expiration(source.getExpiration())
       .priority(source.getPriority())
       .contentType(source.getContentType())
       .contentEncoding(source.getContentEncoding());
   String correlationId = source.getCorrelationId();
   if (StringUtils.hasText(correlationId)) {
     target.correlationId(correlationId);
   }
   String replyTo = source.getReplyTo();
   if (replyTo != null) {
     target.replyTo(replyTo);
   }
   return target.build();
 }
Пример #21
0
    @Override
    public void run() {
      try {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        while (true) {
          final Event event = events.take();
          LoggingEvent logEvent = event.getEvent();

          String name = logEvent.getLogger().getName();
          Level level = logEvent.getLevel();

          MessageProperties amqpProps = new MessageProperties();
          amqpProps.setDeliveryMode(deliveryMode);
          amqpProps.setContentType(contentType);
          if (null != contentEncoding) {
            amqpProps.setContentEncoding(contentEncoding);
          }
          amqpProps.setHeader(CATEGORY_NAME, name);
          amqpProps.setHeader(CATEGORY_LEVEL, level.toString());
          if (generateId) {
            amqpProps.setMessageId(UUID.randomUUID().toString());
          }

          // Set applicationId, if we're using one
          if (null != applicationId) {
            amqpProps.setAppId(applicationId);
          }

          // Set timestamp
          Calendar tstamp = Calendar.getInstance();
          tstamp.setTimeInMillis(logEvent.getTimeStamp());
          amqpProps.setTimestamp(tstamp.getTime());

          // Copy properties in from MDC
          @SuppressWarnings("rawtypes")
          Map props = event.getProperties();
          @SuppressWarnings("unchecked")
          Set<Entry<?, ?>> entrySet = props.entrySet();
          for (Entry<?, ?> entry : entrySet) {
            amqpProps.setHeader(entry.getKey().toString(), entry.getValue());
          }
          LocationInfo locInfo = logEvent.getLocationInformation();
          if (!"?".equals(locInfo.getClassName())) {
            amqpProps.setHeader(
                "location",
                String.format(
                    "%s.%s()[%s]",
                    locInfo.getClassName(), locInfo.getMethodName(), locInfo.getLineNumber()));
          }

          StringBuilder msgBody;
          String routingKey;
          synchronized (layoutMutex) {
            msgBody = new StringBuilder(layout.format(logEvent));
            routingKey = routingKeyLayout.format(logEvent);
          }
          if (layout.ignoresThrowable() && null != logEvent.getThrowableInformation()) {
            ThrowableInformation tinfo = logEvent.getThrowableInformation();
            for (String line : tinfo.getThrowableStrRep()) {
              msgBody.append(String.format("%s%n", line));
            }
          }

          // Send a message
          try {
            Message message = null;
            if (AmqpAppender.this.charset != null) {
              try {
                message =
                    new Message(msgBody.toString().getBytes(AmqpAppender.this.charset), amqpProps);
              } catch (UnsupportedEncodingException e) {
                /* fall back to default */
              }
            }
            if (message == null) {
              message =
                  new Message(
                      msgBody.toString().getBytes(), amqpProps); // NOSONAR (default charset)
            }
            message = postProcessMessageBeforeSend(message, event);
            rabbitTemplate.send(exchangeName, routingKey, message);
          } catch (AmqpException e) {
            int retries = event.incrementRetries();
            if (retries < maxSenderRetries) {
              // Schedule a retry based on the number of times I've tried to re-send this
              retryTimer.schedule(
                  new TimerTask() {
                    @Override
                    public void run() {
                      events.add(event);
                    }
                  },
                  (long) (Math.pow(retries, Math.log(retries)) * 1000));
            } else {
              errorHandler.error(
                  "Could not send log message "
                      + logEvent.getRenderedMessage()
                      + " after "
                      + maxSenderRetries
                      + " retries",
                  e,
                  ErrorCode.WRITE_FAILURE,
                  logEvent);
            }
          }
        }
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
 /** Extract "standard" headers from an AMQP MessageProperties instance. */
 @Override
 protected Map<String, Object> extractStandardHeaders(MessageProperties amqpMessageProperties) {
   Map<String, Object> headers = new HashMap<String, Object>();
   try {
     String appId = amqpMessageProperties.getAppId();
     if (StringUtils.hasText(appId)) {
       headers.put(AmqpHeaders.APP_ID, appId);
     }
     String clusterId = amqpMessageProperties.getClusterId();
     if (StringUtils.hasText(clusterId)) {
       headers.put(AmqpHeaders.CLUSTER_ID, clusterId);
     }
     String contentEncoding = amqpMessageProperties.getContentEncoding();
     if (StringUtils.hasText(contentEncoding)) {
       headers.put(AmqpHeaders.CONTENT_ENCODING, contentEncoding);
     }
     long contentLength = amqpMessageProperties.getContentLength();
     if (contentLength > 0) {
       headers.put(AmqpHeaders.CONTENT_LENGTH, contentLength);
     }
     String contentType = amqpMessageProperties.getContentType();
     if (StringUtils.hasText(contentType)) {
       headers.put(AmqpHeaders.CONTENT_TYPE, contentType);
     }
     byte[] correlationId = amqpMessageProperties.getCorrelationId();
     if (correlationId != null && correlationId.length > 0) {
       headers.put(AmqpHeaders.CORRELATION_ID, correlationId);
     }
     MessageDeliveryMode deliveryMode = amqpMessageProperties.getDeliveryMode();
     if (deliveryMode != null) {
       headers.put(AmqpHeaders.DELIVERY_MODE, deliveryMode);
     }
     long deliveryTag = amqpMessageProperties.getDeliveryTag();
     if (deliveryTag > 0) {
       headers.put(AmqpHeaders.DELIVERY_TAG, deliveryTag);
     }
     String expiration = amqpMessageProperties.getExpiration();
     if (StringUtils.hasText(expiration)) {
       headers.put(AmqpHeaders.EXPIRATION, expiration);
     }
     Integer messageCount = amqpMessageProperties.getMessageCount();
     if (messageCount != null && messageCount > 0) {
       headers.put(AmqpHeaders.MESSAGE_COUNT, messageCount);
     }
     String messageId = amqpMessageProperties.getMessageId();
     if (StringUtils.hasText(messageId)) {
       headers.put(AmqpHeaders.MESSAGE_ID, messageId);
     }
     Integer priority = amqpMessageProperties.getPriority();
     if (priority != null && priority > 0) {
       headers.put(MessageHeaders.PRIORITY, priority);
     }
     String receivedExchange = amqpMessageProperties.getReceivedExchange();
     if (StringUtils.hasText(receivedExchange)) {
       headers.put(AmqpHeaders.RECEIVED_EXCHANGE, receivedExchange);
     }
     String receivedRoutingKey = amqpMessageProperties.getReceivedRoutingKey();
     if (StringUtils.hasText(receivedRoutingKey)) {
       headers.put(AmqpHeaders.RECEIVED_ROUTING_KEY, receivedRoutingKey);
     }
     Boolean redelivered = amqpMessageProperties.isRedelivered();
     if (redelivered != null) {
       headers.put(AmqpHeaders.REDELIVERED, redelivered);
     }
     String replyTo = amqpMessageProperties.getReplyTo();
     if (replyTo != null) {
       headers.put(AmqpHeaders.REPLY_TO, replyTo);
     }
     Date timestamp = amqpMessageProperties.getTimestamp();
     if (timestamp != null) {
       headers.put(AmqpHeaders.TIMESTAMP, timestamp);
     }
     String type = amqpMessageProperties.getType();
     if (StringUtils.hasText(type)) {
       headers.put(AmqpHeaders.TYPE, type);
     }
     String userId = amqpMessageProperties.getUserId();
     if (StringUtils.hasText(userId)) {
       headers.put(AmqpHeaders.USER_ID, userId);
     }
     Object replyCorrelation =
         amqpMessageProperties.getHeaders().get(AmqpHeaders.STACKED_CORRELATION_HEADER);
     if (replyCorrelation instanceof String) {
       if (StringUtils.hasText((String) replyCorrelation)) {
         headers.put(AmqpHeaders.SPRING_REPLY_CORRELATION, replyCorrelation);
       }
     }
     Object replyToStack =
         amqpMessageProperties.getHeaders().get(AmqpHeaders.STACKED_REPLY_TO_HEADER);
     if (replyToStack instanceof String) {
       if (StringUtils.hasText((String) replyToStack)) {
         headers.put(AmqpHeaders.SPRING_REPLY_TO_STACK, replyToStack);
       }
     }
   } catch (Exception e) {
     if (logger.isWarnEnabled()) {
       logger.warn("error occurred while mapping from AMQP properties to MessageHeaders", e);
     }
   }
   return headers;
 }
  /**
   * Maps headers from a Spring Integration MessageHeaders instance to the MessageProperties of an
   * AMQP Message.
   */
  @Override
  protected void populateStandardHeaders(
      Map<String, Object> headers, MessageProperties amqpMessageProperties) {
    String appId = getHeaderIfAvailable(headers, AmqpHeaders.APP_ID, String.class);
    if (StringUtils.hasText(appId)) {
      amqpMessageProperties.setAppId(appId);
    }
    String clusterId = getHeaderIfAvailable(headers, AmqpHeaders.CLUSTER_ID, String.class);
    if (StringUtils.hasText(clusterId)) {
      amqpMessageProperties.setClusterId(clusterId);
    }
    String contentEncoding =
        getHeaderIfAvailable(headers, AmqpHeaders.CONTENT_ENCODING, String.class);
    if (StringUtils.hasText(contentEncoding)) {
      amqpMessageProperties.setContentEncoding(contentEncoding);
    }
    Long contentLength = getHeaderIfAvailable(headers, AmqpHeaders.CONTENT_LENGTH, Long.class);
    if (contentLength != null) {
      amqpMessageProperties.setContentLength(contentLength);
    }
    String contentType = this.extractContentTypeAsString(headers);

    if (StringUtils.hasText(contentType)) {
      amqpMessageProperties.setContentType(contentType);
    }
    Object correlationId = headers.get(AmqpHeaders.CORRELATION_ID);
    if (correlationId instanceof byte[]) {
      amqpMessageProperties.setCorrelationId((byte[]) correlationId);
    }
    MessageDeliveryMode deliveryMode =
        getHeaderIfAvailable(headers, AmqpHeaders.DELIVERY_MODE, MessageDeliveryMode.class);
    if (deliveryMode != null) {
      amqpMessageProperties.setDeliveryMode(deliveryMode);
    }
    Long deliveryTag = getHeaderIfAvailable(headers, AmqpHeaders.DELIVERY_TAG, Long.class);
    if (deliveryTag != null) {
      amqpMessageProperties.setDeliveryTag(deliveryTag);
    }
    String expiration = getHeaderIfAvailable(headers, AmqpHeaders.EXPIRATION, String.class);
    if (StringUtils.hasText(expiration)) {
      amqpMessageProperties.setExpiration(expiration);
    }
    Integer messageCount = getHeaderIfAvailable(headers, AmqpHeaders.MESSAGE_COUNT, Integer.class);
    if (messageCount != null) {
      amqpMessageProperties.setMessageCount(messageCount);
    }
    String messageId = getHeaderIfAvailable(headers, AmqpHeaders.MESSAGE_ID, String.class);
    if (StringUtils.hasText(messageId)) {
      amqpMessageProperties.setMessageId(messageId);
    }
    Integer priority = getHeaderIfAvailable(headers, MessageHeaders.PRIORITY, Integer.class);
    if (priority != null) {
      amqpMessageProperties.setPriority(priority);
    }
    String receivedExchange =
        getHeaderIfAvailable(headers, AmqpHeaders.RECEIVED_EXCHANGE, String.class);
    if (StringUtils.hasText(receivedExchange)) {
      amqpMessageProperties.setReceivedExchange(receivedExchange);
    }
    String receivedRoutingKey =
        getHeaderIfAvailable(headers, AmqpHeaders.RECEIVED_ROUTING_KEY, String.class);
    if (StringUtils.hasText(receivedRoutingKey)) {
      amqpMessageProperties.setReceivedRoutingKey(receivedRoutingKey);
    }
    Boolean redelivered = getHeaderIfAvailable(headers, AmqpHeaders.REDELIVERED, Boolean.class);
    if (redelivered != null) {
      amqpMessageProperties.setRedelivered(redelivered);
    }
    String replyTo = getHeaderIfAvailable(headers, AmqpHeaders.REPLY_TO, String.class);
    if (replyTo != null) {
      amqpMessageProperties.setReplyTo(replyTo);
    }
    Date timestamp = getHeaderIfAvailable(headers, AmqpHeaders.TIMESTAMP, Date.class);
    if (timestamp != null) {
      amqpMessageProperties.setTimestamp(timestamp);
    }
    String type = getHeaderIfAvailable(headers, AmqpHeaders.TYPE, String.class);
    if (type != null) {
      amqpMessageProperties.setType(type);
    }
    String userId = getHeaderIfAvailable(headers, AmqpHeaders.USER_ID, String.class);
    if (StringUtils.hasText(userId)) {
      amqpMessageProperties.setUserId(userId);
    }
    String replyCorrelation =
        getHeaderIfAvailable(headers, AmqpHeaders.SPRING_REPLY_CORRELATION, String.class);
    if (StringUtils.hasLength(replyCorrelation)) {
      amqpMessageProperties.setHeader("spring_reply_correlation", replyCorrelation);
    }
    String replyToStack =
        getHeaderIfAvailable(headers, AmqpHeaders.SPRING_REPLY_TO_STACK, String.class);
    if (StringUtils.hasLength(replyToStack)) {
      amqpMessageProperties.setHeader("spring_reply_to", replyToStack);
    }
  }
  @Test
  public void testReplyToThreeDeepCustomCorrelationKey() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    final RabbitTemplate template =
        new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory));
    template.setCorrelationKey(CORRELATION_HEADER);
    Queue replyQueue = new Queue("replyTo2");
    template.setReplyQueue(replyQueue);

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setReplyTo("replyTo1");
    messageProperties.setCorrelationId("a".getBytes());
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    final AtomicInteger count = new AtomicInteger();
    final List<String> nestedReplyTo = new ArrayList<String>();
    final List<String> nestedCorrelation = new ArrayList<String>();
    doAnswer(
            new Answer<Object>() {
              public Object answer(InvocationOnMock invocation) throws Throwable {
                BasicProperties basicProps = (BasicProperties) invocation.getArguments()[4];
                nestedReplyTo.add(basicProps.getReplyTo());
                nestedCorrelation.add(basicProps.getCorrelationId());
                MessageProperties springProps =
                    new DefaultMessagePropertiesConverter()
                        .toMessageProperties(basicProps, null, "UTF-8");
                Message replyMessage = new Message("!dlrow olleH".getBytes(), springProps);
                if (count.incrementAndGet() < 2) {
                  Message anotherMessage = new Message("Second".getBytes(), springProps);
                  template.setReplyQueue(new Queue("replyTo3"));
                  replyMessage = template.sendAndReceive(anotherMessage);
                  nestedReplyTo.add(replyMessage.getMessageProperties().getReplyTo());
                  nestedCorrelation.add(
                      (String)
                          replyMessage.getMessageProperties().getHeaders().get(CORRELATION_HEADER));
                }
                template.onMessage(replyMessage);
                return null;
              }
            })
        .when(mockChannel)
        .basicPublish(
            Mockito.any(String.class),
            Mockito.any(String.class),
            Mockito.anyBoolean(),
            Mockito.anyBoolean(),
            Mockito.any(BasicProperties.class),
            Mockito.any(byte[].class));
    Message reply = template.sendAndReceive(message);
    assertNotNull(reply);

    assertEquals(3, nestedReplyTo.size());
    assertEquals("replyTo2", nestedReplyTo.get(0));
    assertEquals("replyTo3", nestedReplyTo.get(1));
    assertEquals("replyTo2", nestedReplyTo.get(2)); // intermediate reply

    assertEquals("replyTo1", reply.getMessageProperties().getReplyTo());
    assertEquals("a", new String(reply.getMessageProperties().getCorrelationId(), "UTF-8"));
  }
Пример #25
0
    @Override
    public void run() {
      try {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        while (true) {
          final Event event = events.take();
          ILoggingEvent logEvent = event.getEvent();

          String name = logEvent.getLoggerName();
          Level level = logEvent.getLevel();

          MessageProperties amqpProps = new MessageProperties();
          amqpProps.setDeliveryMode(deliveryMode);
          amqpProps.setContentType(contentType);
          if (null != contentEncoding) {
            amqpProps.setContentEncoding(contentEncoding);
          }
          amqpProps.setHeader(CATEGORY_NAME, name);
          amqpProps.setHeader(CATEGORY_LEVEL, level.toString());
          if (generateId) {
            amqpProps.setMessageId(UUID.randomUUID().toString());
          }

          // Set timestamp
          Calendar tstamp = Calendar.getInstance();
          tstamp.setTimeInMillis(logEvent.getTimeStamp());
          amqpProps.setTimestamp(tstamp.getTime());

          // Copy properties in from MDC
          Map<String, String> props = event.getProperties();
          Set<Entry<String, String>> entrySet = props.entrySet();
          for (Entry<String, String> entry : entrySet) {
            amqpProps.setHeader(entry.getKey(), entry.getValue());
          }
          String[] location = locationLayout.doLayout(logEvent).split("\\|");
          if (!"?".equals(location[0])) {
            amqpProps.setHeader(
                "location", String.format("%s.%s()[%s]", location[0], location[1], location[2]));
          }
          String msgBody;
          String routingKey = routingKeyLayout.doLayout(logEvent);
          // Set applicationId, if we're using one
          if (applicationId != null) {
            amqpProps.setAppId(applicationId);
          }

          if (abbreviator != null && logEvent instanceof LoggingEvent) {
            ((LoggingEvent) logEvent).setLoggerName(abbreviator.abbreviate(name));
            msgBody = layout.doLayout(logEvent);
            ((LoggingEvent) logEvent).setLoggerName(name);
          } else {
            msgBody = layout.doLayout(logEvent);
          }

          // Send a message
          try {
            Message message = null;
            if (AmqpAppender.this.charset != null) {
              try {
                message = new Message(msgBody.getBytes(AmqpAppender.this.charset), amqpProps);
              } catch (UnsupportedEncodingException e) {
                message = new Message(msgBody.getBytes(), amqpProps); // NOSONAR (default charset)
              }
            }

            message = postProcessMessageBeforeSend(message, event);
            rabbitTemplate.send(exchangeName, routingKey, message);
          } catch (AmqpException e) {
            int retries = event.incrementRetries();
            if (retries < maxSenderRetries) {
              // Schedule a retry based on the number of times I've tried to re-send this
              retryTimer.schedule(
                  new TimerTask() {
                    @Override
                    public void run() {
                      events.add(event);
                    }
                  },
                  (long) (Math.pow(retries, Math.log(retries)) * 1000));
            } else {
              addError(
                  "Could not send log message "
                      + logEvent.getMessage()
                      + " after "
                      + maxSenderRetries
                      + " retries",
                  e);
            }
          }
        }
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
 private void checkDeliveryMode(Message<?> requestMessage, MessageProperties messageProperties) {
   if (this.defaultDeliveryMode != null
       && requestMessage.getHeaders().get(AmqpHeaders.DELIVERY_MODE) == null) {
     messageProperties.setDeliveryMode(this.defaultDeliveryMode);
   }
 }