ElasticSearch custom plugin unable to get from post request parameters - post

Hi I am writing custom plugin for elastic search,
but I unable to get the parameter from the post request.
#Inject
public HelloRestHandler(Settings settings, RestController restController, Client esClient) {
super(settings, restController, esClient);
restController.registerHandler(RestRequest.Method.GET, "/_hello", this);
restController.registerHandler(RestRequest.Method.POST, "/_hello", this);
restController.registerHandler(RestRequest.Method.PUT, "/_hello", this);
}
#Override
public void handleRequest(final RestRequest request, final RestChannel channel, Client esClient) {
ObjectMapper mapper = new ObjectMapper();
String json;
try{json= mapper.writeValueAsString(request.params());}catch (Exception exp){ json ="not found";}
channel.sendResponse(new BytesRestResponse(OK,json));}
The curl:
curl -XPOST "http://localhost:9200/_hello/" -d '{"first":"1"}'
response :
"{}" (empty JSON)
Please help me out to fix my issue. Thanks.

request.params() returns the HTTP parameters passed in the query string. In your case, there are none. Try with request.content() instead.
String json;
try{
json = mapper.writeValueAsString(request.content());
} catch (Exception exp){
json ="not found";
}
channel.sendResponse(new BytesRestResponse(OK,json));

Related

How to get both HTTP response body and Status when using Reactor Netty HTTP Client

