PlayFramework Result with Ajax - java

According to : PlayFramework Document 2.0 & PlayFramework Document 2.1
I know that in play I can return:
Ok()
badRequest()
created()
status()
forbidden()
internalServerError()
TODO
etc...
I would like to send with ajax an response with my information in it. Unfortunatelly play sends only status information, and some kind of object which I do not understand.
Only method ok("Test message") sends status and my message information. Rest of it dosnt work.
How to deal with it?
-- Edit --
I have ajax method:
$.post($("#assignmentsubmitAddress").text(), { 'units' : submittedUnits },
function(response, status, xhr) {
showNotyfication(status, response);
})
When I return ok("test");
In java script variable response I have just String test
When I return badRequest("test"); In java script variable response I have java object. When I print variable response I am getting Object object.

To send back a response in the json format to your client send a ok containing a string :
/**
* Translate a json object into a json string.
*/
public static<T> String objToJson(Object obj)
{
ObjectMapper mapper = new ObjectMapper();
try{
String json = mapper.writeValueAsString(obj);
return json;
}catch(java.io.IOException e){
Logger.error(e.getMessage(), e);
}
return "";
}
public static Result actions()
{
Object objToSendBack = ...
return ok(objToJson(objToSendBack));
}
You can send back wathever you want, including html, but json is more convenient for communicating with javascript functions.

I've figure it out.
I've just changed variable response which is an object to response.responseText.
Now it works.

Related

WSO2 ESB Message context cannot be changed through custom class mediator

I'm trying to alter a message using a custom class mediator in wso2 esb. What I'm trying to achieve is to add/set the value of an element in the message sent. The message is sent using a REST API, and it goes through the mentioned class (where the transformation happens). However, when I do a full log of the message after the class, I see that the message keeps the same values that had at first (basically the class only alters the message while it's in the class mediator, so when it comes out of the mediator, it goes back to its original input form).
Input:
Body : <soapenv:Body ...><jsonObject><ts>2020-01-13</ts><temp></temp></jsonObject></soapenv:Body>
Desired output:
Body : <soapenv:Body ...><jsonObject><ts>2020-01-13</ts><temp>Hello</temp></jsonObject></soapenv:Body>
Things that I've tried so far and that didn't work:
Get message context, get the desired element and set the text
Use a OMFactory to create an OMElement and put that new element in the message context
Get the new altered envelope and set it as the new message context envelope
Create a new json payload
Any idea of how to get it working ?
You can refer to the following logic which changes the payload
#Override
public boolean mediate(MessageContext messageContext) {
try {
org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext)messageContext).getAxis2MessageContext();
JSONObject jsonBody = new JSONObject();
JSONObject jsonError = new JSONObject();
jsonError.put("error","Authoraization Missing");
jsonError.put("detail","Authoraization Credentials invalid");
jsonError.put("title","Authoraization Error");
jsonBody.put("status", "403");
jsonBody.put("errorMessage", jsonError);
String transformedJson = jsonBody.toString();
JsonUtil.newJsonPayload(axis2MessageContext,transformedJson, true, true);
// change the response type to XML
axis2MessageContext.setProperty("messageType", "application/xml");
axis2MessageContext.setProperty("ContentType", "application/xml");
} catch (Exception e) {
System.err.println("Error: " + e);
return false;
}
return true;
}
If this doesn't help, kindly share your code to have an idea.
I already tried that tutorial #Nirothipan, but didn't work.
My code:
#Override
public boolean mediate(MessageContext mc){
String measure = mc.getEnvelope().getBody().getFirstElement().getFirstChildWithName(new QName("measure")).getText();
mc.getEnvelope().getBody().getFirstElement().getFirstChildWithName(new QName("temp")).setText(measure);
return true;
}
Should be more than enough to modify that element value imo.

Sparkjava unable to put data into the response body

