open REST cypher transaction - rest

Trying to write a script to open a transaction in groovy. Currently have:
def static transaction(statement, params,success, error)
{
def http = new HTTPBuilder( 'http://localhost:7474' )
http.request( POST, JSON ) {
uri.path = '/db/data/transaction'
headers.'X-Stream' = 'true'
requestContentType = JSON
body = [ statements : statement , params : params ?: [:] ]
// uri.query = [ param : 'value' ]
response.success = { resp, json ->
if (success) success(json)
else {
println "Status ${resp.statusLine} Columns ${json.columns}\nData: ${json.data}"
}
}
response.failure = { resp, message ->
def result=[status:resp.statusLine.statusCode,statusText:resp.statusLine.reasonPhrase]
result.headers = resp.headers.collect { h -> [ (h.name) : h.value ] }
result.message = message
if (error) {
error(result)
} else {
println "Status: ${result.status} : ${result.statusText} "
println 'Headers: ${result.headers}'
println 'Message: ${result.message}'
}
}
}
}
transaction("start n=node(*) return n",[id:56981],{ println "Success: ${it}" },{ println "Error: ${it}" })
However I am getting the following error in the response:
Success: [commit:http://localhost:7474/db/data/transaction/4/commit, results:[], errors:[[code:40001, status:INVALID_REQUEST_FORMAT, message:Unable to deserialize request. Expected [START_OBJECT, FIELD_NAME, START_ARRAY], found [START_OBJECT, FIELD_NAME, VALUE_STRING].]]]
Thoughts? Thanks!

Please check out https://gist.github.com/7053223. Basically you did not build the json structure correctly. According to http://docs.neo4j.org/chunked/milestone/rest-api-transactional.html a json map containing statements key is sent. Inside there's an array of maps containing a statement and parameters key. Compare l.15 vs l.16-18 to see the difference.

Faced same problem with php, statements must contain array of statement:
[
statements => [
statemant
],
resultDataContents => [
'row',
'graph',
],
'includeStats' => true,
]

Related

get pdf from axios utility in node.js

I have created a utility function which is supposed to be common for all the api requests in node.js express app.
function axiosCall(method, endpoint, body) {
let requestConfig = {
url: encodeURI(`${endpoint.host}:${endpoint.port}${endpoint.path}`),
method: method, //can be POST, GET, etc
proxy: false,
data: body,
headers: {
"x-access-token": token,
"X-Correlation-ID": correlationId,
"Content-Type": "application/json"
},
}
axios.request(requestConfig).then(response => {
return response.data;
}).catch((errorRes) => {
throw {
error: errorRes.message, status: errorRes?.response?.status || 500,
responseContent: errorRes?.response?.data || "Server Error"
};
})
}
it works fine for JSON responses, but does not give proper result for files, such as pdf.
the response which i got for a pdf file was like
{
"status": 200,
"statusText": "OK",
"headers": {
"server": "nginx/1.16.1",
"date": "Fri, 02 Sep 2022 07:39:44 GMT",
"content-type": "application/pdf",
"content-length": "47658",
"connection": "close",
},
"config": {...},
"request": {...},
"data": "%PDF-1.4\r\n%����\r\n1 0 obj\r\n<<\r\n/Type /Catalog\r\n/Pages 2 0 R\r\n/AcroForm 3 0 R\r\n>>\r\nendobj\r\n4 0 obj\r\n<<\r\n/�����M��0\u0010��B�C������\u0016�#?���`��\u0003�N���\u0012���~�L��\u001e| O2�y3���;�fP�o�\u0013\u000e�Ҹ�c��}����E�VuS\r�W��Vv�h�>=�\u0001oGwi�j�⯰�\u000f����=�,��5��]��g{�ŧ{���\rݠ\u0012\u0000U�%��Vv��\rUL5�c\u001d���1\u000f\u0015�'�\u001f\u001d*M��jk컲B_�+N�U�$\u0019\u0004�-L\"t��\u0001�s���Z��\t�*MA����\u0005a���h�4O�\u0006�)H�9\bm�j\u0001BkX-Ah-+��i�wm#h\u0017�� �KV{\u0010�\r�\u0003\b햔I#hw��a�嶍\u0006�=��#Xp^��c\u0016ܣ1 ,4+N�Xp^!#a���X�\u0005�c8Ob�Il薑:IC�᭟oJ�\u001e�3����އy�\t�A\u001aG�q(C޵�X��7��\u0000�t��\r\nendstream\r\nendobj\r\n26 0 obj\r\n<<\r\n/Type /Font\r\n/Subtype /CIDFontType2\r\n/BaseFont /GBMOJY+SymbolMT\r\n/CIDToGIDMap /Identity\r\n/DW 1000\r\n/FontDescriptor 31 0 R\r\n/CIDSystemInfo <<\r\n/Registry (Adobe)\r\n/Ordering (Identity)\r\n/Supplement 0\r\n>>\r\n\r\n/W [120 [459]]\r\n>>\r\nendobj\r\n27 0 obj\r\n<<\r\n/Filter /FlateDecode\r\n/Length 225\r\n>>\r\nstream\r\nx^m�ϊ�0\u0010��\u001c� �^�P\n�\"����\u0000i2-��$L�C�~�T\u0014\u0016\u000f\u0019\u0018~�\r_F��sE6��a�k\f�Z2��\u001bY#4�Y\u0012�\u001d\u0018�\u0003,]��W>\u00133]OC����AQ���t\b<��ø\u0006��\r17~��0CM`\u001f��+��W�la��B��6\u000f��6l�$�֥�n��J�K���S[~ݤ�\u0003�5�]}ր����TV���ճG��Di���xQa� ?�K��\r�����ސmT�}q��Ԙ��\u0019�֕�\u0018c�\u0001�\u001a|/}!��qfJў<y��\u0007c��y\t\u001c\b ks]v]Fmz弦o\u0019����u�v_�|�[_F>�G�w�m:n��.�m$�ZҨ�F-i�\u0014〯�o\u001c�\u00120fJ\u0012`��Oz��{rP�v\u0011\u0004�}�����\u001d�\u0016�L\\�\u000b�\u001d�n�C]�I�����MZ�~۷��Iu��\u0014�6o�?�����W��ꡦ#?ZXG��wL�\u0007���G\t���3�Y���DFl�����R� 34\r\n>>\r\n\r\nstartxref\r\n46886\r\n%%EOF\r\n"
}
I am unable to convert this response.data to pdf file.
Then i read about setting responseType: "arraybuffer", which gave the buffer[] and I can use it in code to generate the file. but on setting the responseType, the error was also of buffer type instead of json. which again required further processing to convert it to json format.
so, is there a way to get pdf file from axios, by converting the response.data, which I received with default responseType.
or can we set responseType dynamically after getting response from the server, as i get the content-type in headers. so as to make a utility function which can work with all kinds of responses.
As I didn't get a proper resolution i handled it manually by passing a flag to the axios utility function.
const customObjectify = (data) => {
try {
if(typeof data === "string"){
JSON.parse(data);
}
return data;
} catch (error) {
return data;
}
}
main block is below
//adding a default value false to parameter, so i don't need to change at all function calls.
function axiosCall(method, endpoint, body, isFileInResponse= false) {
let requestConfig = {
url: encodeURI(`${endpoint.host}:${endpoint.port}${endpoint.path}`),
method: method, //can be POST, GET, etc
proxy: false,
data: body,
headers: {
"x-access-token": token,
"X-Correlation-ID": correlationId,
"Content-Type": "application/json"
},
}
if(isFileInResponse){
requestConfig.responseType = "arraybuffer";
}
axios.request(requestConfig).then(response => {
return response.data;
}).catch((errorRes) => {
try {
let responseContent;
if(isFileInResponse) {
// arraybuffer error needs to be converted to json
responseContent = customObjectify(errorRes.response.data.toString());
} else {
responseContent = errorRes.response.data;
}
throw ({ error: errorRes.message, status: errorRes?.response?.status || 500, responseContent});
} catch (error) {
throw ({ error: errorRes.message, status: errorRes?.response?.status || 500, responseContent: "Server Error" });
}
throw {
error: errorRes.message, status: errorRes?.response?.status || 500,
responseContent: errorRes?.response?.data || "Server Error"
};
})
}
As mentioned in this question (https://stackoverflow.com/a/53230807/19179818) you could put code in your .then() to create an anchor tag on your page and click it automatically to download the file, and delete the tag afterwards. (posted as awnser instead of comment because of not enough reputation)

Groovy rest client without libraries

I am using a rest client to do Post
My code is
def postRequest() {
def message = "{ \"fields\": { \"project\": { \"id\": \"001\" },\"summary\": \"Test Issue For Jira Integration\",\"description\": \"Creating of an issue for for projects and issue types using the REST API\", \"issuetype\": { \"id\": \"5\" } }}"
// POST
def post = new URL("https://jira/rest/api/latest/issue").openConnection();
//def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
String userpass = "user:pass" ;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
post.setRequestProperty ("Authorization", basicAuth);
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(201)) {
println(post.getInputStream().getText());
}else
{
println(post.getInputStream().getText());
print(postRC)
}
}
I am getting 400 error code , where its getting wrong
I am successfully able to do the get request with URL
400 = bad request.
it means server tried to validate your post data and it's wrong.
usually this response contains body with explanation...
for 400+ status codes the body comes through getErrorStream() and not through getInputStream()
So, I would do it like this:
def postRequest(url, message) {
def post = new URL(url).openConnection();
//def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
String userpass = "user:pass" ;
String basicAuth = "Basic " + userpass.getBytes("UTF-8").encodeBase64()
post.setRequestProperty("Authorization", basicAuth);
post.setRequestProperty("Content-Type", "application/json")
post.setDoOutput(true)
if( !(message instanceof String) )message = new groovy.json.JsonBuilder(message).toPrettyString()
post.getOutputStream().write(message.getBytes("UTF-8"))
def response=[:]
response.code = post.getResponseCode()
response.message = post.getResponseMessage()
if( response.code>=400 ){
try{
response.body = post.getErrorStream()?.getText("UTF-8")
}catch(e){}
}else{
response.body = post.getInputStream()?.getText("UTF-8")
}
assert response.code in [200,201] : "http call failure ${response.code}: ${ response.body ?: response.message }"
return response
}
def msg = [
fields: [
project : [ id: "001" ],
summary : "Test Issue For Jira Integration",
description : "Creating of an issue for for projects and issue types using the REST API",
issuetype : [ id: "5" ]
]
]
def r = postRequest("http://httpbin.org/post", msg)
println r
The issue was related to certificate , I have to bypass the certificate validation and its working fine. Since both the application are under same network and behind same company's firewall , I have bypass the certificate validations.
Adding the skipping certificate validation part to the above code is working for me

How do I get the value of collection.find(connect.data).fetch()?

I am trying to create a meteor RESTful API for my app based on this The Meteor Chef online tutorial. The HTTP package is installed in the beginning of the tutorial, in order to test the RESTful API once the API development is completed.
I am currently in the testing phase and cant seem to get my GET Methods used to retrieve data from my collection to work.
Find below my GET Method code:
methods: {
pescrow: {
GET: function( context, connection ) {
var hasQuery = API.utility.hasData( connection.data );
console.log("hasQuery value == " +hasQuery+ " on line 183");
if ( hasQuery ) {
connection.data.owner = connection.owner;
console.log("Your in GET::hasQuery: Line 187 " + connection.data );
var getPescrows = recipientsDetails.find( connection.data ).fetch();
console.log("getPescrows value: " +getPescrows+ " Line 203");
if ( getPescrows.length > 0 ) {
// We found some pescrows, we can pass a 200 (success) and return the
// found pescrows.
console.log("getPescrows found Line 205");
API.utility.response( context, 200, getPescrows );
}
else {
console.log("getPescrows NOT found Line 208!");
// Bummer, we didn't find any pescrows. We can pass a 404 (not found)
// and return an error message.
API.utility.response( context, 404, { error: 404, message: "No Pescrows found, dude." } );
}
}
else {
// Our request didn't contain any params, so we'll just return all of
// the pescrows we have for the owner associated with the passed API key.
var getPescrows = recipientsDetails.find( { "owner": connection.owner } ).fetch();
API.utility.response( context, 200, getPescrows );
}
}
}
}
I test my API via the Chrome console by pasting in the below code:
HTTP.get( "http://localhost:8000/paymentC2B/v1", {
params: {
"api_key": "b21d83ef267bd829a9d732551270c718",
"paymentStatus": "Pending",
"recipientNumber" : "0705087633"
}
}, function( error, response ) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
});
And the response I get in the terminal is:
hasQuery == true Line 183
Your in GET::hasQuery: Line 187 [object Object]
getPescrows value: Line 203
getPescrows NOT found Line 208!
When I run the query below in the console it successfully yields:
recipientsDetails.find({paymentStatus:"Pending", recipientNumber: "0705087633"}, {sort: {paymentDate: 'desc' }}).fetch()
Showing:
[{…}]
0
:
key : "b21d83ef267bd829a9d732551270c718"
paymentDate : "2018-04-02 15:15:49"
paymentStatus : "Pending"
recipientAmount : "500"
recipientNumber : "0705087633"
_id : "uSsCbdBmmhR2AF2cy"
__proto__ : Object
length : 1
__proto__ : Array(0)
It seems like the issue is in the recipientsDetails.find( connection.data ).fetch(); query. Can someone kindly point out where I am going wrong in my code?
Looking forward to your response.
When you test your params include api_key. I'm betting this key does not appear in your recipientsDetails collection.
Instead of just doing:
connection.data.owner = connection.owner;
Try:
connection.data.owner = connection.owner;
delete connection.data.api_key;

