Server.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package benchmarks;
  2. import java.io.ByteArrayInputStream;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
  5. import fi.iki.elonen.NanoHTTPD;
  6. public class Server extends NanoHTTPD {
  7. private static final String SERVER_NAME = "NanoHTTPD";
  8. private static final String HELLO_TEXT = "Hello, World!";
  9. private static final byte[] HELLO_BYTES = HELLO_TEXT.getBytes();
  10. private static final int HELLO_LENGTH = HELLO_BYTES.length;
  11. private static final ObjectMapper MAPPER = new ObjectMapper();
  12. static {
  13. MAPPER.registerModule(new AfterburnerModule());
  14. }
  15. public Server(int port) {
  16. super(port);
  17. }
  18. @Override public Response serve(IHTTPSession session) {
  19. Response response;
  20. switch (session.getUri()) {
  21. case "/plaintext":
  22. response = newFixedLengthResponse(Response.Status.OK, "text/plain",
  23. new ByteArrayInputStream(HELLO_BYTES), HELLO_LENGTH);
  24. response.addHeader("Server", SERVER_NAME);
  25. return response;
  26. case "/json":
  27. Message msg = new Message(HELLO_TEXT);
  28. byte[] bytes;
  29. try {
  30. bytes = MAPPER.writeValueAsBytes(msg);
  31. } catch (Exception e) {
  32. throw new RuntimeException(e);
  33. }
  34. response = newFixedLengthResponse(Response.Status.OK, "application/json",
  35. new ByteArrayInputStream(bytes), bytes.length);
  36. response.addHeader("Server", SERVER_NAME);
  37. return response;
  38. default:
  39. return newFixedLengthResponse(Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Not found");
  40. }
  41. }
  42. public static void main(String[] args) throws Exception {
  43. int port = args.length > 0 ? Integer.parseInt(args[0]) : 8080;
  44. NanoHTTPD server = new Server(port);
  45. server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
  46. }
  47. }