java-org.hwo/src/org/hwo/rpc/json/JSONRpcService.java

79 lines
2.0 KiB
Java
Raw Normal View History

2014-09-26 18:14:17 +02:00
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> T createProxy(Class<T> 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<String, Object> req = new HashMap<String, Object>();
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<String, Object> response = (Map<String, Object>)JSONValue.parse(sb.toString());
if (response.containsKey("error") && (response.get("error") != null)) {
throw new RuntimeException("JSON-RPC: " + response.get("error"));
}
return response.get("result");
}
}