How to return error response to calling channel when TCP destination gives 'Connection refused' - mirth

I have this pattern:
channel ESANTE_MPI_CREATE_PATIENT_LISTENER (with a MLLP listener) calls channel ESANTE_MPI_CREATE_PATIENT that calls a TCP destination.
If connection cannot be done in the TCP destination inside ESANTE_MPI_CREATE_PATIENT then this channel reports an error for this destination:(ERROR: ConnectException: Connection refused (Connection refused))
The response transformer does not seem to be called (which is normal as there is no response).
I wonder how I can report the error back to the calling channel ESANTE_MPI_CREATE_PATIENT_LISTENER ?
PS: When tcp destination responds, then I use the response transformer to parse the received frame and create a response message (json error/ok) for the calling channel. Everything works fine here.
My question ends up with: How to trap a Connection refused in a TCP destination to create a response message.

I finally managed this by using the postprocessor script in ESANTE_MPI_CREATE_PATIENT to get the response of the connector and then force a message.
// fake error message prepared for connection refused.
// we put this as the response of the channel destination in order to force a understandable error message.
const sErrorMsg = {
status: "error",
error: "connection refused to eSanté MPI"
};
const TCP_CONNECTOR_ESANTE_MPI_RANK = 2; // WARNING: be sure to take the correct connector ID as displayed into destination.
const TCP_CONNECTOR_ESANTE_MPI_DNAME = 'd' + TCP_CONNECTOR_ESANTE_MPI_RANK; // WARNING: be sure to take the correct connector ID as displayed into destination.
/*
var cms = message.getConnectorMessages(); // returns message but as Immutable
responses. not what we want: we use responseMap instead.
var key = TCP_CONNECTOR_ESANTE_MPI_RANK;
logger.debug(" Response Data=" + cms.get(key).getResponseData());
logger.debug(" Response Data0=" + cms.get(key).getResponseError());
logger.debug(" Response Data1=" + cms.get(key).getResponseData().getError());
logger.debug(" Response Data2=" + cms.get(key).getResponseData().getMessage());
logger.debug(" Response Data3=" + cms.get(key).getResponseData().getStatusMessage());
logger.debug(" Response Data4=" + cms.get(key).getResponseData().getStatus());
*/
var responseMPI = responseMap.get(TCP_CONNECTOR_ESANTE_MPI_DNAME); // return a mutable reponse :-)
if (responseMPI.getStatus()=='ERROR' &&
responseMPI.getStatusMessage().startsWith('ConnectException: Connection refused')) {
// build a error message for this dedicated case
logger.error("connection refused detected");
responseMPI.setMessage(JSON.stringify(sErrorMsg)); // force the message to be responsed.
}
return;

Related

MqttBrowserClient fails to connect due to missing conack package

