Not able to send data on reply channel using tcp-outbound-gateway with ActiveMQ - tcp

My Requirement is to get data from TCP, after getting the data from TCP convert into java object and send on ActiveMQ. Post that after doing some processing need to send the acknowledgement/response code on same channel on TCP.
To fulfill this requirement I am using tcp-outbound-gateway as bidirectional communication is required.
Problem is I am not able to send acknowledgement with ActiveMQ. If I comment out ActiveMQ part and write a dummy string on replyChannel it is visible, but the moment I send the object on Active MQ queue it is giving me a message "null reply received for nothing to send".
I am using a new queue to get the acknowledgement and trying to put the response on reply channel of tcp-outbound-gate, but error message is no output-channel or replyChannel header available.
I got the MessageHeaders details via Incoming message and sending it via queue to use copyHeader. I am able to set the headers and see paylod in Message object, verified the same by applying Interceptos on reply channel, but still getting the same error no output-channel or replyChannel header available.
Code is :
<int:gateway id="gw" default-reply-channel="replyChannel" default-reply-timeout="10000" service-interface= "com.telnet.core.integration.connection.ParseTcpConfiguration$SimpleGateway"
default-request-channel="${server.inboundChannel}"/>
<int:channel id="telnetLandingChannel" />
<ip:tcp-connection-factory id="serverFactory" type="server" host="${server.host}" port="${server.port}" single-use="false"
serializer="${server.serializer}" deserializer="${server.serializer}" task-executor="serverFactoryTaskExecutor"/>
<ip:tcp-inbound-gateway id="serverInboundAdpater" request-channel="telnetLandingChannel" reply-channel="replyChannel"
connection-factory="serverFactory" error-channel="errorChannel" reply-timeout="1000000" auto-startup="false"/>
<int:channel id="replyChannel"></int:channel>
<beans:bean id="acknowledgementHandler" class= "com.telnet.core.integration.AcknowledgementHandler">
</beans:bean>
<int:channel id="incidentDispatchMessageChannel" datatype="${incident.interaction.dispatch.response.datatype}"></int:channel>
<int-jms:message-driven-channel-adapter id="incidentDispatchMessageChannelAdapter" error-channel="errorChannel"
connection-factory="mqConnectionFactory"
destination-name="${incident.processing.tcp.dispatch.response.queues}"
channel="incidentDispatchMessageChannel"/>
<int:transformer id="incidentMessageActivator"
input-channel="incidentDispatchMessageChannel"
output-channel="replyChannel"
ref="acknowledgementHandler" method="incidentAck">
</int:transformer>
public Message incidentAck(final DefaultIncidentAcknowledgeMessage defaultIncidentAcknowledgeMessage){
MessageHeaders ms = (MessageHeaders)defaultIncidentAcknowledgeMessage.getProperties().get("MessageHeader");
Message<String> message = MessageBuilder.withPayload("1").copyHeaders(ms).build();
return message;
}

Need to see your Integration configuration though, but let me guess that you are loosing TemporaryReplyChannel object in the replyChannel header because it isn't Serializable. Consider to use:
<int:header-enricher>
<int:header-channels-to-string/>
</int:header-enricher>
somewhere before sending to the ActveMQ.
See Reference Manual for more information.
UPDATE
Looks like this is a continuation of Receive the acknowledgement from TCP server to our application using spring Integration. And I see you still use the same replyChannel for many places. That isn't going to work properly. The replyChannel header from the gateway can accept only one reply. Even if we figure out what to do with the reply from ActiveMQ, the TemporaryReplyChannel will be fulfilled with the reply from the TCP Outbound Gateway.
If I understand you correctly, alongside with the reply from the TCP you need also get some message from ActiveMQ. And send everything as a reply to the gateway call. For this purpose I suggest you to consider to use Aggregator and figure out some custom correlation strategy to match the reply from TCP to that acknowledge from the ActiveMQ. After aggregation you really can just use the existing replyChannel header to reply to the gateway.

Related

Do not print stack trace on Postfix's mail delivery failure notification

