JSON refactoring of a few methods; fixing JavaScript issues
[jalview.git] / src / jalview / util / Platform.java
index d80e3de..c400d83 100644 (file)
  */
 package jalview.util;
 
+import jalview.javascript.json.JSON;
+
 import java.awt.Toolkit;
 import java.awt.event.MouseEvent;
+import java.io.BufferedReader;
 import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.net.URL;
 import java.util.Properties;
 
 import javax.swing.SwingUtilities;
 
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
+
 /**
  * System platform information used by Applet and Application
  * 
@@ -427,4 +439,69 @@ public class Platform
      */
   }
 
+  public static void setAjaxJSON(URL url)
+  {
+    if (isJS())
+    {
+      JSON.setAjax(url);
+    }
+  }
+
+  public static Object parseJSON(InputStream response)
+          throws IOException, ParseException
+  {
+    if (isJS())
+    {
+      return JSON.getJSONReader(response);
+    }
+
+    BufferedReader br = null;
+    try
+    {
+      br = new BufferedReader(new InputStreamReader(response, "UTF-8"));
+      return parseJSON(br);
+    } finally
+    {
+      if (br != null)
+      {
+        try
+        {
+          br.close();
+        } catch (IOException e)
+        {
+          // ignore
+        }
+      }
+    }
+  }
+
+  public static Object parseJSON(String json) throws ParseException
+  {
+    return (isJS() ? JSON.parse(json)
+            : new JSONParser().parse(json));
+  }
+
+  public static Object parseJSON(Reader r)
+          throws IOException, ParseException
+  {
+    if (r == null)
+    {
+      return null;
+    }
+
+    if (!isJS())
+    {
+      return new JSONParser().parse(r);
+    }
+    // Using a file reader is not currently supported in SwingJS JavaScript
+
+    if (r instanceof FileReader)
+    {
+      throw new IOException(
+              "StringJS does not support FileReader parsing for JSON -- but it could...");
+    }
+    return JSON.parse(r);
+
+  }
+
 }