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

81
LINES

< > BotCompany Repo | #608 // HttpServerWithOnePage (unshortened JavaX example)

JavaX source code - run with: x30.jar

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.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetSocketAddress;

public class main {
  private static HttpServer server;
  private static int port = 8080;

  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 {
      sendHtml(httpExchange, "Hello world! <a href='http://javax.tinybrain.de'>JavaX.</a>");
    }
  }
}

Author comment

Should be self-contained and runnable by x9 just as is.

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

Comments [hide]

ID Author/Program Comment Date
58 stefan Yup it is runnable. "java x9 608" 2015-05-05 18:00:16

add comment

Snippet ID: #608
Snippet name: HttpServerWithOnePage (unshortened JavaX example)
Eternal ID of this version: #608/1
Text MD5: 49ebf4e1127dde49d2b6622ad1d1c5f0
Author: stefan
Category:
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-05-05 17:58:43
Source code size: 2988 bytes / 81 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 1024 / 952
Referenced in: [show references]