package fi.bittiraha.walletd;

import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.InetAddress;

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

import com.thetransactioncompany.jsonrpc2.*;
import com.thetransactioncompany.jsonrpc2.server.*;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.Charsets;

import java.text.*;
import java.util.*;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.Executors;

class JSONRPC2Handler implements HttpHandler {
    private RequestHandler handler;
    private HttpServer server;
    public JSONRPC2Handler(int port, RequestHandler h) throws Exception {
      handler = h;
      server = HttpServer.create(new InetSocketAddress(InetAddress.getByName("localhost"),port), 0);
      server.createContext("/", this);
      server.setExecutor(Executors.newCachedThreadPool()); // creates a default executor
      server.start();
    }
    public void handle(HttpExchange t) throws IOException {
      String response = "Internal Server Error";
      try {
        String req = IOUtils.toString(t.getRequestBody(),Charsets.UTF_8.name());
//          System.out.println("Request: " + req);

        Dispatcher dispatcher = new Dispatcher();
        dispatcher.register(handler);
            
        JSONRPC2Request jsonreq = JSONRPC2Request.parse(req,false,true);
        JSONRPC2Response resp = dispatcher.process(jsonreq, null);
            
        response = resp.toString();

        t.sendResponseHeaders(200, response.length());
      } catch(Exception e) {
        t.sendResponseHeaders(501, response.length());
        e.printStackTrace();
      }
      OutputStream os = t.getResponseBody();
      os.write(response.getBytes());
      os.close();
    }
}


@@ -398,24 +398,95 @@
 .server.*;%0A%0A
+import net.minidev.json.JSONObject;%0Aimport net.minidev.json.JSONValue;%0A
 import org.a
@@ -511,16 +511,16 @@
 OUtils;%0A
-
 import o
@@ -1140,24 +1140,303 @@
 rt();%0A    %7D%0A
+%0A    private static String ensureRequestHasID(String req) %7B%0A        JSONObject parsed = (JSONObject)JSONValue.parse(req);%0A        if (parsed.containsKey(%22id%22)) return req;%0A        else %7B%0A            parsed.put(%22id%22,%22%22);%0A            return parsed.toJSONString();%0A        %7D%0A    %7D%0A%0A
     public v
@@ -1834,19 +1834,39 @@
 t.parse(
+ensureRequestHasID(
 req
+)
 ,false,t

add a function to add id to request in case it's missing.