I am using the Reactor Netty HTTP client here as a stand alone dependency, ie not via spring-webflux because I do not want to drag in Spring related dependencies
As can be seen from the documentation it is possible to make a request that returns HttpClientResponse
import reactor.netty.http.client.HttpClient;
import reactor.netty.http.client.HttpClientResponse;
public class Application {
public static void main(String[] args) {
HttpClientResponse response =
HttpClient.create()
.get()
.uri("http://example.com/")
.response()
.block();
}
}
Thing is HttpClientResponse only contains the headers and the staus. As can be seen from its Java Docs here
Also from the example to consume data one can do
import reactor.netty.http.client.HttpClient;
public class Application {
public static void main(String[] args) {
String response =
HttpClient.create()
.get()
.uri("http://example.com/")
.responseContent()
.aggregate()
.asString()
.block();
}
}
But this only returns the http entity data as string. No information about the headers nor status code.
The problem I have now is I need to make a request and get a response that gives me both the headers, status etc alongside with the http response body.
I cannot seem to find how. Any ideas?qw
Take a look at the following methods:
Flux<V> response(BiFunction<HttpClientResponse,ByteBufFlux,Publisher<V>> receiver)
Mono<V> responseSingle(BiFunction<HttpClientResponse, ByteBufMono, Mono<V>> receiver)
They allow you to access response body, status, and http headers simultaneously.
For example using the responseSingle method you can do the following:
private Mono<Foo> getFoo() {
return httpClient.get()
.uri("foos/1")
.responseSingle(
(response, bytes) ->
bytes.asString()
.map(it -> new Foo(response.status().code(), it))
);
}
The code above translates the response into some domain object Foo defined as follows:
public static class Foo {
int status;
String response;
public Foo(int status, String response) {
this.status = status;
this.response = response;
}
}
The Foo object is null when the http response does not have a body. For example, if HttpStatus 403 is returned, the Foo object is null. I was able to check response code and return just status.
(resp, bytes)-> {
if (resp.status().code()=HttpResponseStatus.OK.code) {
return bytes.asString().map(it->new Foo(resp.status(),it);
} else {
return Mono.just(new Foo(resp.status());
}
}

API returning text/html rather than JSON when triggered using RestArrured

I'm triggering the Zomato api for the collections request, however, I keep getting the headers as if they were text/html. Postman returns them as JSON, which is what I need. All other Zomato apis I've tested so far are returning JSON but collections and not sure why. That's what I have on my attempts to force the JSON as the type for the response.
#Test
public void testGetCousinesApiReturnsItemsInAscendingAlphabeticalOrder() {
Map<String, Object> map = new HashMap<>();
map.put("city_id", 61);
Response r = given()
.baseUri(baseUrl)
.basePath("/cousines")
.queryParams(map)
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
.contentType("application/json\r\n")
.header("Accept", "application/json").and()
.header("Content-Type", "application/json")
.header("user-key", zomatoKey)
.log().body(false)
.get();
System.out.println(r.getContentType());
}
I convert response to JsonPath :
public static JsonPath getJsonPath (Response res) {
String json = res.asString();
System.out.println("returned json: " + json);
return new JsonPath(json);
}
and then use this JsonPath to get each value of Response:
JsonPath jp = getJsonPath(res);
String type = jp.get("type");

How to Put request with json payload with rest assured

I want to load the JSON file in a body with rest assured but getting error 415.
Can you please help me?
code is:
public class Entitlement_Creation extends BaseClass {
#Test
public void JsonPayload() throws IOException
{
Path json_data = Paths.get("test.json");
byte[] wikiArray = Files.readAllBytes(json_data);
String wikiString = new String(wikiArray);
System.out.println(wikiString);
given()
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
.body(wikiString)
.when()
.put()
.then()
.statusCode(200)
.extract()
.response();
}
from this snippet, I can't see any information about URL of your service.
You should put your URL as an argument to put() method.

Create downloadable link and Preview File for OneDrive DriveItem

I've been trying to generate a public downloadable URL for OneDrive
for Business and SharePoint DriveItem object using /createLink api.
curl \
-X POST \
-d '{"type":"view","scope":"anonymous"}' \
-H 'Authorization: bearer xxx_Access_Token_xxx' \
-H 'Content-Type: application/json' \
"https://graph.microsoft.com/v1.0/drive/items/<item-id>/createLink"
Above call returns JSON result with body.link.webUrl (https://my.sharepoint.com/:u:/g/XXXXrKmGKlXXXXXXXXXXsq0Bh3x4TTXXXXXXXXXXXXXXXXX) being the sharable URL. However, this link doesn't contain the reference to file directly.
As per this comment, appending download=1 as query string parameter to generated shared URL will allow the user to open the original file directly. But I could not find any documentation supporting this behavior.
Is it possible to
Download the file directly.
To use public URL as src attribute of img tag.
You may follow official document of OneDrive
You will have to put below line of code in success field of IProgressCallback. Here ItemId is "id of uploaded item".
String itemId = result.id;
TestBase testBase = new TestBase(xdata.getinstance().getSetting(config.onedriveaccesstoken));
AsyncTask<Void, Void, Void> downloadfileonedrive = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(final Void... params) {
com.microsoft.graph.models.extensions.Permission response = testBase.graphClient
.me()
.drive()
.items(itemId)
.createLink("edit", "anonymous")
.buildRequest().post();
Log.e("Sharable link : ", ""+response);
try {
String sharabalelink = new JSONObject(response.getRawObject().getAsJsonObject("link").toString()).getString("webUrl");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}};
downloadfileonedrive.execute();

Struts2 Junit4 tests accumulate JSON responses with every action execution

I've written a few Junit4 tests, which looks like this :
public class TestCampaignList extends StrutsJUnit4TestCase<Object> {
public static final Logger LOG = Logger.getLogger(TestCampaignList.class.getName());
#Before
public void loginAdmin() throws ServletException, UnsupportedEncodingException {
request.setParameter("email", "nitin.cool4urchat#gmail.com");
request.setParameter("password", "22");
String response = executeAction("/login/admin");
System.out.println("Login Response : " + response);
}
#Test
public void testList() throws Exception {
request.setParameter("iDisplayStart", "0");
request.setParameter("iDisplayLength", "10");
String response = executeAction("/campaign/list");
System.out.println("Reponse : " + response);
}
}
Both actions return JSON results and executeAction javadoc says :
For this to work the configured result for the action needs to be FreeMarker, or Velocity (JSPs can be used with the Embedded JSP plugin)
Seems like it's unable to handle JSON results and hence, the second action execution shows accumulated result, such that result_for_second_action= result1 concatenate result2
Is there a solution to get the executeAction() return the actual JSON response, rather than concatenating JSON responses from all previous executions.
This is happening because you are executing action in #Before method. In that way the setUp method of StrutsJUnit4TestCase is not getting called in between your loginAdmin and test method and you previous request parameters are passed to it again. You can call setUp method by yourself in your tests method.
In your case you can actually call initServletMockObjects method to create new mock servlet objects such as request.
#Test
public void testList() throws Exception {
setUp();
// or
// initServletMockObjects();
request.setParameter("iDisplayStart", "0");
request.setParameter("iDisplayLength", "10");
String response = executeAction("/campaign/list");
System.out.println("Reponse : " + response);
}

Resources