00001 package cz.vutbr.fit.dudka.SGVis.Lookup;
00002
00003 import java.net.MalformedURLException;
00004 import java.net.URL;
00005
00006 import org.json.JSONArray;
00007 import org.json.JSONException;
00008 import org.json.JSONObject;
00009
00010 import cz.vutbr.fit.dudka.SGVis.Data.Relation;
00011 import cz.vutbr.fit.dudka.SGVis.Data.RelationStorage;
00012
00019 public class Response {
00020 private JSONObject jsObj;
00021
00027 public Response(String responseText) throws JSONException {
00028 jsObj = new JSONObject(responseText);
00029 }
00030
00037 public void addTo(RelationStorage storage) throws JSONException, MalformedURLException {
00038 ResponseParser parser = new ResponseParser(storage);
00039 parser.parse(jsObj);
00040 }
00041
00042 private class ResponseParser {
00043 private RelationStorage storage;
00044 public ResponseParser(RelationStorage storage) {
00045 this.storage = storage;
00046 }
00047 @SuppressWarnings("unchecked")
00048 public void parse(JSONObject response) throws JSONException, MalformedURLException {
00049 JSONObject nodes = response.getJSONObject("nodes");
00050 java.util.Iterator iter = nodes.keys();
00051 while (iter.hasNext()) {
00052 String hostName = (String) iter.next();
00053 this.handleHost(
00054 hostName,
00055 nodes.getJSONObject(hostName));
00056 }
00057 }
00058 private void handleHost(
00059 String hostName,
00060 JSONObject hostData
00061 ) throws JSONException, MalformedURLException
00062 {
00063 this.handleHostData(hostName, hostData, false);
00064 this.handleHostData(hostName, hostData, true);
00065 }
00066 private void handleHostData(
00067 String hostName,
00068 JSONObject hostData,
00069 boolean backLink
00070 ) throws JSONException, MalformedURLException
00071 {
00072 String nodeName = backLink?
00073 "nodes_referenced_by":
00074 "nodes_referenced";
00075 if (hostData.has(nodeName)) {
00076 JSONObject refs = hostData.getJSONObject(nodeName);
00077 java.util.Iterator iter = refs.keys();
00078 while (iter.hasNext()) {
00079 String refName = (String) iter.next();
00080 this.handleReference(
00081 hostName,
00082 refName,
00083 refs.getJSONObject(refName),
00084 backLink);
00085 }
00086 }
00087 }
00088 private void handleReference(
00089 String hostName,
00090 String refName,
00091 JSONObject refData,
00092 boolean backLink
00093 ) throws JSONException, MalformedURLException
00094 {
00095 JSONArray types = refData.getJSONArray("types");
00096 for(int i=0; i<types.length(); i++)
00097 this.handleRelation(
00098 backLink?refName:hostName,
00099 backLink?hostName:refName,
00100 types.getString(i)
00101 );
00102 }
00103 private void handleRelation(
00104 String from,
00105 String to,
00106 String edgeType
00107 ) throws MalformedURLException
00108 {
00109 URL fromUrl = new URL(from);
00110 URL toUrl = new URL(to);
00111 Relation relation = new Relation(fromUrl, toUrl, edgeType);
00112 storage.add(relation);
00113 }
00114 }
00115 }