aboutsummaryrefslogtreecommitdiffstats
path: root/metrics-proxy/src/test/java/ai/vespa/metricsproxy/service/MockHttpServer.java
blob: 75b55c691ffb458d9f7da56f29d0d8cc41eaaf01 (plain) (blame)
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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.metricsproxy.service;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

/**
 * @author jobergum
 */
public class MockHttpServer {

    private String response;
    private final HttpServer server;

    /**
     * Mock http server that will return response as body
     *
     * @param response the response to return along with 200 OK
     * @param path     the file path that the server will accept requests for. E.g /state/v1/metrics
     */
    public MockHttpServer(String response, String path) throws IOException {
        this.response = response;
        this.server = HttpServer.create(new InetSocketAddress(0), 10);
        this.server.createContext(path, new MyHandler());
        this.server.setExecutor(null); // creates a default executor
        this.server.start();
        System.out.println("Started web server on port " + port());
    }

    public synchronized void setResponse(String r) {
        this.response = r;
    }

    public int port() {
        return server.getAddress().getPort();
    }

    public void close() {
        this.server.stop(0);
    }

    private class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            synchronized (MockHttpServer.this) {
                t.sendResponseHeaders(200, response != null ? response.length() : 0);
                try (OutputStream os = t.getResponseBody()) {
                    if (response != null) os.write(response.getBytes());
                }
            }
        }
    }

}