|
21 | 21 | import java.net.URI;
|
22 | 22 | import java.nio.charset.StandardCharsets;
|
23 | 23 | import java.util.List;
|
| 24 | +import java.util.concurrent.atomic.AtomicReference; |
24 | 25 |
|
25 | 26 | import com.sun.net.httpserver.BasicAuthenticator;
|
| 27 | +import com.sun.net.httpserver.Filter; |
26 | 28 | import com.sun.net.httpserver.Headers;
|
27 | 29 | import com.sun.net.httpserver.HttpContext;
|
28 | 30 | import com.sun.net.httpserver.HttpExchange;
|
@@ -404,4 +406,54 @@ public boolean checkCredentials(String username, String password)
|
404 | 406 | String body = response.getContentAsString();
|
405 | 407 | assertThat(body, is("Hello"));
|
406 | 408 | }
|
| 409 | + |
| 410 | + @Test |
| 411 | + public void testFilter() throws Exception |
| 412 | + { |
| 413 | + final AtomicReference<String> reference = new AtomicReference<String>(); |
| 414 | + |
| 415 | + final HttpContext httpContext = server.createContext("/", new HttpHandler() |
| 416 | + { |
| 417 | + public void handle(HttpExchange exchange) throws IOException |
| 418 | + { |
| 419 | + assertThat(reference.get(), is("before")); |
| 420 | + Headers responseHeaders = exchange.getResponseHeaders(); |
| 421 | + responseHeaders.set("Content-Type", "text/plain"); |
| 422 | + exchange.sendResponseHeaders(200, 0); |
| 423 | + |
| 424 | + OutputStream responseBody = exchange.getResponseBody(); |
| 425 | + responseBody.write("Hello".getBytes(StandardCharsets.ISO_8859_1)); |
| 426 | + responseBody.close(); |
| 427 | + } |
| 428 | + }); |
| 429 | + |
| 430 | + httpContext.getFilters().add(new Filter() |
| 431 | + { |
| 432 | + @Override |
| 433 | + public void doFilter(HttpExchange exchange, Chain chain) throws IOException |
| 434 | + { |
| 435 | + reference.set("before"); |
| 436 | + chain.doFilter(exchange); |
| 437 | + reference.set("after"); |
| 438 | + |
| 439 | + } |
| 440 | + |
| 441 | + @Override |
| 442 | + public String description() |
| 443 | + { |
| 444 | + return "test"; |
| 445 | + } |
| 446 | + }); |
| 447 | + |
| 448 | + Request request = client.newRequest("localhost", port) |
| 449 | + .scheme("http") |
| 450 | + .method(HttpMethod.GET) |
| 451 | + .path("/"); |
| 452 | + |
| 453 | + ContentResponse response = request.send(); |
| 454 | + assertThat(response.getStatus(), is(200)); |
| 455 | + String body = response.getContentAsString(); |
| 456 | + assertThat(body, is("Hello")); |
| 457 | + assertThat(reference.get(), is("after")); |
| 458 | + } |
407 | 459 | }
|
0 commit comments