nadavgam
nadavgam

Reputation: 2406

how to share data between filter and controller method in jax-rs/guice application

I'm new to Guice and I'm not sure I understand scopes binding.

I want to be able to "share" simple pojo between a filter and a controller. I though that @RequestScope mean that guice will create and use one instance from the class in each request lifetime.

Here is the code:


import com.google.inject.Inject
import com.google.inject.servlet.RequestScoped

@RequestScoped
data class DynamicValueContainer @Inject constructor (var dynamicVal: String){
    fun setDynamicValue(dval: String) {
        this.dynamicVal = dval
    }
}

and the container request filter

import com.google.inject.Inject
import javax.ws.rs.container.ContainerRequestContext
import javax.ws.rs.container.ContainerRequestFilter
import javax.ws.rs.ext.Provider

@Provider
class ExtUserFilter @Inject constructor (var dyVal:DynamicValueContainer): ContainerRequestFilter {

    override fun filter(requestContext: ContainerRequestContext?) {

        dyVal.setDynamicValue(requestContext!!.getHeaderString("dv"))
        println(requestContext!!.headers.get("dv"))
        println("inside Ext filter")

    }
}

and then the resource/controller class constructor would look like:

@Singleton
@Path("/users")
class UsersResource @Inject constructor(
    private val dyVal:DynamicValueContainer
){
// here ideally dyVal will have the value I set inside the filter...
//eventually it will be used for authenticated user info
}

When I run the application, I get the following error:

[Guice/ErrorInCustomProvider]: OutOfScopeException: Cannot access scoped [DynamicValueContainer]. Either we are not currently inside an HTTP Servlet request, or you may have forgotten to apply GuiceFilter as a servlet filter for this request. at DynamicValueContainer.class(DynamicValueContainer.kt:6)

so what am i doing wrong?

The objective in the end, is to create a small library that adds a filter, that authenticate the user for each request, and create a user object ready to be use from the controller endpoint method

I'm sure it doesn't matter but im working in Kotlin

Upvotes: 0

Views: 25

Answers (0)

Related Questions