How do I get the JSON body in Jersey? - java

Is there a #RequestBody equivalent in Jersey?
#POST()
#Path("/{itemId}")
#Consumes(MediaType.APPLICATION_JSON)
public void addVote(#PathParam("itemId") Integer itemId, #RequestBody body) {
voteDAO.create(new Vote(body));
}
I want to be able to fetch the POSTed JSON somehow.

You don't need any annotation. The only parameter without annotation will be a container for request body:
#POST()
#Path("/{itemId}")
#Consumes(MediaType.APPLICATION_JSON)
public void addVote(#PathParam("itemId") Integer itemId, String body) {
voteDAO.create(new Vote(body));
}
or you can get the body already parsed into object:
#POST()
#Path("/{itemId}")
#Consumes(MediaType.APPLICATION_JSON)
public void addVote(#PathParam("itemId") Integer itemId, Vote vote) {
voteDAO.create(vote);
}

#javax.ws.rs.Consumes(javax.ws.rs.core.MediaType.APPLICATION_JSON)
should already help you here and just that the rest of the parameters must be marked using annotations for them being different types of params -
#POST()
#Path("/{itemId}")
#Consumes(MediaType.APPLICATION_JSON)
public void addVote(#PathParam("itemId") Integer itemId, <DataType> body) {
voteDAO.create(new Vote(body));
}

if you want your json as an Vote object then simple use #RequestBody Vote body in your mathod argument , Spring will automatically convert your Json in Vote Object.

Related

How to automatically map multipart/form-data input to a bean in Jersey

