javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/ConvertTypes.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 18 Apr 2013 16:58:55 +0200
branchfx
changeset 1011 9cc253aa9405
parent 997 e9b07d41de7f
child 1012 b22c86471837
permissions -rw-r--r--
Getting bunch of the knockout tests work in FX Web View
     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.MalformedURLException;
    26 import java.net.URL;
    27 import java.util.Iterator;
    28 import java.util.concurrent.Executor;
    29 import java.util.concurrent.Executors;
    30 import java.util.logging.Level;
    31 import java.util.logging.Logger;
    32 import javafx.application.Platform;
    33 import javafx.scene.web.WebEngine;
    34 import netscape.javascript.JSObject;
    35 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    36 import org.json.JSONArray;
    37 import org.json.JSONException;
    38 import org.json.JSONObject;
    39 import org.json.JSONTokener;
    40 
    41 /**
    42  *
    43  * @author Jaroslav Tulach <jtulach@netbeans.org>
    44  */
    45 public final class ConvertTypes {
    46     private static final Logger LOG = Logger.getLogger(ConvertTypes.class.getName());
    47     ConvertTypes() {
    48     }
    49     
    50     public static String toString(Object object, String property) {
    51         Object ret = getProperty(object, property);
    52         return ret == null ? null : ret.toString();
    53     }
    54 
    55     public static double toDouble(Object object, String property) {
    56         Object ret = getProperty(object, property);
    57         return ret instanceof Number ? ((Number)ret).doubleValue() : Double.NaN;
    58     }
    59 
    60     public static int toInt(Object object, String property) {
    61         Object ret = getProperty(object, property);
    62         return ret instanceof Number ? ((Number)ret).intValue() : Integer.MIN_VALUE;
    63     }
    64 
    65     public static <T> T toModel(Class<T> modelClass, Object object, String property) {
    66         Object ret = getProperty(object, property);
    67         if (ret instanceof JSObject) {
    68             Object real = ((JSObject)ret).getMember("koModel");
    69             if (real != null) {
    70                 ret = real;
    71             }
    72         }
    73         if (ret == null || modelClass.isInstance(ret)) {
    74             return modelClass.cast(ret);
    75         }
    76         throw new IllegalStateException("Value " + ret + " is not of type " + modelClass);
    77     }
    78     
    79     public static String toJSON(Object value) {
    80         if (value == null) {
    81             return "null";
    82         }
    83         if (value instanceof String) {
    84             return '"' + 
    85                 ((String)value).
    86                     replace("\"", "\\\"").
    87                     replace("\n", "\\n").
    88                     replace("\r", "\\r").
    89                     replace("\t", "\\t")
    90                 + '"';
    91         }
    92         return value.toString();
    93     }
    94     
    95     @JavaScriptBody(args = { "object", "property" },
    96         body = "if (property === null) return object;\n"
    97         + "var p = object[property]; return p ? p : null;"
    98     )
    99     private static Object getProperty(Object object, String property) {
   100         if (property == null) {
   101             return object;
   102         } else {
   103             if (object instanceof JSObject) {
   104                 JSObject jo = (JSObject)object;
   105                 return jo.getMember(property);
   106             }
   107             return null;
   108         }
   109     }
   110     
   111     private static String findBaseURL() {
   112         WebEngine eng = (WebEngine) System.getProperties().get("webEngine");
   113         return (String)eng.executeScript(
   114           "var h;"
   115         + "if (!!window && !!window.location && !!window.location.href)\n"
   116         + "  h = window.location.href;\n"
   117         + "else "
   118         + "  h = null;"
   119         + "h\n"
   120         );
   121     }
   122     
   123     public static String createJSONP(Object[] jsonResult, Runnable whenDone) {
   124         return "json" + Integer.toHexString(whenDone.hashCode());
   125     }
   126 
   127     public static void loadJSON(
   128         String url, Object[] jsonResult, Runnable whenDone, String jsonp
   129     ) {
   130         REQ.execute(new LoadJSON(url, jsonResult, whenDone, jsonp));
   131     }
   132     
   133     private static final Executor REQ = Executors.newCachedThreadPool();
   134     private static final class LoadJSON implements Runnable {
   135         
   136         private final String url;
   137         private final Object[] jsonResult;
   138         private final Runnable whenDone;
   139         private final String jsonp;
   140         private final URL base;
   141 
   142         LoadJSON(String url, Object[] jsonResult, Runnable whenDone, String jsonp) {
   143             this.url = url;
   144             this.jsonResult = jsonResult;
   145             this.whenDone = whenDone;
   146             this.jsonp = jsonp;
   147             URL b;
   148             try {
   149                 b = new URL(findBaseURL());
   150             } catch (MalformedURLException ex) {
   151                 LOG.log(Level.SEVERE, "Can't find base url for " + url, ex);
   152                 b = null;
   153             }
   154             this.base = b;
   155         }
   156 
   157         @Override
   158         public void run() {
   159             if (Platform.isFxApplicationThread()) {
   160                 whenDone.run();
   161                 return;
   162             }
   163             try {
   164                 URL u = new URL(base, url.replace(" ", "%20"));
   165                 InputStream is = u.openStream();
   166                 if (jsonp != null) {
   167                     PushbackInputStream pis = new PushbackInputStream(is, 1);
   168                     is = pis;
   169                     for (;;) {
   170                         int ch = pis.read();
   171                         if (ch == -1) {
   172                             break;
   173                         }
   174                         if (ch == '{') {
   175                             pis.unread(ch);
   176                             break;
   177                         }
   178                     }
   179                 }
   180                 Reader r = new InputStreamReader(is, "UTF-8");
   181                 
   182                 JSONTokener tok = new JSONTokener(r);
   183                 JSONObject obj = new JSONObject(tok);
   184                 jsonResult[0] = convertToArray(obj);
   185             } catch (JSONException | IOException ex) {
   186                 jsonResult[0] = ex;
   187                 LOG.log(Level.WARNING, "Cannot connect to " + url, ex);
   188             } finally {
   189                 Platform.runLater(this);
   190             }
   191         }
   192         
   193         private static Object convertToArray(Object o) throws JSONException {
   194             if (o instanceof JSONArray) {
   195                 JSONArray ja = (JSONArray)o;
   196                 Object[] arr = new Object[ja.length()];
   197                 for (int i = 0; i < arr.length; i++) {
   198                     arr[i] = convertToArray(ja.get(i));
   199                 }
   200                 return arr;
   201             } else if (o instanceof JSONObject) {
   202                 JSONObject obj = (JSONObject)o;
   203                 Iterator it = obj.keys();
   204                 while (it.hasNext()) {
   205                     String key = (String)it.next();
   206                     obj.put(key, convertToArray(obj.get(key)));
   207                 }
   208                 return obj;
   209             } else {
   210                 return o;
   211             }
   212         }
   213     }
   214     
   215     @JavaScriptBody(args = { "url", "jsonp" }, body = 
   216         "var scrpt = window.document.createElement('script');\n "
   217         + "scrpt.setAttribute('src', url);\n "
   218         + "scrpt.setAttribute('id', jsonp);\n "
   219         + "scrpt.setAttribute('type', 'text/javascript');\n "
   220         + "var body = document.getElementsByTagName('body')[0];\n "
   221         + "body.appendChild(scrpt);\n"
   222     )
   223     private static void loadJSONP(String url, String jsonp) {
   224         
   225     }
   226     
   227     public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
   228         if (jsonObject instanceof JSONObject) {
   229             JSONObject obj = (JSONObject)jsonObject;
   230             for (int i = 0; i < props.length; i++) {
   231                 try {
   232                     values[i] = obj.get(props[i]);
   233                 } catch (JSONException ex) {
   234                     LOG.log(Level.SEVERE, "Can't read " + props[i] + " from " + jsonObject, ex);
   235                 }
   236             }
   237             
   238         }
   239         
   240     }
   241     
   242 }