Java - Neo4J Rest call to put labels to nodes - java

I've been trying to place labels over newly created nodes using Neo4J restful api. The following is the CURL request I've tried.
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:7474/db/data/");
String propertyUri_labels = "http://localhost:7474/db/data/node/9/labels";
Response response = target
.path(propertyUri_labels)
.request(MediaType.APPLICATION_JSON)
.header("application/xml", "true")
.accept(MediaType.APPLICATION_JSON)
.put(Entity.entity("\"" + "Artist" + "\"", MediaType.APPLICATION_JSON_TYPE));
System.out.println( String.format( "PUT to [%s], status code [%d]",
propertyUri_labels, response.getStatus() ) );
However, I have not been successful and got an status code [400]. Is there something wrong with my URL "http://localhost:7474/db/data/node/9/labels" ?
Pls help.
Thanks!

Try a POST instead of PUT.
Check the documentation => http://neo4j.com/docs/rest-docs/current/#rest-api-node-labels

Related

Cant Get Discord UserID using Get with Jsoup

Im trying to use Jsoup to make http Get request Discord Api, to get users information like this, what am I doing wrong ?
thread {
val id = "MY_ID:"
val token = "MY_TOKEN_BOT"
val source = Jsoup.connect("https://discord.com/api/v9/users/${id}")
.header("Authorization","Bot $token")
.ignoreContentType(true)
.method(Connection.Method.GET)
.execute()
.body()
runOnUiThread {
binding.txv.text = JSONObject(source).toString()
}
}
Response code GET 403
org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403, URL=[https://discord.com/api/v9/users/264097054047862794]
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:890)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:829)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:366)
at com.example.jsouptester.MainActivity$testing$1.invoke(MainActivity.kt:80)
at com.example.jsouptester.MainActivity$testing$1.invoke(MainActivity.kt:62)
at kotlin.concurrent.ThreadsKt$thread$thread$1.run(Thread.kt:30)

REST-ASSURED posting empty request body for generated object

I'm using rest assured to send a post with a generated body from a model class. The model class uses the builder pattern and I confirmed that it is getting built correctly:
Request body:
McpSalesInvoicesPost(invoices=[McpSalesInvoices(type=PRE_ORDER, amount=212.0, currencyCode=INR, transactionDate=2020-10-24T22:43:24, payments=[McpSalesPayments(type=CASH, amount=212.0, currencyCode=INR, reference=reference text sample 376, transactionDate=2014-08-20T19:23:51)])])
When I use that object in the rest assured post call I get an empty body in the request. Here is the rest assured code:
response = SerenityRest
.given()
.filters(Arrays.asList(new RequestLoggingFilter(), new ResponseLoggingFilter()))
.contentType(ContentType.JSON)
.header(new Header("x-openapi-clientid", "client-id-1"))
.body(requestBody)
.when()
.request(verb, SALES_BASE_URL + endpoint);
where request body is the built object mentioned above and this gives:
Body:
{
}
for the request. Any ideas on where I'm going wrong?
A
Maybe try .with().body(object).
response = SerenityRest
.given()
.filters(Arrays.asList(new RequestLoggingFilter(), new ResponseLoggingFilter()))
.contentType(ContentType.JSON)
.header(new Header("x-openapi-clientid", "client-id-1")).with().
.body(requestBody)
.when()
.request(verb, SALES_BASE_URL + endpoint);

How to get big response body Jsoup

Tell me what the problem is, and how to solve it. I need to get a response array json format. On the server, the response is formed in about 30 minutes, collects an array of 150K elements. Then it comes to dispatch, and hangs on hold for more than 24 hours. But even after such a long time, the answer does not come. There are no errors on the server. If you take 10K, then the answer comes without problems. I tried to save the answer to a TXT file, its size is +-35MB, and contains 35K stock.
This is how I execute the request:
Connection.Response response = Jsoup.connect(URLs.sayt + "/" + URLs.api + "/hs/CLIENTS/LIST/")
.method(Connection.Method.GET)
.maxBodySize(0)
.timeout(0)
.userAgent(URLs.getUserAgentMobile())
.header("Authorization", "Basic " + base64login)
.header("Accept-Language", "*")
.header("mode", "tobase")
.execute();
if(response != null){
ArrayList<Client> clients = new Gson().fromJson(response.body(), new TypeToken<List<Client>>() {}.getType());
for (Client client:clients){
sqLiteWork.AddToClient(client);
}
}
Here is an example of an element from the json array:
{"id": "9812d904-2d8a-11e8-80bb-a45d36c35311", "name": "Afaq", "code": "", "isGroup": false, "parent": "null", "address": "", "phone": "+994(12) 436 71 88", "phoneMore": "+994(50)2409696", "phoneHome": "", "debt": 0 }
I haven't found a solution to my question. I've tried both okhttp and httpurlconnection. Apparently, the android client itself does not support such a large string response in the body. Maybe it would be a solution via a file. But this is not a solution when you need actual data. Therefore, I made a response from the server for 10K elements. Full loading of 150K elements takes 2 hours.
Please note, I'm talking up-to-date data, if 2 hours is a long time, then online mode is also supported in my application.
Connection connection = Jsoup.connect(URLs.sayt + "/" + URLs.api + "/hs/CLIENTS/LIST/")
.method(Connection.Method.GET)
.ignoreContentType(true)
.maxBodySize(0)
.timeout(0)
.userAgent(URLs.getUserAgentMobile())
.header("Authorization", "Basic " + base64login)
.header("Accept-Language", "*")
.header("mode", "tobase");
Connection.Response response = connection.execute();
ArrayList<Client> clients = new Gson().fromJson(response.body(), new TypeToken<List<Client>>() {}.getType());
Client last = null;
for (Client client:clients){
last = client;
sqLiteWork.AddToClient(client);
}
while (clients.size() > 0){
response = connection.header("last", last.id).execute();
clients = new Gson().fromJson(response.body(), new TypeToken<List<Client>>() {}.getType());
for (Client client:clients){
last = client;
sqLiteWork.AddToClient(client);
}
}

