How can I extract request attributes from Jersey's ContainerRequest? - java

HttpServletRequest has a method setAttribute(String, Object).
How can I extract this attribute from ContainterRequest?
I didn't find: getAttribute method!
Code
public class AuthenticationFilter implements Filter {
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) servletRequest;
// .... ....
httpReq.setAttribute("businessId", businessId);
}
}
In Jersey Filter:
private class Filter implements ResourceFilter, ContainerRequestFilter {
public ContainerRequest filter(ContainerRequest request) {
// ..extract the attribute from the httpReq
}
}

You can't. They're not exposed through the Jersey API in any way. If you search the Jersey codebase, you'll find that there are no uses of HttpServletRequest.getAttributeNames(), which you'd expect to be used if they were being copied en masse. You'll also find that there are only a handful of uses of HttpServletRequest.getAttribute(), and it's strictly for internal bookkeeping.
Note, however, that when deployed in a Servlet Context, JAX-RS allows you to inject the original HttpServletRequest using the #Context annotation. I'm not certain whether you can do this in a Jersey filter, but it works in MessageBodyReaders/Writers and in resource classes.
Update: I've checked, and you can, in fact, inject the HttpServletRequest into a Jersey ContainerRequestFilter by simply including:
#Context private HttpServletRequest httpRequest;

If you're using Jersey 2, which implements JAX-RS 2.0, you can implement a ContainerRequestFilter which defines a filter method as follows:
public void filter(ContainerRequestContext requestContext) throws IOException;
ContainerRequestContext has getProperty(String) and setProperty(String, Object) methods, which in a Servlet environment (ServletPropertiesDelegate), map to the servlet request's getAttribute(String) and setAttribute(String, Object) methods.
See: Jersey on GitHub

I got the #Context working, but have the problem is that my ContainerRequestFilter is singleton.
I had to implement a custom javax.servlet.Filter and use a ThreadLocal to store the HttpServletRequest.

I wanted to add to previous answers my solution, in addition to adding context:
#Context
private HttpServletRequest httpRequest;
You should set and get attributes from the session.
Set:
httpRequest.getSession().setAttribute("businessId", "yourId");
Get:
Object attribute = httpRequest.getSession().getAttribute("businessId");

Related

spring boot get controller class out of ServletRequest in a AuthorizationFilter

Heee there,
right now I am totally stuck. I spend hours asking google but I haven't found any solution or approach yet. Maybe you guys can help me.
Some background information:
I am developing a microservice into an existing microservice infrastructure. I want to use spring boot and connect the service to our existing authentication service. There are plenty of other jax rs microservices which are already connected to it. I started with an authentication and an authorization filter. The authentication filter works perfectly.
The problem:
I want to use my own "Secured" annotation like in the other services.
So there are some annotated resource methods in controllers like this example one:
#Secured({Role.ADMIN,...})
#RequestMapping(value = "/interfaces", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ExportInvoiceInterfaceResponseRepListWrapper> getAll() {
...
}
so when the following filter gets triggered I want to read the roles of the annotated controller method. In jax rs I just used the Class ResourceInfo to do so. As you may know I can't use this class in a default spring boot setup. Is there any way to get the class "the spring boot way"?
public class AuthorizationFilter extends GenericFilterBean {
#Context
private ResourceInfo resourceInfo;
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// Get the resource class which matches with the requested URL
// Extract the roles declared by it
Class<?> resourceClass = resourceInfo.getResourceClass();
List<Role> classRoles = extractRoles(resourceClass);
...
}
Any help would be awesome. Thank you in advanced.
Cheers
Frank

how to convert HTTPServletResponse into HttpEntity?

