How to put failed custom object of javax.mail.Message into jms queue (using Activemq) - activemq

I am creating utiltiy which send mail using my outlook account, to do so I am creating object of javax.mail.Message and send it, if message sending is failed due to SendingFailedException, I want to add those messages into jms queue, and at the other end listener will run at every 10 min interval to consume these messages from the queue and try to resend those messages.
I have gone through some of the stackoverflow topics related to same, they instructed to change message into xml or in JSON, I just want to know how to deal with it, if that would be the way to implement this.
Thanks in advance

Using the MimeMessage.writeTo method you can turn the message into a byte stream. Collect it in a ByteArrayOutputStream and then include the bytes in the JMS message. At the other end, you can reconstitute the message using the MimeMessage constructor that takes an InputStream.
For example:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
msg.writeTo(bos);
byte[] data = bos.toByteArray();
// put the data in a JMS message
// in the receiver, extract the byte array from the message
byte[] data = ...
MimeMessage msg = new MimeMessage(session, data);
Sorry, I can't help you with the JMS part.

Related

How to send a message to an endpoint in Mule 4 to trigger a flow

With Mule 3 it was possible to send messages asynchronously to an endpoint using MuleClient:
MuleClient client = new MuleClient(muleContext);
client.dispatch("vm://vm.queue", "Message Payload", null);
Is there a way to migrate this functionality in Mule 4 since MuleClient has been removed?
I came across a post that suggested getting the flow by name and publishing the message to the flow as follows
Flow flow = registry.lookupByName("MyFlow").get();
InputEvent event = new DefaultInputEvent();
event.message(Message.of(payload));
flow.execute(event);
but I get a ClassNotFoundException for the class org.mule.runtime.internal.event.DefaultInputEvent
Using Harshank's recommendation I was able to push messages to a flow simply by getting a reference to the flow and triggering the flow by sending messages to the source.
Flow flow = registry.lookupByName(flowName).get();
ComponentLocation location = DefaultComponentLocation.from(flowName + "/source");
...
Message message = Message.of(payload);
CoreEvent coreEvent = CoreEvent.builder(EventContextFactory.create(flow, location)).message(message).build();
flow.process(coreEvent);
This is a much cleaner solution than what is implemented in the blog and works from beans initialized in the Spring module. As aled mentioned, this is bad practice, but in the interest of time it is a solution.

Get messages by property or header in RabbitMQ

I'm new in to RabbitMQ and I've faced a problem. I'm trying to get messages from queue by API method. I've made that by now I want to get messages from queue by header or property if it is possible. I read the documentation about HTTP API. I have not found such an API for filtering messages by some headers or properties.
I use that kind of API to get messages from queue:
/api/queues/vhost/name/get
and in the body:
{"count":20,"ackmode":"ack_requeue_true","encoding":"auto"}
I was thinking, maybe it is possible to somehow pass some filter in the body so it could filter and return the message what I want.
This is how my message looks like :
I have tried to pass in the body type = "myType" or header = "myHeader"
I've made that by now I want to get messages from queue by header or
property if it is possible.
RabbitMQ only delivers messages in order from a queue. There is no way to filter once a message is in a queue.
You can filter messages as they are published to an exchange, however. Use a headers exchange and bind queues based on header values. Then, each queue will contain the messages you expect and you can then consume from them.
The RabbitMQ tutorials have a section that use a "headers exchange". Use that as a guide.
Finally, only use the HTTP API for testing. It is a very inefficient way to retrieve messages.
NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.
A bit late to the party, but I think you can achieve the same like this
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(hostname);
Connection conn = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueBind(queueName, exchangeName, "");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
Map<String, Object> headers = delivery.getProperties().getHeaders();
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "', with header : " + headers.get("TestHeader") );
};
channel.basicConsume(queue, true, deliverCallback, consumerTag -> { });

Azure Queue, AddMessage then UpdateMessage

