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