When our service fails to deliver an email, the rejection notification returned to the sender contains the stack trace of the code that failed. Is there a way to send the delivery notification, without the attached errors?
We have a postfix server that handles incoming emails in a catchall python script. That script uploads the email to one of our services and throws an exception in case it failed.
This is the template we are using
failure_template = <<EOF
Charset: us-ascii
From: MAILER-DAEMON (Mail Delivery System)
Subject: Undelivered Mail Returned to Sender
Postmaster-Subject: Postmaster Copy: Undelivered Mail
This is the mail system at host $myhostname.
I'm sorry to have to inform you that your message could not
be delivered to one or more recipients. It's attached below.
For further assistance, please send mail to <postmaster>
If you do so, please include this problem report. You can
delete your own text from the attached returned message.
The mail system
EOF
Expected result would be just the template notification, without the strack trace of the catch-all script.
The mail server simply includes in the bounce whatever your Python program displays on its standard error. Maybe call the script via a wrapper which saves the standard error to a sane place (or even discards it, if you are sure it never contains anything useful).
#!/bin/sh
python3 /path/to/deliver.py 2>>/var/log/deliver.log
Your mail server obviously needs to have write access to the log, and you'll probably want to set up periodic log rotation for the file.
Probably a better overall approach is for the Python program to not crash.

FCM notification reply to server

There is a push notification service that sends a message from a web server to an app device. The app has onMessageReceived() method implemented. However, not all the messages are being delivered and I have read somewhere that the delivery_receipt_request field, when set to true then (FCM), replies to the server mentioning the message being either delivered or not. I want to know that how can I catch that reply from the app if the message is delivered to my sender's side code.
Option 1: Via XMPP
You need to run an XMPP client on your backend. This client should connect to FCM with your project parameters. You will then be able to process message delivery stanzas sent to you by FCM. Here are the baby steps:
Follow the steps in https://www.npmjs.com/package/node-xcs to setup the XMPP client, exporting environmental variables with your FCM project parameters.
You can send messages through there.
Listen for message delivery stanzas:
client.on('stanza', function(stanza) {
//HERE IS WHERE YOU PROCESS THE STANZA
console.log('Please process me. I AM, the stanza: ', stanza.toString())
})
The stanza you will get for message delivery will look like this:
<message id="">
<gcm xmlns="google:mobile:data">
{
"category":"com.example.yourapp", // to know which app sent it
"data":
{
“message_status":"MESSAGE_SENT_TO_DEVICE",
“original_message_id”:”m-1366082849205”
“device_registration_id”: “REGISTRATION_ID”
},
"message_id":"dr2:m-1366082849205",
"message_type":"receipt",
"from":"gcm.googleapis.com"
}
</gcm>
</message>
Currently only CCS (XMPP) supports upstream messaging. Knock yourself out.
Option 2: Via HTTP
Now, if you decide to use the FCM HTTP protocol instead to send the messages, then you will have to interpret the response that you get back when you make the HTTP call. You can tell whether the message was delivered or not by looking at the HTTP response header and the error in the body of the response. The structure of the response is described here: https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream
Again, knock yourself out.

Why can't I defer sending a message for a one-way client

What is the rationale behind the following exception when trying to Defer the sending of a message on a one-way client:
System.InvalidOperationException "Cannot use ourselves as timeout manager because we're a one-way client"
A one-way client is a Rebus client that is not capable of receiving messages, so it has no input queue.
The way await bus.Defer(...) works, is by sending a message with some special headers to a "timeout manager", which by default is the endpoint that defers the message.
But since a one-way client has no input queue, it has no place to send the deferred message to.
You can make a one-way client defer messages by configuring an external timeout manager like this:
Configure.With(...)
.(...)
.Options(o => o.UseExternalTimeoutManager(anotherQueue))
.Start();
which will then cause the client to send the deferred message to that queue.
Moreover, you would have to manually set the rbs2-defer-recipient header to some other input queue, so that the timeout manager knows where to send the message when it is time to be consumed(*).
I hope that explains it :) please let me know if it is not clear.
*) This is actually not the case with Rebus 4, because bus.Defer uses the normal endpoint mappings to route messages.
If Rebus.AzureServiceBus is used there is more simple (or hacky) way to send delayed messages.
You have to specify 2 headers: rbs2-deferred-until and rbs2-defer-recipient and call Publish method like in the example.
var deferredUntil = DateTimeOffset.UtcNow.AddDays(1);
var headers = new Dictionary<string, string>();
headers.Add(Headers.DeferredUntil, deferredUntil.ToString("O", CultureInfo.InvariantCulture));
headers.Add(Headers.DeferredRecipient, #"Rebus requires this ¯\_(ツ)_/¯");
await bus.Publish(new SomeMessage(), headers);
Note: rbs2-defer-recipient is required by Rebus so any dummy values are okay.
Be careful, it looks like a workaround so it may not work after Rebus.AzureServiceBus update. It works for me in 5.0.1.

Asynchronous WebSockets in Winhttp Windows 8

I want just to add WebSockets to my app that uses WinHTTP in async mode.
When I need a WebSocket I call the following.
Before sending request:
WinHttpSetOption(context->hRequest, WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET, NULL, 0);
In WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE:
appContext->pIoRequest->hWebSocketHandle = WinHttpWebSocketCompleteUpgrade(appContext->hRequest, NULL);
WinHttpWebSocketReceive(appContext->pIoRequest->hWebSocketHandle, appContext->pszOutBuffer,RESPONSE_BUFFER_SIZE, NULL, NULL);
all without errors.
Now I see in Fiddler that the server sends some data to my WebSocket but there is no WINHTTP_CALLBACK_STATUS_READ_COMPLETE triggered.
Any ideas why this is? How can I read asynchronously from my WebSocket? Sending data to the WebSocket works well.
Omg! I found how its work!
You MUST call additional WinHttpSetStatusCallback to set WebSocket callback for WebSocketHandle returned in WinHttpWebSocketCompleteUpgrade and this callback MUST differ then that from call WinHttpWebSocketCompleteUpgrade was made!
It is no possible to set a context pointer by WinHttpSetOption with WINHTTP_OPTION_CONTEXT_VALUE flag! Its not work. dwContext In WebSocketCallback has wrong data. Call to WinHttpQueryOption in WebSocketCallback return wrong context data. I think that is a BUG in Windows 8.1. I write my own handler to connect my context with WebSocketHandle.
All of this is NOT documented in MSDN! Most of all, I did not google any info about async winhttp websocket usage... So, I am the first=) I will be very glad if my research will help you!
It seems websockets do not get PING and PONG messages to the callback!

