wrong encoding in jaxrs post method - java

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=عمرو دياب]

Related

JAVA: Stripe webhook error: No signatures found matching the expected signature for payload

I have been trying to set a webhook for the person.updated API from Stripe. I am trying a test webhook where I send a String in the method, like this:
#ApiOperation(value = "Webhook controller")
#PostMapping("/accountUpdate")
public void handle(#RequestBody String event1, Response response, HttpServletRequest httpServletRequest){
}
and then in my Webhook.constructEvent, I am passing that String event1 as follows:
try {
event = Webhook.constructEvent(
event1, sigHeader, endpointSecret
);
}
But I am getting an error saying: No signatures found matching the expected signature for payload
I have tried to parse the String event1 (Which is the request body) into Json and it doesn't work. Passing the Request object instead of String didn't work either.
It seems like your end point Secret which you are providing in your code is incorrect or not matching to your person.update webhook's secret. End point secret goes like this.
"secret": "whsec_gaasdfkalkkklasew**********"

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

405 error returned when using POST method in Jersey

I'm using Jersey and have had no problem with GET and PUT calls but for some reason POST refuses to work; I keep getting a 405 returned.
I've tried multiple permutations for the signature on my method and I'm starting to wonder if there is something else I'm missing.
Here's an example of what won't work:
Server-side:
#Path("/tmm")
public class TmmRes {
#POST
#Path("/mypost")
#Consumes(MediaType.APPLICATION_JSON)
public Response postTest(String input) {
System.out.println("Made it to POST: "+input);
return Response.status(201).entity(input).build();
}
}
Client-side:
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8888/api/v1").path("tmm").path("mypost");
String input = "{\"address\":\"myaddress\",\"user\":4}";
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
I realize that using JSON I should have an object that the input binds to, but I've reduced the complexity to simply get the thing working.
Anybody have any insight? By the way, I'm using Tomcat (6.0.43).
I think you have to create a POJO like this:
public class User {
private String address;
private Integer user;
// getters and setters
}
and then change
#POST
#Path("/mypost")
#Consumes(MediaType.APPLICATION_JSON)
public Response postTest(String input) {
System.out.println("Made it to POST: "+input);
return Response.status(201).entity(input).build();
}
to:
#POST
#Path("/mypost")
#Consumes(MediaType.APPLICATION_JSON)
public Response postTest(User input) {
System.out.println("Made it to POST: "+input);
return Response.status(201).entity(input).build();
}
OK, with the help of a friend, I was able to figure this out. My URL was hitting a redirect. This was causing my POST to turn into a GET. Thanks for the help everyone. Your confirmations eliminated possibilities and helped guide me to the answer.
I solved this in IntelliJ.
Go to the menu: BUILD ->BUILD ARTIFACTS -> BUILD or REBUILD and that's it.

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.

PlayFramework Result with Ajax

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.

Categories

Resources