How to work with Resteasy interceptor with Undertow

806 views Asked by At

Resteasy interceptor implements the ContainerRequestFilter. But the undertow DeploymentInfo's addFilter needs the Filter Class needs to implemented.

How to solve this issue? we have to write as Filter only?

If that is the case I need to know about the java.lang.reflect.Method from the plain servlet context?

2

There are 2 answers

0
ant1g On

The ContainerRequestFilter is a JAX-RS component that has to be registered like you would register any other JAX-RS providers (i.e scanning for @Provider class annotation, overriding the getClasses method of the JAX-RS Application, add it in your web.xml context params, etc...)

The addFilter method in the Undertow DeploymentInfo class has a completely different meaning, as it allows you to add Servlet Filters to the Deployment.

To solve your issue, either use Resteasy to register your ContainerRequestFilter, or use a Servlet Filter to implement the same logic and register it via Undertow's DeploymentInfo.

0
Stan Sokolov On

Step 1: assume you know how to create a Rest Service application and you have a class like this

public class App extends javax.ws.rs.core.Application{...//set a list of services here using 
@Override
public Set<Object> getSingletons(){
    final Set<Object> objects=new HashSet<>();
    objects.add(new MyService()));
    return objects;
}

}

Step 2: create a standard Filter class. Nothing special here.

public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
 
        filterChain.doFilter(servletRequest,servletResponse);
    }
    // overwrite doInit ass well
}

Step 3: Deploy it

    FilterInfo filterInfo = new FilterInfo("MyFilter", MyFilter.class);
    ResteasyDeployment deployment = new ResteasyDeployment();
    deployment.setApplication(new App());

    UndertowJaxrsServer restServer = new UndertowJaxrsServer();
    DeploymentInfo deploymentWrapper = restServer.undertowDeployment(deployment);
    deploymentWrapper.setDeploymentName("mysite.myext");
    deploymentWrapper.setClassLoader(this.getClass().getClassLoader());
    deploymentWrapper.setContextPath("/");
    deploymentWrapper.addFilter(filterInfo);
    deploymentWrapper.addFilterServletNameMapping("MyFilter","ResteasyServlet", DispatcherType.REQUEST);//Name of servlet is hardcoded in UndertowJaxrsServer class


    try {
        
        Undertow.Builder restServerBuilder = Undertow.builder()
                .addHttpListener(8080, "0.0.0.0").setWorkerThreads(200);
        restServer.start(restServerBuilder);
        restServer.deploy(deploymentWrapper);
        
    } catch (Exception ex) {
        logger.error("We got a problem {}", ExceptionUtils.getRootCauseMessage(ex),ex);
        throw ex;
    }