Intercept all responses in Play 2.1
Is there a way to intercept all HTTP responses when using Play Framework 2.1?
This is what I have in the Global.java file to intercept all requests, but I also want to intercept responses:
import java.lang.reflect.Method;
import play.GlobalSettings;
import play.mvc.*;
import play.mvc.Http.*;
import views.html.*;
public class Global extends GlobalSettings {
private static BasicAuthHandler AUTH;
@SuppressWarnings("rawtypes")
@Override
public Action onRequest(Request request, Method actionMethod) {
if ( ... ) {
return new Action.Simple() {
@Override
public Result call(Context ctx) throws Throwable {
return unauthorized();
}
};
}
return super.onRequest(request, actionMethod);
}
}
I've read the documentation on manipulating the answer , but it only describes how to do it for each result individually.
source to share
TransactionalAction is an example of a request / response interceptor. It extends Action and provides the Transactional annotation that defines the type or method of the controller.
An example of a controller method annotated with an action:
@Transactional
public static Result ok(){
return ok();
}
Example of action registration responses (mind, actions that don't provide annotations such as Transactional extend Action.Simple):
public class LogAction extends Action.Simple {
@Override
public F.Promise<Result> call(Http.Context ctx) throws Throwable {
F.Promise<Result> call = delegate.call(ctx);
return call.map(r -> {
String responseBody = new String(JavaResultExtractor.getBody(r, 0L));
Logger.info(responseBody);
return r;
});
}
}
Usage, method definition:
@With(LogAction.class)
public static Result ok(){
return ok();
}
Usage, class definition - all methods are intercepted:
@With(LogAction.class)
public class BaseController extends Controller {
....
}
You can go one step further if you don't like the @With annotation. Define a custom annotation yourself:
@With({ LogAction.class })
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
}
and use it like this:
@Log
public static Result ok(){
return ok();
}
If your custom annotation takes parameters, change the definition of LogAction as follows:
public class LogAction extends Action<Log> {
// use configuration object to access your custom annotation configuration
}
source to share