Can't get data from Bosch IoT API

this is my first question to this great community, so please have mercy.
I currently have following problem:
I want to recieve data from Bosch IoT API, but even following their documentation (https://bosch-iot-insights.com/static-contents/docu/html/Java.html >> Synchronous query execution - Example) didnt help me.
My code looks exactly the same as theirs:
String resourceUrl = "https://bosch-iot-insights.com/mongodb-query-service/v2/my-project";
String username = "my-user";
String password = "my-pw";
String authorizationCredentials = generateAuthorizationToken( username, password );
String payload = new String(Files.readAllBytes(Paths.get("C:/Users/my-name/Desktop/payload.json")));
String contentType = "application/json";
WebResource service = Client.create().resource( resourceUrl );
ClientResponse response = service.header( "Authorization", authorizationCredentials )
.header( "Content-Type", contentType )
.post( ClientResponse.class, payload );
System.out.println( response );
if ( response.getStatus() == 200 ) {
System.out.println( parseJson( response.getEntity( String.class ) ) );
}
I've also tried some solutions with C# and PHP, but they all had the same output: 403 Forbidden
When I am opening the project URL I can normally log in, but then I get obviously a 405 Method not allowed - Error, because there is no GET-Method.
I even contacted them and asked for help, but with my credentials they were getting following result:
POST https://bosch-iot-insights.com/mongodb-query-service/v2/my-project/execute-aggregation-query returned a response status of 200 OK
[
{
"key": value
}
]
I know what the Status Code 403 means, but even Bosch can't help me in this problem, because for them everything looked fine..
I'd appreciate and be very grateful if someone could help me or give me some ideas why this error is being produced.
(For more information feel free to ask!)

java neo4j rest how to get the url of a created node

I am creating some nodes within a transaction in neo4j using the rest api. After all nodes have been created (typically between 3 and 5 in one transaction), I have to create some relationships between them. To do this I need, of course the location of the nodes, and this is the source of my problem. I can't figure out how to get this location.
According to documentation, I should be able to get the location of a node from the response-object, after creating the node, like so:
nodeLocation = response.getLocation();
But in a transaction, this of course returns the url of the transaction:
http://localhost:7474/db/data/transaction/108
Then I thought, if I query for the just created node, maybe in that response I can find the location. Again, according to documentation, the node location should be presented in the json-structure extensions in the field self.
"self" : "http://localhost:7474/db/data/node/357",
But my response to the query does not seem to contain an extension structure.
This is the query I'm using:
{"statements": [ {"statement": "MATCH (p:POST {sn_id: 'TW', id: '536982477664190465'} ) RETURN p"} ] }
I send it to the open transaction, and I get this back:
GET to http://localhost:7474/db/data/transaction/108 returned status code 200, returned data: {"commit":"http://localhost:7474/db/data/transaction/108/commit","results":[{"columns":["p"],"data":[]}],"transaction":{"expires":"Mon, 24 Nov 2014 20:40:34 +0000"},"errors":[]}
Just for completeness, this is the code for my query:
String payload = "{\"statements\": "
+ "[ "
+ "{\"statement\": "
+ "\"MATCH (p:POST {sn_id: 'TW', id: '536982477664190465'} ) RETURN p\""
+ "} "
+ "] "
+ "}";
logger.trace("sending cypher {} to endpoint {}", payload, endpointLoc);
WebResource resource = Client.create().resource( endpointLoc );
ClientResponse response = resource
.accept( MediaType.APPLICATION_JSON )
.type( MediaType.APPLICATION_JSON )
.entity( payload )
.get(ClientResponse.class);
//.post( ClientResponse.class );
String responseEntity = response.getEntity(String.class).toString();
int responseStatus = response.getStatus();
logger.trace("GET to {} returned status code {}, returned data: {}",
endpointLoc, responseStatus,
responseEntity);
JSONParser reponseParser = new JSONParser();
Object responseObj = reponseParser.parse(responseEntity);
JSONObject jsonResponseObj = responseObj instanceof JSONObject ?(JSONObject) responseObj : null;
if(jsonResponseObj == null)
throw new ParseException(0, "returned json object is null");
String result = (String) jsonResponseObj.get("results").toString();
logger.trace("result is {} ", result);
String error = (String) jsonResponseObj.get("errors").toString();
Am I missing something? Do I need to use a special call?
Can someone help me with this? Thanks in advance,
Christian
What do you need the node-URL for?
That's the old RESTful representation. You can either get it by using the old HTTP endpoint /db/data/cypher or better by specifying the (very verbose) resultDataContents type REST
You can also specify other types like "row" and "graph" in parallel.
{"statements": [
{"statement": "MATCH (p:POST {sn_id: 'TW', id: '536982477664190465'} ) RETURN p",
"resultDataContents":["REST"]}
] }

Categories

Resources