Web interface for java application

Web interface for java application
-------------- WebInterface.java ---------------

import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
import java.nio.charset.*;
import com.sun.net.httpserver.*;

public class WebInterface {

  String appRootPath;

  public static void main(String args[]) { new WebInterface(args); }

  WebInterface(String argv[]) {

    final String hostname = "";
    final int port = 8000;

    appRootPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
    if (getClass().getResource("/" + getClass().getName() + ".class").toString().startsWith("jar:")) {
      appRootPath = appRootPath.substring(0, appRootPath.lastIndexOf("/") + 1);
    }
    try {
      HttpServer server = HttpServer.create(new InetSocketAddress(hostname, port), 0);
      HttpContext context = server.createContext("/", new MyHandler());
      //server.setExecutor(java.util.concurrent.Executors.newFixedThreadPool(5));
      server.start();

      System.out.println("http://" + server.getAddress().getHostName() + ":" + server.getAddress().getPort());
      System.out.println("^C to exit");
    } catch (Exception e) { e.printStackTrace(); }
  }

  class MyHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange exchange) throws IOException {
      exchange.getResponseHeaders().set("Content-Type", "text/html; charset=utf-8");
      String query = exchange.getRequestURI().getRawQuery();
      String s;
      if (query == null || query.isEmpty()) {
        s = htmlMain();
      } else {
        String url = urlDecode(query);
        String path;
        if (url.equals(".")) {
          path = appRootPath;
        } else {
          path = url;
        }
        s = htmlFileList(path);
      }
      byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
      exchange.sendResponseHeaders(200, bytes.length);
      try (OutputStream os = exchange.getResponseBody()) {
        os.write(bytes);
      }
    }
  } // End class MyHandler

  String htmlMain() {
    StringBuilder sb = new StringBuilder();
    sb.append("<head>\n")
      .append("  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n")
      .append("  <script type=\"text/javascript\">\n")
      .append("    function f1(p1) {\n")
      .append("      xhttp = new XMLHttpRequest();\n")
      .append("      xhttp.onreadystatechange = function() {\n")
      .append("        if (xhttp.readyState == 4 && xhttp.status == 200) document.getElementById(\"div1\").innerHTML = xhttp.responseText;\n")
      .append("      };\n")
      .append("      xhttp.open(\"GET\", \"?\" + p1, true);\n")
      .append("      xhttp.send();\n")
      .append("    }\n")
      .append("    window.onload = f1('").append(urlEncode(".")).append("');\n")
      .append("  </script>\n")
      .append("</head>\n")
      .append("<body bgcolor=\"#FEFEFE\" style=\"font-size: 14pt;\">\n")
      .append("  <div id=\"div1\" style=\"margin: 20px;\"></div>\n")
      .append("</body>\n");
    return sb.toString();
  }

  String htmlFileList(String path) {
    SimpleDateFormat dateFormat = new SimpleDateFormat();
    NumberFormat numberFormat = NumberFormat.getIntegerInstance();
    File file = new File(path);
    while (!file.exists() || file.isFile()) {
      file = file.getParentFile();
      if (file == null) return "<p>Wrong path</p>";
    }
    StringBuilder sb = new StringBuilder();
    sb.append("<p style=\"font-size: 20pt;\">Index of "+htmlEncode(file.getPath())+"</p>\n");
    sb.append("<table width=\"70%\"><col width=\"60%\"><col width=\"25%\"><col width=\"15%\">\n");
    sb.append("  <tr>\n");
    sb.append("    <th style=\"border-bottom: thin solid black;\">Name</td>\n");
    sb.append("    <th style=\"border-bottom: thin solid black;\">Last modified</td>\n");
    sb.append("    <th style=\"border-bottom: thin solid black;\">Size</td>\n");
    sb.append("  </tr>\n");
    File parent = file.getParentFile();
    if (parent != null) {
      sb.append(" <tr><td><a href=\"javascript:f1('"+urlEncode(parent.getPath())+"');\">..</a><br></td><td></td><td></td>\n");
    }
    File[] files = file.listFiles();
    if (files != null && files.length > 0) {
      Arrays.sort(files, (f1, f2) -> {
        return f1.isDirectory() == f2.isDirectory() ?
               f1.getName().compareToIgnoreCase(f2.getName()) :
               f1.isDirectory() ? -1 : 1;
      });
      for (File childFile : files) {
        String fln = childFile.getName();
        String s1, s2, s3;
        if (childFile.isFile()) {
          s1 = htmlEncode(fln);
          s2 = htmlEncode(dateFormat.format(new Date(childFile.lastModified())));
          s3 = htmlEncode(numberFormat.format(childFile.length()));
        } else {
          s1 = "<a href=\"javascript:f1('"+urlEncode(childFile.getPath())+"');\">"+htmlEncode(fln)+"/</a>";
          s2 = s3 = "";
        }
        sb.append(" <tr>\n");
        sb.append("   <td>").append(s1).append("</td>\n");
        sb.append("   <td>").append(s2).append("</td>\n");
        sb.append("   <td align=\"right\">").append(s3).append("</td>\n");
        sb.append(" </tr>\n");
      }
    }
    sb.append("</table>\n");
    return sb.toString();
  }

  String htmlEncode(String text) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < text.length(); i++) {
      char c = text.charAt(i);
      switch(c) {
        case '&': sb.append("&amp;"); break;
        case '<': sb.append("&lt;"); break;
        case '>': sb.append("&gt;"); break;
        case '\"': sb.append("&quot;"); break;
        case '\'': sb.append("&apos;"); break;
        default:
          if(c > 126) sb.append("&#").append((int)c).append(';');
          else sb.append(c);
      }
    }
    return sb.toString();
  }

  String urlEncode(String url) {
    try {
      return new String(Base64.getUrlEncoder().encode(url.getBytes(StandardCharsets.UTF_8)));
    } catch (Exception e) { return ""; }
  }

  String urlDecode(String txt) {
    try {
      return new String(Base64.getUrlDecoder().decode(txt), StandardCharsets.UTF_8);
    } catch (Exception e) { return ""; }
  }
}

Download ZIP

Back