I have a Jersey REST api that receives inputs as multipart/form-data. The signature is as follows:
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Path("/getorders")
public Response getOrders(final FormDataMultiPart request) {
The input parameters in the form are:
clientName
orderType
year
I would like instead to have something like this:
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Path("/getOrders")
public Response getOrders(final OrderBean order) {
And get all my inputs in a bean like this:
public class OrderBean {
private String clientName;
private int orderType;
private int year;
// Getters and setters
}
Is there a way to do that automatically with Jersey? I know that I can map the fields manually and fill in the bean, but actually I'm looking for an annotation or something like that, that can fill in the bean automatically.
Jersey supports #FormDataParams in a #BeanParam bean. If you were to do this (as you would see in most examples):
#POST
public Response post(#FormDataParam("clientName") String clientName) {}
Then you can also do
class OrderBean {
#FormDataParam("clientName")
private String clientName;
// getter/setters
}
#POST
public Response post(#BeanParam OrderBean order) {}

How to pass List of hash map as query param in jersey

I tried something like below, M getting error
[[FATAL] No injection source found for a parameter of type public Response
#context UriInfo wont work as i need different data types as query param,like it may be integers and date.Kindly Help.
#GET
#Path("/getdetails")
#Produces({ "application/json", "application/xml" })
public Response getDetails(#QueryParam("field1") String fieldOne,#QueryParam("field2") List<HasMap<String,String>> fieldTwo){
//Processing
}
You will have to use POST and attach the list inside the request body
If the list your passing is json, you should also add the appropriate #Consumes value.
#POST
#Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
#Consumes(MediaType.APPLICATION_JSON)
public void getDetails(List<HasMap<String,String>> listFromClient) {
// do something with your list..
}

How to retrieve the JSON message body in JAX-RS REST method?

I have the following JSON that will be passed as part of a HTTP request, in the message body.
{
"names": [
{
"id":"<number>",
"name":"<string>",
"type":"<string>",
}
]
}
My current REST handler is below. I am able to get the Id and `Version that is passed in as path params, but I am not sure how to retrieve the contents on the message body?
#PUT
#Path("/Id/{Id}/version/{version}/addPerson")
public Response addPerson(#PathParam("Id") String Id,
#PathParam("version") String version) {
if (isNull(Id) || isEmpty(version)) {
return ResponseBuilder.badRequest().build();
}
//HOW TO RECIEVE MESSAGE BODY?
//carry out PUT request and return DTO: code not shown to keep example simple
if (dto.isSuccess()) {
return Response.ok().build();
} else {
return Response.serverError().build();
}
}
Note: I am using the JAX-RS framework.
You just need to map your name json to a POJO and add #Consumes annotation to your put method, here is an example:
#PUT
#Consumes("application/json")
#Path("/Id/{Id}/version/{version}/addPerson")
public Response addPerson(#PathParam("Id") String Id,
#PathParam("version") String version,
List<NamObj> names) {
I assume you are trying to retrieve a list of elements if is not the case just use you POJO as it in the param.
Depending on what json library are you using in your server you may need to add #xml annotation to your POJO so the parser could know how to map the request, this is how the mapping for the example json should look like:
#XmlRootElement
public class NameObj {
#XmlElement public int id;
#XmlElement public String name;
#XmlElement public String type;
}
Jersey doc: https://jersey.java.net/documentation/latest/user-guide.html#json
#cosumes reference: http://docs.oracle.com/javaee/6/tutorial/doc/gilik.html#gipyt

restful post with additional url parameters?

I have a web service which consumes a json request and outputs a json response. I have an issue where the customer needs to send an additional parameter in the url that can't be in the json body. Is there a way to do that?
For example, here is the method of a #WebService that consumes the incoming json request:
#POST
#Path("/bsghandles")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public BsgHandleResponse getBsgHandlesJson(BsgHandleRequest obj) {
HttpServletRequest request = getRequestObject();
return processGetBsgHandleByRateCode("key", obj.getRateCodes(), obj.getCorp(),
obj.getHeadend(), obj.getEquipmentProtocolAiu(), obj.getEquipmentTypeAiu(), request);
}
Notice that "key" is a hard-coded parameter. I need that parameter to be passed to it by the user in the url, but not the json structure. Is there a way to do that?
Just add a parameter annotated with #QueryParam to your method:
#POST
#Path("/bsghandles")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public BsgHandleResponse getBsgHandlesJson(#QueryParam("key") String key,
BsgHandleRequest obj) {
...
}
And consume it using:
POST /api/bsghandles?key=value HTTP/1.1
Content-Type: application/json
Accept: application/json
{
...
}
Yes there is!
You can pass it as a Query Param. For example:
www.yourhost.com/server?key=value
In java, yo can define it like this in your code:
#GET
#Path("/server")
public Response myMethod(#QueryParam("key") String value) { //your RESTFULL code}
So if you call that url as said before, you will have what you want in the variable value.
Hope it helps..
Cheers

Injection of HttpServletRequest in Jersey POST handler

Consider this case:-
I am injecting HttpServletRequest in a Rest Service like
#Context
HttpServletRequest request;
And use it in a method like:-
#GET
#Path("/simple")
public Response handleSimple() {
System.out.println(request.getParameter("myname"));
return Response.status(200).entity("hello.....").build();
}
This works fine but when I try to send it through POST method and replace the #GET by #POST annotation, I get the parameter value null.
Please suggest me where I am mistaking.
You do not need to get your parameters etc out of the request. The JAX-RS impl. handles that for you.
You have to use the parameter annotations to map your parameters to method parameters. Casting converting etc. is done automaticly.
Here your method using three differnt ways to map your parameter:
// As Pathparameter
#POST
#Path("/simple/{myname}")
public Response handleSimple(#PathParam("myname") String myName) {
System.out.println(myName);
return Response.status(200).entity("hello.....").build();
}
// As query parameter
#POST
#Path("/simple")
public Response handleSimple(#QueryParam("myname") String myName) {
System.out.println(myName);
return Response.status(200).entity("hello.....").build();
}
// As form parameter
#POST
#Path("/simple")
public Response handleSimple(#FormParam("myname") String myName) {
System.out.println(myName);
return Response.status(200).entity("hello.....").build();
}
Documentation about JAX-RS Annotations from Jersey you can find here:
https://jersey.java.net/documentation/latest/jaxrs-resources.html

Categories