Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can add parameter to request from jersey filter request (ContainerRequestFilter)

I am use Jersey + Spring. I have Jersey filter which implements ContainerRequestFilter, and i need transfer object in my jersey resource.

For example:

@Provider

public class UnmarshalEntityFilter implements ContainerRequestFilter {

private static final Logger LOGGER = LoggerFactory.getLogger(UnmarshalEntityFilter.class);

@Override
public ContainerRequest filter(ContainerRequest containerRequest) {

    final String xml = getRequestBody(containerRequest);
    // Parse this xml to Object

    // How I can add this Object to my request and get from Jersey Resource ?

    return containerRequest;
}

private String getRequestBody(ContainerRequest request) {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream in = request.getEntityInputStream();
    StringBuilder sb = new StringBuilder();
    try {
        if (in.available() > 0) {
            ReaderWriter.writeTo(in, out);

            byte[] requestEntity = out.toByteArray();
            sb.append(new String(requestEntity, "UTF-8"));
        }

        return sb.toString();
    } catch (IOException ex) {
        throw new ContainerException(ex);
    }

}

}

like image 609
Malahov Avatar asked Oct 22 '22 00:10

Malahov


1 Answers

See the ContainerRequest#setProperty(String, Object) method which states

In a Servlet container, the properties are synchronized with the ServletRequest and expose all the attributes available in the ServletRequest. Any modifications of the properties are also reflected in the set of properties of the associated ServletRequest.

So you can simply call

final String xml = getRequestBody(containerRequest);
containerRequest.setProperty("xml", xml);

then inject the HttpServletRequest in your handler and access it with HttpServletRequest#getAttribute("xml").

With Jersey 1.17, the corresponding method is ContainerRequest#getProperties() which returns a mutable Map<String, Object> to which you can put attributes that will be synchronized with the ServletRequest.

You can retrieve a property in your Jersey resource from HttpContext:

@Context
private HttpContext httpCtx
...
final String xml = httpCtx.getProperties().get("xml")

On a different note, careful consuming the request InputStream. If some other component in your stack needs to read from the stream as well, it will fail.

like image 151
Sotirios Delimanolis Avatar answered Oct 27 '22 10:10

Sotirios Delimanolis