Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can @GET define Consumes Content-Type for JAX-RS implementation?

I have been trying few samples on JAXRS (used Jersey for this example). The following is a sample stub implemenatation I have:

    @Path("stubservice")
public class StubImpl
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String getString(@QueryParam("first")
    int first, @QueryParam("second")
    int second)
    {
        return "first: " + first + " second: " + second;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String getSize(@QueryParam("size")
                              int size,
                              @Context
                              HttpHeaders headers)
    {
        Gson gson = new Gson();
        return gson.toJson("something else");
    }
}

Without getSize method having @Consumes(MediaType.APPLICATION_JSON) in its definition, this class is having errors during initialization. But with it, StubImpl class initializes correctly and serves the requests based on whether the incoming requests have their Content-Type as application/json.

Error during initialization:

SEVERE: The following errors and warnings have been detected with resource and/or provider classes: SEVERE: Producing media type conflict. The resource methods public java.lang.String StubImpl.getString(int,int) and public java.lang.String StubImpl.getSize(int,javax.ws.rs.core.HttpHeaders) can produce the same media type

As I understand, @GET requests would never need @Consumes(MediaType.APPLICATION_JSON) as it is meant for the content type in the body (and GET method doesn't have body).

Is the existing behavior expected ?

Thanks in advance

like image 752
Chris Avatar asked Mar 25 '23 00:03

Chris


1 Answers

Not a JAX-RS expert at all, so this is just a guess.

How could Jersey decide which method to invoke when a GET request comes in if you don't set @Consumes(MediaType.APPLICATION_JSON)?

Both methods answer to GET requests, on the same path, accept any media type, and produce the same media type. So my guess is that Jersey can't decide (other than randomly) which method to call when a GET request comes in to this path, and thus refuses to start up.

The @Consumes annotation makes it call getSize when request has a JSON body (i.e. never), and the other method in all the other cases (i.e. always).

like image 172
JB Nizet Avatar answered Apr 24 '23 12:04

JB Nizet