3

I've a filter through which POST REST api goes with and i want to extract the below part of my payload in the filter.

{
      "foo": "bar",
      "hello": "world"
} 

Filter code :-

public class PostContextFilter implements ContainerRequestFilter {
    @Override
    public void filter(ContainerRequestContext requestContext)
            throws IOException {
        String transactionId = requestContext.getHeaderString("id");
     // Here how to get the key value corresponding to the foo.  
        String fooKeyVal = requestContext. ??
    }
}

I don't see any easy method to get the payload to the api using the ContainerRequestContext object.

So my question is how do i get the key value corresponding to the foo key in my payload.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
Amit
  • 30,756
  • 6
  • 57
  • 88

1 Answers1

2

Whereas filters are primarily intended to manipulate request and response parameters like HTTP headers, URIs and/or HTTP methods, interceptors are intended to manipulate entities, via manipulating entity input/output streams.

A ReaderInterceptor allows you to manipulate inbound entity streams, that is, the streams coming from the "wire". Using Jackson to parse the inbound entity stream, your interceptor could be like:

@Provider
public class CustomReaderInterceptor implements ReaderInterceptor {

    // Create a Jackson ObjectMapper instance (it can be injected instead)
    private ObjectMapper mapper = new ObjectMapper();

    @Override
    public Object aroundReadFrom(ReaderInterceptorContext context)
                      throws IOException, WebApplicationException {

        // Parse the request entity into the Jackson tree model
        JsonNode tree = mapper.readTree(context.getInputStream());

        // Extract the values you need from the tree

        // Proceed to the next interceptor in the chain
        return context.proceed();
    }
}

This answer and this answer may also be related to your question.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359