ko-fx/src/main/java/org/apidesign/html/kofx/LoadJSON.java
changeset 37 184f08369400
child 54 0cc18086f731
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/ko-fx/src/main/java/org/apidesign/html/kofx/LoadJSON.java	Thu Apr 25 16:21:50 2013 +0200
     1.3 @@ -0,0 +1,182 @@
     1.4 +/**
     1.5 + * HTML via Java(tm) Language Bindings
     1.6 + * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     1.7 + *
     1.8 + * This program is free software: you can redistribute it and/or modify
     1.9 + * it under the terms of the GNU General Public License as published by
    1.10 + * the Free Software Foundation, version 2 of the License.
    1.11 + *
    1.12 + * This program is distributed in the hope that it will be useful,
    1.13 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
    1.14 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1.15 + * GNU General Public License for more details. apidesign.org
    1.16 + * designates this particular file as subject to the
    1.17 + * "Classpath" exception as provided by apidesign.org
    1.18 + * in the License file that accompanied this code.
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License
    1.21 + * along with this program. Look for COPYING file in the top folder.
    1.22 + * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
    1.23 + */
    1.24 +package org.apidesign.html.kofx;
    1.25 +
    1.26 +import java.io.IOException;
    1.27 +import java.io.InputStreamReader;
    1.28 +import java.io.PushbackInputStream;
    1.29 +import java.io.Reader;
    1.30 +import java.net.MalformedURLException;
    1.31 +import java.net.URL;
    1.32 +import java.util.Iterator;
    1.33 +import java.util.concurrent.Executor;
    1.34 +import java.util.concurrent.Executors;
    1.35 +import java.util.logging.Level;
    1.36 +import java.util.logging.Logger;
    1.37 +import javafx.application.Platform;
    1.38 +import javafx.scene.web.WebEngine;
    1.39 +import netscape.javascript.JSObject;
    1.40 +import org.apidesign.html.json.spi.JSONCall;
    1.41 +import org.json.JSONArray;
    1.42 +import org.json.JSONException;
    1.43 +import org.json.JSONObject;
    1.44 +import org.json.JSONTokener;
    1.45 +
    1.46 +/**
    1.47 + *
    1.48 + * @author Jaroslav Tulach <jtulach@netbeans.org>
    1.49 + */
    1.50 +final class LoadJSON implements Runnable {
    1.51 +    private static final Logger LOG = FXContext.LOG;
    1.52 +    private static final Executor REQ = Executors.newCachedThreadPool();
    1.53 +
    1.54 +    private final JSONCall call;
    1.55 +    private final URL base;
    1.56 +    private Throwable error;
    1.57 +    private Object json;
    1.58 +
    1.59 +
    1.60 +    private LoadJSON(JSONCall call) {
    1.61 +        this.call = call;
    1.62 +        URL b;
    1.63 +        try {
    1.64 +            b = new URL(findBaseURL());
    1.65 +        } catch (MalformedURLException ex) {
    1.66 +            LOG.log(Level.SEVERE, "Can't find base url for " + call.composeURL("dummy"), ex);
    1.67 +            b = null;
    1.68 +        }
    1.69 +        this.base = b;
    1.70 +    }
    1.71 +
    1.72 +    public static void loadJSON(JSONCall call) {
    1.73 +        REQ.execute(new LoadJSON((call)));
    1.74 +    }
    1.75 +
    1.76 +    @Override
    1.77 +    public void run() {
    1.78 +        if (Platform.isFxApplicationThread()) {
    1.79 +            if (error != null) {
    1.80 +                call.notifyError(error);
    1.81 +            } else {
    1.82 +                call.notifySuccess(json);
    1.83 +            }
    1.84 +            return;
    1.85 +        }
    1.86 +        final String url;
    1.87 +        if (call.isJSONP()) {
    1.88 +            url = call.composeURL("dummy");
    1.89 +        } else {
    1.90 +            url = call.composeURL(null);
    1.91 +        }
    1.92 +        try {
    1.93 +            final URL u = new URL(base, url.replace(" ", "%20"));
    1.94 +            final PushbackInputStream is = new PushbackInputStream(u.openStream(), 1);
    1.95 +            boolean array = false;
    1.96 +            if (call.isJSONP()) {
    1.97 +                for (;;) {
    1.98 +                    int ch = is.read();
    1.99 +                    if (ch == -1) {
   1.100 +                        break;
   1.101 +                    }
   1.102 +                    if (ch == '[') {
   1.103 +                        is.unread(ch);
   1.104 +                        array = true;
   1.105 +                        break;
   1.106 +                    }
   1.107 +                    if (ch == '{') {
   1.108 +                        is.unread(ch);
   1.109 +                        break;
   1.110 +                    }
   1.111 +                }
   1.112 +            } else {
   1.113 +                int ch = is.read();
   1.114 +                array = ch == '[';
   1.115 +                is.unread(ch);
   1.116 +            }
   1.117 +            Reader r = new InputStreamReader(is, "UTF-8");
   1.118 +
   1.119 +            JSONTokener tok = new JSONTokener(r);
   1.120 +            Object obj = array ? new JSONArray(tok) : new JSONObject(tok);
   1.121 +            json = convertToArray(obj);
   1.122 +        } catch (JSONException | IOException ex) {
   1.123 +            error = ex;
   1.124 +            LOG.log(Level.WARNING, "Cannot connect to " + url, ex);
   1.125 +        } finally {
   1.126 +            Platform.runLater(this);
   1.127 +        }
   1.128 +    }
   1.129 +
   1.130 +    private static Object convertToArray(Object o) throws JSONException {
   1.131 +        if (o instanceof JSONArray) {
   1.132 +            JSONArray ja = (JSONArray)o;
   1.133 +            Object[] arr = new Object[ja.length()];
   1.134 +            for (int i = 0; i < arr.length; i++) {
   1.135 +                arr[i] = convertToArray(ja.get(i));
   1.136 +            }
   1.137 +            return arr;
   1.138 +        } else if (o instanceof JSONObject) {
   1.139 +            JSONObject obj = (JSONObject)o;
   1.140 +            Iterator it = obj.keys();
   1.141 +            while (it.hasNext()) {
   1.142 +                String key = (String)it.next();
   1.143 +                obj.put(key, convertToArray(obj.get(key)));
   1.144 +            }
   1.145 +            return obj;
   1.146 +        } else {
   1.147 +            return o;
   1.148 +        }
   1.149 +    }
   1.150 +    
   1.151 +    public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
   1.152 +        if (jsonObject instanceof JSONObject) {
   1.153 +            JSONObject obj = (JSONObject)jsonObject;
   1.154 +            for (int i = 0; i < props.length; i++) {
   1.155 +                try {
   1.156 +                    values[i] = obj.has(props[i]) ? obj.get(props[i]) : null;
   1.157 +                } catch (JSONException ex) {
   1.158 +                    LoadJSON.LOG.log(Level.SEVERE, "Can't read " + props[i] + " from " + jsonObject, ex);
   1.159 +                }
   1.160 +            }
   1.161 +        }
   1.162 +        if (jsonObject instanceof JSObject) {
   1.163 +            JSObject obj = (JSObject)jsonObject;
   1.164 +            for (int i = 0; i < props.length; i++) {
   1.165 +                Object val = obj.getMember(props[i]);
   1.166 +                values[i] = isDefined(val) ? val : null;
   1.167 +            }
   1.168 +        }
   1.169 +    }
   1.170 +    
   1.171 +    private static String findBaseURL() {
   1.172 +        WebEngine eng = (WebEngine) System.getProperties().get("webEngine");
   1.173 +        return (String) eng.executeScript(
   1.174 +            "var h;"
   1.175 +            + "if (!!window && !!window.location && !!window.location.href)\n"
   1.176 +            + "  h = window.location.href;\n"
   1.177 +            + "else "
   1.178 +            + "  h = null;"
   1.179 +            + "h\n");
   1.180 +    }
   1.181 +
   1.182 +    private static boolean isDefined(Object val) {
   1.183 +        return !"undefined".equals(val);
   1.184 +    }
   1.185 +}