Vert.x event bus consumer called twitce - vert.x

i wrote a simple code for communicate between a java server in vert.x and a browser client with the event bus library. The client send a message to the server through the event bus and the server call eventbus.consumer to read the message and reply to it.
I notice something strange, idk why the consumer method is called twice, I aspect it call one. How can i solve this? Thanks.
This is my code:
SERVER
SockJSBridgeOptions options = new SockJSBridgeOptions().
addInboundPermitted(new PermittedOptions().setAddressRegex("out"));
sockJSHandler.bridge(options);
router.route("/eventbus/*").handler(sockJSHandler);
eventBus.<String>consumer("out", event -> {
logger.info(event.body());
event.reply("TEST");
});
vertx.createHttpServer().requestHandler(router).listen(serverPort, res -> {
if (res.succeeded()) {
startPromise.complete();
} else {
startPromise.fail(res.cause());
}
});
CLIENT
var eb = new EventBus('http://localhost:8088/eventbus');
eb.onopen = () => {
eb.send('out', {name: 'tim', age: 5817}, (e, m) => {
console.log("TEST RESPONSE")
console.log(JSON.stringify(m));
});
}
CONSOLE SERVER OUTPUT
apr 07, 2022 7:55:43 PM it.unibo.guessthesong.lobby.LobbyVerticle
INFO: {"name":"tim","age":5817}
apr 07, 2022 7:55:43 PM it.unibo.guessthesong.lobby.LobbyVerticle
INFO: {"name":"tim","age":5817}
CONSOLE CLIENT OUTPUT
TEST RESPONSE
{"type":"rec","address":"92888ada-fada-43ff-9677-9eeed95b44da","body":"TEST"}
TEST RESPONSE
{"type":"rec","address":"2ced1214-13cf-4ebf-b7d8-6773612097e7","body":"TEST"}

Related

RESTful client in Unity - validation error

I have a RESTful server created with ASP.Net and am trying to connect to it with the use of a RESTful client from Unity. GET works perfectly, however I am getting a validation error when sending a POST request. At the same time both GET and POST work when sending requests from Postman.
My Server:
[HttpPost]
public IActionResult Create(User user){
Console.WriteLine("***POST***");
Console.WriteLine(user.Id+", "+user.sex+", "+user.age);
if(!ModelState.IsValid)
return BadRequest(ModelState);
_context.Users.Add(user);
_context.SaveChanges();
return CreatedAtRoute("GetUser", new { id = user.Id }, user);
}
My client:
IEnumerator PostRequest(string uri, User user){
string u = JsonUtility.ToJson(user);
Debug.Log(u);
using (UnityWebRequest webRequest = UnityWebRequest.Post(uri, u)){
webRequest.SetRequestHeader("Content-Type","application/json");
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError || webRequest.isHttpError){
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
else{
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
}
}
}
I was trying both with the Json conversion and writing the string on my own, also with the WWWForm, but the error stays.
The error says that it's an unknown HTTP error. When printing the returned text it says:
"One or more validation errors occurred.","status":400,"traceId":"|b95d39b7-4b773429a8f72b3c.","errors":{"$":["'%' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."]}}
On the server side it recognizes the correct method and controller, however, it doesn't even get to the first line of the method (Console.WriteLine). Then it says: "Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ValidationProblemDetails'".
Here're all of the server side messages:
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 POST http://localhost:5001/user application/json 53
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint 'TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect)'
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Route matched with {action = "Create", controller = "User"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Create(TheNewestDbConnect.Data.Entities.User) on controller TheNewestDbConnect.Controllers.UserController (TheNewestDbConnect).
info: Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor[1]
Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.ValidationProblemDetails'.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect) in 6.680400000000001ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'TheNewestDbConnect.Controllers.UserController.Create (TheNewestDbConnect)'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 11.3971ms 400 application/problem+json; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
I have no idea what is happening and how to solve it. Any help will be strongly appreciated!
Turned out I was just missing an upload handler. Adding this line solved it: webRequest.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(JsonObject));

