javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/ConvertTypes.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 16 Apr 2013 08:39:54 +0200
branchfx
changeset 997 e9b07d41de7f
parent 992 bae9b96bfd2c
child 1011 9cc253aa9405
permissions -rw-r--r--
Log exception while fetching JSON
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 2 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.bck2brwsr.htmlpage;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 import java.io.InputStreamReader;
    23 import java.io.PushbackInputStream;
    24 import java.io.Reader;
    25 import java.net.URL;
    26 import java.util.Iterator;
    27 import java.util.concurrent.Executor;
    28 import java.util.concurrent.Executors;
    29 import java.util.logging.Level;
    30 import java.util.logging.Logger;
    31 import javafx.application.Platform;
    32 import netscape.javascript.JSObject;
    33 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    34 import org.json.JSONArray;
    35 import org.json.JSONException;
    36 import org.json.JSONObject;
    37 import org.json.JSONTokener;
    38 
    39 /**
    40  *
    41  * @author Jaroslav Tulach <jtulach@netbeans.org>
    42  */
    43 public final class ConvertTypes {
    44     private static final Logger LOG = Logger.getLogger(ConvertTypes.class.getName());
    45     ConvertTypes() {
    46     }
    47     
    48     public static String toString(Object object, String property) {
    49         Object ret = getProperty(object, property);
    50         return ret == null ? null : ret.toString();
    51     }
    52 
    53     public static double toDouble(Object object, String property) {
    54         Object ret = getProperty(object, property);
    55         return ret instanceof Number ? ((Number)ret).doubleValue() : Double.NaN;
    56     }
    57 
    58     public static int toInt(Object object, String property) {
    59         Object ret = getProperty(object, property);
    60         return ret instanceof Number ? ((Number)ret).intValue() : Integer.MIN_VALUE;
    61     }
    62 
    63     public static <T> T toModel(Class<T> modelClass, Object object, String property) {
    64         Object ret = getProperty(object, property);
    65         if (ret instanceof JSObject) {
    66             Object real = ((JSObject)ret).getMember("koModel");
    67             if (real != null) {
    68                 ret = real;
    69             }
    70         }
    71         if (ret == null || modelClass.isInstance(ret)) {
    72             return modelClass.cast(ret);
    73         }
    74         throw new IllegalStateException("Value " + ret + " is not of type " + modelClass);
    75     }
    76     
    77     public static String toJSON(Object value) {
    78         if (value == null) {
    79             return "null";
    80         }
    81         if (value instanceof String) {
    82             return '"' + 
    83                 ((String)value).
    84                     replace("\"", "\\\"").
    85                     replace("\n", "\\n").
    86                     replace("\r", "\\r").
    87                     replace("\t", "\\t")
    88                 + '"';
    89         }
    90         return value.toString();
    91     }
    92     
    93     @JavaScriptBody(args = { "object", "property" },
    94         body = "if (property === null) return object;\n"
    95         + "var p = object[property]; return p ? p : null;"
    96     )
    97     private static Object getProperty(Object object, String property) {
    98         if (property == null) {
    99             return object;
   100         } else {
   101             if (object instanceof JSObject) {
   102                 JSObject jo = (JSObject)object;
   103                 return jo.getMember(property);
   104             }
   105             return null;
   106         }
   107     }
   108     
   109     public static String createJSONP(Object[] jsonResult, Runnable whenDone) {
   110         return "json" + Integer.toHexString(whenDone.hashCode());
   111     }
   112 
   113     public static void loadJSON(
   114         String url, Object[] jsonResult, Runnable whenDone, String jsonp
   115     ) {
   116         REQ.execute(new LoadJSON(url, jsonResult, whenDone, jsonp));
   117     }
   118     
   119     private static final Executor REQ = Executors.newCachedThreadPool();
   120     private static final class LoadJSON implements Runnable {
   121         
   122         private final String url;
   123         private final Object[] jsonResult;
   124         private final Runnable whenDone;
   125         private final String jsonp;
   126 
   127         LoadJSON(String url, Object[] jsonResult, Runnable whenDone, String jsonp) {
   128             this.url = url;
   129             this.jsonResult = jsonResult;
   130             this.whenDone = whenDone;
   131             this.jsonp = jsonp;
   132         }
   133 
   134         @Override
   135         public void run() {
   136             if (Platform.isFxApplicationThread()) {
   137                 whenDone.run();
   138                 return;
   139             }
   140             try {
   141                 URL u = new URL(url.replace(" ", "%20"));
   142                 InputStream is = u.openStream();
   143                 if (jsonp != null) {
   144                     PushbackInputStream pis = new PushbackInputStream(is, 1);
   145                     is = pis;
   146                     for (;;) {
   147                         int ch = pis.read();
   148                         if (ch == -1) {
   149                             break;
   150                         }
   151                         if (ch == '{') {
   152                             pis.unread(ch);
   153                             break;
   154                         }
   155                     }
   156                 }
   157                 Reader r = new InputStreamReader(is, "UTF-8");
   158                 
   159                 JSONTokener tok = new JSONTokener(r);
   160                 JSONObject obj = new JSONObject(tok);
   161                 jsonResult[0] = convertToArray(obj);
   162             } catch (JSONException | IOException ex) {
   163                 jsonResult[0] = ex;
   164                 LOG.log(Level.WARNING, "Cannot connect to " + url, ex);
   165             } finally {
   166                 Platform.runLater(this);
   167             }
   168         }
   169         
   170         private static Object convertToArray(Object o) throws JSONException {
   171             if (o instanceof JSONArray) {
   172                 JSONArray ja = (JSONArray)o;
   173                 Object[] arr = new Object[ja.length()];
   174                 for (int i = 0; i < arr.length; i++) {
   175                     arr[i] = convertToArray(ja.get(i));
   176                 }
   177                 return arr;
   178             } else if (o instanceof JSONObject) {
   179                 JSONObject obj = (JSONObject)o;
   180                 Iterator it = obj.keys();
   181                 while (it.hasNext()) {
   182                     String key = (String)it.next();
   183                     obj.put(key, convertToArray(obj.get(key)));
   184                 }
   185                 return obj;
   186             } else {
   187                 return o;
   188             }
   189         }
   190     }
   191     
   192     @JavaScriptBody(args = { "url", "jsonp" }, body = 
   193         "var scrpt = window.document.createElement('script');\n "
   194         + "scrpt.setAttribute('src', url);\n "
   195         + "scrpt.setAttribute('id', jsonp);\n "
   196         + "scrpt.setAttribute('type', 'text/javascript');\n "
   197         + "var body = document.getElementsByTagName('body')[0];\n "
   198         + "body.appendChild(scrpt);\n"
   199     )
   200     private static void loadJSONP(String url, String jsonp) {
   201         
   202     }
   203     
   204     public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
   205         if (jsonObject instanceof JSONObject) {
   206             JSONObject obj = (JSONObject)jsonObject;
   207             for (int i = 0; i < props.length; i++) {
   208                 try {
   209                     values[i] = obj.get(props[i]);
   210                 } catch (JSONException ex) {
   211                     LOG.log(Level.SEVERE, "Can't read " + props[i] + " from " + jsonObject, ex);
   212                 }
   213             }
   214             
   215         }
   216         
   217     }
   218     
   219 }