In my project i have multiple API's(implemented using Spring REST API).
Now i have this requirement that i have to manipulate the response in specific way before it is sent to client and changing it in every API method does not seems to be a good option.
Only solution i can think of is using servlet.Filter (by extending filter class)
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
> chain.doFilter(req, res);
and write my logic after
chain.doFilter(req, res);
but i am struggling to convert ServletResponse or HTTPServletResponse into HttpEntity.
Please help me how can i achieve this ? and is there any better approach available ?
Thanks
UPDATE
#jny solution has helped me.
little code snippet to show how it works.
#ControllerAdvice(basePackages = { "com.test.controller" }) // package where it will look for the controllers.
public class ResponseFilter implements ResponseBodyAdvice<Object> {
#Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
ServerHttpResponse response) {
//here you can manipulate the body the way you want.
return body;
}
important is that your controller should be annotated with #ResponseBody
It depends on what exactly you need.
If you need to make changes of the body of the response,
if you use Spring 4.1 or higher, you can use ResponseBodyAdvice to manipulate the body of the response.
If you need to filter certain fields, there are other options available.
From documentation:
Implementations may be may be registered directly with
RequestMappingHandlerAdapter and ExceptionHandlerExceptionResolver or
more likely annotated with #ControllerAdvice in which case they will
be auto-detected by both.
This may point you in the right direction: Spring MVC: How to modify json response sent from controller
It involves wrapping the ServletResponse before invoking doFilter and using a custom ServletOutputStream that allows the response data to be manipulated after it would normally have been closed. HttpEntity is not involved.

Using javax.ws.rs.core.Context with fabric3

I am trying to implement a ContainerRequestFilter for a RESTful web service with fabric3v2.5.3. I have the filter working, but I need to grab the ip address in the request. I have tried using
#Context
HttpServletRequest servletRequest;
But it throws a null pointer exception when trying access the HttpServletRequest. We are using the built in jersey 2.13 that comes with the JAX-RS fabric3 extension. Is there a way to get the #Context to work within fabric3?
#Context injection support will be added in Fabric 3.0 and is not available in previous versions.
For versions earlier than Fabric3 3.0, you can retrieve the HTTP servlet request and response objects via an injected Fabric3RequestContext:
public class SomeFilter implements .... {
#Context
protected F3RequestContext context;
public void filter(ContainerRequestContext requestContext) {
HttpServletRequest req =
context.getHeader(HttpServletRequest.class, "fabric3.httpRequest");
}
}

Setting response header using interceptor?

I'm writing jax-rs end points. For some set of end points (existing code), I want to set an extra response header which was actually generated in #AroundInvoke interceptor and set to HttpServletRequest attribute. In #AroundInvoke I'm able to access HttpServletRequest using #Inject. But it seems I cannot access HttpServletResponse in the same interceptor itself.
It seems I can do with PostProcessorInterceptor but again I'm confused with the following doc.
The org.jboss.resteasy.spi.interception.PostProcessInterceptor runs after the JAX-RS method was invoked but before MessageBodyWriters are invoked. They can only be used on the server side. Use them if you need to set a response header when there might not be any MessageBodyWriter invoked.
I'm using resteasy, jackson. If I use PostProcessorInterceptor can I inject HttpServletResponse? Or Can I set new http header there some how?
Any code example/direction would be appreciated.
With JaxRS 2 (which comes with javaEE 7) you can use a ContainerResponseFilter see also
public class PoweredByResponseFilter implements ContainerResponseFilter {
#Inject
HttpServletRequest request;
#Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
String name = "X-My-Header";
String value = "";// some data from request
responseContext.getHeaders().add(name, value);
}
}

How to GET and POST requests separately with HttpRequestHandler

I'm using HttpRequestHandler to inject Spring beans into Servlets:
#Component("myServlet")
public class MyServlet implements HttpRequestHandler {
#Autowired
private MyService myService;
HttpServlet has separate methods doGet, doPost etc for different request methods.
But HttpRequestHandler has only one:
public void handleRequest (HttpServletRequest req, HttpServletResponse resp)
So how to handle GET and POST requests in this method separately? I need to have different logic for different request methods.
UPDATE:
Also I have a question: is there possibility to restrict handleRequest method to support only POST requests by configuration and to sendHTTP Error 405 automatically for other requests?
The HttpServletRequest provides the method getMethod()
Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. Same as the value of the CGI variable REQUEST_METHOD.
public void handleRequest (HttpServletRequest req, HttpServletResponse resp)
{
if(req.getMethod().equalsIgnoreCase("GET")){
//GET BODY
}
else if(req.getMethod().equalsIgnoreCase("POST")){
//POST BODY
}
}

Categories