How to check MailMessage was delivered in .NET?

Is there a way to check if SmtpClient successfully delivered an email? SmtpClient.Send() does not appear to return anything other than an exception. So if the method completes is it safe to assume the email will be successfully sent to the appropriate email box? My code is below:
MailMessage emailMessage = new MailMessage();
emailMessage.Subject = SubjectText;
emailMessage.IsBodyHtml = IsBodyHtml;
emailMessage.Body = BodyText;
emailMessage.From = new MailAddress(Settings.Default.FromEmail,Settings.Default.FromDisplayName);
//add recipients
foreach (string recipientAddress in RecipientAddresses.Split(new char[{','},StringSplitOptions.RemoveEmptyEntries))
emailMessage.To.Add(recipientAddress);
using (SmtpClient smtpClient = new SmtpClient())
{
smtpClient.Send(emailMessage);
}
No, there is no reliable way to find out if a message was indeed delivered.
Doing so will require access to the end SMTP server for every person you are emailing.
If you do not get an exception, you can assume that the SMTP server did its best to deliver the email.
There's no way to be 100% sure that a mail message has been received when sent via SmtpClient due to the way email works. The fact that SmtpClient doesn't throw an exception essentially means that you've done everything right, but a failure can happen further down the line, for example:
The receiving mail server could reject the mail
An intermediate mail server could reject the mail
The server that SmtpClient is transmitting mail through could decide to refuse to transmit the mail
One solution you could use is to create an httphandler for your website images. If you send an HTML message which includes at least 1 image, then you could embed querystring data to the end of that image. This could even be something like a 1x1 transparent image. When the user reads the email, this sends the request to the server to fetch the image data, and in turn, you could capture that request and denote that the message was read.
This is not bulletproof however, because most email clients block images by default unless the user specifies they would like to view images in the email.
If the recipient e-mail address is valid you don't get an immediate return value about the successful delivery of the message; see the signature:
public void Send(MailMessage message)
The SMTP server will notify the sender (or whoever you specify for the notification) almost immediately with an 'Undeliverable' notification whenever the recipient e-mail address is invalid/fake.
SMTP servers are required to periodically retry delivery. When the recipient e-mail address is a valid address but for some reason the SMTP server could not deliver the message, the SMTP server will return a failure message to the sender if it cannot deliver the message after a certain period of time.
RFC 2821 contains more details.
From section 2.1 Basic Structure
In other words, message transfer can occur in a single connection
between the original SMTP-sender and the final SMTP-recipient, or can
occur in a series of hops through intermediary systems. In either
case, a formal handoff of responsibility for the message occurs: the
protocol requires that a server accept responsibility for either
delivering a message or properly reporting the failure to do so.
See sections 4.5.4 and 4.5.5
From section 6.1 Reliable Delivery and Replies by Email
If there is a delivery failure after acceptance of a message, the
receiver-SMTP MUST formulate and mail a notification message. This
notification MUST be sent using a null ("<>") reverse path in the
envelope. The recipient of this notification MUST be the address from
the envelope return path (or the Return-Path: line).

Resources