ElasticSearch SearchTemplate request Java API - java

I'm stuck with a SearchTemplate request, until now I've been able to write queries through the QueryBuilder and execute them calling the "search" method of the RestHighLevelClient java client, but when I try to execute the searchTemplate method I get a parse exception from the server "request body or source parameter is required".
So far I've been reading the documentation but nothing, the guide about the SearchTemplate is very poor.
This is how I'm currently trying to follow the basic steps from the official documentation:
SearchTemplateRequest request = new SearchTemplateRequest();
request.setRequest(new SearchRequest(indexPI));
request.setScriptType(ScriptType.INLINE);
request.setScript( "{" +
" \"query\": { \"match\" : { \"{{field}}\" : \"{{value}}\" } }," +
" \"size\" : \"{{size}}\"" +
"}");
Map<String, Object> scriptParams = new HashMap<>();
scriptParams.put("from","");
scriptParams.put("size","");
scriptParams.put("field", "title");
scriptParams.put("value", "elasticsearch");
scriptParams.put("size", 5);
request.setScriptParams(scriptParams);
SearchTemplateResponse response = elasticSearchClient.searchTemplate(request,
RequestOptions.DEFAULT);
The error I get:
Elasticsearch exception [type=parse_exception, reason=request body or source parameter is required]
At this point, I'm trying to understand how to set the request body for the above request and actually wondering if it is possible to do.
Any clue about what is missing besides the "unsettable" request body from the exception?

Related

how do I use JAX-WS Entity.json

I am trying to request a json file from openrouteservice.org and I dont know that much about json so I used the code exmaple on their site https://openrouteservice.org/dev/#/api-docs/v2/directions/{profile}/json/post in java. I replaced the coordinates with my list of coordinates(Double[]), but it says i`d need other tokens. Heres the code:
Client client = ClientBuilder.newClient();
Entity<String> payload = Entity.json({"coordinates":[list]});
Response response = client.target("https://api.openrouteservice.org/v2/directions/foot-walking/json")
.request()
.header("Authorization", "***")
.header("Accept", "application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8")
.header("Content-Type", "application/json; charset=utf-8")
.post(payload);
System.out.println("status: " + response.getStatus());
System.out.println("headers: " + response.getHeaders());
System.out.println("body:" + response.readEntity(String.class));
}
In the line
Entity<String> payload = Entity.json({"coordinates":[list]});
it says illegal start of expression in the .json() but I couldnt find how to use it properly, even on the official oracle site I didnt manage to understand how to solve it. I know its probably a very stupid question but thank you very much for erveryone who can help me

AWS API Gateway Integration Response

