Search code examples
restservletsjerseyjax-rsservlet-3.0

Using a PreMatching filter to change uri path


In short, I have a Jersey REST service in a jar that I need to deploy in my webapp using mapping that differs from that which is defined in the annotations of the service. In the service, I have @ApplicationPath("/rest") and @Path("/foo"). However, incoming requests will be of the form: http://example.com/delegate/rest/foo (note that delegate is NOT a context path, rather it is mapped to servlet in the ROOT webapp that loads session information and proxies the request to my webapp, which means I cannot override @ApplicationPath with a servlet-mapping as would usually be the case). So, what I am trying to do, is this:

@PreMatching
@Priority( 500 )
public class DelegateRemappingFilter implements ContainerRequestFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger( DelegateRemappingFilter.class );

    @Override
    public void filter( ContainerRequestContext requestContext ) throws IOException {
        UriInfo uriInfo = requestContext.getUriInfo();

        // convert baseUri to http://example.com/delegate/rest
        URI baseUri = uriInfo.getBaseUriBuilder()
                .path( uriInfo.getPathSegments().get( 0 ).getPath() ).build();
        URI requestUri = uriInfo.getRequestUri();

        // As expected, this will print out
        // setRequestUri("http://example.com/delegate/rest","http://example.com/delegate/rest/foo")
        LOGGER.debug( "setRequestUri(\"{}\",\"{}\")", baseUri, requestUri );
        requestContext.setRequestUri( baseUri, requestUri );
    }
}

However, this ends up failing to match. Is it not possible to modify the path portion of the URI in a @PreMatching filter? I thought that is what this type of filter was for...


Solution

  • I hate when I find my own answer MINUTES after posting... Anyway, the baseUri MUST end in a /. So changing this:

        URI baseUri = uriInfo.getBaseUriBuilder()
                .path( uriInfo.getPathSegments().get( 0 ).getPath() ).build();
    

    to this:

        URI baseUri = uriInfo.getBaseUriBuilder()
                .path( uriInfo.getPathSegments().get( 0 ).getPath() + "/" ).build();
    

    did the trick.