Exception with REST implementation with jersey - json

I am building a REST service with jersey and I am stuck with a weird exception.
I want to hit a REST uri similar to:
http://localhost:9889/rest/Users/{userid}
the content to be sent with the request is in JSON similar to:
{
"attr1":"name",
"attr2":"age"
}
The endpoint url code is as shwon below:
#Path("/rest/Users")
class Users
{
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/{userId}")
#Consumes(MediaType.APPLICATION_JSON)
public String getUserInfoQuery(
QueryDoc reqJSON,
#PathParam("userId") String userId,
#HeaderParam("Session-Token") String sessionId,
#HeaderParam("Authorization") String authToken)
)
{
.
.
.
.
}
}
And QueryDoc resource looks like this:
#XmlRootElement
#XmlAccessorType(XmlAccessType.NONE)
public class QueryDoc
{
#XmlElement(name = "attr1")
private String attr1;
#XmlElement(name = "attr2")
private String attr2;
//getters and setters
.
.
.
.
}
When I am starting the server, an exception is thrown
com.sun.jersey.api.container.ContainerException: Fatal issues found at
class com.test.Users. See logs for more details.
at com.sun.jersey.server.impl.application.WebApplicationImpl.newResourceClass(WebApplicationIm....
I could find this exception here http://www.skybert.net/java/jersey/
and as mentioned in this link..the reason is
public String getUserInfoQuery(
QueryDoc reqJSON,
reqJSON is not being annotated. If I annotate it with some annotation the exception is not thrown when server is started but in this case url response is meaningless. If i remove this parameter the url works but it doesn't consume the request JSON.
How can I make it work where I want to consume JSON content of the request as well as HeaderParams and PathParams

Is your getUserInfoQuery() method annotated with #GET annotation? If so, it is mapped to HTTP GET request. You cannot send entity in HTTP GET, so the unannotated parameter does not make sense (as Jersey maps entity to the unannotated param, but as said, in case of GET there is no entity).

Change your method getUserInfoQuery() to #PUT. In the QueryDoc class remove all annotations except #XmlRootElement. Since the attribute name you pass in the request body is same as the those in QueryDoc #XmlElement is not required. Moreover #XmlElement should be given to ge getter method.This is a good article on ReST with Jersey.

Try this:
I had the same exception with no additional details on Jersey's 'newResourceClass' method;
after hours of debugging, I realized it happened due to ambiguous URIs.
Check your URIs and eliminate any possible duplicates, such as this one:
#Path("/users")
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<String> getUsers() {
...
}
#Path("/users") // BAD
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getUserById(#QueryParam("userId") String userId) {
...
}

Related

Is it possible to get an InvalidFormatException not as a HttpMessageNotReadableException in Spring when processing JSON?

I have a simple RestController:
#RestController
public class MailboxController{
#RequestMapping(value = "/mailbox/{id}", method = RequestMethod.PUT)
public void createMailbox(#PathVariable #NotNull String mailboxID, #Validated #RequestBody Mailbox mailbox){
//do something with Mailbox here
}
}
The Mailbox class looks as follows:
#Validated
public class Mailbox{
#JsonProperty("email")
#EmailValidator //some validation of EMail String
public String email;
#JsonProperty("type")
public Type type; //Type is an enum
}
If I post a valid JSON-String where the value of type is not listed in the enumeration then I get a 400 (Bad Request) error. Internally a HttpMessageNotReadableException with a InvalidFormatException gets thrown. If I post a JSON-String where the email doesn't get accepted by the EmailValidator I get a 400 (Bad Request) error as well (from a MethodArgumentNotValidException). In both cases I would expect a 422 since the JSON is well formatted but the content is semantically wrong.
Either way I try to handle both cases similary and wonder if there is a way to redirect the InvalidFormatException in a way that I get MethodArgumentNotValidException when the given type is not part of the Type enumeration.
Currently I have a ResponseEntityExceptionHandler with one method that catchest the HttpMessageNotReadableException and builds the ResponseEntity depending on the causing exception and a method that handles the MethodArgumentNotValidException. I would prefer it if the InvalidFormatException could be handled in the method where I handle the MethodArgumentNotValidException as well.

POSTing `JSON` to an `ArrayList` gets the response "Request JSON Mapping Error"

I have a problem POSTing JSON to an ArrayList
I have a class Plan
public class Plan {
private String planId;
private String planName;
:
:
}
and an ArrayList of Plan - PlanList
public class PlanList {
private List<Plan> plans = new ArrayList<Plan>();
:
:
}
I have POST and GET REST APIs
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Plan createPlan(#CookieParam(SmsHttpHeaders.X_SMS_AUTH_TOKEN) String token, Plan plan, #HeaderParam("Organization-Id") String organizationIdByService);
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public PlanList createPlans(#CookieParam(SmsHttpHeaders.X_SMS_AUTH_TOKEN) String token, PlanList plans, #HeaderParam("Organization-Id") String organizationIdByService);
#GET
#Produces(MediaType.APPLICATION_JSON)
public PlanList retrieveAllPlans(#CookieParam(SmsHttpHeaders.X_SMS_AUTH_TOKEN) String token, #HeaderParam("Organization-Id") String organizationIdByService);
When I GET retrieveAllPlans, I get back the following JSON, just as I expect.
{
"plans": [
{
"planId":"1",
"planName":"Plan 1"
},
{
"planId":"2",
"planName":"Plan 2"
},
{
"planId":"3",
"planName":"Plan 3"
}
]
}
POSTing a single Plan, createPlan, works correctly.
However, when I try to POST to createPlans in the same format that the GET returns, I get the response "Request JSON Mapping Error".
Is the JSON incorrectly formatted? Is my REST definition wrong?
Both of your post functions are being mapped to the same http endpoint. There is probably a #Path notation on the class specifying a single endpoint for all its methods and RestEasy is trying to distinguish by http method (post, get, etc..).
You'll need to specify a unique #Path annotation for each post function. Say:
#Path("/plan")
For the first, and
#Path("/plans")
For the second.
The problem is, that when you try to POST to createPlans, the request is being handled by createPlan method, because both methods are handling the same URL.
The soultion is to make two different #Path for these methods.

Unsupported Media Type Error in AJAX-Spring

I am trying to pass POST data from my jsp with jquery-ajax to my Spring-MVC controller function. The data is passed fine and I can print the JSON data when I use a String object to receive the RequestBody. But when I employ a DTO which has a List variable declared with its own objects the controller returns a '415 Unsupported Media Type Error' with the following statement,
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
below given is the DTO class
public class anyClassDTO{
private String name;
private List<anyClassDTO> subList = new ArrayList<anyClassDTO>();
//getters and setters here
}
Now, here is the controller function
#RequestMapping(headers ={"Accept=application/json"}, value = "urlFromJsp", method = RequestMethod.POST)
public #ResponseBody
String addData (HttpServletRequest request,
#RequestBody List<anyClassDTO> dtoObject,
Model model)
{
return "{\"value\":\"true\"}";
}
Is it not possible for a list of objects to be received from the jsp page to a controller via AJAX?
Here is a set of sample data being passed from the jsp
[{"name":"module1","subList":[{"name":"chapter1","subList":[{"name":"subchapter1","subList":null}]}]},{"name":"module2","subList":[{"name":"chapter1","subList":[{"name":"subchapter1","subList":null}]}]}]
Make sure your AJAX request sets the request's Content-Type to application/json.
Spring typically uses a MappingJacksonHttpMessageConverter to convert the request body when you specify #RequestBody. This HttpMessageConverter only supports application/*+json type content types, so you have to make sure your request contains it.
Well, we could make it work as it is by adding a little more detail. Instead of receiving the #ResponseBody as a List object I created another DTO which holds a List object of the original DTO. So the second DTO is basically a dummy which receives the data from AJAX as a single object.
Like I have said in the question I have a DTO as follows
public class AnyClassDTO{
private String name;
private List<anyClassDTO> subList = new ArrayList<anyClassDTO>();
//getters and setters here
}
I created another DTO which holds a List of the above DTO
public class DummyDTO{
private List<AnyClassDTO> dummyObj;
//getters and setters here
}
Then in the controller I changed the function to
#RequestMapping(headers ={"Accept=application/json"}, value = "urlFromJsp", method = RequestMethod.POST)
public #ResponseBody
String addData (HttpServletRequest request,
#RequestBody DummyDTO dummyDTOObj,
Model model)
{
return "{\"value\":\"true\"}";
}
Earlier if I was sending a list directly from AJAX, now I am sending a stringified litteral with a variable which holds the whole data.
And it works like a charm!

how to store JSON into POJO using Jackson

I am developing a module where i am using rest service to get data. i am not getting how to store JSON using Jackson and store it which has Queryparam also. Any help is really appreciated as I am new to this.I am trying to do server side filtering in extjs infinte grid which is sending the below request to rest service.
When the page load first time, it sends:
http://myhost/mycontext/rest/populateGrid?_dc=9999999999999&page=1&start=0&limit=500
When you select filter on name and place, it sends:
http://myhost/mycontext/rest/populateGrid?_dc=9999999999999&filter=[{"type":"string","value":"Tom","field":"name"},{"type":"string","value":"London","field":"Location"}]&page=1&start=0&limit=500
I am trying to save this in POJO and then sending this to database to retrieve data. For this on rest side I have written something like this:
#Provider
#Path("/rest")
public interface restAccessPoint {
#GET
#Path("/populateGrid")
#Produces({MediaType.APPLICATION_JSON})
public Response getallGridData(FilterJsonToJava filterparam,#QueryParam("page") String page,#QueryParam("start") String start,#QueryParam("limit") String limit);
}
public class FilterJsonToJava {
#JsonProperty(value ="filter")
private List<Filter> data;
.. getter and setter below
}
public class Filter {
#JsonProperty("type")
private String type;
#JsonProperty("value")
private String value;
#JsonProperty("field")
private String field;
...getter and setters below
}
I am getting the below error:
The following warnings have been detected with resource and/or provider classes: WARNING: A HTTP GET method, public abstract javax.ws.rs.core.Response com.xx.xx.xx.xxxxx (com.xx.xx.xx.xx.json.FilterJsonToJava ,java.lang.String,java.lang.String,java.lang.String), should not consume any entity.
com.xx.xx.xx.xx.json.FilterJsonToJava, and Java type class com.xx.xx.xx.FilterJsonToJava, and MIME media type application/octet-stream was not found
[11/6/13 17:46:54:065] 0000001c ContainerRequ E The registered message body readers compatible with the MIME media type are:
application/octet-stream
com.sun.jersey.core.impl.provider.entity.ByteArrayProvider com.sun.jersey.core.impl.provider.entity.FileProvider com.sun.jersey.core.impl.provider.entity.InputStreamProvider com.sun.jersey.core.impl.provider.entity.DataSourceProvider com.sun.jersey.core.impl.provider.entity.RenderedImageProvider */* -> com.sun.jersey.core.impl.provider.entity.FormProvider ...
You should try to do it this way:
Response getallGridData(#QueryParam("filter") String filterparam, ...) {
ObjectMapper mapper = new ObjectMapper();
Filter yourObject = mapper.readValue(filterparam, Filter.class);
}
This is the way, because your payload is in the query parameter. The object injected as it is with POST requests when there is a payload.

Consuming JSON object in Jersey service

I've been Googling my butt off trying to find out how to do this: I have a Jersey REST service. The request that invokes the REST service contains a JSON object. My question is, from the Jersey POST method implementation, how can I get access to the JSON that is in the body of the HTTP request?
Any tips, tricks, pointers to sample code would be greatly appreciated.
Thanks...
--Steve
As already suggested, changing the #Consumes Content-Type to text/plain will work, but it doesn't seem right from an REST API point of view.
Imagine your customer having to POST JSON to your API but needing to specify the Content-Type header as text/plain. It's not clean in my opinion. In simple terms, if your API accepts JSON then the request header should specify Content-Type: application/json.
In order to accept JSON but serialize it into a String object rather than a POJO you can implement a custom MessageBodyReader. Doing it this way is just as easy, and you won't have to compromise on your API spec.
It's worth reading the docs for MessageBodyReader so you know exactly how it works. This is how I did it:
Step 1. Implement a custom MessageBodyReader
#Provider
#Consumes("application/json")
public class CustomJsonReader<T> implements MessageBodyReader<T> {
#Override
public boolean isReadable(Class<?> type, Type genericType,
Annotation[] annotations,MediaType mediaType) {
return true;
}
#Override
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException {
/* Copy the input stream to String. Do this however you like.
* Here I use Commons IOUtils.
*/
StringWriter writer = new StringWriter();
IOUtils.copy(entityStream, writer, "UTF-8");
String json = writer.toString();
/* if the input stream is expected to be deserialized into a String,
* then just cast it
*/
if (String.class == genericType)
return type.cast(json);
/* Otherwise, deserialize the JSON into a POJO type.
* You can use whatever JSON library you want, here's
* a simply example using GSON.
*/
return new Gson().fromJson(json, genericType);
}
}
The basic concept above is to check if the input stream is expected to be converted to a String (specified by Type genericType). If so, then simply cast the JSON into the specified type (which will be a String). If the expected type is some sort of POJO, then use a JSON library (e.g. Jackson or GSON) to deserialize it to a POJO.
Step 2. Bind your MessageBodyReader
This depends on what framework you're using. I find that Guice and Jersey work well together. Here's how I bind my MessageBodyReader in Guice:
In my JerseyServletModule I bind the reader like so --
bind(CustomJsonReader.class).in(Scopes.SINGLETON);
The above CustomJsonReader will deserialize JSON payloads into POJOs as well as, if you simply want the raw JSON, String objects.
The benefit of doing it this way is that it will accept Content-Type: application/json. In other words, your request handler can be set to consume JSON, which seems proper:
#POST
#Path("/stuff")
#Consumes("application/json")
public void doStuff(String json) {
/* do stuff with the json string */
return;
}
Jersey supports low-level access to the parsed JSONObject using the Jettison types JSONObject and JSONArray.
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.8</version>
</dependency>
For example:
{
"A": "a value",
"B": "another value"
}
#POST
#Path("/")
#Consumes(MediaType.APPLICATION_JSON)
public void doStuff(JSONObject json) {
/* extract data values using DOM-like API */
String a = json.optString("A");
Strong b = json.optString("B");
return;
}
See the Jersey documentation for more examples.
I'm not sure how you would get at the JSON string itself, but you can certainly get at the data it contains as follows:
Define a JAXB annotated Java class (C) that has the same structure as the JSON object that is being passed on the request.
e.g. for a JSON message:
{
"A": "a value",
"B": "another value"
}
Use something like:
#XmlAccessorType(XmlAccessType.FIELD)
public class C
{
public String A;
public String B;
}
Then, you can define a method in your resource class with a parameter of type C. When Jersey invokes your method, the JAXB object will be created based on the POSTed JSON object.
#Path("/resource")
public class MyResource
{
#POST
public put(C c)
{
doSomething(c.A);
doSomethingElse(c.B);
}
}
This gives you access to the raw post.
#POST
#Path("/")
#Consumes("text/plain")
#Produces(MediaType.APPLICATION_JSON)
public String processRequset(String pData) {
// do some stuff,
return someJson;
}
Submit/POST the form/HTTP.POST with a parameter with the JSON as the value.
#QueryParam jsonString
public desolveJson(jsonString)
Some of the answers say a service function must use consumes=text/plain but my Jersey version is fine with application/json type. Jackson and Jersey version is
jackson-core=2.6.1, jersey-common=2.21.0.
#POST
#Path("/{name}/update/{code}")
#Consumes({ "application/json;charset=UTF-8" })
#Produces({ "application/json;charset=UTF-8" })
public Response doUpdate(#Context HttpServletRequest req, #PathParam("name") String name,
#PathParam("code") String code, String reqBody) {
System.out.println(reqBody);
StreamingOutput stream = new StreamingOutput() {
#Override public void write(OutputStream os) throws IOException, WebApplicationException {
..my fanzy custom json stream writer..
}
};
CacheControl cc = new CacheControl();
cc.setNoCache(true);
return Response.ok().type("application/json;charset=UTF-8")
.cacheControl(cc).entity(stream).build();
}
Client submits application/json request with a json request body. Servlet code may parse string to JSON object or save as-is to a database.
SIMPLE SOLUTION:
If you just have a simple JSON object coming to the server and you DON'T want to create a new POJO (java class) then just do this.
The JSON I am sending to the server
{
"studentId" : 1
}
The server code:
//just to show you the full name of JsonObject class
import javax.json.JsonObject;
#Path("/")
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response deleteStudent(JsonObject json) {
//Get studentId from body <-------- The relevant part
int studentId = json.getInt("studentId");
//Return something if necessery
return Response.ok().build();
}