Send HTTP Request from local server to remote server - xquery

I am using BaseX version 9.5, I am trying to send HTTP request from local to remote server to read database, but not getting the response.
let $server := 'http://10.102.xxx.xxx:8984/rest/'
let $sendreq := (http:send-request(
<http:request method='POST' username='admin' password='admin' send-authorization='true'
href='{$server}' auth-method='Basic'>
<http:body media-type="application/xml">
{
collection('test')/*
}</http:body>
</http:request>
))[2]
return $sendreq
Can anyone suggest how can I send query to remote server so that I could read and query to remote server database from my local server?

To execute your query on a remote instance of basex
http:send-request(
<http:request method='POST'
href='{$remote-server-rest-endpoint}'
username='{$remote-instance-user}'
password='{$remote-instance-user-password}'
send-authorization='true'
auth-method='Basic'>
<http:body media-type="application/xml">
<query xmlns="http://basex.org/rest">
<text><![CDATA[
declare variable $a as xs:integer external;
declare variable $b as xs:integer external;
<mult>{ $a * $b }</mult>
]]></text>
<variable name="a" value="21"/>
<variable name="b" value="2"/>
</query>
</http:body>
</http:request>
)
Adapted from the example found in the docs: https://docs.basex.org/wiki/REST#POST_Method

Related

Why is UDP Socket connector timing out?

I am trying to use a UDP socket to send a simple datagram to a local service. I've tested the request and response using a nodejs client, but I cannot get the same response when using Mulesoft.
This is the nodejs code that works:
const dgram = require('node:dgram');
const process = require('node:process');
const buffer = require('node:buffer');
var soc = dgram.createSocket('udp4');
soc.on('error', (err) => {
console.error(`socket error:\n${err.stack}`);
});
soc.on('message', (msg) => {
console.log(`message received: ${msg}`);
});
soc.connect(1434, () => {
console.log(`socket connected`);
const queryInstanceCode = 3;
const buff = buffer.Buffer.alloc(1);
buff[0] = queryInstanceCode;
soc.send(buff);
});
Executing this node app will query the local service and return expected data.
My mule app uses the socket connector with this configuration:
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting" xmlns:sockets="http://www.mulesoft.org/schema/mule/sockets"
xmlns:http="http://www.mulesoft.org/schema/mule/http"
xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/sockets http://www.mulesoft.org/schema/mule/sockets/current/mule-sockets.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd">
<http:listener-config name="HTTP_Listener_config" doc:name="HTTP Listener config" doc:id="aaeb8ad9-c25d-4076-90b4-5fbf0584fefa" >
<http:listener-connection host="0.0.0.0" port="8081" />
</http:listener-config>
<sockets:request-config name="SQLServiceBrowserSocket" doc:name="Sockets Request config" doc:id="ccebf069-3ea5-403b-8f38-14a1b181c93f" >
<sockets:udp-requester-connection host="127.0.0.1" port="1434" clientTimeout="5000"/>
</sockets:request-config>
<flow name="named.instance.finderFlow" doc:id="f0259fdc-c7ce-43ba-a124-07df0bee9ec4" >
<http:listener doc:name="Listener" doc:id="3ece9740-15b6-4681-b5e3-20ff66fa46c7" config-ref="HTTP_Listener_config" path="/mssqlhost/{host}/instance/{instance}/port" allowedMethods="GET" responseStreamingMode="NEVER">
</http:listener>
<logger level="INFO" doc:name="Log Request" doc:id="3bd2076d-23f6-4388-a3d8-0da2816d00dc" message="#attributes"/>
<sockets:send-and-receive doc:name="Query SQL Server Browser" doc:id="14f15af2-ee9a-41f9-9890-a021fd066d35" config-ref="SQLServiceBrowserSocket" target="instancePort" outputMimeType="application/octet-stream" outputEncoding="US-ASCII">
<non-repeatable-stream />
<sockets:content><![CDATA[3]]></sockets:content>
</sockets:send-and-receive>
<logger level="INFO" doc:name="Logger" doc:id="6ca780c0-21c7-409c-9c64-17cb0a0fc543" message="#payload"/>
</flow>
</mule>
When running the Mule app and performing a simple CURL on the url, the flow will timeout after 5 seconds, with no additional information than "UDP connection timed out".
I've tried adding debug logging for sockets, but I get no additional information. How do I get additional information on why the UDP Sockets connector is not properly interacting with the service?
The nodejs application works and proves that the service is available and functioning. The Mule application times out after 5 seconds without any further information. I have tried increasing level logging by adding this logger:
<AsyncLogger name="org.mule.extension.socket" level="DEBUG"/>
To the log4j2.xml of the package, but I get no additional information.
I expect the Sockets connector to send the UDP packate and receive the same response that the nodejs application receives. Instead the Socket connector times out.
The issue was encoding. Supplying the string "3" to the content of the socket made it encoded in ASCII. Instead, use dataweave:
%dw 2.0
output application/octet-stream
---
3

How to get the client IP adress using HTTP.jl

I'm trying to get the both the client request and IP address from http requests to my HTTP.jl server (based on the basic server example in the docs).
using HTTP
using Sockets
const APP = HTTP.Router()
# My request handler function can see the request's method
# and target but not the IP address it came from
HTTP.#register(APP,"GET","/",req::HTTP.Request -> begin
println("$(req.method) request to $(req.target)")
"Hello, world!"
end)
HTTP.serve(
APP,
Sockets.localhost,
8081;
# My tcpisvalid function can see the client's
# IP address but not the HTTP request
tcpisvalid=sock::Sockets.TCPSocket -> begin
host, port = Sockets.getpeername(sock)
println("Request from $host:$port")
true
end
)
My best guess would be that there's a way to parse the TCPSocket.buffer into an HTTP request but I can't find any methods to do it.
Can you suggest a way to get an HTTP.Request from a TCPSocket or a different way to approach this problem?
Thanks in advance!
The router (APP) is a (collection of) "request handler(s)" which can only access the HTTP.Request -- you can not get the stream from it. Instead you can define a "stream handler", which is passed the stream. From the stream you can get the client's IP adress using Sockets.getpeername (requires HTTP.jl version 0.9.7 when called on a HTTP.Stream as in the examples below).
using HTTP, Sockets
const APP = HTTP.Router()
function request_handler(req::HTTP.Request)
println("$(req.method) request to $(req.target)")
return "Hello, world!"
end
HTTP.#register APP "GET" "/" request_handler
function stream_handler(http::HTTP.Stream)
host, port = Sockets.getpeername(http)
println("Request from $host:$port")
return HTTP.handle(APP, http) # regular handling
end
# HTTP.serve with stream=true to specify that stream_handler is a function
# that expects a HTTP.Stream as input (and not a HTTP.Request)
HTTP.serve(stream_handler, Sockets.localhost, 8081; stream=true) # <-- Note stream=true
# or HTTP.listen
HTTP.listen(stream_handler, Sockets.localhost, 8081)

AZURE API Management - Object reference not set to an instance of an object

Azure API Management is with a response "System.NullReferenceException: Object reference not set to an instance of an object."
MyFunction.Run(HttpRequest req, ILogger log) in MyFunction.cs:line 61
method signature
public async Task Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
ILogger log)
Sorry everybody, I newer in Azure APIM!
When I send JSON below in request body to c# azure function API, everything works as well!!
{
"Id":40,
"status":"Doing",
"startedDateTime":"2019-10-17T17:50:44.1314885Z"
}
But when I sending it thru the Azure API Management to serverless azure function API Microservice,
I'm getting the error message "Object reference not set to an instance of an object."
My Azure function has only APIM Key into headers and no more things; I just created APIM consumption for use as an endpoint,
I have only CORS policy and trying to use for a test, but I got the same problem with
<policies>
<inbound>
<base />
<choose>
<when condition="#(context.Request.Body != null)">
<set-body template="liquid">
<value>#(context.Request.Body.As<JObject>(preserveContent: true).Value<string>())</value>
</set-body>
</when>
</choose>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Someone can help me?
What would be the same solution?

socket connection

I would like to send a string via a socket to an external display unit via the oracle 11g database
I gather that the character or string first has to be converted to hex and at the end of the string a checksum must be addead (to validate the string to be sent)
Can anyone tell me how a socket connection can be opened and a string can be sent?
Thank you
DECLARE
bt_conn UTL_TCP.connection;
retval BINARY_INTEGER;
l_sequence VARCHAR2 (50) := '#0100010303000118000201001401000201'; --string to be sent
BEGIN
bt_conn :=
UTL_TCP.open_connection (remote_host => '127.0.0.1', --IP of socket to be opened
remote_port => 26665, -- port number of socket
tx_timeout => 15);
DBMS_LOCK.SLEEP(1); -- this is to ensure a slight pause once opening the connection before --sending the string
retval := UTL_TCP.write_line (bt_conn, l_sequence);
UTL_TCP.flush (bt_conn);
UTL_TCP.close_connection (bt_conn);
EXCEPTION
WHEN OTHERS
THEN
raise_application_error (-20101, SQLERRM);
UTL_TCP.close_connection (bt_conn);
end;
Theoretically you can achieve this by using Java stored procedure - if you grant yourself priv to open a TCP socket from Oracle JVM. But this way the data will be sent regardless on transaction result(commit or rollback). The better solution would to store those strings in some queue table and then withdraw them using some external process.
You can also use DBMS_PIPE.

Downloading files from Alfresco with MuleSoft CMIS connector

I have a little problem with the MuleSoft CMIS connector. I have an application that uploads and downloads files from Alfresco. I connect to Alfresco through AtomPub and use CMIS for all actions towards the Alfresco.
The problem is this:
I used to get the object from the repository and it worked fine. In my flow I added one component that takes the object from the flow, which is of type DocumentImpl, get InputStream, cast it to an Object and return it. The browser starts the download of the file but it has no idea what the file is because it has no extension attached to it.
And finally the question: How do I attach the extension to the file being downloaded?
EDIT some code added
#Override
public Object onCall(MuleEventContext eventContext) throws Exception {
MuleMessage mes = eventContext.getMessage();
System.out.println("Message is :" +mes);
DocumentImpl doc = mes.getPayload(DocumentImpl.class);
HttpResponse res = new HttpResponse();
InputStream a = doc.getContentStream().getStream();
String m = doc.getContentStreamMimeType();
String n = doc.getContentStreamFileName();
res.setBody(mes);
return a;
}
Ok i solved the problem. Basically the best way to do this is to change the flow to this:
<set-payload value ="#[payload.getContentStream()]" />
<set-variable value="#[payload.getMimeType()]" variableName="mime" doc:name="Variable" />
<set-variable value="#[payload.getFileName()]" variableName="name" doc:name="Variable" />
<!-- Set Content-Type to stored mimetype -->
<set-property value="#[flowVars['mime']]" propertyName="Content-Type" />
<set-property propertyName="File-Name" value="#[flowVars['name']]"/>
<set-property value="attachment; filename=#[flowVars['name']]" propertyName="Content-Disposition" />
this should be in the Mule Flow after
This takes mime type and file name from the payload and returns it!

Resources