How to detect hangup event in Freeswitch?

I'm new to Freeswitch and looking for help from experts. My problem is below.
I'm trying to do below scenario in Perl:
When I'm getting an incoming call to script (test.pl) I play a file to it and then put inbound session to on-hold. Then I try to make new outbound session from a separate script (test2.pl). If outbound call get answer, then I break inbound session from on-hold and bridge both sessions. The scrips are like below.
test.pl
use strict;
use warnings;
our $session;
if( $session->ready() ) {
$session->setVariable( 'hangup_after_bridge', 'false' );
$session->setVariable( 'continue_on_fail', 'true' );
$session->answer();
my $api = new freeswitch::API;
$api->execute('perlrun', '/usr/share/freeswitch/scripts/test2.pl ' . $session->get_uuid());
$session->setVariable('playback_timeout_sec', '70');
$session->execute("playback", '$${hold_music}');
if ($session->getVariable('outbound_answered') == 'true') {
my $outbound_uuid = $session->getVariable('outbound_uuid');
my $outbound_session = new freeswitch::Session($outbound_uuid);
if ($outbound_session->ready()) {
$session->bridge($outbound_session);
} else {
# outbound session disconnected.
}
} else {
# outbound session didn't answer.
}
} else {
# Inbound disconneected.
}
1;
test2.pl
use strict;
use warnings;
my $api = new freeswitch::API;
my $inbound_uuid = $ARGV[0];
my $inbound_session = new freeswitch::Session( $inbound_uuid );
my $originate_str = "sofia/gateway/outbound/0416661666";
my $outbound_session = new freeswitch::Session( $originate_str );
my $hangup_cause_out = $outbound_session->hangupCause();
$inbound_session->setVariable( 'outbound_uuid', $outbound_session->get_uuid() );
if ( $outbound_session->ready() ) {
if ( $inbound_session->ready() ) {
$inbound_session->setVariable('outbound_answered', 'true');
$outbound_session->streamFile("/usr/share/freeswitch/sounds/en/us/callie/ivr/8000/ivr-please_hold_while_party_contacted.wav");
$inbound_session->execute('break');
while ($inbound_session->ready()) {
sleep(10);
# Inbound sessnio ok, continue outbound session.
}
} else {
# Inbound session got disconnected while we trying outbound.
}
} else {
# Outbound call failed.
}
1;
Debian syslog:
Jul 19 13:14:50 XXX systemd[1]: freeswitch.service: Main process exited, code=killed, status=6/ABRT
Jul 19 13:14:50 XXX systemd[1]: freeswitch.service: Unit entered failed state.
Jul 19 13:14:50 XXX systemd[1]: freeswitch.service: Failed with result 'signal'.
Jul 19 13:14:50 XXX systemd[1]: freeswitch.service: Service hold-off time over, scheduling restart.
Jul 19 13:14:50 XXX systemd[1]: Stopped freeswitch.
Jul 19 13:14:50 XXX systemd[1]: Starting freeswitch...
The expected scenario work without issues. But my issue is Freeswitch getting restart when inbound session hangup by incoming call party while Freeswitch ringing outbound party.
UPDATE1:
I think I need to handle inbound session hangup event but kinda lost here. May be I'm doing all wrong.
UPDATE2:
I been seen this issue in Freeswitch 1.8.7. I tried testing the same code in Freeswitch 1.6.20 and it didn't crash, but gave below error,
[ERR] freeswitch_perl.cpp:114 session is not initalized
So it seems Freeswitch 1.8 mod_perl module not handling it properly.
Looking for suggestions from Freeswitch experts.
Thank you!

unable to upload an image file to slack through hubot

