2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
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.
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.
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.
18 package org.apidesign.bck2brwsr.htmlpage;
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;
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;
43 * @author Jaroslav Tulach <jtulach@netbeans.org>
45 public final class ConvertTypes {
46 private static final Logger LOG = Logger.getLogger(ConvertTypes.class.getName());
50 public static String toString(Object object, String property) {
51 Object ret = getProperty(object, property);
52 return ret == null ? null : ret.toString();
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;
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;
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");
73 if (ret == null || modelClass.isInstance(ret)) {
74 return modelClass.cast(ret);
76 throw new IllegalStateException("Value " + ret + " is not of type " + modelClass);
79 public static String toJSON(Object value) {
83 if (value instanceof String) {
86 replace("\"", "\\\"").
92 return value.toString();
95 @JavaScriptBody(args = { "object", "property" },
96 body = "if (property === null) return object;\n"
97 + "var p = object[property]; return p ? p : null;"
99 private static Object getProperty(Object object, String property) {
100 if (property == null) {
103 if (object instanceof JSObject) {
104 JSObject jo = (JSObject)object;
105 return jo.getMember(property);
111 private static String findBaseURL() {
112 WebEngine eng = (WebEngine) System.getProperties().get("webEngine");
113 return (String)eng.executeScript(
115 + "if (!!window && !!window.location && !!window.location.href)\n"
116 + " h = window.location.href;\n"
123 public static String createJSONP(Object[] jsonResult, Runnable whenDone) {
124 return "json" + Integer.toHexString(whenDone.hashCode());
127 public static void loadJSON(
128 String url, Object[] jsonResult, Runnable whenDone, String jsonp
130 REQ.execute(new LoadJSON(url, jsonResult, whenDone, jsonp));
133 private static final Executor REQ = Executors.newCachedThreadPool();
134 private static final class LoadJSON implements Runnable {
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;
142 LoadJSON(String url, Object[] jsonResult, Runnable whenDone, String jsonp) {
144 this.jsonResult = jsonResult;
145 this.whenDone = whenDone;
149 b = new URL(findBaseURL());
150 } catch (MalformedURLException ex) {
151 LOG.log(Level.SEVERE, "Can't find base url for " + url, ex);
159 if (Platform.isFxApplicationThread()) {
164 URL u = new URL(base, url.replace(" ", "%20"));
165 InputStream is = u.openStream();
167 PushbackInputStream pis = new PushbackInputStream(is, 1);
180 Reader r = new InputStreamReader(is, "UTF-8");
182 JSONTokener tok = new JSONTokener(r);
183 JSONObject obj = new JSONObject(tok);
184 jsonResult[0] = convertToArray(obj);
185 } catch (JSONException | IOException ex) {
187 LOG.log(Level.WARNING, "Cannot connect to " + url, ex);
189 Platform.runLater(this);
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));
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)));
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"
223 private static void loadJSONP(String url, String jsonp) {
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++) {
232 values[i] = obj.get(props[i]);
233 } catch (JSONException ex) {
234 LOG.log(Level.SEVERE, "Can't read " + props[i] + " from " + jsonObject, ex);