ko-fx/src/main/java/org/netbeans/html/kofx/LoadJSON.java
branchnetbeans
changeset 362 92fb71afdc0e
parent 358 80702021b851
child 365 5c93ad8c7a15
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/ko-fx/src/main/java/org/netbeans/html/kofx/LoadJSON.java	Mon Dec 16 16:59:43 2013 +0100
     1.3 @@ -0,0 +1,267 @@
     1.4 +/**
     1.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     1.6 + *
     1.7 + * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
     1.8 + *
     1.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
    1.10 + * Other names may be trademarks of their respective owners.
    1.11 + *
    1.12 + * The contents of this file are subject to the terms of either the GNU
    1.13 + * General Public License Version 2 only ("GPL") or the Common
    1.14 + * Development and Distribution License("CDDL") (collectively, the
    1.15 + * "License"). You may not use this file except in compliance with the
    1.16 + * License. You can obtain a copy of the License at
    1.17 + * http://www.netbeans.org/cddl-gplv2.html
    1.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
    1.19 + * specific language governing permissions and limitations under the
    1.20 + * License.  When distributing the software, include this License Header
    1.21 + * Notice in each file and include the License file at
    1.22 + * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
    1.23 + * particular file as subject to the "Classpath" exception as provided
    1.24 + * by Oracle in the GPL Version 2 section of the License file that
    1.25 + * accompanied this code. If applicable, add the following below the
    1.26 + * License Header, with the fields enclosed by brackets [] replaced by
    1.27 + * your own identifying information:
    1.28 + * "Portions Copyrighted [year] [name of copyright owner]"
    1.29 + *
    1.30 + * Contributor(s):
    1.31 + *
    1.32 + * The Original Software is NetBeans. The Initial Developer of the Original
    1.33 + * Software is Oracle. Portions Copyright 2013-2013 Oracle. All Rights Reserved.
    1.34 + *
    1.35 + * If you wish your version of this file to be governed by only the CDDL
    1.36 + * or only the GPL Version 2, indicate your decision by adding
    1.37 + * "[Contributor] elects to include this software in this distribution
    1.38 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
    1.39 + * single choice of license, a recipient has the option to distribute
    1.40 + * your version of this file under either the CDDL, the GPL Version 2 or
    1.41 + * to extend the choice of license to its licensees as provided above.
    1.42 + * However, if you add GPL Version 2 code and therefore, elected the GPL
    1.43 + * Version 2 license, then the option applies only if the new code is
    1.44 + * made subject to such option by the copyright holder.
    1.45 + */
    1.46 +package org.netbeans.html.kofx;
    1.47 +
    1.48 +import java.io.IOException;
    1.49 +import java.io.InputStream;
    1.50 +import java.io.InputStreamReader;
    1.51 +import java.io.OutputStream;
    1.52 +import java.io.PushbackInputStream;
    1.53 +import java.io.Reader;
    1.54 +import java.net.HttpURLConnection;
    1.55 +import java.net.MalformedURLException;
    1.56 +import java.net.URL;
    1.57 +import java.net.URLConnection;
    1.58 +import java.util.Iterator;
    1.59 +import java.util.concurrent.Executor;
    1.60 +import java.util.concurrent.Executors;
    1.61 +import java.util.concurrent.ThreadFactory;
    1.62 +import java.util.logging.Level;
    1.63 +import java.util.logging.Logger;
    1.64 +import javafx.application.Platform;
    1.65 +import net.java.html.js.JavaScriptBody;
    1.66 +import netscape.javascript.JSObject;
    1.67 +import org.apidesign.html.json.spi.JSONCall;
    1.68 +import org.json.JSONArray;
    1.69 +import org.json.JSONException;
    1.70 +import org.json.JSONObject;
    1.71 +import org.json.JSONTokener;
    1.72 +
    1.73 +/** This is an implementation package - just
    1.74 + * include its JAR on classpath and use official {@link Context} API
    1.75 + * to access the functionality.
    1.76 + *
    1.77 + * @author Jaroslav Tulach <jtulach@netbeans.org>
    1.78 + */
    1.79 +final class LoadJSON implements Runnable {
    1.80 +    private static final Logger LOG = FXContext.LOG;
    1.81 +    private static final Executor REQ = Executors.newCachedThreadPool(new ThreadFactory() {
    1.82 +        @Override
    1.83 +        public Thread newThread(Runnable runnable) {
    1.84 +            Thread thread = Executors.defaultThreadFactory().newThread(runnable);
    1.85 +            thread.setDaemon(true);
    1.86 +            return thread;
    1.87 +        }
    1.88 +    });
    1.89 +
    1.90 +    private final JSONCall call;
    1.91 +    private final URL base;
    1.92 +    private Throwable error;
    1.93 +    private Object json;
    1.94 +
    1.95 +
    1.96 +    private LoadJSON(JSONCall call) {
    1.97 +        this.call = call;
    1.98 +        URL b;
    1.99 +        try {
   1.100 +            b = new URL(findBaseURL());
   1.101 +        } catch (MalformedURLException ex) {
   1.102 +            LOG.log(Level.SEVERE, "Can't find base url for " + call.composeURL("dummy"), ex);
   1.103 +            b = null;
   1.104 +        }
   1.105 +        this.base = b;
   1.106 +    }
   1.107 +
   1.108 +    public static void loadJSON(JSONCall call) {
   1.109 +        assert !"WebSocket".equals(call.getMethod());
   1.110 +        REQ.execute(new LoadJSON((call)));
   1.111 +    }
   1.112 +
   1.113 +    @Override
   1.114 +    public void run() {
   1.115 +        if (Platform.isFxApplicationThread()) {
   1.116 +            if (error != null) {
   1.117 +                call.notifyError(error);
   1.118 +            } else {
   1.119 +                call.notifySuccess(json);
   1.120 +            }
   1.121 +            return;
   1.122 +        }
   1.123 +        final String url;
   1.124 +        if (call.isJSONP()) {
   1.125 +            url = call.composeURL("dummy");
   1.126 +        } else {
   1.127 +            url = call.composeURL(null);
   1.128 +        }
   1.129 +        try {
   1.130 +            final URL u = new URL(base, url.replace(" ", "%20"));
   1.131 +            URLConnection conn = u.openConnection();
   1.132 +            if (conn instanceof HttpURLConnection) {
   1.133 +                HttpURLConnection huc = (HttpURLConnection) conn;
   1.134 +                if (call.getMethod() != null) {
   1.135 +                    huc.setRequestMethod(call.getMethod());
   1.136 +                }
   1.137 +                if (call.isDoOutput()) {
   1.138 +                    huc.setDoOutput(true);
   1.139 +                    final OutputStream os = huc.getOutputStream();
   1.140 +                    call.writeData(os);
   1.141 +                    os.flush();
   1.142 +                }
   1.143 +            }
   1.144 +            final PushbackInputStream is = new PushbackInputStream(
   1.145 +                conn.getInputStream(), 1
   1.146 +            );
   1.147 +            boolean array = false;
   1.148 +            boolean string = false;
   1.149 +            if (call.isJSONP()) {
   1.150 +                for (;;) {
   1.151 +                    int ch = is.read();
   1.152 +                    if (ch == -1) {
   1.153 +                        break;
   1.154 +                    }
   1.155 +                    if (ch == '[') {
   1.156 +                        is.unread(ch);
   1.157 +                        array = true;
   1.158 +                        break;
   1.159 +                    }
   1.160 +                    if (ch == '{') {
   1.161 +                        is.unread(ch);
   1.162 +                        break;
   1.163 +                    }
   1.164 +                }
   1.165 +            } else {
   1.166 +                int ch = is.read();
   1.167 +                if (ch == -1) {
   1.168 +                    string = true;
   1.169 +                } else {
   1.170 +                    array = ch == '[';
   1.171 +                    is.unread(ch);
   1.172 +                    if (!array && ch != '{') {
   1.173 +                        string = true;
   1.174 +                    }
   1.175 +                }
   1.176 +            }
   1.177 +            try {
   1.178 +                if (string) {
   1.179 +                    throw new JSONException("");
   1.180 +                }
   1.181 +                Reader r = new InputStreamReader(is, "UTF-8");
   1.182 +
   1.183 +                JSONTokener tok = new JSONTokener(r);
   1.184 +                Object obj;
   1.185 +                obj = array ? new JSONArray(tok) : new JSONObject(tok);
   1.186 +                json = convertToArray(obj);
   1.187 +            } catch (JSONException ex) {
   1.188 +                Reader r = new InputStreamReader(is, "UTF-8");
   1.189 +                StringBuilder sb = new StringBuilder();
   1.190 +                for (;;) {
   1.191 +                    int ch = r.read();
   1.192 +                    if (ch == -1) {
   1.193 +                        break;
   1.194 +                    }
   1.195 +                    sb.append((char)ch);
   1.196 +                }
   1.197 +                json = sb.toString();
   1.198 +            }
   1.199 +        } catch (IOException ex) {
   1.200 +            error = ex;
   1.201 +        } finally {
   1.202 +            Platform.runLater(this);
   1.203 +        }
   1.204 +    }
   1.205 +
   1.206 +    static Object convertToArray(Object o) throws JSONException {
   1.207 +        if (o instanceof JSONArray) {
   1.208 +            JSONArray ja = (JSONArray)o;
   1.209 +            Object[] arr = new Object[ja.length()];
   1.210 +            for (int i = 0; i < arr.length; i++) {
   1.211 +                arr[i] = convertToArray(ja.get(i));
   1.212 +            }
   1.213 +            return arr;
   1.214 +        } else if (o instanceof JSONObject) {
   1.215 +            JSONObject obj = (JSONObject)o;
   1.216 +            Iterator it = obj.keys();
   1.217 +            while (it.hasNext()) {
   1.218 +                String key = (String)it.next();
   1.219 +                obj.put(key, convertToArray(obj.get(key)));
   1.220 +            }
   1.221 +            return obj;
   1.222 +        } else {
   1.223 +            return o;
   1.224 +        }
   1.225 +    }
   1.226 +    
   1.227 +    public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
   1.228 +        if (jsonObject instanceof JSONObject) {
   1.229 +            JSONObject obj = (JSONObject)jsonObject;
   1.230 +            for (int i = 0; i < props.length; i++) {
   1.231 +                try {
   1.232 +                    values[i] = obj.has(props[i]) ? obj.get(props[i]) : null;
   1.233 +                } catch (JSONException ex) {
   1.234 +                    LoadJSON.LOG.log(Level.SEVERE, "Can't read " + props[i] + " from " + jsonObject, ex);
   1.235 +                }
   1.236 +            }
   1.237 +        }
   1.238 +        if (jsonObject instanceof JSObject) {
   1.239 +            JSObject obj = (JSObject)jsonObject;
   1.240 +            for (int i = 0; i < props.length; i++) {
   1.241 +                Object val = obj.getMember(props[i]);
   1.242 +                values[i] = isDefined(val) ? val : null;
   1.243 +            }
   1.244 +        }
   1.245 +    }
   1.246 +    
   1.247 +    public static Object parse(InputStream is) throws IOException {
   1.248 +        try {
   1.249 +            InputStreamReader r = new InputStreamReader(is, "UTF-8");
   1.250 +            JSONTokener t = new JSONTokener(r);
   1.251 +            return new JSONObject(t);
   1.252 +        } catch (JSONException ex) {
   1.253 +            throw new IOException(ex);
   1.254 +        }
   1.255 +    }
   1.256 +
   1.257 +    @JavaScriptBody(args = {  }, body = 
   1.258 +          "var h;"
   1.259 +        + "if (!!window && !!window.location && !!window.location.href)\n"
   1.260 +        + "  h = window.location.href;\n"
   1.261 +        + "else "
   1.262 +        + "  h = null;"
   1.263 +        + "return h;\n"
   1.264 +    )
   1.265 +    private static native String findBaseURL();
   1.266 +    
   1.267 +    private static boolean isDefined(Object val) {
   1.268 +        return !"undefined".equals(val);
   1.269 +    }
   1.270 +}