Pergunta

In Play Framework 2.2.2, I'd like to return a Promise. However I'm calling a function which needs access to the variables stored in Http.Context.current() (the current logged in user, the JPA connection...).

Of course, since the Promise is executed in another thread, it doesn't have access to Http.Context.current(). Can I preserve it in the Promise, or should I restore it manually? Is there another pattern I should use?

Example:

public static Promise<Result> getAvailableServices() {
    return new Promise.promise(new Function0<Result>(){
        @Override
        public Result apply() throws Throwable {
            // Long operation
            List<Services> data = buildResult();
            // Render the template
            // (The header of the template requires access to 
            // Http.Context.current().args.get("usermodel"))
            return Results.ok(services_template.render(services));
        }
    });
}
Foi útil?

Solução

Yes, HttpExecutionContext is what you need.

When an HttpExecutionContext is created it gets the current thread's Http.Context and stores it. Then, when the HttpExecutionContext is later used to execute code it restores the Http.Context.

All Promise methods use an HttpExecutionContext wrapped around the default ExecutionContext so they should propagate the Http.Context correctly across threads.

Your example code above should work fine, for example. However you do need to make sure that when you call getAvailableServices, that the Http.Context is available in the thread you're calling from. If the Http.Context isn't available when you call the method, then the HttpExecutionContext will be unable to capture the Http.Context from that thread and propagate it when the promise's Function0 is applied.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top