package org.hwo.rpc.json; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.json.simple.JSONValue; public class JSONRpcService implements InvocationHandler{ private String url; private Integer nextid; public JSONRpcService(String url){ this.url = url; this.nextid = 0; } public T createProxy(Class iface){ T proxy = (T) Proxy.newProxyInstance(iface.getClassLoader(), new Class[]{ iface }, this); return proxy; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { HashMap req = new HashMap(); req.put("id", this.nextid++ ); req.put("method", method.getName()); req.put("params", Arrays.asList(args)); String reqString = JSONValue.toJSONString(req); System.err.println(reqString); URL url = new URL(this.url); URLConnection conn = url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); OutputStream out = conn.getOutputStream(); out.write(reqString.getBytes()); out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader( conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine())!=null) { sb.append(line); } System.err.println("Response: " + sb.toString()); Map response = (Map)JSONValue.parse(sb.toString()); if (response.containsKey("error") && (response.get("error") != null)) { throw new RuntimeException("JSON-RPC: " + response.get("error")); } return response.get("result"); } }