get method in restful service , return {} - rest

I want to pass an JSONObject from restful service to a restful client . Here is pice of my service code :
#GET
#Path("/getJson")
#Produces(MediaType.APPLICATION_JSON)
public JSONObject getJson() {
try {
JSONObject json=new JSONObject();
json.put("PoprocessingCode", "123456789");
json.put("TransactionAmount", "0000000");
System.out.println(json);
return json;
} catch (Exception e) {
System.err.println(e.getMessage());
return null;
}
}
and here is pice of my restful client :
Client c = Client.create();
WebResource resource = c.resource("http://localhost:8080/TestJsonService/jaxrs/JsonService/getJson");
JSONObject json=new JSONObject();
json=resource.accept(MediaType.APPLICATION_JSON_TYPE).get(JSONObject.class);
try {
System.out.println("json.getString = "+json.getString("PoprocessingCode"));
} catch (JSONException e1) {
e1.printStackTrace();
}
when I ran it , I get this error :
org.json.JSONException: JSONObject["PoprocessingCode"] not found.
at org.json.JSONObject.get(JSONObject.java:459)
at org.json.JSONObject.getString(JSONObject.java:640)
at JsonClient.main(JsonClient.java:30)
I tested my service by Test with "REST Web Service Explorer" in myeclipse and recognized get method in service T returned just this
{}
and there isn't anything in it and it is empty , I don't know why?!
please guide me in order to solve it.
thanks...

Please pass the JsonObject in this form, this will work :
#Path("Excel")
#POST
#GET
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String ExportToExcel(String jsonString)
And post this using REST Console.
In case of :
JsonObject then use this --->
#Path("/rename")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Event renameEvent(Event newEvent)
And the object that you pass from the REST CONSOLE should be of following pattern :
{"measures":null,"eventScenarioId":2016,"timeId":20378,"promoPrice":1.979734,"oiAllowancePerunit":0.0,"productId":7158,"scanAllowancePerUnit":0.0,"eventProductStrategy":[{"name":"FND","tsId":4,"tsACV":10.0,"eventProductScenarioId":5069,"id":3},{"name":"TPR","tsId":1,"tsACV":0.0,"eventProductScenarioId":5069,"id":4},{"name":"DISPLAY","tsId":3,"tsACV":2.0,"eventProductScenarioId":5069,"id":2},{"name":"FEATURE","tsId":2,"tsACV":9.0,"eventProductScenarioId":5069,"id":1}],"addEstimatedIncrementalUnits":0.0,"shippedBaseUnits":4365.000000000001,"edShelfPrice":1.979734,"eventFixedCost":0.0,"shippedUnitPct":100.0,"edlpPricePerUnit":0.0,"manuFixedCost":0.0,"customerId":null,"id":5069}

Related

REST Response is {}

I am new to REST. I have written a small REST resource and Whenever I try to invoke the REST service from POSTMAN, i get a empty response {} and status code 200
The Request :
http://localhost:8080/demo/managers
#GET
#Path("managers")
#Produces({"application/json"})
public Response getManagers() throws GeneralException, JSONException
{
JSONArray valueString = COMING_FROM_OTHER_METHOD();
System.out.println("==== "+valueString.toString());
return Response.ok(valueString,MediaType.APPLICATION_JSON).build();
}
The correct value I can see in System.out.println():
[{"display":"john","id":"003"},{"display":"hansi","id":"004"},{"display":"samy gayle","id":"005"}]
I want to a JSONArray Response but everytime I get an empty response
{}
But when modify the code like below it gives correct response
#GET
#Path("managers")
#Produces({"application/json"})
public String getManagers() throws GeneralException, JSONException
{
JSONArray valueString = COMING_FROM_OTHER_METHOD();
System.out.println("==== "+valueString.toString());
return valueString.toString();
}
Kindly Help. why am I getting {} when trying to return a Response object J
I would use domain objects rather than String instances:
class Manager {
private String id;
private String display;
... setters/getters ...
}
public ResponseEntity<ArrayList<Manager>> getManagers() throws GeneralException {
ArrayList<Manager> managers = COMING_FROM_OTHER_METHOD();
return new ResponseEntity<>(managers, HttpStatus.OK);
}

Spring REST Exception - getting the response payload

I have the following:
The "400 Bad request" is converted to a ResourceAccessException in Spring.
Is there any way to retrieve the payload here? I want to send the "errorMessage" further up the call chain.
Code-wise the following is used to do the request:
public <T> T post(String url, Object request, Class<T> className) {
try {
return logEnhancedRestTemplate.postForObject(url, request, className);
} catch(RestClientException ex) {
throw handleErrors(ex, url);
}
}
It is in the "handleErrors" method I want to use the "errorMessage" from the body.
If you want to retrieve the message of an exception use the method getMessage().
In your specific example maybe is better if you catch a generic exception, since I suppose that every type of Runtime exception should call your method handleErrors(ex, url).
If this is the case, I suggest you to modify your code with:
public <T> T post(String url, Object request, Class<T> className) {
try {
return logEnhancedRestTemplate.postForObject(url, request, className);
} catch(Exception ex) {
throw handleErrors(ex, url);
}
}

WireMock: Stubbing - How get object "testClient"?

I want to test http request/response. So I use WireMock.
I want to stub response for specific request:
Here code:
public class WireMockPersons {
#Rule
public WireMockRule wireMockRule = new WireMockRule(8089);
#Test
public void exactUrlOnly() {
stubFor(get(urlEqualTo("/some/thing"))
.willReturn(aResponse()
.withHeader("Content-Type", "text/plain")
.withBody("Hello world!")));
assertThat(testClient.get("/some/thing").statusCode(), is(200));
assertThat(testClient.get("/some/thing/else").statusCode(), is(404));
}
Code is not compile because no object testClient. How I can get testClient object?
testClient is your client library for the API you are mocking.
Looks like you have copied directly from the examples which are indicative only.
Replace testClient with the HTTP library of your choosing, for example HttpClient.
String url = "http://localhost:8089/some/thing";
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
HttpGet get = new HttpGet(url);
HttpEntity entity = client.execute(get).getEntity();
return EntityUtils.toString(entity, "UTF-8");
} catch (IOException e) {
throw new RuntimeException("Unable to call " + url, e);
}

Is it possible to apply dictionaries for Citrus static response adapter response template?

I'm using Citrus static response adapter to mock services, and I need to change values in its payload for every test case. Ideally I think about usage of dictionaries for each test case. There is sample of my current scenario:
#Autowired
#Qualifier("checkRegistrationEndpointAdapter")
public StaticResponseEndpointAdapter checkRegistrationEndpointAdapter;
protected void setAdapterResponse(StaticResponseEndpointAdapter adapter, String filenamepath){
URL url = this.getClass().getResource(filenamepath);
String payload = null;
try {
payload = Resources.toString(url, Charsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
adapter.setMessagePayload(payload);
}
#CitrusTest
public void TestCase02() throws IOException {
http()
.client(CLIENT)
.post()
.payload(new ClassPathResource("templates/thisStartRequestMsg.xml", getClass()))
.dictionary("TC02");
http()
.client(CLIENT)
.response()
.messageType("xml")
.payload(new ClassPathResource("templates/thisStartResponseMsg.xml", getClass()));
action(new AbstractTestAction() {
#Override
public void doExecute(TestContext testContext) {
setAdapterResponse(checkRegistrationEndpointAdapter, "templates/check-registration-v1CheckRegistrationResponseMsg.xml");
}
});
http()
.client(CLIENT)
.response()
.messageType("xml")
.payload(new ClassPathResource("templates/check-registration-v1CheckRegistrationRequestMsg.xml", getClass()))
.dictionary("TC02");
}
How can I apply dictionary to the payload set in my setAdapterResponse method?
Note: this question relates to Can I use Citrus variable in Citrus static response adapter payload?
Static response adapter has currently no support for data dictionaries. I wonder why you put so much effort into static response adapters? Why not using the full Citrus http server power with receiving the request and providing a response inside the test case?

Pass Multiple parameters in a REST call

My server code is as:
#POST
#Path("/getMapping")
public ListResponse getMapping(Long id, String name, String clientName, String instanceName) {
ListResponse response = null;
try {
response = new ListResponse();
List<Mappings> mappings = service.getMapping(id, name, clientName, instanceName);
response.setStatusCode(SUCCESS);
response.setMappings(mappings);
} catch (Exception e) {
setResponseErrors(response, e);
}
return response;
}
I am using Jersey REST client, but I dont think there is an option to have multiple params passed in the post method like:
ClientResponse clientResponse = webResource.type(XML_TYPE).post(ClientResponse.class, id, name, clientName, instanceName);
Is there a way to accomplish this?
I could use MultiValuedMap or #QueryParams in this case, but there are other cases where multiple params are more complex Objects. Also, wrapping all in a "paramContainer" will be an inefficient solution since there are so many such methods with multiple params with different combinations.
(As an aside, why would REST not support multiple params?)
Any help greatly appreciated.
here is how I'll do it
SERVER CODE
1.1 should have to use #FormParam in order to declare parameters in #FormDataParam
1.2 a POST is better if encrypted for that use #Consumes(MediaType.MULTIPART_FORM_DATA)
you will have a server code like this :
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Path("/getMapping")
public ListResponse getMapping(#FormParam("id")Long id, #FormParam("name") String name, #FormParam("clientName") String clientName, #FormParam("instanceName") String instanceName) {
ListResponse response = null;
try {
response = new ListResponse();
List<Mappings> mappings = service.getMapping(id, name, clientName, instanceName);
response.setStatusCode(SUCCESS);
response.setMappings(mappings);
} catch (Exception e) {
setResponseErrors(response, e);
}
return response;
}
CLIENT CODE
Form form = new Form();
form.add("id", "1");
form.add("name", "je#rizze.com");
form.add("clientName","firefox");
form.add("instanceName","node45343.rizze.com");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
enjoy :)
An addition to jeorfevre's answer above:
In case you're using Jersey 1.x, this is how it works:
Client: (pure Java):
public Response testPost(String param1, String param2) {
// Build the request string in this format:
// String request = "param1=1&param2=2";
String request = "param1=" + param1+ "&param2=" + param2;
WebClient client = WebClient.create(...);
return client.path(CONTROLLER_BASE_URI + "/test")
.post(request);
}
Server:
#Path("/test")
#POST
#Produces(MediaType.APPLICATION_JSON)
public void test(#FormParam("param1") String param1, #FormParam("param2") String param2) {
...
}