users@jersey.java.net

[Jersey] Jersey on Heroku

From: Robert DiFalco <robert.difalco_at_gmail.com>
Date: Wed, 12 Mar 2014 14:54:08 -0700

I am deploying Jersey on Heroku. So I have created a ContainerRequestFilter
that resets the Base and Request URI based on the scheme and port that
heroku forwarded.

On Jetty I did not have to set the port but on Grizzly I do.

Okay the question. Is this following the best way to achieve this? Am I
doing anything naive here?

@PreMatching
public class HerokuContainerRequestFilter implements ContainerRequestFilter
{

    @Override
    public void filter( ContainerRequestContext ctx ) throws IOException {

        String scheme = getValue( ctx.getHeaders(), "x-forwarded-proto" );
        String port = getValue( ctx.getHeaders(), "x-forwarded-port" );
        if ( scheme == null && port == null )
            return;

        UriBuilder baseBuilder = ctx.getUriInfo().getBaseUriBuilder();
        UriBuilder requestBuilder = ctx.getUriInfo().getRequestUriBuilder();
        if ( scheme != null ) {
            baseBuilder.scheme( scheme );
            requestBuilder.scheme( scheme );
        }

        if ( port != null ) {
            int nPort = Integer.parseInt( port );
            baseBuilder.port( nPort );
            requestBuilder.port( nPort );
        }

        ctx.setRequestUri( baseBuilder.build(), requestBuilder.build() );
    }

    private String getValue( MultivaluedMap<String,String> headers, String
header ) {
        List<String> values = headers.get( header );
        if ( values == null || values.isEmpty() )
            return null;

        return values.get( 0 );
    }
}