I'm trying to a client (Android) talk to our server which is using sparkjava, but running into the issue that when the client is trying to parse the body of the response response.data with Volley, it's getting that the response body is empty. The client is sending a JsonRequestObject , which will throw a JSONException if the response's body is empty.
Here is our sparkJava controller:
public static String doThis(Request request, Response response) {
response.type("application/json");
// If the request fails validations, then return a 400
if (request.failsValidations()) {
response.status(HTTP_BAD_REQUEST); // 400
response.header("Error", "Bad request");
} else {
response.status(HTTP_SUCCESS); // 200
// Put the response into the data
String responseData = "{//someJson}"
response.header("data", responseData);
response.body(data);
}
return "";
}
I'm setting the same data in the header and body, but when I look at the response received on the client, the data is only in the header and not in the body. So I was thinking that Spark's response.body() method isn't really putting the data into the response being sent back.
Is the way response.body is represented in sparkjava different from how volley views it? Or is there another way to put data into the response body from spark?
You can do it in two ways:
Using a JSON Object
public static Object doThis(Request request, Response response) {
response.type("application/json");
JSONObject jo = new JSONObject();
jo.put("data", "someData");
return jo;
}
Using a string formatted as JSON
public static Object doThis(Request request, Response response) {
response.type("application/json");
return "{\"data\":\"someData\"}";
}
The first one is better IMO because you can modify the JSON object in a much more convenient way (but you have to import org.json.JSONObject).
Then, on the client side, you should treat the data as JSON data type. Hope it helps.

Getting "malformed syntax" while hitting REST Controller POST method sending "Request Body"

Here is the Rest Controller Service signature
#RequestMapping(value = "/getFilteredReport", method = RequestMethod.POST)
public void getFilteredReport(#RequestBody FilteredReportVO filteredReportVO,HttpServletRequest request,HttpServletResponse response) {
Now below is the JSON structure I am sending
{
"filterAttributesFactory":{
"930000":{
"metaDataId":930000,
"displayText":"Select Category",
"attributeType":211009,
"userInputValue":null,
"dropDownoptions":null,
"isMandatory":false,
"isDropDown":false,
"defaultValue":null,
"isdefaultValue":false,
"constraintId":null
},
"930001":{
"metaDataId":930001,
"displayText":"Item Status",
"attributeType":211005,
"userInputValue":null,
"dropDownoptions":{
"157005":"FC - fake scrap",
"157006":"FH - firearm hold",
"157008":"IN - inventory"
},
"isMandatory":false,
"isDropDown":true,
"defaultValue":null,
"isdefaultValue":false,
"constraintId":213007
}
},
"reportId":132030,
"location":1202
}
Here is the FilteredReportVO POJO
public class FilteredReportVO {
private HashMap<Integer,FilterAttributeVO> filterAttributesFactory=new HashMap<Integer,FilterAttributeVO>();
private Integer reportId;
private Long location; .....GETTERS and setters below
FilterAttributeVO pojo structure is below..
public class FilterAttributeVO {
Integer metaDataId;
//String elementName;
String displayText;
Integer attributeType;
Object userInputValue;
Map<Integer,String> dropDownoptions;
Boolean isMandatory=false;;
Boolean isDropDown=false;
Object defaultValue;
Boolean isdefaultValue=false;
Integer constraintId=null;...Getters n setters..
I am hitting the service through POSTMAN plugin.
Getting error:
"The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications".
FYI in POSTMAN I am putting the JSON structure inside "Body", selected "raw", type as "JSON(application/json)".
Notice I am using 2 object type attributes userInputValue and defaultValue inside FilteredAttributeVO. R we allowed to keep object type?
Where is the problem here?
If you see the screen shot of your input JSON with JSONlint your json is not valid.Please fix your json object and validate it using jsonlint
you can try following code in your Test to Resolve this issue coz Spring internally uses Jackson library
ObjectMapper mapper = new ObjectMapper();
Staff obj = mapper.readValue(jsonInString, FilteredReportVO.class);
If this works fine then their should be issue with your Postman RequestBody preparation otherwise you will get detailed stacktrace :)
The problem was with FilteredReportVO POJO. I was setting values of the attributes "location" and "reportId" through a constructor. No setter methods were defined for these 2 attributes.
It was my bad, if I would have posted the complete POJO class u guys must have figured it out. Anyway thanks everyone for ur help

How to consume json parameter in java restful service

How can i consume json parameter in my webservice, I can able to get the parameters using #PathParam but to get the json data as parameter have no clue what to do.
#GET
#Path("/GetHrMsg/json_data")
#Consumes({ MediaType.APPLICATION_JSON })
#Produces(MediaType.APPLICATION_JSON)
public String gethrmessage(#PathParam("emp_id") String empid) {
}
What to use in place of #PathParam and how to parse it later.
I assume that you are talking about consuming a JSON message body sent with the request.
If so, please note that while not forbidden outright, there is a general consensus that GET requests should not have request bodies. See the "HTTP GET with request body" question for explanations why.
I mention this only because your example shows a GET request. If you are doing a POST or PUT, keep on reading, but if you are really doing a GET request in your project, I recommend that you instead follow kondu's solution.
With that said, to consume a JSON or XML message body, include an (unannotated) method parameter that is itself a JAXB bean representing the message.
So, if your message body looks like this:
{"hello":"world","foo":"bar","count":123}
Then you will create a corresponding class that looks like this:
#XmlRootElement
public class RequestBody {
#XmlElement String hello;
#XmlElement String foo;
#XmlElement Integer count;
}
And your service method would look like this:
#POST
#Path("/GetHrMsg/json_data")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public void gethrmessage(RequestBody requestBody) {
System.out.println(requestBody.hello);
System.out.println(requestBody.foo);
System.out.println(requestBody.count);
}
Which would output:
world
bar
123
For more information about using the different kinds of HTTP data using JAXB, I'd recommend you check out the question "How to access parameters in a RESTful POST method", which has some fantastic info.
Bertag is right about the comment on the GET. But if you want to do POST request that consumes json data, then you can refer to the code below:
#POST
#Path("/GetHrMsg/json_data")
#Consumes(MediaType.APPLICATION_JSON)
public Response gethrmessage(InputStream incomingData) {
StringBuilder crunchifyBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
String line = null;
while ((line = in.readLine()) != null) {
crunchifyBuilder.append(line);
}
} catch (Exception e) {
System.out.println("Error Parsing: - ");
}
System.out.println("Data Received: " + crunchifyBuilder.toString());
// return HTTP response 200 in case of success
return Response.status(200).entity(crunchifyBuilder.toString()).build();
}
For referencing please click here
#PathParam is used to match a part of the URL as a parameter. For example in an url of the form http:/example.com/books/{bookid}, you can use #PathParam("bookid") to get the id of a book to a method.
#QueryParam is used to access key/value pairs in the query string of the URL (the part after the ?). For example in the url http:/example.com?bookid=1, you can use #QueryParam("bookid") to get the value of `bookid.
Both these are used when the request url contains some info regarding the parameters and you can use the data directly in your methods.
Please specify the problem in detail if this post doesn't help you.

