Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

79
LINES

< > BotCompany Repo | #611 // HTTP server serving a snippet as a page (half-shortened JavaX example)

JavaX source code - run with: x30.jar

!592 1000265 // auto import, standard functions

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

public class main {
  private static HttpServer server;
  private static int port = 8080;
  private static String snippetID = "#2000335";

  public static void main(String[] args) throws Exception {
    server = HttpServer.create(new InetSocketAddress(port), 0);
    createHttpContext("/", new MainContext());
    server.setExecutor(null); // creates a default executor
    server.start();
    System.out.println("HTTP server started (listening on port " + port + "!)");
  }

  private static void createHttpContext(String path, HttpHandler handler) {
    server.createContext(path, new SafeHttpHandler(handler));
  }

  public static class SafeHttpHandler implements HttpHandler {
    private HttpHandler handler;

    public SafeHttpHandler(HttpHandler handler) {
      this.handler = handler;
    }

    public void handle(HttpExchange exchange) throws IOException {
      System.out.println("[web server] Handling request: " + exchange.getRequestURI());
      try {
        handler.handle(exchange);
      } catch (Throwable e) {
        String stackTrace = getStackTrace(e);
        sendServerError(exchange, stackTrace);
        System.out.println(stackTrace);
      } finally {
        exchange.close();
        System.out.println("[web server] Done handling request: " + exchange.getRequestURI());
      }
    }
  }

  public static String getStackTrace(Throwable e) {
    StringWriter stringWriter = new StringWriter();
    e.printStackTrace(new PrintWriter(stringWriter));
    return stringWriter.toString();
  }

  public static void sendHtml(HttpExchange exchange, String content) throws IOException {
    int responseCode = 200;
    String contentType = "text/html";
    sendHttpTextResponse(exchange, responseCode, content, contentType);
  }

  public static void sendHttpTextResponse(HttpExchange exchange, int responseCode, String content, String contentType) throws IOException {
    byte[] bytes = content.getBytes("UTF-8");
    String header = contentType + "; charset=utf-8";
    System.out.println("Sending content type: " + header);
    exchange.getResponseHeaders().set("Content-Type", header);
    exchange.sendResponseHeaders(responseCode, bytes.length);
    OutputStream os = exchange.getResponseBody();
    os.write(bytes);
    os.close();
  }

  public static void sendServerError(HttpExchange exchange, String response) throws IOException {
    sendHttpTextResponse(exchange, 500, response, "text/plain");
  }

  public static class MainContext implements HttpHandler {
    public void handle(HttpExchange httpExchange) throws IOException {
      String html = loadSnippet(snippetID);
      sendHtml(httpExchange, html);
    }
  }
}

Author comment

Began life as a copy of #608

Snippet is loaded live at each request.

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #611
Snippet name: HTTP server serving a snippet as a page (half-shortened JavaX example)
Eternal ID of this version: #611/1
Text MD5: ce900b3a8f5df79e21fd334e633e9ab5
Author: stefan
Category:
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-05-06 19:41:28
Source code size: 2920 bytes / 79 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 699 / 612
Referenced in: [show references]