4
votes

@Context injection works with classes but not able to make it work with Objects.

httpServletRequest in ContainerRequestFilter produces null pointer.

Dropwizard Version:- 1.1.0

ContainerRequestFilter

public class ApplicationIPAuthFilter implements ContainerRequestFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationIPAuthFilter.class);
    private HerculesRestAccessor restAccessor;
    private String applicationName;

    @Context
    private HttpServletRequest httpServletRequest;

    public ApplicationIPAuthFilter(){
    }

    public ApplicationIPAuthFilter(HerculesRestAccessor accessor, String applicationName) {
        restAccessor = accessor;
        this.applicationName = applicationName;
    }

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        // need remote Ip
        String remoteIp = this.httpServletRequest.getRemoteAddr();
        ....
    }
}

DynamicFeature


@Provider
public class ApplicationIPAuthFeature implements DynamicFeature {

    private final HerculesRestAccessor accessor;
    private final String applicationName;

    public ApplicationIPAuthFeature(HerculesRestAccessor accessor, String applicationName) {

        this.accessor = accessor;
        this.applicationName = applicationName;
    }

    @Override
    public void configure(ResourceInfo resourceInfo, FeatureContext context) {
        if (resourceInfo.getResourceMethod().getAnnotation(ApplicationIPAuthRequired.class) != null) {

            // not working
            context.register(new ApplicationIPAuthFilter(accessor, applicationName));

             //@Context injection works in ContainerRequestFilter for classes
            //context.register(ApplicationIPAuthFilter.class);
        }
    }
}

I'm trying to fetch remote ip in ContainerRequestFilter to authenticate request based on ip.

How do I fix this.. need help?

1

1 Answers

4
votes

It's a known issue with DynamicFeature. Injections don't work when registering as an object.

One thing you can do is manually inject it, like mentioned in this post.

Another thing you can do is make the HerculesRestAccessor and the applicationName injectable. Or rather then making the application name injectable, you can make it a configuration property and inject the configuration. If you do this, then you can register the filter as a class, and all the injections should work.