I am trying to get an image of a web page using pageres package, And post the image to slack using hubot. I am able to get the image, but for some reason i am not able to post it to slack using slack upload api. Here is my code, can you tell me what could be wrong? (not a coffee lint issue)
fs = require("fs")
Pageres = require('pageres')
util = require("util")
request = require("request")
module.exports = (robot) ->
robot.respond /screenshot page (\S*)?( at )?(\S*)?/i, (msg) ->
pageres = new Pageres({delay: 30})
domain = msg.match[1].replace("http://", "")
if msg.match[3] == undefined
size = '960x1024'
else
size = msg.match[3]
dest = './screenshots'
msg.send "Acquiring screenshot of #{domain}"
pageres.src(domain, [size]).dest(dest)
pageres.run (err) ->
if err
robot.logger.error err
msg.send "Um..., you better check the log"
else
opts = {
method: 'POST',
uri: 'https://slack.com/api/files.upload',
formData: {
channels: process.env.HUBOT_SCREENSHOT_SLACK_CHANNEL,
initial_comment: "Screenshot of #{domain}",
token: process.env.HUBOT_SLACK_TOKEN,
file: fs.createReadStream("#{dest}/#{domain}.png")
}
}
request.post opts, (error, response, body) ->
if error
robot.logger.error error
else
robot.logger.debug 'screenshot posted to slack'
return
The bot is connected to slack, and receiving messages from slack, parsing them fine and getting the image back to the local destination, but not able to post it to slack, There are no errors as well in the log.
[Wed Apr 11 2018 16:16:47 GMT+0000 (UTC)] DEBUG Received message: '#hubot screenshot page http://www.google.com' in channel: ****, from: ******
[Wed Apr 11 2018 16:16:47 GMT+0000 (UTC)] DEBUG Message '#hubot screenshot page http://www.google.com' matched regex //^\s*[#]?hubot[:,]?\s*(?:screenshot page (\S*)?( at )?(\S*)?)/i/; listener.options = { id: null }
[Wed Apr 11 2018 16:16:47 GMT+0000 (UTC)] DEBUG Executing listener callback for Message '#hubot screenshot page http://www.google.com'
[Wed Apr 11 2018 16:16:47 GMT+0000 (UTC)] DEBUG Sending to *****: Acquiring screenshot of www.google.com
You can use curl command which can be called using child_process to upload a file in the channel.
curl -F file=#dramacat.gif -F channels=C024BE91L,#general -F token=xxxx-xxxxxxxxx-xxxx https://slack.com/api/files.upload
It seems the formData property in your opts variable should be slightly different like this:
formData: {
token: process.env.HUBOT_SLACK_TOKEN,
title: "Screenshot of #{domain}",
filename: "image.png",
filetype: "auto",
channels: channel_id,
file: fs.createReadStream("path_to_your_image"),
}
The channel_id is your slack channel id which you can see in the browser address bar when you access the channel.

Akka-Http client: How to get binary data from an http response?

I call an API to get a zip file response. The API responds correctly but I am unable to get the byte array from response because the future that should complete on getting the ByteString never completes:
val authorization = akka.http.javadsl.model.headers.Authorization.basic("xxxxx", "xxxxxx")
val query = Map("fed" -> "xxxx", "trd" -> "yyy", "id" -> "zzz")
val request = HttpRequest(HttpMethods.GET, Uri("https://xxxx.yyyy.com/ggg/ttt.php").withQuery(Query(params = query))).addHeader(authorization)
val responseFut = http.singleRequest(request)
responseFut1.map(response => {
println("*******************************")
println(response)
response.status match {
case akka.http.javadsl.model.StatusCodes.OK => {
println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" + response._3)
val entityFut = response.entity.toStrict(60.seconds)
val byteStringFut = entityFut.flatMap(entity => {
entity.dataBytes.runFold(ByteString.empty)(_ ++ _)
})
println("#############################")
try {
byteStringFut.map(x => {
//this never prints =======================================problem
println("----------------------------" + x.toArray[Byte])
})
}catch{
case e: Exception => println("Error: " + e)
}
}
case _ => {}
}
})
If I print out the response this is what it looks like:
*******************************
HttpResponse(200 OK,List(Date: Fri, 08 Sep 2017 20:58:43 GMT, Server: Apache/2.4.18 (Ubuntu), Content-Disposition: attachment; filename="xxxxx.zip", Pragma: public, Cache-Contr
ol: public, must-revalidate, Content-Transfer-Encoding: binary),HttpEntity.Chunked(application/x-zip),HttpProtocol(HTTP/1.1))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^HttpEntity.Chunked(application/x-zip)
#############################
So response is coming back fine, but I still cannot get the binary data for the zip file.
We use akka-http in other places to call APIs that return json response and this approach seems to work fine there.
Why doesnt it work here? What am I doing wrong?
Any advice is appreciated.
Thanks.
Update
Adding byteStringFut.failed.foreach(println(_)) shows this exception: akka.http.scaladsl.model.EntityStreamException: HTTP chunk size exceeds the configured limit of 1048576 bytes
It looks like something went wrong and an exception was thrown in the async computation. You can check the exception by inspecting Future in the following way:
byteStringFut.failed.foreach(println)

