JSON refactoring of a few methods; fixing JavaScript issues
[jalview.git] / src / jalview / javascript / web / ClientResponse.java
index 9a9dba6..23580ed 100644 (file)
@@ -1,6 +1,9 @@
 package jalview.javascript.web;
 
-import java.net.URI;
+import jalview.javascript.json.JSON;
+import jalview.util.Platform;
+
+import java.net.URL;
 
 /**
  * minimal implementation of com.sun.jersey.api.client.ClientResponse
@@ -10,21 +13,47 @@ import java.net.URI;
  */
 public class ClientResponse
 {
-  
+
   private String response;
-  private String[] encoding;
 
-  public ClientResponse(String response, String... encoding) 
+  private boolean isJSON;
+
+  private Object jsonData;
+
+  int responseCode = -1;
+
+  public ClientResponse(URL url, String[] encoding)
   {
-    this.response = response;
-    this.encoding = encoding;
+    // OK, so it turns out that ajax "json" format - or for that matter, any
+    // format for json is still just text. There is no point in getting this
+    // using special jQuery "json" formats. Duh. BH wasted a whole day try to
+    // "do it right".
+    response = Platform.getFileAsString(url.toString());
+    responseCode = (response == null || response == "" ? 404 : 200);
+    isJSON = encoding[0].equals("application/json");
+    if (isJSON)
+    {
+      try
+      {
+        jsonData = JSON.parse(response);
+      } catch (Exception e)
+      {
+        jsonData = null;
+      }
+      if (jsonData == null)
+      {
+        responseCode = 400;
+      }
+    }
   }
 
-  public String getEntity(Class<?> c)
-  {  
-    
-    // c will be String.class
-    
+  public Object getEntity(Class<?> c)
+  {
+
+    if (c == java.util.Map.class)
+    {
+      return jsonData;
+    }
     return response;
   }
 
@@ -52,9 +81,12 @@ public class ClientResponse
 
   public int getStatus()
   {
-    // note, we could get the actual response. I am just assuming it is 200 or 400
-    return (response != null && (response.startsWith("{") == encoding[0].equals("application/json"))
-            ? 200 : 400);
+    return responseCode;
+  }
+
+  public Object getJSONData()
+  {
+    return jsonData;
   }
 
 }