Fancytree lazy load exception : assertion failed: expected array of children

I have an existing tree which builds off of JSON with 3 level hierarchy.
Root ->
ChildLevel1 ->
ChildLevel2 (lazy =true)
The above tree data is loaded as the source on pageload., everything works fine at this point.Now - on childlevel2 I am trying to fill children on the fly as such :
lazyLoad: function (event, data) {
var json = "{children:[ {\"title\": \"Sub item\", \"lazy\": true }, {\"title\": \"Sub folder\", \"folder\": true, \"lazy\": true } ]}";
data.result = json;
}
I keep getting the following exception :
Uncaught Error: Fancytree assertion failed: expected array of children
at Function.error (jquery-1.12.4.min.js:2)
at _assert (jquery.fancytree.js:82)
at jquery.fancytree.js:3242
at i (jquery-1.12.4.min.js:2)
at Object.add [as done] (jquery-1.12.4.min.js:2)
at Fancytree.nodeLoadChildren (jquery.fancytree.js:3229)
at Fancytree._callHook (jquery.fancytree.js:2289)
at FancytreeNode.load (jquery.fancytree.js:1229)
at Fancytree.nodeSetExpanded (jquery.fancytree.js:3965)
at Fancytree.nodeToggleExpanded (jquery.fancytree.js:4230)
You are passing JSON string that defines an object, but the plugin requires an "array of children". Try:
lazyLoad: function (event, data) {
var res = [
{ title: "Sub item", lazy: true },
{ title: "Sub folder", folder: true, lazy: true }
];
data.result = res;
}

