I'm trying to read a REST HATEOAS response like this one :
{
"_embedded": {
"tasks": [
{
"id": 1,
"name":"task1"
"_links": {
"self": {
"href": "http://localhost:8080/v1/tasks/1"
},
"tasks": {
"href": "http://localhost:8080/v1/tasks"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/v1/tasks?page=0&size=1"
}
},
"page": {
"size": 1,
"totalElements": 1,
"totalPages": 1,
"number": 0
}
}
I'm trying to folloaw the example of spring's documentation : spring hateoas traverson.
Java code :
...
TypeReferences.ResourcesType<Resources<Task>> resourceParameterizedTypeReference = new TypeReferences.ResourcesType<Resources<Task>>(){};
Traverson traverson = new Traverson(new URI("http://localhost:8080/v1/tasks"), MediaTypes.HAL_JSON);
Traverson.TraversalBuilder builder = traverson.follow(rel("tasks")).withHeaders(headers);
Resources<Resources<Task>> taskResources = builder.toObject(resourceParameterizedTypeReference);
...
But I obtain this error :
Did not find LinkDiscoverer supporting media type text/html!
Cause : "follow(rel("tasks"))" don't find "tasks".
I'm trying other solutions like this one :
Deserialize JSON containing (_links and _embedded) using spring-hateoas, I obtain the error "Expected to find link with rel ..." too.
Maybe finaly I'm not understand the good manner to use traverson object.
I solve my problem by parsing myself the response in Json, but are they another way to get the list contains in the "_embedded" tags in a list of beans ?
If you have some examples I'm interesting :).
I think you need to use a Json Path expression to access the embedded content.
Traverson.TraversalBuilder builder = traverson.follow("$._embedded.tasks[0]").withHeaders(headers);
Resources<Resources<Task>> taskResources = builder.toObject(resourceParameterizedTypeReference);
The following tool is useful for playing with the path expression: http://www.jsonquerytool.com/
BTW, your JSON is missing a "," after the "name".
Related
I've REST API which exposes the JSON with a link to the next page and data as shown below:
{
"nextPageLink" : "rest_api_url_to_next_page"
"myData" : [ {
"key" : {
"d1" : "d1_value",
"d2" : "d2_value"
},
"productData" : {
"d3" : "d3_value",
"d4" : "d4_value"
}
"d5" : "d5_value",
"d6" : "d6_value"
}
There are around 1000s of pages with nextPageLink. On the last page, its empty. Can you please guide me how to design this in java. Also, I've such 10 more different REST APIs to handle.
My approach:
Create 2 pojos, one for key (keyPojo) and another for rest of the data(restDataPojo). Create a map with key as keyPojo and value as restDataPojo.
Create a pojo which has all the values, and dump data in the list of type pojo.
Is there any better approach to store such data? is this approach efficient enough?
The 'standard' solution to this sort of problem recommended by the RESTful Web Services Cookbook is to have an array of links tagged by a relationship type (typically called rel).
A typical 'page' would look like this:
{
"links": [{
"rel": "previous",
"href": "http://example.com/pages/41"
},
{
"rel": "next",
"href": "http://example.com/pages/43"
}
],
"otherAttributes": "go here"
}
On the first page, you omit the previous link:
{
"links": [
{
"rel": "next",
"href": "http://example.com/pages/43"
}
],
"otherAttributes": "go here"
}
and on the last page, you omit the next link:
{
"links": [{
"rel": "previous",
"href": "http://example.com/pages/41"
}
],
"otherAttributes": "go here"
}
Since links is an array, you can back all three cases with the same underlying DTO.
I have the following example URI:
localhost/users
and this JSON coming as response when I send a request to it:
[
{
"id": 1,
"name": "Joe"
,
{
"id": 3,
"name": "Ben"
,
{
"id": 4,
"name": "Jim"
}
}
]
How do I verify with RestAssured, for example that there are no user with id = 2?
Would it be something along the lines of this semi-pseudo:
given().spec(requestSpecification)
.when().get("/users")
.and().body("id==2", ????);
Any advice/guidance will be appreciated, thank you.
try this:
given().spec(requestSpecification)
.when().get("/users")
.and().body("id", is(not(equalTo(2))));
Usage rest-assured documentation section Use the response to verify other parts of the response provides more detail.
is(not(Matcher)) is provided by hamcrest
Here is the Json I am trying to handle with Traverson to extract a single link from this HAL:
{
"_links": {
"curies": [
{
"href": "https://localhost/auth/def/rels/{rel}",
"name": "auth",
"templated": true
}
],
"self": {
"href": "https://localhost/auth/identity"
}
},
"_embedded": {
"auth": [
{
"_links": {
"auth:ad": [
{
"href": "https://localhost/auth/ad"
}
]
},
"kind": "oauth2"
},
{
"_links": {
"auth:default": [
{
"href": "https://localhost/auth/default" // **Link that I need**
}
]
},
"kind": "oauth2"
}
]
}
}
Java code responsible for handling ideally should look like this:
Link test = traverson
.follow("auth")
.follow("$.['_embedded']['auth']..['_links']['auth:default']..['href'][0]")
.asLink();
But for some reason I am getting no hits despite the fact that right before adding the last [0] in the JSONPath expression I am getting an array of one element. Is there a way to extract this single link so that I am not returned with an array? I used this tool for testing.
The code necessary to achieve what I should look like this:
JsonPathLinkDiscoverer disc = new JsonPathLinkDiscoverer("$._embedded..auth.._links..['%s']..href", MediaTypes.HAL_JSON);
Link authLink = disc.findLinksWithRel("auth:default", <json>).get(0);
where <json> should be the json representation of the example in the original question (probably like a reponse from other call).
I need to dynamically build the following post request JSON body with jmeter beanshell preprocessor. I am referring to the following question which has a solution for my problem with looped strings. I would need to do this with json-property(variables) an array of JSON objects with different name and values. Thanks a lot.
{
"processDefinitionId":"optaplannerkey:1:dbc4af8f-7e04-11e9-afa3-1ecac26bb5e0",
"businessKey":"optaplannerkey",
"returnVariables":true,
"variables": [
{
"name": "TaskDescription",
"value": "Fixing the issue with sink"
},
{
"name": "TaskCategory",
"value": "plumbing"
},
{
"name": "Priority",
"value": "Medium"
},
{
"name": "Status",
"value": "New"
},
{
"name": "SkillsRequired",
"value": "Plumbing Skills"
},
{
"name": "DueDate",
"value": "2019-05-24T11:23:08.030+05:30"
}
]
}
Use dummy sampler with the parameterized json request and CSV Data Set Config for the dynamic input. Below, I have paremeterized only two for demo.
Then, Use JSR223 Post processor with the following code:-
vars.put("responseVar",prev.getResponseDataAsString());
This will put response body in "responseVar" variable. Fetch it using ${responseVar}
Hope this helps.
I have a use case where I have a Json data and I have to convert that into JSONLD format.
First Question : Can this be done easily , like some API for this, that probably I am missing ?
Second Question : If not then what are the steps that needs to be taken.
So the Json Looks like :
{
key:"language",
value: "scala"
}
And I want to convert it into the JSONLD format.
Any help is appreciated.
You can simply add a context on this json object like :
{
#context: {
"key": "http://schema.org/description",
"value": "http://schema.org/value"
},
key: "language",
value: "scala"
}
If you are interested in using JavaScript library to do this task, then npm module JSONLD is great one.
Note: This library has dependency on PYTHON.
JavaScript code Example from JSONLD site:
var doc = {
"http://schema.org/name": "Manu Sporny",
"http://schema.org/url": {"#id": "http://manu.sporny.org/"},
"http://schema.org/image": {"#id": "http://manu.sporny.org/images/manu.png"}
};
var context = {
"name": "http://schema.org/name",
"homepage": {"#id": "http://schema.org/url", "#type": "#id"},
"image": {"#id": "http://schema.org/image", "#type": "#id"}
};
// compact a document according to a particular context
// see: http://json-ld.org/spec/latest/json-ld/#compacted-document-form
jsonld.compact(doc, context, function(err, compacted) {
console.log(JSON.stringify(compacted, null, 2));
});
Output:
{
"#context": {...},
"name": "Manu Sporny",
"homepage": "http://manu.sporny.org/",
"image": "http://manu.sporny.org/images/manu.png"
}
When I was searching for JavaScript library for the JSON to JSONLD transformation, I could come up with this one. But, as this library has PYTHON dependency, I am searching for other JavaScript library for the same.