ExampleFilter.java 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package filters;
  2. import akka.stream.Materializer;
  3. import java.util.concurrent.CompletionStage;
  4. import java.util.concurrent.Executor;
  5. import java.util.function.Function;
  6. import javax.inject.*;
  7. import play.mvc.*;
  8. import play.mvc.Http.RequestHeader;
  9. /**
  10. * This is a simple filter that adds a header to all requests. It's
  11. * added to the application's list of filters by the
  12. * {@link Filters} class.
  13. */
  14. @Singleton
  15. public class ExampleFilter extends Filter {
  16. private final Executor exec;
  17. /**
  18. * @param mat This object is needed to handle streaming of requests
  19. * and responses.
  20. * @param exec This class is needed to execute code asynchronously.
  21. * It is used below by the <code>thenAsyncApply</code> method.
  22. */
  23. @Inject
  24. public ExampleFilter(Materializer mat, Executor exec) {
  25. super(mat);
  26. this.exec = exec;
  27. }
  28. @Override
  29. public CompletionStage<Result> apply(
  30. Function<RequestHeader, CompletionStage<Result>> next,
  31. RequestHeader requestHeader) {
  32. return next.apply(requestHeader).thenApplyAsync(
  33. result -> result.withHeader("X-ExampleFilter", "foo"),
  34. exec
  35. );
  36. }
  37. }