Created
September 26, 2018 14:04
-
-
Save atgper/4f007fbffc5655fd3e408f0bbed9f0d8 to your computer and use it in GitHub Desktop.
A Mock server built in Java. Add your expectations in Java.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package se.atg.nanomock; | |
import com.sun.net.httpserver.Headers; | |
import com.sun.net.httpserver.HttpContext; | |
import com.sun.net.httpserver.HttpExchange; | |
import com.sun.net.httpserver.HttpServer; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import java.net.InetSocketAddress; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.Set; | |
public class NanoMockServer { | |
private static final int THREADS = 0; | |
private static final int PORT = 8090; | |
public static void main(String[] args) throws IOException { | |
long startTime = System.currentTimeMillis(); | |
new NanoMockServer().run(HttpServer.create(new InetSocketAddress(PORT), THREADS)); | |
System.out.println(String.format("Server started in %d ms", (System.currentTimeMillis() - startTime))); | |
} | |
private void run(HttpServer httpServer) { | |
createRootContext(httpServer); | |
httpServer.start(); | |
} | |
private void createRootContext(HttpServer httpServer) { | |
HttpContext context = httpServer.createContext("/"); | |
context.setHandler(httpExchange -> { | |
String payload = getPayload(httpExchange); | |
httpExchange.sendResponseHeaders(200, payload.getBytes().length); | |
final OutputStream output = httpExchange.getResponseBody(); | |
output.write(payload.getBytes()); | |
output.flush(); | |
httpExchange.close(); | |
}); | |
} | |
private String getPayload(HttpExchange httpExchange) { | |
return "URI: '" + | |
httpExchange.getRequestURI() + | |
"'\n" + | |
"Method: " + | |
httpExchange.getRequestMethod() + | |
"\nHeaders:\n" + | |
getHeaders(httpExchange.getRequestHeaders()) | |
; | |
} | |
private String getHeaders(Headers requestHeaders) { | |
StringBuilder result = new StringBuilder(); | |
Set<Map.Entry<String, List<String>>> entries = requestHeaders.entrySet(); | |
for (Map.Entry<String, List<String>> entry : entries) { | |
result.append(entry.getKey()); | |
result.append(": "); | |
result.append(String.join(",", entry.getValue())); | |
result.append("\n"); | |
} | |
return result.toString(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment