javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/ConvertTypes.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 18 Apr 2013 23:09:30 +0200
branchfx
changeset 1016 6dc2c6c752df
parent 1014 7a7686e6f875
permissions -rw-r--r--
Can execute 'dual' tests: bck2brwsr can use regular launcher, javaquery.api can use FX Web View one
     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.InputStreamReader;
    22 import java.io.PushbackInputStream;
    23 import java.io.Reader;
    24 import java.net.MalformedURLException;
    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 javafx.scene.web.WebEngine;
    33 import netscape.javascript.JSObject;
    34 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    35 import org.json.JSONArray;
    36 import org.json.JSONException;
    37 import org.json.JSONObject;
    38 import org.json.JSONTokener;
    39 
    40 /**
    41  *
    42  * @author Jaroslav Tulach <jtulach@netbeans.org>
    43  */
    44 public final class ConvertTypes {
    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     private static String findBaseURL() {
   110         WebEngine eng = (WebEngine) System.getProperties().get("webEngine");
   111         return (String)eng.executeScript(
   112           "var h;"
   113         + "if (!!window && !!window.location && !!window.location.href)\n"
   114         + "  h = window.location.href;\n"
   115         + "else "
   116         + "  h = null;"
   117         + "h\n"
   118         );
   119     }
   120     
   121     public static String createJSONP(Object[] jsonResult, Runnable whenDone) {
   122         return "json" + Integer.toHexString(whenDone.hashCode());
   123     }
   124 
   125     @JavaScriptBody(args = { "url", "jsonResult", "whenDone", "jsonp" }, body = "throw 'ignore';")
   126     public static void loadJSON(
   127         String url, Object[] jsonResult, Runnable whenDone, String jsonp
   128     ) {
   129         LoadJSON.REQ.execute(new LoadJSON(url, jsonResult, whenDone, jsonp));
   130     }
   131     
   132     private static final class LoadJSON implements Runnable {
   133         static final Executor REQ = Executors.newCachedThreadPool();
   134         private static final Logger LOG = Logger.getLogger(ConvertTypes.class.getName());
   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                 PushbackInputStream is = new PushbackInputStream(u.openStream(), 1);
   166                 boolean array = false;
   167                 if (jsonp != null) {
   168                     for (;;) {
   169                         int ch = is.read();
   170                         if (ch == -1) {
   171                             break;
   172                         }
   173                         if (ch == '[') {
   174                             is.unread(ch);
   175                             array = true;
   176                             break;
   177                         }
   178                         if (ch == '{') {
   179                             is.unread(ch);
   180                             break;
   181                         }
   182                     }
   183                 } else {
   184                     int ch = is.read();
   185                     array = ch == '[';
   186                     is.unread(ch);
   187                 }
   188                 Reader r = new InputStreamReader(is, "UTF-8");
   189                 
   190                 JSONTokener tok = new JSONTokener(r);
   191                 Object obj = array ? new JSONArray(tok) : new JSONObject(tok);
   192                 jsonResult[0] = convertToArray(obj);
   193             } catch (JSONException | IOException ex) {
   194                 jsonResult[0] = ex;
   195                 LOG.log(Level.WARNING, "Cannot connect to " + url, ex);
   196             } finally {
   197                 Platform.runLater(this);
   198             }
   199         }
   200         
   201         private static Object convertToArray(Object o) throws JSONException {
   202             if (o instanceof JSONArray) {
   203                 JSONArray ja = (JSONArray)o;
   204                 Object[] arr = new Object[ja.length()];
   205                 for (int i = 0; i < arr.length; i++) {
   206                     arr[i] = convertToArray(ja.get(i));
   207                 }
   208                 return arr;
   209             } else if (o instanceof JSONObject) {
   210                 JSONObject obj = (JSONObject)o;
   211                 Iterator it = obj.keys();
   212                 while (it.hasNext()) {
   213                     String key = (String)it.next();
   214                     obj.put(key, convertToArray(obj.get(key)));
   215                 }
   216                 return obj;
   217             } else {
   218                 return o;
   219             }
   220         }
   221     }
   222     
   223     @JavaScriptBody(args = { "url", "jsonp" }, body = 
   224         "var scrpt = window.document.createElement('script');\n "
   225         + "scrpt.setAttribute('src', url);\n "
   226         + "scrpt.setAttribute('id', jsonp);\n "
   227         + "scrpt.setAttribute('type', 'text/javascript');\n "
   228         + "var body = document.getElementsByTagName('body')[0];\n "
   229         + "body.appendChild(scrpt);\n"
   230     )
   231     private static void loadJSONP(String url, String jsonp) {
   232         
   233     }
   234 
   235     @JavaScriptBody(args = { "jsonObject", "props", "values" }, body = "throw 'ignore extractJSON';")
   236     public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
   237         if (jsonObject instanceof JSONObject) {
   238             JSONObject obj = (JSONObject)jsonObject;
   239             for (int i = 0; i < props.length; i++) {
   240                 try {
   241                     values[i] = obj.has(props[i]) ? obj.get(props[i]) : null;
   242                 } catch (JSONException ex) {
   243                     LoadJSON.LOG.log(Level.SEVERE, "Can't read " + props[i] + " from " + jsonObject, ex);
   244                 }
   245             }
   246             
   247         }
   248         
   249     }
   250     
   251 }