DynamoDB PutItemOutcome#getPutItemResult() returns empty object

I'm trying to run the following example from AWS Dynamo tutorial locally, Step 3: Put, Update, and Delete an Item.
In my case, it is:
val client: AmazonDynamoDBClient = new AmazonDynamoDBClient().withEndpoint("http://localhost:7777")
val dynamoDB: DynamoDB = new DynamoDB(client)
val table: Table = dynamoDB.getTable("Catalog")
try {
val rating: java.util.List[Float] = new java.util.LinkedList[Float]()
rating.add(1)
val newItem: Item = new Item().withPrimaryKey("Title", "Title here").withInt("Country", 1).
withList("Ratings", rating)
val outcome: PutItemOutcome = table.putItem(newItem)
System.out.println("PutItem succeeded:\n" + outcome.getPutItemResult)
} catch {
case exception: Exception => System.out.println(exception.getMessage)
}
The output is:
PutItem succeeded: {}
While in local DynamoDB console:
var params = {
TableName: "Catalog",
Key: {
"Title":"Title Here",
}
};
docClient.get(params, function(err, data) {
if (err)
console.log(JSON.stringify(err, null, 2));
else
console.log(JSON.stringify(data, null, 2));
});
Output:
{
"Item": {
"Title": "Title Here",
"Ratings": [
1
],
"Country": 1
}
}
You need to set ReturnValues to ALL_OLD in the PutItem request to get a value returned, but even then it will only have the values that were replaced.
http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html#DDB-PutItem-request-ReturnValues
With your code you'd need to do something like replace
val outcome: PutItemOutcome = table.putItem(newItem)
with
val putItemSpec: PutItemSpec = new PutItemSpec()
.withItem(newItem)
.withReturnValues(ReturnValue.ALL_OLD)
val outcome: PutItemOutcome = table.putItem(putItemSpec)