Is it possible to Add a message to an Azure queue then, in the same flow, update or delete that message?
The idea would be to use the queue to ensure that some work gets done - there's a worker role monitoring that queue. But, the Web role which added the message may be able to make some progress toward (and sometimes even to complete) the transaction.
The worker would already be designed to handle double-delivery and reprocessing partially handled messages (from previous, failed worker attempts) - so there isn't a technical problem here, just time inefficiency and some superfluous storage transactions.
So far it seems like adding the message allows for a delivery delay, giving the web role some time, but doesn't give back a pop-receipt which it seems like we'd need to update/delete the message. Am I missing something?
It seems this feature was added as part of the "2016-05-31” REST API
we now make pop receipt value available in the Put Message (aka Add Message) response which allows users to update/delete a message without the need to retrieve the message first.
I suggest you follow these steps as it worked for me
How to: Create a queue
A CloudQueueClient object lets you get reference objects for queues. The following code creates a CloudQueueClient object. All code in this guide uses a storage connection string stored in the Azure application's service configuration. There are also other ways to create a CloudStorageAccount object. See CloudStorageAccount documentation for details.
// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the queue client
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
Use the queueClient object to get a reference to the queue you want to use. You can create the queue if it doesn't exist.
// Retrieve a reference to a queue
CloudQueue queue = queueClient.GetQueueReference("myqueue");
// Create the queue if it doesn't already exist
queue.CreateIfNotExists();
How to: Insert a message into a queue
To insert a message into an existing queue, first create a new CloudQueueMessage. Next, call the AddMessage method. A CloudQueueMessage can be created from either a string (in UTF-8 format) or a byte array. Here is code which creates a queue (if it doesn't exist) and inserts the message 'Hello, World':
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");
// Create the queue if it doesn't already exist.
queue.CreateIfNotExists();
// Create a message and add it to the queue.
CloudQueueMessage message = new CloudQueueMessage("Hello, World");
queue.AddMessage(message);
For more details, refer this link.
http://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-queues/
Girish Prajwal

2 identical message from buffer.CreateMessage() in WCF right approach?

What is best approach to create 2 identical copy from CreateBufferedCopy in WCF ?
approach 1 or approach 2 and why?
enter code here
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
request = buffer.CreateMessage();
//approach 1
Message message1 = buffer.CreateMessage();
Message message2 = buffer.CreateMessage();
//approach 2
Message message1 = request;
Message message2 = request;
foreach (MessageHeader h in message1 .Headers)
{
Console.WriteLine("\n{0}\n", h);
}
return null;
}
Messages in WCF are read-once. This is because they may be streamed and therefore the streamed data will not be magically resent
To "process" a message more than once you have to copy it and the only way to copy it is to use a MessageBuffer as you have in approach 1. Processing a message may be just inspecting the body to perform data dependent routing of the content but as soon as you are going to touch the body you must copy it for the message to be successfully processed by the rest of the WCF infrastructure
Note that if all you want to do is look at the headers you do not need to copy the message as headers are always buffered - it is only the body that is potentially streamed
as #hyp says, approach 2 does not copy the message at all - it just gives you two references to the same message - it may be worth rereading something about reference types and value types - here's an article that may help
I never used the MessageBuffer before but approach 2 won't give you what you're looking for. In approach 2 you're only assigning the reference of the request to two objects so you still have only 1 request object. In other words changes to Message1 will be reflected in Message2.

Getting an item from the MSMQ Journal, which WCF created

I have a message in a Journal of a Private queue (.\Private$\theQueue\Journal$)
The message was created by WCF and processed (thus on the Journal).
The problem is I want to get the message (the body is too large to view in the Admin Tools) so i have created the following code
MessageQueue myQueue = new MessageQueue(txtQueueName.Text);
Message peekByLookupId = myQueue.PeekById(txtLookUpId.Text);
StreamReader reader = new StreamReader(peekByLookupId.BodyStream);
txtResult.Text = reader.ReadToEnd();
but the StreamReader does not return any result for the ReadToEnd. however the Stream does have a length (peekByLookupId.BodyStream.Length) of 1676
does any one have the code to peek at the XML of the object which WCF created (using the DataContractFormatter)
Or does anyone know where is the DataContractFormatter, as i could use this deserialise the object. (I have added the System.Runtime.Serialization to the project and it still does not recognise the object)
Many thanks
In the end I pulled out the body stream as bytes (do not convert into a string). converted into hex and viewed in WinHex..
there has to be a better way