Healthcheck for endpoints - quick and dirty version

I have a few REST endpoints and few [asmx/svc] endpoints.
Some of them are GET and the others are POST operations.
I am trying to put together a quick and dirty , repeatable healthcheck sequence for finding if all the endpoints are responsive or if any are down.
Essentially either get a 200 or 201 and report error if otherwise.
What is the easiest way to do this?
SOAPUI use internally apache http-client 4.1.1 version, you can use it inside a groovy script testStep to perform your checks.
Add a groovy script testStep to your testCase an inside use the follow code; which basically try to perform a GET against a list of URLs, if its returns http-status 200 or 201 its considered that is working, if http-status 405 (Method not allowed) is returned then it tries with POST and perform the same status code check, otherwise it's considered down.
Note that some services can be running however can return for example 400 (BAD request) if the request is not correct, so think about if you need to rethink the way you want perform a check or add some other status codes to consider if the server is running correctly.
import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.DefaultHttpClient
// urls to check
def urls = ['http://google.es','http://stackoverflow.com']
// apache http-client to use in closue
DefaultHttpClient httpclient = new DefaultHttpClient()
// util function to get the response
def getStatus = { httpMethod ->
HttpResponse response = httpclient.execute(httpMethod)
// consume the entity to avoid error with http-client
if(response.getEntity() != null) {
response.getEntity().consumeContent();
}
return response.getStatusLine().getStatusCode()
}
HttpGet httpget;
HttpPost httppost;
// finAll urls that are working
def urlsWorking = urls.findAll { url ->
log.info "try GET for $url"
httpget = new HttpGet(url)
def status = getStatus(httpget)
// if status are 200 or 201 it's correct
if(status in [200,201]){
log.info "$url is OK"
return true
// if GET is not allowed try with POST
}else if(status == 405){
log.info "try POST for $url"
httppost = new HttpPost(url)
status = getStatus(httpget)
// if status are 200 or 201 it's correct
if(status in [200,201]){
log.info "$url is OK"
return true
}
log.info "$url is NOT working status code: $status"
return false
}else{
log.info "$url is NOT working status code: $status"
return false
}
}
// close connection to release resources
httpclient.getConnectionManager().shutdown()
log.info "URLS WORKING:" + urlsWorking
This scripts logs:
Tue Nov 03 22:37:59 CET 2015:INFO:try GET for http://google.es
Tue Nov 03 22:38:00 CET 2015:INFO:http://google.es is OK
Tue Nov 03 22:38:00 CET 2015:INFO:try GET for http://stackoverflow.com
Tue Nov 03 22:38:03 CET 2015:INFO:http://stackoverflow.com is OK
Tue Nov 03 22:38:03 CET 2015:INFO:URLS WORKING:[http://google.es, http://stackoverflow.com]
Hope it helps,