wrong encoding in jaxrs post method

I'm having an Encoding problem when trying to consume an Arabic json message, however when producing the json in a get method I get the message right here is the code:
#Path("/json")
public class HelloJson {
#GET
#Path("/get")
#Produces("application/json; charset=UTF-8")
public Track getTrackInJSON() {
Track track = new Track();
track.setTitle("الليله");
track.setSinger("عمرو دياب");
return track;
}
#POST
#Path("/post")
#Consumes("application/json; charset=UTF-8")
public Response createTrackInJSON(Track track) throws UnsupportedEncodingException{
String result = new String (("Track saved : " + track).getBytes(), "UTF-8");
System.out.println(result);
return Response.status(201).entity(result).type("text/plain; charset=UTF-8").build();
}
}
you can try this webservice on the following link:
http://java7learning-khalidspace.rhcloud.com/rest/json/get
if asked for authentication use username admin and password admin
this link will return you a json with Arabic values without any Encoding problems.
now take this json message and use it in the post method using the following link:
http://java7learning-khalidspace.rhcloud.com/rest/json/post
you can use the post method using the webservice tester from eclipse or any other webservice just insert the content-type=application/json and authorization = Basic YWRtaW46YWRtaW4= as request headers and but the json in the request body.
the post method will return a massage with the arabic characters as "????"
please tell me what I'm missing and thanks for help.
Already have you tried to send them with the escaped characters?:
{
"title" : "\u0627\u0644\u0644\u064A\u0644\u0647",
"singer" : "\u0639\u0645\u0631\u0648 \u062F\u064A\u0627\u0628"
}
I get with this way using SoapUI and your http://java7learning-khalidspace.rhcloud.com/rest/application.wadl:
Track saved : Track [title=الليله, singer=عمرو دياب]

Categories

Resources