forked from junit-team/junit5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpServerResource.java
75 lines (62 loc) · 1.92 KB
/
HttpServerResource.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* Copyright 2015-2025 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v2.0 which
* accompanies this distribution and is available at
*
* https://www.eclipse.org/legal/epl-v20.html
*/
package example.extensions;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.extension.ExtensionContext.Store;
/**
* Demonstrates an implementation of {@link Store.CloseableResource} using an {@link HttpServer}.
*/
// tag::user_guide[]
@SuppressWarnings("deprecation")
class HttpServerResource implements Store.CloseableResource {
private final HttpServer httpServer;
// end::user_guide[]
/**
* Initializes the Http server resource, using the given port.
*
* @param port (int) The port number for the server, must be in the range 0-65535.
* @throws IOException if an IOException occurs during initialization.
*/
// tag::user_guide[]
HttpServerResource(int port) throws IOException {
InetAddress loopbackAddress = InetAddress.getLoopbackAddress();
this.httpServer = HttpServer.create(new InetSocketAddress(loopbackAddress, port), 0);
}
HttpServer getHttpServer() {
return httpServer;
}
// end::user_guide[]
/**
* Starts the Http server with an example handler.
*/
// tag::user_guide[]
void start() {
// Example handler
httpServer.createContext("/example", exchange -> {
String body = "This is a test";
exchange.sendResponseHeaders(200, body.length());
try (OutputStream os = exchange.getResponseBody()) {
os.write(body.getBytes(UTF_8));
}
});
httpServer.setExecutor(null);
httpServer.start();
}
@Override
public void close() {
httpServer.stop(0);
}
}
// end::user_guide[]