In the onMessage event, if the message does not get converted as a Spring Integration message it will try and use the MessageBuilder to rebuild it. But it doesn't include the headers. This seems incorrect. We're using Apache Artemis 1.2 and Spring 4.2.5.
Here is the code in question from SubscribableJmsChannel:
public void onMessage(javax.jms.Message message) {
Message<?> messageToSend = null;
try {
Object converted = this.jmsTemplate.getMessageConverter().fromMessage(message);
if (converted != null) {
messageToSend = (converted instanceof Message<?>) ? (Message<?>) converted
: this.messageBuilderFactory.withPayload(converted).build();
this.dispatcher.dispatch(messageToSend);
}
else if (this.logger.isWarnEnabled()) {
logger.warn("MessageConverter returned null, no Message to dispatch");
}
}
Sometimes we see messages get converted as Spring messages and sometimes they are attempted to be converted from the Spring message payload (1 in 20 times or so). In that case, the below code seems to try and handle recreating the Spring message envelope - but it will drop the headers.
What's interesting is that our code is always sending the exact same message in a load test. I haven't figured out why the messages would be received differently yet.
Related
The requirement is like to process the messages from dead letter queue by exposed a REST service API(Spring Boot).
So that once REST service is called, one message will be consumed from the DL queue and will publish in the main queue again for processing.
#RabbitListener(queues = "QUEUE_NAME") consumes the message immediately which is not required as per the scenario. The message only has to be consumed by the REST service API.
Any suggestion or solution?
I do not think RabbitListener will help here.
However you could implement this behaviour manually.
Spring Boot automatically creates RabbitMq connection factory so you could use it. When http call is made just read single message from the queue manually, you could use basic.get to synchronously get just one message:
#Autowire
private ConnectionFactory factory
void readSingleMessage() {
Connection connection = null;
Channel channel = null;
try {
connection = factory.newConnection();
channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
GetResponse response = channel.basicGet(QUEUE_NAME, true);
if (response != null) {
//Do something with the message
}
} finally {
//Check if not null
channel.close();
connection.close();
}
}
If you are using Spring; you can avoid all the boilerplate in the other answer using RabbitTemplate.receive(...).
EDIT
To manually ack/reject the message, use the execute method instead.
template.execute(channel -> {
GetResponse got = channel.basicGet("foo", false);
// ...
channel.basicAck(got.getEnvelope().getDeliveryTag(), false);
return null;
});
It's a bit lower level, but again, most of the boilerplate is taken care of for you.
I have a java spring integration project that is receving emails through the below code:
ClassPathXmlApplicationContext ac =
new ClassPathXmlApplicationContext(
"/integration/gmail-imap-idle-config.xml");
DirectChannel inputChannel = ac.getBean("receiveChannel", DirectChannel.class);
inputChannel.subscribe(message -> {
org.springframework.messaging.Message<MimeMailMessage> received =
(org.springframework.messaging.Message<MimeMailMessage>) message;
log.info("content" + message);
List<String> sentences = null;
try {
} catch (Exception e) {
}
I get the email, and I can get the subject, but I can never actually extract the message body. How do I do this?
Thank you!
You have to use this option on the channel adapter:
simple-content="true"
See its description:
When 'true', messages produced by the source will be rendered by 'MimeMessage.getContent()'
which is usually just the body for a simple text email. When false (default) the content
is rendered by the 'getContent()' method on the actual message returned by the underlying
javamail implementation.
For example, an IMAP message is rendered with some message headers.
This attribute is provided so that users can enable the previous behavior, which just
rendered the body.
But still it is doubtful, since I see in case of GMail message it is never simple. The content is a MimeMultipart and we need to read its parts to get access to the real body.
So, this is how you should change your code as well:
log.info("content" + ((MimeMultipart) ((MimeMessage) message.getPayload()).getContent()).getBodyPart(0).getContent());
I use Camel spring-ws component to expose SOAP web service by specifying it in the 'from' part of the route.
It happens to be, that at the end of the route logic, the 'out' message of Exchange is not populated, however the 'in' message contains desired response data.
Default convention for producer component is to use 'in' message of exchange if 'out' is not present when generating final response.
SpringWebserviceConsumer however only supports scenario when final exchange has the 'out' message.
Here is the snippet of code from https://github.com/apache/camel/blob/master/components/camel-spring-ws/src/main/java/org/apache/camel/component/spring/ws/SpringWebserviceConsumer.java:
public void invoke(MessageContext messageContext) throws Exception {
Exchange exchange = getEndpoint().createExchange(ExchangePattern.InOptionalOut);
populateExchangeFromMessageContext(messageContext, exchange);
// start message processing
getProcessor().process(exchange);
if (exchange.getException() != null) {
throw exchange.getException();
} else if (exchange.getPattern().isOutCapable()) {
Message responseMessage = exchange.getOut(Message.class);
if (responseMessage != null) {
Source responseBody = responseMessage.getBody(Source.class);
WebServiceMessage response = messageContext.getResponse();
configuration.getMessageFilter().filterConsumer(exchange, response);
XmlConverter xmlConverter = configuration.getXmlConverter();
xmlConverter.toResult(responseBody, response.getPayloadResult());
}
}
}
This results in no response generated to the SOAP request.
Question:
Is this a bug/limitation of camel-spring-ws or I'm not using the spring-ws consumer correctly?
Otherwise, it sounds like I have to explicitly set the exchange patter to InOut?
Until CAMEL-10888 is released, as a work-around, in the route, you can set the exchange pattern to InOut to get not-null 'out' message of Exchange:
.setExchangePattern(ExchangePattern.InOut)
I have a C++ component which passes message to JMS broker via tcp using ActiveMQ. My broker is written in JAVA. I want these two to communicate; to C++ component send messages to the JAVA broker.
On C++ side what I am doing is creating a message (using protocol buffer), converting that to vector of bytes and passing it to the broker. On JAVA side (broker), I am constantly listening and acting upon a received message.
Now, I can tell that the system somehow works, since when I execute my C++ component (and when it passes the messages), I see my JAVA broker printing an error message: unexpected error:null per each message that I am sending from my C++ component. This means that at least my messages do reach to the broker, but somehow they cannot be decrypted, hence the null issue.
I am using the following for composing the message from C++ side:
// convert pointmsg to byte
int size = pointmsg.ByteSize();
char* byteArray = new char[size];
pointmsg.SerializeToArray(byteArray, size);
// convert bytearray to vector
vector<unsigned char> v(byteArray, byteArray + sizeof byteArray / sizeof byteArray[0]);
// pass as a vector
BytesMessage *message = session->createBytesMessage();
message->writeBytes(v);
producer->send(message);
printf("Sent message #%d from thread %s\n", ix + 1, threadIdStr.c_str());
pointmsg is just an object that I create and fill in, and it is not null, I tested it already and it has data in it. I am converting pointmsg to byte array since this is the way to pass an object as far as I read in the documantation. And since the writeBytes() function expects a vector, I am converting the byte array into a vector. I suspect there might be some problem in this part.
On JMS side I am simply listening the upcoming messages with:
public void onMessage(final javax.jms.Message message) {
final Timer traceTimer = new Timer();
final long messageReceived = System.currentTimeMillis();
try {
if (message instanceof ActiveMQBytesMessage) {
final ActiveMQBytesMessage amqBytesMsg = (ActiveMQBytesMessage) message;
final byte[] buffer = amqBytesMsg.getContent().data;
final String msgType = amqBytesMsg.getStringProperty(LLCom.MSG_PROP_CLASS_NAME);
final String topic = amqBytesMsg.getStringProperty(LLCom.MSG_PROP_TOPIC_NAME);
String msgLookUpType;
if (topic == null || topic.isEmpty()) {
// get message class name: foo.bar$MessageMsg
msgLookUpType = msgType.split("\\$")[1];
} else {
// it's a topic we assume, that all subscribers have the
// correct type
msgLookUpType = topic;
}
if (logger.isDebugEnabled())
logger.debug("Router(" + name + ") received message ( " + buffer.length + "bytes)of type or topic " + msgLookUpType);
final Message req = parsers.createMessage(buffer, msgType);
// process explicit topic/queue subscriber
processServiceMessage(msgLookUpType, messageReceived, amqBytesMsg, req, traceTimer);
} else {
logger.error("Not supported JMS MessageType: " + message);
}
} catch (final Exception e) {
logger.error("Unexpected error: " + e.getMessage());
// e.printStackTrace();
}
}
When I debug it I can see that msgType and topic variables (on JMS side) are coming as null, which means that activemq message is somehow not decrypted. What could be the reason for that? I can see the message is being sent, received but not understood.
Any thoughts?
Update: I noticed that I am expecting to get stringProperties on JMS side, which I am not setting on C++ side, but I am not sure whether it causes the problem or not.
Ok, It seems the error was related to set properties, msgType and topic, I gave them the expected strings with using setStringProperty() on C++ side with the required methods, and now that initial error is gone.
message->setStringProperty();
everyone. I have an HTTP API for posting messages in a RabbitMQ broker and I need to implement the request-response pattern in order to receive the responses from the server. So I am something like a bridge between the clients and the server. I push the messages to the broker with specific routing-key and there is a Consumer for that messages, which is publishing back massages as response and my API must consume the response for every request. So the diagram is something like this:
So what I do is the following- For every HTTP session I create a temporary responseQueue(which is bound to the default exchange, with routing key the name of that queue), after that I set the replyTo header of the message to be the name of the response queue(where I will wait for the response) and also set the template replyQueue to that queue. Here is my code:
public void sendMessage(AbstractEvent objectToSend, final String routingKey) {
final Queue responseQueue = rabbitAdmin.declareQueue();
byte[] messageAsBytes = null;
try {
messageAsBytes = new ObjectMapper().writeValueAsBytes(objectToSend);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
MessageProperties properties = new MessageProperties();
properties.setHeader("ContentType", MessageBodyFormat.JSON);
properties.setReplyTo(responseQueue.getName());
requestTemplate.setReplyQueue(responseQueue);
Message message = new Message(messageAsBytes, properties);
Message receivedMessage = (Message)requestTemplate.convertSendAndReceive(routingKey, message);
}
So what is the problem: The message is sent, after that it is consumed by the Consumer and its response is correctly sent to the right queue, but for some reason it is not taken back in the convertSendAndReceived method and after the set timeout my receivedMessage is null. So I tried to do several things- I started to inspect the spring code(by the way it's a real nightmare to do that) and saw that is I don't declare the response queue it creates a temporal for me, and the replyTo header is set to the name of the queue(the same what I do). The result was the same- the receivedMessage is still null. After that I decided to use another template which uses the default exchange, because the responseQueue is bound to that exchange:
requestTemplate.send(routingKey, message);
Message receivedMessage = receivingTemplate.receive(responseQueue.getName());
The result was the same- the responseMessage is still null.
The versions of the amqp and rabbit are respectively 1.2.1 and 1.2.0. So I am sure that I miss something, but I don't know what is it, so if someone can help me I would be extremely grateful.
1> It's strange that RabbitTemplate uses doSendAndReceiveWithFixed if you provide the requestTemplate.setReplyQueue(responseQueue). Looks like it is false in your explanation.
2> To make it worked with fixed ReplyQueue you should configure a reply ListenerContainer:
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(rabbitConnectionFactory);
container.setQueues(responseQueue);
container.setMessageListener(requestTemplate);
3> But the most important part here is around correlation. The RabbitTemplate.sendAndReceive populates correlationId message property, but the consumer side has to get deal with it, too: it's not enough just to send reply to the responseQueue, the reply message should has the same correlationId property. See here: how to send response from consumer to producer to the particular request using Spring AMQP?
BTW there is no reason to populate the Message manually: You can just simply support Jackson2JsonMessageConverter to the RabbitTemplate and it will convert your objectToSend to the JSON bytes automatically with appropriate headers.