How to Put request with json payload with rest assured - 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.

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");

ElasticSearch custom plugin unable to get from post request parameters

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));

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);
}

Posting multipart form data to seam+RESTeasy fails marshalling to InputStream

I'm trying to post image data to a seam+RESTeasy endpoint and I'm getting a very cryptic error during JBoss startup. The HTTP request I'm sending has a content-type of multipart/form-data which has a single image/jpeg part with name "attachment". My service method looks like this:
#POST
#Path("uploadSymptomsImage/{appointmentGUID}")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("application/json")
public String uploadSymptomsImage( #FormParam("attachment") InputStream fileInputStream,
#PathParam("appointmentGUID") String strAppointmentGUID )
{ ...
The error that I get is during startup:
Caused by: java.lang.RuntimeException: Unable to find a constructor that takes a String param or a valueOf() or fromString() method for javax.ws.rs.FormParam("attachment") on public java.lang.String com....AppointmentRestService.uploadSymptomsImage(java.io.InputStream,java.lang.String) for basetype: java.io.InputStream
at org.jboss.resteasy.core.StringParameterInjector.initialize(StringParameterInjector.java:206) [:]
at org.jboss.resteasy.core.StringParameterInjector.<init>(StringParameterInjector.java:57) [:]
at org.jboss.resteasy.core.FormParamInjector.<init>(FormParamInjector.java:22) [:]
My understanding was that media types could be automatically marshalled to InputStream. I've also tried java.io.File, java.io.Reader - both with same error. When I replace with byte[] or String I get a zero length array, or null as the parameter value.
How would you go about debugging this? Also, is it possible to access the raw request or pre-marshalled values?
Any suggestions here would be greatly appreciated.
You should retrieve the contents using MultipartFormDataInput. See the following example:
#POST
#Path("uploadSymptomsImage/{appointmentGUID}")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("application/json")
public String uploadSymptomsImage(#PathParam("appointmentGUID") String strAppointmentGUID,
MultipartFormDataInput formData) {
Map<String, List<InputPart>> formDataMap = formData.getFormDataMap();
List<InputPart> attachments = formDataMap.get("attachment");
for(InputPart attachment : attachments) {
String fileName = extractFilename(attachment);
if(fileName.isEmpty()) continue;
InputStream in = attachment.getBody(new GenericType<InputStream>() {});
// Interact with stream
}
// Respond
}
The extractFilename method is a helper method I wrote:
private static String extractFilename(final InputPart attachment) {
Preconditions.checkNotNull(attachment);
MultivaluedMap<String, String> headers = attachment.getHeaders();
String contentDispositionHeader = headers.getFirst("Content-Disposition");
Preconditions.checkNotNull(contentDispositionHeader);
for(String headerPart : contentDispositionHeader.split(";(\\s)+")) {
String[] split = headerPart.split("=");
if(split.length == 2 && split[0].equalsIgnoreCase("filename")) {
return split[1].replace("\"", "");
}
}
return null;
}

Resources