I am using AWS Lambda and API Gateway and facing an issue with my API's response code,
In case of an exception I am setting responseCode as 400 in my response,
But the API status is 200.
I found that my solution is related to AWS API Gateway's Integration Response,
I created all the possible Http Status codes that my application needs,
And I set the Lambda Error Regex in Integration Response,
But I still get API status as 200 despite me sending "responseCode" : "400", in my APIs response(response type is JsonObject in Java).
I have the following code AWS Lambda code,
I am passing ErrorCode as query parameter to my Get method,
And returning the same Error code in response eg. "responseCode" : "400".
My expected output is "responseCode" : "400" but, the API's status should also become 400 instead of 200.
public class MainHandler implements RequestHandler<JSONObject, JSONObject> {
public JSONObject handleRequest(JSONObject request, Context context) {
try {
JSONObject requestJson = (JSONObject) new JSONParser().parse(request.toString());
System.out.println("RequestJson : " + requestJson);
JSONObject params = (JSONObject) requestJson.get("params");
System.out.println("Params : " + params);
JSONObject queryString = (JSONObject) params.get("querystring");
System.out.println("QueryString : " + queryString);
String error = (String) queryString.get("errorCode");
System.out.println("ErrorCode : " + error);
JSONObject resp = new JSONObject();
resp.put("responseCode", error);
return resp;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
AWS API Gateway Method Response -
AWS API Gateway Integration Response -
Postman response -
The API status shows 200 Ok, whereas I want it as 400.
I am referring the following links -
1. https://forums.aws.amazon.com/thread.jspa?threadID=192918
2. Is there a way to change the http status codes returned by Amazon API Gateway?
Your Lambda Error Regex is not a regular expression. Changing it to .*"responseCode":\s"400".* should do it.
But for that use case it would be better to activate Lambda proxy integration. This provides a more flexible way to set the response code directly from the lambda function.

unable to pass map to restful method

I am trying to call this API via postman:
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void printDetails(final MultivaluedMap<String, String> formParams) {
for(String key : formParams.keySet()) {
System.out.println(key + " " + formParams.get(key));
}
}
But the map turns out to be empty. Please help me with the same.
PS: This is the first time I am trying to pass variable number of parameters to the api. I have referred to
sending List/Map as POST parameter jersey and How to access parameters in a RESTful POST method.
I think my mistake is in the way I am passing the parameters in postman: postman image
Please help me with the same. Also please help with how to call this API via an ajax (in JS) call.
Set the request header as "application/x-www-form-urlencoded".
Request body - Select raw and provide values as mentioned below:-
{
"LOCATION": "Singapore"
}
I have found out one possible answer.
#POST
public void printDetails() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
Map<String, String[]> mapp = request.getParameterMap();
for(String key : mapp.keySet()) {
System.out.println(key + " " + mapp.get(key)[0]);
}
}
Still not sure how to do it by passing "final MultivaluedMap" in the arguments

Receiving Unexpected Token Error When Passing Graphql query as JSON string

Thanks in advance for the help. I'm testing a GRAPHQL API using rest assured on testng in java.
I am trying to send agraphQL object disguised as JSON as a post, but when trying to package the string up as a JSON object I am getting the following error:
SyntaxError: Unexpected token B<br> at Object.parse (native)<br> at parse (/app/node_modules/body-parser/lib/types/json.js:88:17)<br> at /app/node_modules/body-parser/lib/read.js:116:18<br> at invokeCallback (/app/node_modules/raw-body/index.js:262:16)<br> at done (/app/node_modules/raw-body/index.js:251:7)<br> at IncomingMessage.onEnd (/app/node_modules/raw-body/index.js:307:7)<br> at emitNone (events.js:80:13)<br> at IncomingMessage.emit (events.js:179:7)<br> at endReadableNT (_stream_readable.js:913:12)<br> at _combinedTickCallback (internal/process/next_tick.js:74:11)<br> at process._tickDomainCallback (internal/process/next_tick.js:122:9)
The JSON object I am trying to create is here:
"{\"query\":\"{marketBySlug(slug: \"Boston\") {countryCode}}\"}"
I've figured out that my problem is the escaped quotes identifying Boston as a string are breaking the internally constructed Graphql query string, but I'm not sure how to get around this.
Try this:
"{\"query\":\"{marketBySlug(slug: \\\"Boston\\\") {countryCode}}\"}"
Instead of messing with strings and escaping, you should use parameterized queries. Your code will look like this:
String query =
"query MarketBySlug($slug: String!) {\n" +
" marketBySlug(slug: $slug) {\n" +
" countryCode\n" +
" }\n" +
"}";
Map<String, Object> variables = new HashMap<>();
variables.put("slug", slug);
given()
.body(new QueryDto(query, variables))
.when()
.post("/graphql")
.then()
.contentType(JSON)
.statusCode(HttpStatus.OK.value())
.body("data.marketBySlug.countryCode", equalTo(countryCode));
QueryDto is just a simple dto with the two fields (query and variables), setters and getters.

Blogger JSON API add a post

I want to add post to my blog using Blogger API. I successfully got rights to use Blogger API and activated them in Google API console. I used this tutorial to obtain access_token. I found this question , so before ever request I obtain new request_token.
When I make first request to add post, I got en error: 401 "message": "Invalid Credentials", "location": "Authorization".
When I make second request to add post with new token, I got error: 403 "message": "Daily Limit Exceeded. Please sign up"
Code for my request is:
final JSONObject obj = new JSONObject();
obj.put("id", mUserID);
final JSONObject requestBody = new JSONObject();
requestBody.put("kind", "blogger#post");
requestBody.put("blog", obj);
requestBody.put("title", msg[0]);
requestBody.put("content", msg[0] + " " + msg[1]);
final HttpPost request = new HttpPost("https://www.googleapis.com/blogger/v3/blogs/" + mUserID + "/posts");
request.addHeader("Authorization", "Bearer " + mToken);
request.addHeader("Content-Type", "application/json");
request.setEntity(new StringEntity(requestBody.toString()));
final HttpResponse response = mHttpClient.execute(request);
final HttpEntity ent = response.getEntity();
Log.i(SocialPoster.LOG, EntityUtils.toString(ent));
ent.consumeContent();
UPDATE
Solution was found: simply adding "?key={MY_API_KEY}" to request's URL solved the problem
The Tutorial site you linked states
"The API Key is mandatory as it identifies your application and therefore allows the API to deduct quota and use the quota rules defined for your project. You need to specify the API Key on your Tasks service Object."
useTasksAPI(String accessToken) {
// Setting up the Tasks API Service
HttpTransport transport = AndroidHttp.newCompatibleTransport();
AccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(accessToken);
Tasks service = new Tasks(transport, accessProtectedResource, new JacksonFactory());
service.accessKey = INSERT_YOUR_API_KEY;
service.setApplicationName("Google-TasksSample/1.0");
// TODO: now use the service to query the Tasks API
}
Sounds to me like you are missing the API key, using it wrong, misplaced it in your code or supplied it to the service in the wrong way.
I haven't looked over the code here, but this is Google's sample code for what you are trying to do. Test your API key with this code.

Categories