How to use my registered providers with a dynamically created jersey resource class?

JayD :

I just want to know how can we use our registered providers(MessageBodyReader and MessageBodyWriter) with a dynamically created jersey resource class i.e. a jersey resource created programmatically via the programmatic jersey resource api such as

 Resource.Builder resourceBuilder = Resource.builder();
        resourceBuilder.path("helloworld/{name}");

        ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod("POST");
        methodBuilder.produces(MediaType.TEXT_PLAIN_TYPE).consumes(MediaType.TEXT_PLAIN_TYPE)
                .handledBy(new MyInflector());
         Resource resource = resourceBuilder.build();
        registerResources(resource);

now how to use my registered MessageBodyReader and Writer in the MyInflector class which is as follows

public class MyInflector implements Inflector<ContainerRequestContext, String>{

    @Override
    public String apply(ContainerRequestContext arg0) {
        System.out.println("Processing request");
         MultivaluedMap<String, String> pParams =arg0.getUriInfo().getPathParameters();
         InputStream stream=arg0.getEntityStream();
         if (stream != null) {
                Writer writer = new StringWriter();

                char[] buffer = new char[5120];
                try {
                    Reader reader = new BufferedReader(
                            new InputStreamReader(stream, "UTF-8"));
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, n);
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    try {
                        stream.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                return writer.toString();
            } else {
                return "";
            }
    }

}
Paul Samsotha :

What you can do is cast the ContainerRequestContext to ContainerRequest (which is a Jersey implementation of the ContainerRequestContext interface. With this class, you can call containerRequest.readEntity(Pojo.class). This will cause the reader for the Pojo.class class to be called (assuming the content-type also matches with the media type the endpoint consumes).

@Override
public String apply(ContainerRequestContext requestContext) {
    ContainerRequest containerRequest = (ContainerRequest)requestContext;
    Model model = containerRequest.readEntity(Model.class);
    ...
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=160433&siteId=1