I am trying to make webapp over flutter which will connect to HIVE broker. I took the broker name from the official website, set the port number to 8000 just like mentioned there and still get the error message as below:
error is mqtt-client::NoConnectionException: The maximum allowed connection attempts ({1}) were exceeded. The broker is not responding to the connection request message (Missing Connection Acknowledgement?
I really have no clue how to proceed. Can someone please help?
Below is my code:
MqttBrowserClient mq = MqttBrowserClient(
'wss://broker.mqttdashboard.com:8000', '',
maxConnectionAttempts: 1);
/*
MqttBrowserClient mq = MqttBrowserClient('ws://test.mosquitto.org', 'client-1',
maxConnectionAttempts: 1);
*/
class mqttService {
Future<MqttBrowserClient?> connectToServer() async {
try {
final connMess = MqttConnectMessage()
.withClientIdentifier('clientz5tWzoydVL')
.authenticateAs('a14guguliye', 'z5tWzoydVL')
.withWillTopic('willtopic')
.withWillMessage('My Will message')
.startClean() // Non persistent session for testing
.withWillQos(MqttQos.atLeastOnce);
mq.port = 1883;
mq.keepAlivePeriod = 50;
mq.connectionMessage = connMess;
mq.websocketProtocols = MqttClientConstants.protocolsSingleDefault;
mq.onConnected = onConnected;
var status = await mq.connect();
return mq;
} catch (e) {
print("error is " + e.toString());
mq.disconnect();
return null;
}
}
}
That port 8000 may be open but the HiveMQ broker may not be listening.
Make sure that the broker is fully booted and binds to that IP:Port combo.
In the HiveMQ broker startup output, you should see something similar to:
Started Websocket Listener on address 0.0.0.0 and on port 8000
If needed, the HiveMQ Broker configuration documentation is here.
You can use the public HiveMQ MQTT Websocket demo client to test your connection to make sure it's not a local code issue.
As a last option, use Wireshark to monitor MQTT traffic with a filter of tcp.port == 8000 and mqtt

KSQL Java Client app Received 404 response from server:

I have written KSQL Client Java app to fetch the topic message details from KSQL Tables. This is the code snippet to read the topic messages from KSQL table. But when i run this program getting below error. Please let me know how to resolve this issue.
KSQLClient Code:
ClientOptions options = ClientOptions.create()
.setHost(KSQLDB_SERVER_HOST)
.setPort(KSQLDB_SERVER_HOST_PORT);
Client client = Client.create(options);
System.out.println("Client object value ---->"+client);
// Send requests with the client by following the other examples
String query = "SELECT * FROM TESTKSQLTBLE EMIT CHANGES;";
Map<String, Object> properties = Collections.singletonMap("auto.offset.reset", "earliest");
client.streamQuery(query, properties)
.thenAccept(streamedQueryResult -> {
System.out.println("Result column names: " + streamedQueryResult.columnNames());
// RowSubscriber subscriber = new RowSubscriber();
//streamedQueryResult.subscribe(subscriber);
}).exceptionally(e -> {
System.out.println("Push query request failed: " + e);
return null;
});
Exception details:
Exception in thread "main" java.util.concurrent.ExecutionException: io.confluent.ksql.api.client.exception.KsqlClientException: Received 404 response from server: HTTP 404 Not Found. Error code: 40400
at java.util.concurrent.CompletableFuture.reportGet(Unknown Source)
at java.util.concurrent.CompletableFuture.geta(Unknown Source)
at my.ksqldb.app.KSQLExampleApp.main(KSQLExampleApp.java:55)

POST request on arduino with ESP8266 using WifiESP library

I am attempting to make RESTful POST request using the WifiESP library (https://github.com/bportaluri/WiFiEsp). I'm able to successfully make the request with curl, but consistently get an error using the Arduino and ESP. I suspect the problem is related to the manual formatting of the POST request the library requires, but I don't see anything wrong. Here my sanitized code:
if (client.connect(server, 80)) {
Serial.println("Connected to server");
// Make a HTTP request
String content = "{'JSON_key': 2.5}"; // some arbitrary JSON
client.println("POST /some/uri HTTP/1.1");
client.println("Host: http://things.ubidots.com");
client.println("Accept: */*");
client.println("Content-Length: " + sizeof(content));
client.println("Content-Type: application/json");
client.println();
client.println(content);
}
The error I get (via serial monitor) is this:
Connected to server
[WiFiEsp] Data packet send error (2)
[WiFiEsp] Failed to write to socket 3
[WiFiEsp] Disconnecting 3
My successful curl requests looks like this:
curl -X POST -H "Content-Type: application/json" -d 'Some JSON' http://things.ubidots.com/some/uri
After some experimentation, here is the solution to the multiple problems.
The JSON object was not correctly formatted. Single quotes were not accepted, so I needed to escape the double quotes.
The host does not need "http://" in a POST request; POST is a HTTP method.
The sizeof() method returns the size, in bytes, of the variable in memory rather than the length of the string. It needs to be replaced by .length().
Appending an integer to a string requires a cast.
This is the corrected code:
if (client.connect(server, 80)) {
Serial.println("Connected to server");
// Make the HTTP request
int value = 2.5; // an arbitrary value for testing
String content = "{\"JSON_key\": " + String(value) + "}";
client.println("POST /some/uri HTTP/1.1");
client.println("Host: things.ubidots.com");
client.println("Accept: */*");
client.println("Content-Length: " + String(content.length()));
client.println("Content-Type: application/json");
client.println();
client.println(content);
}
The code explained by Troy D is right and it's working .I think the error in posting the data to the server is due to this line
client.println("Content-Length: " + sizeof(content));
and the correct way is
client.println("Content-Length: " + String(content.length()));
Now coming to this error
Connected to server
[WiFiEsp] Data packet send error (2)
[WiFiEsp] Failed to write to socket 3
[WiFiEsp] Disconnecting 3
This is the error of library you can ignore it.
The problem with "Data packet send error (2)", "Failed to write to socket 3" and "Disconnecting 3" is not a problem within the WifiEsp library as far as I can see, believe it's more likely to be within the AT firmware. By default the http headers contain a "Connection: close" parameter which in normal cases should be correct. However with this bug the server will get disconnected before the reply is received on the client side and any response from the server will be identified as garbage data. Using the value "Connection: keep-alive" as a workaround will make it possible to receive the acceptance from the server in a proper way.
I'm running my Arduino + ESP8266-07 against a MVC based Web Api that I created on one of my servers and in the controllers Post-method I use a single string as return value, the value I return if everything is ok is simply one of the strings that WifiEsp keeps track of (It will still include the http status code in the response header that it returns)
public async Task<string> Post([FromBody]JObject payload)
{
//Code to handle the data received, in my case I log unit ip, macaddress, datetime and sensordata into a db with entity framework
return "SEND OK";
}
So in your Arduino code try following instead:
String PostHeader = "POST http://" + server + ":" + String(port) + "/api/values HTTP/1.1\r\n";
PostHeader += "Connection: keep-alive\r\n";
PostHeader += "Content-Type: application/json; charset=utf-8\r\n";
PostHeader += "Host: " + server + ":" + String(port) + "\r\n";
PostHeader += "Content-Length: " + String(jsonString.length()) + "\r\n\r\n";
PostHeader += jsonString;
client.connect(server.c_str(), port);
client.println(PostHeader);
client.stop();
In the file debug.h located in the library source code you could alter a define and get more output to your serial console. Open the file and change
#define _ESPLOGLEVEL_ 3
to
#define _ESPLOGLEVEL_ 4
Save the file and recompile/deploy your source code to your Arduino and you will get extensive information about all AT commands the library sends and what the library receives in return.

Adding a websocket "put" request in the bootstrap.js file in sails : cannot find io

I need to call a socket request from the bootstrap.js file in sails.
The bootstrap.js file has some code checking if some game engine has updated some file. If so, it needs send a message with some updated data via socket to some defined route called "/update"... e.g.
io.socket.put('/update', {history:{sessions:[1,2,3,4]}},function gotResponse(body, response) {
console.log('Server sending request ot server ');
})
The problem is that it tells me that io is not recognised.
I tried to do npm install for both sails.io.js and socket.io-client and then write:
var io = require('sails.io.js')( require('socket.io-client') );
at the top.
Unfortunately, it gives me the following error message:
C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\socket.io-client\lib\url.js:29
if (null == uri) uri = loc.protocol + '//' + loc.host;
^
TypeError: Cannot read property 'protocol' of undefined
at url (C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\socket.io-client\lib\url.js:29:29)
at lookup (C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\socket.io-client\lib\index.js:44:16)
at goAheadAndActuallyConnect (C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\sails.io.js\sails.io.js:835:21)
at selfInvoking (C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\sails.io.js\sails.io.js:812:18)
at SailsSocket.SailsIOClient.SailsSocket._connect (C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\sails.io.js\sails.io.js:831:9)
at null._onTimeout (C:\Users\Evolver\Documents\programming\pipegame\game6\node_modules\sails.io.js\sails.io.js:1463:17)
at Timer.listOnTimeout (timers.js:92:15)
Any idea ?
Ok.
It now works, once npm install has been done for socket.io-client and sails.io.js if I do exactly the following:
var socketIOClient = require('socket.io-client');
var sailsIOClient = require('sails.io.js');
// Instantiate the socket client (`io`)
var io = sailsIOClient(socketIOClient);
io.sails.url = 'http://localhost:1337';
// then I send something via my socket
io.socket.put('/update', {history:{sessions:[1,2,3,4]}},function gotResponse(body, response) {
console.log('Server sending request ot server ');
})

how to check if connection is established when use libev with non-block socket

I have some code use libev on how to deal with connection timeout as below (please refer to http://lists.schmorp.de/pipermail/libev/2011q2/001365.html):
sd = create_socket()
set_socket_nonblock(sd)
connect("127.0.0.1", port) // connect to an invalid port
ev_io_init(&w_io, connect_cb, sd, EV_WRITE)
ev_io_start(...)
ev_timer_init(&w_timer, timeout_cb, 5.0, 0)
ev_timer_start(...)
and in someplace perform ev_run. The connect_cb is called and in this callback function I checked the revents with EV_ERROR, the result is no error. This is strange because I provide an invalid port number which is not listening in local machine. Anyway, I try to send a message in the connect_cb function, got an error 111, which means that connection refused. I'm confused! How to check if the connection is established correctly when use non-block socket?
getsockopt is possible way to get if the connection has some error happen:
int err;
socklen_t len = sizeof(err);
getsockopt(sd, SOL_SOCKET, SO_ERROR, &err, &len);
if (err) {
// error happen
} else {
connection is OK
}